1. 程式人生 > >微信公眾號介面相關操作

微信公眾號介面相關操作

<?php
/**
* 微信公眾號介面相關操作
*/
class WeChat
{
private $_appid;
private $_appsecret;
private $_token;
public function __construct($_appid,$_appsecret,$_token)
{
$this->_appid=$_appid;
$this->_appsecret=$_appsecret;
$this->_token=$_token;
}
//獲得微信通訊token
public function requestUrl($curl,$https=true,$method='GET',$data=null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curl);
curl_setopt($ch, CURLOPT_HEADER, false);//這裡不需要頭資訊只要內容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($https){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);//是否進行伺服器主機驗證
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,2);//是否進行https證書檢查(2僅校驗是否有CN欄位)
}
if($method == 'POST'){
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
//獲取token
public function getAccessToken()
{
$file = './wxaccesstoken.json';//儲存到檔案不用每次都請求介面
if(is_file($file)){
$content = file_get_contents($file);
$content = json_decode($content);
if(time() - filemtime($file) < $content->expires_in){
return $content->access_token;
}
}
$curl='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->_appid.'&secret='.$this->_appsecret;
$content = $this->requestUrl($curl);
file_put_contents($file, $content);
$content = json_decode($content);
return $content->access_token;
}
//獲取ticket
public function getTicket($sceneid,$type='temp',$expire_seconds=604800)
{
if($type == 'temp'){//臨時二維碼
$data = '{"expire_seconds": %s, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": %s}}}';
$data = sprintf($data,$expire_seconds,$sceneid);
}else{//永久二維碼
$data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": %s}}}';
$data = sprintf($data,$sceneid);
}
$curl = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$this->getAccessToken();
$content = $this->requestUrl($curl,true,'POST',$data);
$content = json_decode($content);
return $content->ticket;
}
//獲取二微碼
public function getQRCode($sceneid,$type='temp',$expire_seconds=604800){
$ticket = $this->getTicket($sceneid,$type,$expire_seconds);
$content = $this->requestUrl('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.urlencode($ticket));
return $content;
}
}
 
//公眾賬號測試介面可免費申請https://mp.weixin.qq.com/wiki (下面請自行修改)
$wechat = new wechat('wx487a542e3e7f3b84','5cddf41d16111222e321b48e213875b8','');
//1. 獲得token
//echo $wechat->getAccessToken();
//2. 獲得二維碼
header('Content-type:image/jpeg');
echo $wechat->getQRCode(123);
 
?>