做者作過微信二維碼和地理信息的程序,本章介紹一下獲取二維碼和處理用戶掃描二維碼的過程。php
要想開通生成二維碼api必須是認證的服務號,若是沒有能夠採用公衆平臺測試帳號,地址:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/loginjson
登錄後臺的界面如圖:api
終於看到了傳說中的appID,appsecret。微信
當微信用戶掃描二維碼時,實現兩個功能:session
其中的場景值就是,二維碼攜帶的一個參數,該參數的類型:app
永久二維碼和臨時二維碼的區別:curl
臨時二維碼只能在一段時間內掃碼,這段時間內後臺能夠接受到掃碼事件,超過這段時間後臺就不能接收到了,這個功能適用在二維碼驗證信息的方面。post
永久二維碼不限時間,可是數量有限,共100000個。測試
獲取永久二維碼api官方說明爲url
http請求方式: POST URL: https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN POST數據格式:json POST數據例子:{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 123}}}
請求api中首先要得到access_token
http請求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
得到access_token就要用到appID、appsecret兩個參數。得到access_token的頻次是有限制的,所以不要請求一次二維碼就申請一次token。能夠將access_token存儲在session中,須要判斷是否過時,過時了再從新申請。php示例代碼
<?php
define('APPID', 'wxa4e7830fd');
define('APPSECRET','f013408d50e0c8d');
@session_start(); if(isset($_SESSION['dotime']) && ($_SESSION['dotime']+7200)>time()) {
//access_token存儲在session中
} else { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $out = curl_exec($ch); $json = json_decode($out,true); curl_close($ch); $_SESSION['access_token']=$json['access_token']; $_SESSION['dotime'] = time(); } for($index=1;$index<10;$index++) { $ch = curl_init(); @$obj->action_name = "QR_LIMIT_SCENE"; @$obj->action_info->scene->scene_id =$index; $data_string = json_encode($obj); $ch = curl_init('https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$_SESSION['access_token']); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string); //curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); $out = curl_exec($ch); curl_close($ch); $json = json_decode($out,true); $ticket = $json['ticket']; $ch = curl_init('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$ticket); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $out = curl_exec($ch); file_put_contents("/opt/lampp/htdocs/barcode/".$index.".jpg", $out); echo $index."jpg<br/>"; } ?>
掃描二維碼的,微信後臺接受到xml文件,解析xml文件,掃碼是EVENT類型的信息。
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; $recvMsgType = $postObj->MsgType; if($recvMsgType=='event') { $recvEvent = $postObj->Event; if($recvEvent=='SCAN') { $scan = $postObj->EventKey; //已經關注公衆帳號
} else if($recvEvent=="subscribe") { $qrscene = $postObj->EventKey; $id = substr($qrscene, 8); //掃碼關注公衆帳號
} }