Scan the WeChat public account

step

According to the WeChat JS-JDK documentation, there are the following major steps to implement a scan:

  1. Bind domain name
  2. Import JS files
  3. Inject permission verification configuration through the config interface
  4. Handle successful verification through the ready interface
  5. Handling failed validation through the error interface

Bind domain name

Fill in the domain name in the JS interface security domain name, pay attention to not include http, as shown in the figure:

Import JS files

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

Inject permission verification configuration through the config interface

$.ajax({
    url: "${pageContext.request.contextPath}/wechat/jsapisign",
    type: "post",
    data: {
        url: location.href.split('#')[0]
    },
    contentType: 'application/x-www-form-urlencoded;charset=utf-8',
    async: true,
    success: function (data) {
        wx.config({
            debug: false,
            appId: data.appid, // Required, the unique ID of the official account
            timestamp: data.timestamp, // required, the timestamp of the generated signature
            nonceStr: data.nonceStr, // Required, generate a random string for signature
            signature: data.signature,// Required, signature, see Appendix 1
            jsApiList: ["scanQRCode"] // Required, a list of JS interfaces to be used, see Appendix 2 for a list of all JS interfaces
        });
    }
});

WeChat jsapi verification

public Map<String, String> jsApiSign(String url) {
    Map<String, String> ret = new HashMap<String, String>(16);
    String nonce_str = CheckUtil.create_nonce_str();
    String timestamp = CheckUtil.create_timestamp();
    String string1;
    String signature = "";

    String jsapi_ticket = wechatAccessTokenService.getJsApiTicket();
    //Note that the parameter names here must be all lowercase and must be in order
    string1 = "jsapi_ticket=" + jsapi_ticket +
            "&noncestr=" + nonce_str +
            "×tamp=" + timestamp +
            "&url=" + url;
    logger.info("jsApiSign===" + string1);

    try {
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(string1.getBytes("UTF-8"));
        signature = CheckUtil.byteToHex(crypt.digest());
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        e.printStackTrace ();
    }

    ret.put("appid", appid);
    ret.put("url", url);
    ret.put("jsapi_ticket", jsapi_ticket);
    ret.put("nonceStr", nonce_str);
    ret.put("timestamp", timestamp);
    ret.put("signature", signature);
    logger.info("jsApiSign===url=" + url + "==jsapi_ticket" + jsapi_ticket +
    "==nonce_str" + nonce_str + "==timestamp" + timestamp + "==signature" + signature);
    return ret;
}

Controller layer code

@RequestMapping(value = "/jsapisign", method = {RequestMethod.GET, RequestMethod.POST},
produces = MEDIATYPE_CHARSET_JSON_UTF8)
@ResponseBody
public String jsApiSign(String url) {
    //Add WeChat js signature information
    Map<String, String> signMap = wechatService.jsApiSign(url);

    return JSON.toJSONString(signMap);
}

The complete code of the front JSP page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="zh-CN">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=320.1,initial-scale=1,minimum-scale=1,maximum-scale=1,
user-scalable=no">
<head>
    <base href="<%=basePath%>">
    <title>Scan the code to return the book</title>
    <link rel="stylesheet" href="http://203.195.235.76/jssdk/css/style.css"/>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
    <link rel="stylesheet" type="text/css" href="../../../resources/css/bookdetail.css">

</head>

<body>
<div class="wrap" style="width: 100% ;height: 100%">
    <img src="../../../resources/images/borrow/return.png" alt="" style="width: 100% ;height: 75%">
    <div style="text-align: center; background-color: #f5f5f5; ">
        <img src="../../../resources/images/borrow/scanReturn.png" alt="" style="width: 40% ;height: 25%;" id="scanQRCode1">
    </div>

</div>

<script type="text/javascript">
    $.ajax({
        url: "${pageContext.request.contextPath}/wechat/jsapisign",
        type: "post",
        data: {
            url: location.href.split('#')[0]
        },
        contentType: 'application/x-www-form-urlencoded;charset=utf-8',
        async: true,
        success: function (data) {
            wx.config({
                debug: false,
                appId: data.appid, // Required, the unique ID of the official account
                timestamp: data.timestamp, // required, the timestamp of the generated signature
                nonceStr: data.nonceStr, // Required, generate a random string for signature
                signature: data.signature,// Required, signature, see Appendix 1
                jsApiList: ["scanQRCode"] // Required, a list of JS interfaces to be used, see Appendix 2 for a list of all JS interfaces
            });
        }
    });
    wx.ready(function () {
        // 9.1.2 Scan the QR code and return the result
        document.querySelector('#scanQRCode1').onclick = function () {
            wx.scanQRCode({
                needResult: 1,
                desc: 'scanQRCode desc',
                success: function (res) {
                    //After scanning the code, get the result parameter and assign it to Input
                    var url = res.resultStr;
                    //Commodity barcode, take "," behind
                    if (url.indexOf(",") >= 0) {
                        var tempArray = url.split (',');
                        var barCode = tempArray[1];
                        window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?
                        appid=wx96668744efc2b2de&redirect_uri=http://cx.ngrok.xiaomiqiu.cn/wechat/
                        toReturnDetail?barCode=" + barCode + "&response_type=code&scope=snsapi_base
                        &state=BINDFACE#wechat_redirect";

                    } else {
                        alert("Please scan the barcode!");
                    }
                }
            });
        };
    });
    //Initialize the jsapi interface state
    wx.error(function (res) {
        alert("The status returned by calling WeChat jsapi:" + res.errMsg);
    });

</script>
</body>
</html>

Note: Signature verification errors are prone to occur during development. We can judge by the consistency of the front and back urls. The second is to note that sometimes the error is because the accessToken is not refreshed and needs to be refreshed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325321222&siteId=291194637