java微信公众号扫一扫 java实现微信公众号扫一扫
小小渔夫 人气:0想了解java实现微信公众号扫一扫的相关内容吗,小小渔夫在本文为您仔细讲解java微信公众号扫一扫的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java微信公众号扫一扫,java微信扫一扫,java公众号扫一扫,下面大家一起来学习吧。
步骤
根据微信JS-JDK文档说明,实现扫一扫主要有以下几大步骤:
- 绑定域名
- 引入JS文件
- 通过config接口注入权限验证配置
- 通过ready接口处理成功验证
- 通过error接口处理失败验证
绑定域名
在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" 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 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, // 必填,公众号的唯一标识 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.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("请对准条形码扫码!"); } } }); }; }); //初始化jsapi接口 状态 wx.error(function (res) { alert("调用微信jsapi返回的状态:" + res.errMsg); }); </script> </body> </html>
注:开发中容易出现的有signature验签错误,我们可以透过前后端url一致性来判断。其次就是注意有时候的错误是由于accessToken没有刷新的缘故,需要重新刷新。
加载全部内容