微信公衆號JS-SDK開發

日常開發中,有時候會使用到微信的js,所以我們需要做JS-SDK開發,在這裏記錄一下JS-SDK開發過程

在後臺配置好JS安全域名,此處域名和上面網頁授權的域名一致。

配置完成後,在前端需要使用微信JS的頁面上請求後臺去驗證簽名是否正確,如果正確,後臺返回簽名等信息,然後前端再使用簽名等信息調用wx.config,在wx.config裏面jsApiList[]裏面的就是我們需要用到的微信JS方法。

<!DOCTYPE html>
<html  lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="renderer" content="webkit">
    <title>微信簽到系統</title>
    <!--[if lt IE 9]>
    <meta http-equiv="refresh" content="0;ie.html"/>
    <![endif]-->

    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div id="wrapper">

index.html

</div>

<script>
    $(function () {
        getJsSdk();
        console.log(location.href.split('#')[0]);
    })

    function getJsSdk(){
        $.ajax({
            url : "/wx/getJs-SDK",
            type : 'post',
            dataType : 'json',
            data : {
                //'url' : encodeURIComponent(location.href.split('#')[0])
                'url':location.href.split('#')[0]
            },
            success:function(data){
                wx.config({
                    beta: true,// 必須這麼寫,否則wx.invoke調用形式的jsapi會有問題
                    debug: false, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
                    appId: data.appId, // 必填,企業微信的corpID
                    timestamp: data.timestamp, // 必填,生成簽名的時間戳
                    nonceStr: data.nonceStr, // 必填,生成簽名的隨機串
                    signature: data.signature,// 必填,簽名,見 附錄-JS-SDK使用權限簽名算法
                    jsApiList: ['openDefaultBrowser'] // 必填,需要使用的JS接口列表,凡是要調用的接口都需要傳進來
                });

                wx.ready(function(){
                    wx.invoke('openDefaultBrowser', {
                        'url': 'http://www.baidu.com' // 在默認瀏覽器打開redirect_uri,並附加code參數;也可以直接指定要打開的url,此時不會附帶上code參數。
                    }, function(res){
                        if(res.errMsg == "openDefaultBrowser:ok"){
                            wx.closeWindow();
                            window.close();
                        }
                    });

                });

                wx.error(function(res){
                    console.log(res);
                    // config信息驗證失敗會執行error函數,如簽名過期導致驗證失敗,具體錯誤信息可以打開config的debug模式查看,也可以在返回的res參數中查看,對於SPA可以在這裏更新簽名。
                });
            }
        })
    }

</script>
</body>
</html>
@PostMapping("/getJs-SDK")
    @ResponseBody
    public Map<String,Object> getJSSDKSignature(String url,HttpServletRequest request)throws Exception{
        if(StringUtils.isBlank(url)) {
            throw new Exception("請求路徑不能爲空");
        }
        //url = URLDecoder.decode(url, "UTF-8");
        Date time = new Date();
        //去redis裏面獲取token和Ticket
        String accessTokenUrl = WxConstants.QIYE_ACCESS_TOKEN_URL.replace("ID", WxConstants.CORPID).replace("SECRET", WxConstants.SECRETID);
        String tokenJson = WxUtil.loadJson(accessTokenUrl);
        System.out.println(tokenJson);
        //String access_token =   (String) WxUtil.parseJSON2Map(tokenJson).get("access_token");
        String access_token = "g8LKjbYzkcmxVf2CDNGl-Ty43JORbn6tbLxepEzoV2MNrXwRWvcFWqt44HYH8eFw6koV0N5RkKiOOzQjlARcAA4_-H2TZ8Ws-7tU0vlQPwR_vBzNg47aBuddLYJhV9fnEQl8px4dd5fQaiuJ6GLyxQX_YrzS_12de5MzTYMIMpsLblCRNj6qZs1nBcY8aVuLexiRvvDZed2-7LxPSJc5RQ";
        System.out.println(access_token);
        //ticket
        //String ticket = WxUtil.getJsApiTicket(access_token);
        String ticket = "bxLdikRXVbTPdHSM05e5u74DjS18dxtXsnW1O7AWO91EmVMctXZoI_g5slEuuBDprWzl0btNpgqKbY-GXvp5yA";
        //存入Redis

        Map<String,Object> resultMap = new HashMap<>();
        System.out.println("ticket === "+ticket);
        //隨機字符串
        String nonceStr = UUIDUtil.randomUUID8();
        // 時間戳
        long timestamp = time.getTime();
        String str = "jsapi_ticket=" + ticket;
        str += "&noncestr=" + nonceStr;
        str += "&timestamp=" + timestamp;
        str += "&url=" + url;
        //微信簽名
        String signature = DigestUtils.sha1Hex(str);
        resultMap.put("nonceStr", nonceStr);
        resultMap.put("signature", signature);
        resultMap.put("timestamp", timestamp);
        resultMap.put("appId", WxConstants.CORPID);
        for(String key:resultMap.keySet()){
            System.out.println("key === "+key+"value === "+ resultMap.get(key));
        }
        return resultMap;
    }

如果是企業微信,在配置完成js-sdk域名之後,還需要下載一個文件,然後放在resources文件夾下面

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章