天天看點

JS-SDK擷取微信接口權限微信的JS-SDK通過config接口注入權限驗證配置:

微信的JS-SDK通過config接口注入權限驗證配置:

前端頁面JS代碼:

wx.config({  
    // 開啟調試模式,調用的所有api的傳回值會在用戶端alert出來,若要檢視傳入的參數,可以在pc端打開,參數資訊會通過log打出,僅在pc端時才會列印。
    debug: true,   
    appId: '', // 必填,公衆号的唯一辨別  
    timestamp: , // 必填,生成簽名的時間戳  
    nonceStr: '', // 必填,生成簽名的随機串  
    signature: '',// 必填,簽名  
    jsApiList: [] // 必填,需要使用的JS接口清單  
});  
           

jsapi_ticket

        生成簽名之前必須先了解一下jsapi_ticket,jsapi_ticket是公衆号用于調用微信JS接口的臨時票據。

        正常情況下,jsapi_ticket的有效期為7200秒,通過access_token來擷取。

        由于擷取jsapi_ticket的api調用次數有限,頻繁重新整理jsapi_ticket會導緻api調用受限,影響自身業務,

        開發者必須在自己的服務全局緩存jsapi_ticket 。

1、擷取access_token(有效期7200秒,開發者必須在自己的服務全局緩存access_token)

2、用第一步拿到的access_token 采用http GET方式請求獲得jsapi_ticket(有效期7200秒,開發者必須在自己的服務全局緩存jsapi_ticket)

     成功傳回如下JSON:

{  
"errcode":0,  
"errmsg":"ok",  
"ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",  
"expires_in":7200  
}  
           

獲得jsapi_ticket之後,就可以生成JS-SDK權限驗證的簽名了

簽名算法

        簽名生成規則如下:

       參與簽名的字段包括:

       noncestr(随機字元串), 有效的jsapi_ticket, timestamp(時間戳), url(目前網頁的URL,不包含#及其後面部分) 。

        對所有待簽名參數按照字段名的ASCII 碼從小到大排序(字典序)後,使用URL鍵值對的格式(即key1=value1&key2=value2…)拼接成字元串string1。

        這裡 需要注意的是所有參數名均為小寫字元。對string1作sha1加密,字段名和字段值都采用原始值,不進行URL 轉義。

步驟1. 對所有待簽名參數按照字段名的ASCII 碼從小到大排序(字典序)後,使用URL鍵值對的格式(即key1=value1&key2=value2…)拼接成字元串string1。

步驟2. 對string1進行sha1簽名,得到signature。

注意事項:

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

2、簽名用的url必須是調用JS接口頁面的完整URL。

3、出于安全考慮,開發者必須在伺服器端實作簽名的邏輯。

以上的東西加起來就是四步:

* : 必須将伺服器的外網IP位址添加到公衆号的IP白名單上

1、使用APPID和APPSecret擷取access_token;

2、使用access_token擷取jsapi_ticket ;

3、用時間戳、随機數、jsapi_ticket和要通路的url按照簽名算法拼接字元串;

4、對第三步的字元串進行SHA1加密,得到簽名。

Java代碼實作:

第一步、擷取access_token

public static String getAccessToken() {  
    String access_token = "";  
    String grant_type = "client_credential";//擷取access_token填寫client_credential
    //APPID和APPSECRET可以去微信公衆平台---“開發----基本配置”中查找。
    String AppId="APPID";//第三方使用者唯一憑證  
    String secret="APPSECRET";//第三方使用者唯一憑證密鑰,即appsecret   
    //這個url連結位址和參數皆不能變  
    String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+AppId+"&secret="+secret;  
       
    try {  
        URL urlGet = new URL(url);  
        HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();  
        http.setRequestMethod("GET"); // 必須是get方式請求  
        http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
        http.setDoOutput(true);  
        http.setDoInput(true);  
        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 連接配接逾時30秒  
        System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 讀取逾時30秒  
        http.connect();  
        InputStream is = http.getInputStream();  
        int size = is.available();  
        byte[] jsonBytes = new byte[size];  
        is.read(jsonBytes);  
        String message = new String(jsonBytes, "UTF-8");  
        JSONObject demoJson = JSONObject.fromObject(message);  
        System.out.println("JSON字元串:"+demoJson);  
        access_token = demoJson.getString("access_token");  
        is.close();  
    } catch (Exception e) {  
            e.printStackTrace();  
    }  
    return access_token;  
} 
           

第二步、擷取jsapi_ticket

public static String getTicket(String access_token) {  
    String ticket = null;  
    String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token +"&type=jsapi";//這個url連結和參數不能變  
    try {  
        URL urlGet = new URL(url);  
        HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();  
        http.setRequestMethod("GET"); // 必須是get方式請求  
        http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
        http.setDoOutput(true);  
        http.setDoInput(true);  
        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 連接配接逾時30秒  
        System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 讀取逾時30秒  
        http.connect();  
        InputStream is = http.getInputStream();  
        int size = is.available();  
        byte[] jsonBytes = new byte[size];  
        is.read(jsonBytes);  
        String message = new String(jsonBytes, "UTF-8");  
        JSONObject demoJson = JSONObject.fromObject(message);  
        System.out.println("JSON字元串:"+demoJson);  
        ticket = demoJson.getString("ticket");  
        is.close();  
    } catch (Exception e) {  
            e.printStackTrace();  
    }  
    return ticket;  
}
           

拿到了jsapi_ticket之後就要參數名排序和拼接字元串,并加密了。以下為sha1的加密算法:

public static String SHA1(String decript) {  
    try {
    MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
    digest.update(decript.getBytes());
    byte[] messageDigest = digest.digest();
    // Create Hex String
    StringBuilder hexString = new StringBuilder();
    // 位元組數組轉換為 十六進制 數
    for (byte b : messageDigest) {
        String shaHex = Integer.toHexString(b & 0xFF);
        if (shaHex.length() < 2) {
            hexString.append(0);
        }
        hexString.append(shaHex);
    }
    return hexString.toString();
} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
}
return null;
} 
           

