java实现微信公众号扫一扫

时间:2021-05-02

本文实例为大家分享了微信公众号扫一扫的具体代码,供大家参考,具体内容如下

步骤

根据微信js-jdk文档说明,实现扫一扫主要有以下几大步骤:

  • 绑定域名
  • 引入js文件
  • 通过config接口注入权限验证配置
  • 通过ready接口处理成功验证
  • 通过error接口处理失败验证

绑定域名

在js接口安全域名填入域名,注意不带http,如图:

引入js文件

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

通过config接口注入权限验证配置

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 $.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验签

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 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; } ? 1 2 3 4 5 6 7 8 9 10 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层代码

? 1 2 3 4 5 6 7 8 @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页面完整代码

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 <%@ 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没有刷新的缘故,需要重新刷新。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/PreachChen/p/8659184.html

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章