哎!苦于客戶一直要求,官方文檔看起來又蛋疼,磨了一個下午整理出一套試用Thinkphp5.1 調用微信掃一掃示例
別小瞧這些代碼哦,它們能幫你實現幾乎所有的微信功能^_^
示例地址:http://spt.zmtek.net/Wxshop/Wxtest/options (手機微信打開)
1 先在Thinkphp -- Vendor 目錄下面創建WxJDK文件夾,然后在創建文件JSSDK.php.
<?php
namespace WxJDK;
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 = session('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
# - }
//? ? ? ? ? ? ? ? session('ticket',$ticket,$result['expires_in']);
? ? ? ? ? ? ? ? session('ticket',$ticket);
}
}
? ? ? ? # - 返回
? ? ? ? return $ticket;
}
? ? /**
? ? * @name? ? ? ? 獲取AccessToken
? ? * @author? ? ? ? cq <just_leaf@foxmail.com>
? ? * @copyright? ? zydbbt 2018-10-27
*/
? ? private function getAccessToken(){
? ? ? ? # - 判斷緩存
? ? ? ? $access_token = session('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){
//? ? ? ? ? ? ? ? session('accesToken',$result['access_token'],$result['expires_in']);
? ? ? ? ? ? ? ? session('accesToken',$result['access_token']);
}
}
? ? ? ? # - 返回
? ? ? ? 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_URL,$url);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_TIMEOUT,500);
# - 請求
? ? ? ? $res = curl_exec($curl);
//? ? ? ? $res = json_decode($res, true);
# - 關閉
? ? ? ? curl_close($curl);
# - 返回
? ? ? ? return $res;
}
? ? /**
? ? * @name? ? ? ? POST請求
? ? * @author? ? ? ? cq <just_leaf@foxmail.com>
? ? * @copyright? ? zydbbt 2018-10-27
*/
? ? private function httpPost($url,$query_data){
? ? ? ? # - 初始化
? ? ? ? $curl = curl_init();
# - 為保證第三方服務器與微信服務器之間數據傳輸的安全性,所有微信接口采用https方式調用,必須使用下面2行代碼打開ssl安全校驗。
# - 如果在部署過程中代碼在此處驗證失敗,請到 http://curl.haxx.se/ca/cacert.pem 下載新的證書判別文件。
? ? ? ? curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_POSTFIELDS,$query_data);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_TIMEOUT,500);
# - 請求
? ? ? ? $res = curl_exec($curl);
//? ? ? ? $res = json_decode($res, true);
# - 關閉
? ? ? ? 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;
}
? ? public function getCommodityInfo($sub){
//聚合數據接口
# - 如果是企業號用以下URL獲取access_token
? ? ? ? $url = "http://feedback.api.juhe.cn/ISBN?key=c74a5cde7c1e58709624454f18447a54&sub=".$sub;
# - get請求,轉換數組
? ? ? ? $result = json_decode($this->httpGet($url),true);
halt($result);
}
}
2 把網站的Ip 授權,不然無法獲取access_token值,那么jspai_ticket也將無法獲取
使用方法看下列代碼:
php:action如下
namespace app\index\controller;
use app\common\controller\Base;
use think\Loader;
class Smsb extends Base
{
? ? public function index()
{
? ? ? ? # 公眾號獲取
? ? ? ? $appid = config('wechat')['wechat_options']['appid'];
# 公眾號獲取
? ? ? ? $appSecret = config('wechat')['wechat_options']['appsecret'];
# 實例化
? ? ? ? $wx = new \WxJDK\JSSDK($appid,$appSecret);
# 獲取參數
? ? ? ? $info = $wx-> getWxConfig();
$info['url']=str_replace('http://','',$info['url']);
# 傳參頁面
? ? ? ? $this -> assign('wxConfig',$info);
return $this->fetch('');
}
? public function WeChat()
{
? ? ? ? return ['appId'=>config('WeChat')['appId'],'timestamp'=>time(),'noncestr'=>'123456','signature'=>''];
}
? ? public function sp(){
? ? ? ? # 公眾號獲取
? ? ? ? $appid = config('wechat')['wechat_options']['appid'];
# 公眾號獲取
? ? ? ? $appSecret = config('wechat')['wechat_options']['appsecret'];
$wx = new \WxJDK\JSSDK($appid,$appSecret);
$wx->getCommodityInfo(input('ISBN'));
return $this->fetch('index');
}
? ? public function hello($name = 'ThinkPHP5')
{
? ? ? ? return 'hello,' . $name;
}
}
html:頁面如下
<!DOCTYPE html>
<html>
? <head>
? ? ? <meta charset="utf-8" />
? ? ? <title></title>
? ? ? <script src="/static/js/jquery-1.8.3.min.js" type="text/javascript" charset="utf-8"></script>
? ? ? <script src="/static/js/jweixin-1.4.0.js" type="text/javascript" charset="utf-8"></script>
? </head>
? <body>
? ? ? <a class="weui-btn weui-btn_primary submit-btn" id="wxcode" type="button">掃一掃</a>
? <div id="content"></div>
? </body>
</html>
<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: 1,// 默認為0,掃描結果由微信處理,1則直接返回掃描結果,
? ? ? ? ? ? scanType: ["qrCode","barCode"],// 可以指定掃二維碼還是一維碼,默認二者都有
? ? ? ? ? ? success: function (res){
? ? ? ? ? ? ? var result = res.resultStr;// 當needResult 為 1 時,掃碼返回的結果
? ? ? ? ? ? ? result=result.replace('EAN_13,','');
var url= '{:url("smsb/sp")}';
url = url+'?ISBN='+result;
//? ? ? ? ? ? $('#content').html(url);
? ? ? ? ? ? ? window.location = url;
}
? ? ? ? });
})
});
</script>