作者做過微信二維碼和地理信息的程序,本章介紹一下獲取二維碼和處理用戶掃描二維碼的過程。
要想開通生成二維碼api必須是認證的服務號,如果沒有可以采用公眾平台測試賬號,地址:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
登陸后台的界面如圖:
終於看到了傳說中的appID,appsecret。
當微信用戶掃描二維碼時,實現兩個功能:
- 如果用戶還未關注公眾號,則用戶可以關注公眾號,關注后微信會將帶場景值關注事件推送給開發者。
- 如果用戶已經關注公眾號,在用戶掃描后會自動進入會話,微信也會將帶場景值掃描事件推送給開發者。
其中的場景值就是,二維碼攜帶的一個參數,該參數的類型:
- 臨時二維碼時為32位非0整型,
- 永久二維碼時最大值為100000(目前參數只支持1--100000)
永久二維碼和臨時二維碼的區別:
臨時二維碼只能在一段時間內掃碼,這段時間內后台可以接受到掃碼事件,超過這段時間后台就不能接收到了,這個功能適用在二維碼驗證信息的方面。
永久二維碼不限時間,但是數量有限,共100000個。
獲取永久二維碼api官方說明為
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); //掃碼關注公眾賬號
} }