經過PHP調用微信JSSDK實例

JSSDK使用步驟:

1. 先登陸微信公衆平臺進入「公衆號設置」的「功能設置」裏填寫「JS接口安全域名」。javascript

2. 採用http GET方式請求得到access_token(有效期7200秒)。php

3. 用上一步拿到的access_token 採用http GET方式請求得到jsapi_ticket(有效期7200秒)。html

4. 得到jsapi_ticket以後,就能夠生成JS-SDK權限驗證的簽名了,簽名生成規則以下:參與簽名的字段包括noncestr(隨機字符串), 有效的jsapi_ticket, timestamp(時間戳), url(當前網頁的URL,不包含#及其後面部分) 。對全部待簽名參數按照字段名的ASCII 碼從小到大排序(字典序)後,使用URL鍵值對的格式(即key1=value1&key2=value2…)拼接成字符串string1。這裏須要注意的是全部參數名均爲小寫字符。對string1做sha1加密,字段名和字段值都採用原始值,不進行URL 轉義。java

5. 在須要調用JS接口的頁面引入以下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.4.0.jsjson

6. 在須要的H5頁面上調用JSSDK。後端

 

注意事項api

1.簽名用的noncestr和timestamp必須與wx.config中的nonceStr和timestamp相同。安全

2.簽名用的url必須是調用JS接口頁面的完整URL。服務器

3.出於安全考慮,開發者必須在服務器端實現簽名的邏輯。微信

<?php

// 微信 JS 接口簽名校驗工具: https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
$appid = 'your appid';
$secret = 'your secret';


// 獲取token
$token_data = file_get_contents('./wechat_token.txt');
if (!empty($token_data)) {
    $token_data = json_decode($token_data, true);
}

$time  = time() - $token_data['time'];
if ($time > 3600) {
    $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
    $token_res = https_request($token_url);
    $token_res = json_decode($token_res, true);
    $token = $token_res['access_token'];

    $data = array(
        'time' =>time(),
        'token' =>$token
    );
    $res = file_put_contents('./wechat_token.txt', json_encode($data));
    if ($res) {
        echo '更新 token 成功';
    }
} else {
    $token = $token_data['token'];
}


// 獲取ticket
$ticket_data = file_get_contents('./wechat_ticket.txt');
if (!empty($ticket_data)) {
    $ticket_data = json_decode($ticket_data, true);
}

$time  = time() - $ticket_data['time'];
if ($time > 3600) {
    $ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi";
    $ticket_res = https_request($ticket_url);
    $ticket_res = json_decode($ticket_res, true);
    $ticket = $ticket_res['ticket'];

    $data = array(
        'time'    =>time(),
        'ticket'  =>$ticket
    );
    $res = file_put_contents('./wechat_ticket.txt', json_encode($data));
    if ($res) {
        echo '更新 ticket 成功';
    }
} else {
    $ticket = $ticket_data['ticket'];
}


// 進行sha1簽名
$timestamp = time();
$nonceStr = createNonceStr();

// 注意 URL 建議動態獲取(也能夠寫死).
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; // 調用JSSDK的頁面地址
// $url = $_SERVER['HTTP_REFERER']; // 先後端分離的, 獲取請求地址(此值不許確時能夠經過其餘方式解決)

$str = "jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
$sha_str = sha1($str);


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;
}


/**
 * 模擬 http 請求
 * @param  String $url  請求網址
 * @param  Array  $data 數據
 */
function https_request($url, $data = null){
    // curl 初始化
    $curl = curl_init();

    // curl 設置
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    // 判斷 $data get  or post
    if ( !empty($data) ) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    // 執行
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}

?>




<html>
<head>
  <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
   <h2 onclick="test()">掃一掃</h2>
    
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
    <script type="text/javascript">
        wx.config({
            debug: true, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。
            appId: '<? echo $appid ?>', // 必填,公衆號的惟一標識
            timestamp: <? echo $timestamp ?>, // 必填,生成簽名的時間戳
                nonceStr: '<? echo $nonceStr ?>', // 必填,生成簽名的隨機串
                signature: '<? echo $sha_str ?>',// 必填,簽名
            jsApiList: ['scanQRCode'] // 必填,須要使用的JS接口列表
        });

        wx.ready(function(){
            console.log('接口配置成功');
        });

        function test(){
            console.log('ok啦');
            wx.scanQRCode({
                needResult: 1, // 默認爲0,掃描結果由微信處理,1則直接返回掃描結果,
                scanType: ["qrCode","barCode"], // 能夠指定掃二維碼仍是一維碼,默認兩者都有
                success: function (res) {
                    var result = res.resultStr; // 當needResult 爲 1 時,掃碼返回的結果
                    console.log(result);
                }
            });
        }
  </script>
</body>
</html>
相關文章
相關標籤/搜索