This article has shared the specific code of scanning the WeChat public account for your reference. The specific content is as follows
step
According to the WeChat JS-JDK document description, there are mainly the following steps to implement scanning:
Bind domain name
Fill in the domain name in the JS interface security domain name, be careful not to bring http, as shown in the figure:
Introduce JS files
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
Verify configuration via 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, generate the signature timestamp nonceStr: data.nonceStr, // Required, generate a random string signature signature: data.signature,// Required, signature, see Appendix 1 jsApiList: ["scanQRCode"] // Required, list of JS interfaces to be used, see Appendix 2 for all JS interface lists; } });WeChat jsapi visa 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 ordered 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" + timesstamp + "==signature" + signature); return return; } public String getJsApiTicket() { AugeWechatAccessToken wechatAccessTokenMapper.selectByPrimaryKey(jsApiTicketId); logger.info("getJsApiTicket===" + wechatAccesstoken.getAccessToken()); if (Strings.isNullOrEmpty(wechatAccesstoken.getAccessToken()) || wechatAccesstoken.getExpiresIn() - 100 * 1000 < System.currentTimeMillis()) { //Empty or expired, refresh return refreshJsApiTicket(); } else { return wechatAccesstoken.getAccessToken(); } }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); }Front desk JSP page complete code
<%@ 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%>" rel="external nofollow" > <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" rel="external nofollow" ></head><body><div> <img src="../../../resources/images/borrow/return.png"> <div style="text-align: center; background-color: #f5f5f5; "> <img src="../../../resources/images/borrow/scanReturn.png" 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 identifier of the official account timestamp: data.timestamp, // Required, generate the timestamp of the signature nonceStr: data.nonceStr, // Required, generate the random string of the signature signature signature: data.signature,// Required, see Appendix 1 jsApiList: ["scanQRCode"] // Required, list of JS interfaces to be used}); } }); 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) { //Scan the code and get the result parameter to Input var url = res.resultStr; //The product barcode, take the 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 jsapi interface status wx.error(function (res) { alert("Returned status by calling WeChat jsapi:" + res.errMsg); });</script></body></html>Note: Signature verification errors are prone to occur during development. We can judge through the consistency of the front and back end URLs. Secondly, note that sometimes the error is because the accessToken is not refreshed and needs to be refreshed again.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.