curl.phpphp
define("APPID",""); define("APPSECRET",""); define("TOKEN","weixin"); require("./wechat.inc.php"); header("content-type:image/jpg"); $wechat=new WeChat(APPID,APPSECRET,TOKEN); echo $wechat->_getQRCode();
WeChat.inc.phpjson
class WeChat{ private $_appid; private $_appsecret; private $_token; public function __construct($appid,$appsecret,$token) { $this->_appid=$appid; $this->_appsecret=$appsecret; $this->_token=$token; } private function _request($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,FALSE);//不作客戶端認證 } if($method=='post') { curl_setopt($ch, CURLOPT_POST,true);//設置請求是post方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//設置post請求數據 } $str=curl_exec($ch);//執行訪問 curl_close($ch);//關閉curl,釋放資源 return $str; } private function _getAccesstoken() { $file="./accesstoken"; if(file_exists($file)) { $content=file_get_contents($file); $content=json_decode($content); if(time()-filemtime($file)<$content->expires_in) { return $content->access_token; } } $content=_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->_appid."&secret=".$this->_appsecret); file_put_contents($file,$content); $content=json_decode($content); return $content->access_token; } /*獲取ticket expire_seconds:二維碼有效期(秒) type:二維碼類型(臨時或永久) scene:場景編號 */ public function _getTicket($expire_seconds=604800,$type="temp",$scene=1) { if($type=="temp"){ $data='{"expire_seconds": '.$expire_seconds.', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene.'}}}'; return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->_getAccesstoken(),true,"post",$data); }else { $data='{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$scene.'}}}'; return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->_getAccesstoken(),true,"post",$data); } } /* 經過ticket獲取二維碼 */ public function _getQRCode($expire_seconds=604800,$type="temp",$scene=1) { $content=json_decode($this->_getTicket($expire_seconds,$type,$scene)); $ticket=$content->ticket; $image=$this->_request("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket)); //$file="./".$type.$scene.".jpg"; //設置圖片名字 //file_put_contents($file,$content); //二維碼保存到本地 return $image; } }