哎!苦於客戶一直要求,官方文檔看起來又蛋疼,磨了一個下午整理出一套試用Thinkphp 調用微信掃一掃示例
別小瞧這些代碼哦,它們能幫你實現幾乎所有的微信功能^_^
1 先在Thinkphp -- Vendor 目錄下面創建WxJDK文件夾,然后在創建文件jssdk.php.
<?php # +=========================================================================== # | Author : cq <just_leaf@foxmail.com> # | 微信文檔 :https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115 # +=========================================================================== class JSSDK { # - 公眾號appid ,公眾號開發配置處可查看 public $appId; # - 公眾號appi , 公眾號開發配置處可查看 private $appSecret; /** * @name 初始化參數 * @author cq <just_leaf@foxmail.com> * @copyright zydbbt 2018-10-27 */ public function __construct( $appId , $appSecret ) { $this -> appId = $appId; $this -> appSecret = $appSecret; } /** * @name 獲取accessToken * @author cq <just_leaf@foxmail.com> * @copyright zydbbt 2018-10-27 */ public function getAcc(){ return $this -> getAccessToken(); } /** * @name 獲取config接口注入權限驗證配置 * @author cq <just_leaf@foxmail.com> * @copyright zydbbt 2018-10-27 */ public function getWxConfig() { # - 獲取 jsapi_ticket $jsapiTicket = $this -> getJsApiTicket(); # - 獲取調用頁面的url $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; # - 時間戳 $timestamp = time(); # - 獲取隨機字符串 $nonceStr = $this -> createNonceStr(); # - 這里參數的順序要按照 key 值 ASCII 碼升序排序 # - 亦可把參數以數組存值,ksort() - 以升序對關聯數組進行排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url"; # - sha1獲取簽名 $signature = sha1($string); # - 頁面所需注入參數 $WxConfig = array( "appId" => $this -> appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ); # - 返回 return $WxConfig; } /** * @name 獲取JsApiTicket * @author cq <just_leaf@foxmail.com> * @copyright zydbbt 2018-10-27 */ private function getJsApiTicket() { # - 判斷緩存 $ticket = S('ticket'); if(!$ticket) { # - 獲取 $accessToken = $this->getAccessToken(); # - 獲取Ticket # - 如果是企業號用以下 URL 獲取 ticket $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken"; # - get請求,轉換數組 $result = json_decode($this->httpGet($url),true); $ticket = $result['ticket']; # - 全局緩存 if ($ticket) { # - 官方返回 # - { # - "errcode":0, # - "errmsg":"ok", # - "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA", # - "expires_in":7200 # - } S('ticket',$ticket,$result['expires_in']); } } # - 返回 return $ticket; } /** * @name 獲取AccessToken * @author cq <just_leaf@foxmail.com> * @copyright zydbbt 2018-10-27 */ private function getAccessToken() { # - 判斷緩存 $access_token = S('accesToken'); if(!$access_token) { # - 如果是企業號用以下URL獲取access_token $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret"; # - get請求,轉換數組 $result = json_decode($this->httpGet($url),true); $access_token = $result['access_token']; # - 全局緩存 if ($access_token) { S('accesToken',$result['access_token'],$result['expires_in']); } } # - 返回 return $access_token; } /** * @name GET請求 * @author cq <just_leaf@foxmail.com> * @copyright zydbbt 2018-10-27 */ private function httpGet($url) { # - 初始化 $curl = curl_init(); # - 為保證第三方服務器與微信服務器之間數據傳輸的安全性,所有微信接口采用https方式調用,必須使用下面2行代碼打開ssl安全校驗。 # - 如果在部署過程中代碼在此處驗證失敗,請到 http://curl.haxx.se/ca/cacert.pem 下載新的證書判別文件。 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_URL, $url); # - 請求 $res = curl_exec($curl); # - 關閉 curl_close($curl); # - 返回 return $res; } /** * @name 產生隨機字符串 * @author cq <just_leaf@foxmail.com> * @copyright zydbbt 2018-10-27 */ private function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } }
2 把網站的Ip 授權,不然無法獲取access_token值,那么jspai_ticket也將無法獲取
使用方法看下列代碼:
php:action如下
/** * # +======================================================================== * # | - @name 初始化參數 * # | - @author cq <just_leaf@foxmail.com> * # | - @copyright zmtek 2018-11-12 * # +------------------------------------------------------------------------ * # | - 1.初始化傳參值頁面 * # +======================================================================== */ public function _initialize() { # 引入 Vendor('WxJDK.jssdk'); # 公眾號獲取 $appid = C('APPID'); # 公眾號獲取 $appSecret = C('APPSECRET'); # 實例化 $wx = new \JSSDK($appid,$appSecret); # 獲取參數 $info = $wx-> getWxConfig(); # 傳參頁面 $this -> assign('wxConfig',$info); }
html:頁面如下
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/> <title>微信掃一掃</title> </head> <body> <h1 id="wxcode" style="text-align: center;">掃一掃</h1> </body> <script src="__ROOT__/statics/Wxshop/js/jquery.min.js" type="text/javascript"></script> <script src='https://res.wx.qq.com/open/js/jweixin-1.4.0.js'></script> <script> wx.config({ // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。 debug: false, // 必填,公眾號的唯一標識 appId: "{$wxConfig.appId}", // 必填,生成簽名的時間戳 timestamp:"{$wxConfig.timestamp}", // 必填,生成簽名的隨機串 nonceStr:"{$wxConfig.nonceStr}", // 必填,簽名,見附錄1 signature:"{$wxConfig.signature}", // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2 jsApiList : [ 'scanQRCode' ] }); wx.error(function(res) { // alert("----------出錯了-----------:" + res.errMsg);//這個地方的好處就是wx.config配置錯誤,會彈出窗口哪里錯誤,然后根據微信文檔查詢即可。 }); wx.ready(function() { wx.checkJsApi({ jsApiList : ['scanQRCode'], success : function(res) { } }); //點擊按鈕掃描二維碼 $('#wxcode').click(function(){ // alert(1); wx.scanQRCode({ needResult: 0, // 默認為0,掃描結果由微信處理,1則直接返回掃描結果, scanType: ["qrCode","barCode"], // 可以指定掃二維碼還是一維碼,默認二者都有 success: function (res) { var result = res.resultStr; // 當needResult 為 1 時,掃碼返回的結果 } }); }) }); </script> </html>