使用到微信接口是“生成帶參數的二維碼”,可以生成兩種二維碼,一種是臨時二維碼,會過期,生成量大,主要用於帳號綁定等不要求二維碼永久保存的業務場景;另一種是永久二維碼,沒有過期時間,但生成量小(目前為最多10萬個),主要用於適用於帳號綁定、用戶來源統計等場景。掃碼之后,如果用戶沒關注公眾號會提示關注,如果已關注就直接進入公眾號對話框。
首先創建二維碼ticket,然后憑借ticket到指定URL換取二維碼,具體介紹可以看官方文檔 https://developers.weixin.qq.com/doc/offiaccount/Account_Management/Generating_a_Parametric_QR_Code.html
示例代碼:
<?php namespace app\index\controller; use think\Controller; /** * 微信類 */ class Wechat extends Controller { protected $APPID = 'xxxxxxxxxxx'; protected $APPSECRET = 'xxxxxxxxxxxxxx'; /** * curl請求 */ public function http_curl($url, $type = 'get', $res = 'json', $arr = ''){ $cl = curl_init(); curl_setopt($cl, CURLOPT_URL, $url); curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, false); if($type == 'post'){ curl_setopt($cl, CURLOPT_POST, 1); curl_setopt($cl, CURLOPT_POSTFIELDS, $arr); } $output = curl_exec($cl); curl_close($cl); return json_decode($output, true); if($res == 'json'){ if( curl_error($cl)){ return curl_error($cl); }else{ return json_decode($output, true); } } } /** * 獲取 AccessToken */ public function getAccessToken() { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->APPID."&secret=".$this->APPSECRET; // 先判斷 access_token 文件里的token是否過期,沒過期繼續使用,過期就更新 $data = json_decode($this->get_php_file(ROOT_PATH."public".DS."wxtxt".DS."access_token.txt")); // 過期 更新 if ($data->expire_time < time()) { $res = $this->http_curl($url); $access_token = $res['access_token']; if ($access_token) { // 在當前時間戳的基礎上加7000s (兩小時) $data->expire_time = time() + 7000; $data->access_token = $res['access_token']; $this->set_php_file(ROOT_PATH."public".DS."wxtxt".DS."access_token.txt",json_encode($data)); } }else{ // 未過期 直接使用 $access_token = $data->access_token; } return $access_token; } // 獲取存儲文件中的token private function get_php_file($filename) { return trim(file_get_contents($filename)); } // 把token 存儲到文件中 private function set_php_file($filename, $content) { $fp = fopen($filename, "w"); fwrite($fp, $content); fclose($fp); } /** * 生成二維碼 */ public function getQrcode(){ $token = $this->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$token";
// 參數 $param = array(); $param['action_name'] = "QR_LIMIT_SCENE"; $param['action_info'] = array( 'scene' => array( 'scene_id'=>'123' ) ); $param = json_encode($param); // 返回二維碼的ticket和二維碼圖片解析地址 $res = $this->http_curl($url, 'post', 'json', $param);
// 通過ticket換取二維碼 $qrcode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$res['ticket'];
//輸出二維碼圖片路徑
echo "<center><img src=".$qrcode."></center>"; } }
運行getQrcode()方法,效果如下
思路說明:
1.獲取Token,注意過期時間
2.獲取ticket,拿Token和二維碼的一些參數,換取ticket
3.生成二維碼,拿ticket換取二維碼地址