您好,登錄后才能下訂單哦!
本文實例為大家分享了微信公眾號掃一掃的具體代碼,供大家參考,具體內容如下
步驟
根據微信JS-JDK文檔說明,實現掃一掃主要有以下幾大步驟:
綁定域名
在JS接口安全域名填入域名,注意不帶http,如圖:
引入JS文件
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
通過config接口注入權限驗證配置
$.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, // 必填,公眾號的唯一標識 timestamp: data.timestamp, // 必填,生成簽名的時間戳 nonceStr: data.nonceStr, // 必填,生成簽名的隨機串 signature: data.signature,// 必填,簽名,見附錄1 jsApiList: ["scanQRCode"] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2 }); } });
微信jsapi驗簽
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(); //注意這里參數名必須全部小寫,且必須有序 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; }
public String getJsApiTicket() { AugeWechatAccessToken wechatAccesstoken = augeWechatAccessTokenMapper.selectByPrimaryKey(jsApiTicketId); logger.info("getJsApiTicket===" + wechatAccesstoken.getAccessToken()); if (Strings.isNullOrEmpty(wechatAccesstoken.getAccessToken()) || wechatAccesstoken.getExpiresIn() - 100 * 1000 < System.currentTimeMillis()) { //空或者過期,刷新 return refreshJsApiTicket(); } else { return wechatAccesstoken.getAccessToken(); } }
Controller層代碼
@RequestMapping(value = "/jsapisign", method = {RequestMethod.GET, RequestMethod.POST}, produces = MEDIATYPE_CHARSET_JSON_UTF8) @ResponseBody public String jsApiSign(String url) { //添加微信js簽名信息 Map<String, String> signMap = wechatService.jsApiSign(url); return JSON.toJSONString(signMap); }
前臺JSP頁面完整代碼
<%@ 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>掃碼還書</title> <link rel="stylesheet" /> <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 class="wrap" > <img src="../../../resources/images/borrow/return.png" alt="" > <div > <img src="../../../resources/images/borrow/scanReturn.png" alt="" 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, // 必填,公眾號的唯一標識 timestamp: data.timestamp, // 必填,生成簽名的時間戳 nonceStr: data.nonceStr, // 必填,生成簽名的隨機串 signature: data.signature,// 必填,簽名,見附錄1 jsApiList: ["scanQRCode"] // 必填,需要使用的JS接口列表 }); } }); wx.ready(function () { // 9.1.2 掃描二維碼并返回結果 document.querySelector('#scanQRCode1').onclick = function () { wx.scanQRCode({ needResult: 1, desc: 'scanQRCode desc', success: function (res) { //掃碼后獲取結果參數賦值給Input var url = res.resultStr; //商品條形碼,取","后面的 if (url.indexOf(",") >= 0) { var tempArray = url.split(','); var barCode = tempArray[1]; window.location. + barCode + "&response_type=code&scope=snsapi_base&state=BINDFACE#wechat_redirect"; } else { alert("請對準條形碼掃碼!"); } } }); }; }); //初始化jsapi接口 狀態 wx.error(function (res) { alert("調用微信jsapi返回的狀態:" + res.errMsg); }); </script> </body> </html>
注:開發中容易出現的有signature驗簽錯誤,我們可以透過前后端url一致性來判斷。其次就是注意有時候的錯誤是由于accessToken沒有刷新的緣故,需要重新刷新。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。