微信JSSDK调用微信扫一扫功能的方法
hfhwfw 人气:0如何利用微信JSSDK调用微信扫一扫功能?具体内容如下
1. 确保有 调起微信扫一扫接口 权限,测试号可能不行;
2. 导入相关JS
<script type="text/javascript" http://test.com/zepto_touch.js"></script> <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
3. 页面触发扫码元素
<img src="../../../images/right.jpg" onclick="scanCode()" class="img">
4. 相关JS代码
<script type="text/javascript"> var _appId = "wxz88dbd30e5580e59"; var _data = { appId : _appId, url : location.href, t : Math.random() }; var _getWechatSignUrl = 'http://test.com/getWechatSign.do'; // 获取微信签名 $.ajax({ url : _getWechatSignUrl, data : _data, success : function(o) { console.log(o); if (o.returnCode == "00") { wxConfig(o.detail[0].timestamp, o.detail[0].nonceStr, o.detail[0].signature); } } }); function wxConfig(_timestamp, _nonceStr, _signature) { //alert('获取数据:'+_timestamp+'\n'+_nonceStr+'\n'+_signature); console.log('获取数据:' + _timestamp + '\n' + _nonceStr + '\n' + _signature); wx.config({ debug : true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId : _appId, // 必填,公众号的唯一标识 timestamp : _timestamp, // 必填,生成签名的时间戳 nonceStr : _nonceStr, // 必填,生成签名的随机串 signature : _signature,// 必填,签名,见附录1 jsApiList : [ 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'scanQRCode' ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); } function scanCode() { wx.scanQRCode({ needResult : 1, scanType : [ "qrCode", "barCode" ], success : function(res) { console.log(res) alert(JSON.stringify(res)); var result = res.resultStr; }, fail : function(res) { console.log(res) alert(JSON.stringify(res)); } }); } </script>
5. 获取签名接口getWechatSign.do各值生成方式
timestamp
Long timestamp = System.currentTimeMillis() / 1000;
nonceStr
String nonceStr = RandomStringUtils.randomAlphanumeric(16);
signature
public static String getSign(String jsapi_ticket, String noncestr, Long timestamp, String url) throws NoSuchAlgorithmException { String shaStr = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url; MessageDigest mDigest = MessageDigest.getInstance("SHA1"); byte[] result = mDigest.digest(shaStr.getBytes()); StringBuffer signature = new StringBuffer(); for (int i = 0; i < result.length; i++) { signature.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1)); } return signature.toString(); }
6. 微信参考文档
获取access_token https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183
获取jsapi_ticket https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
加载全部内容