加密算法轉載自:http://www.open-open.com/lib/view/open1392185662160.html

第三步、擷取簽名:

public static void main(String[] args) {  
    //1、擷取AccessToken  
    String accessToken = getAccessToken();  
      
    //2、擷取Ticket  
    String jsapi_ticket = getTicket(accessToken);  
      
    //3、時間戳和随機字元串  
    String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随機字元串  
    String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//時間戳  
      
    System.out.println("accessToken:"+accessToken+"\njsapi_ticket:"+jsapi_ticket+"\n時間戳:"+timestamp+"\n随機字元串:"+noncestr);  
      
    //4、擷取url,前端傳過來目前頁面的URL  
    String url="";  
    /*根據JSSDK上面的規則進行計算,這裡比較簡單,我就手動寫啦 
    String[] ArrTmp = {"jsapi_ticket","timestamp","nonce","url"}; 
    Arrays.sort(ArrTmp); 
    StringBuffer sf = new StringBuffer(); 
    for(int i=0;i<ArrTmp.length;i++){ 
        sf.append(ArrTmp[i]); 
    } 
    */  
      
    //5、将參數排序并拼接字元串  
    String str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;  
     
    //6、将字元串進行sha1加密  
    String signature =SHA1(str);  
    System.out.println("參數:"+str+"\n簽名:"+signature);  
} 
           

第四步、将背景擷取到的  時間戳(10位)、随機字元串、簽名等資訊傳回給前端,在使用時可以擷取權限。  

              再次回到最開始的config配置(VUE),

import wx from 'weixin-js-sdk'
import getWchartCon from '@/http/api'// 連接配接背景接口
// 設定 wx.config
        signInfo(){
            let sign_url;
            let ua = navigator.userAgent.toLowerCase();
            if (/iphone|ipad|ipod|ios/.test(ua)) {
                sign_url = encodeURIComponent(window.location.href.split('#')[0]);
                // eslint-disable-next-line no-console
            }else{
                sign_url = encodeURIComponent(window.location.href);
            }
            // getWchartCon是封裝過的調取背景接口方法
            // import { post } from './axios';
            // export const getWchartCon = params => post('/getWxConfig', params); getWxConfig 背景接口名稱
            getWchartCon({
                // 此處傳到背景的url需要進行URL解碼
                url : sign_url
            }).then(res => {
                wx.config({
                    // 開啟調試模式,調用的所有api的傳回值會在用戶端alert出來,若要檢視傳入的參數,可以在pc端打開,參數資訊會通過log打出,僅在pc端時才會列印。
                    debug: false,
                    // 必填,公衆号的唯一辨別
                    appId: "wx66871d0a78fd725b",
                    // 必填,生成簽名的時間戳
                    timestamp: res.timestamp,
                    // 必填,生成簽名的随機串
                    nonceStr: res.nonceStr,
                    // 必填,簽名
                    signature: res.signature,
                    // 必填,需要使用的JS接口清單,所有JS接口清單
                    jsApiList: ['checkJsApi', 'scanQRCode']
                });
            }).catch (err => {
                return;
            })
        },
        // 掃描
        scanCode(){
            let that = this
            wx.ready(function () {
                wx.checkJsApi({
                    jsApiList: ['scanQRCode'],
                    success: function (res) {
                        wx.scanQRCode({
                            needResult: 1, // 預設為0,掃描結果由微信處理,1則直接傳回掃描結果,
                            scanType: ["qrCode"], // 可以指定掃二維碼還是一維碼,預設二者都有
                            success: function (res) {
                                let result = res.resultStr; // 當needResult 為 1 時,掃碼傳回的結果
                            // 添加掃描完成後的操作
                            }
                        });
                    }
                });
            });
        }, 
           

 以上的時間戳、随機數、簽名一定要跟main方法中擷取到的一緻,否則會報invalid signature錯誤。

 另外,這個簽名的有效時間為7200秒,也就是2個小時,是以當超過兩個小時候,再通路也會報invalid signature錯誤。

 另外還有一個錯誤:invalid url domain

 這個跟生成簽名時用的url有關系,官網的說法是:

 invalid url domain目前頁面所在域名與使用的appid沒有綁定,請确認正确填寫綁定的域名,如果使用了端口号,則配置的綁定   域名也要加上端口号(一個appid可以綁定三個有效域名)

 這個url必須是:“公衆号設定---功能設定----JS接口安全域名”中綁定的三個域名之一

 若是以上的配置沒有問題,且dubug也設定為了true,那麼再通路的時候,就會出現一個config:ok,這就說明配置成功。