uniapp 实现微信H5扫码功能 |
您所在的位置:网站首页 › 太阳码怎么扫 › uniapp 实现微信H5扫码功能 |
最近用uniapp开发h5 实现扫码功能 前端界面如图 步骤一:引入sdk 这里有两种引入方式: 1.按照文档的方法,下载js文件,直接引入到项目里 2.通过npm安装 npm install weixin-js-sdk --save // 按需引入 import wx from 'weixin-js-sdk';步骤二:配置微信config信息 // 最好是在onLoad中调用 onLoad: function () { this.getCofig(); }, methods: { // 配置信息 getCofig() { const that = this; let url = ''; let ua = navigator.userAgent.toLowerCase(); url = window.location.href.split('#')[0]; //获取到的url是当前页面的域名 // GetWeixinScan 后端提供配置信息 uni.request({ url: '/api/goods/wx/wx_jsapi_ticket', // 此处找后端要接口 微信不能使用端口访问端口改为 wx method: 'GET', data: { url: url // 当前页面的域名 }, success: (response) => { const res = response.data; console.log(res, 'resres') if (res) { that.wxConfig( res.appId, res.timestamp, res.nonceStr, res.signature ); } else { alert('获取配置信息返回为空'); } } , fail: error => { console.log(error, '请求获取微信配置失败 请求方法:http://xx.haileer.top:8901/wx_jsapi_ticket'); } }); }, //wx.config的配置 wxConfig(appId, timestamp, nonceStr, signature) { wx.config({ debug: false, // 开启调试模式, appId: appId, // 必填,企业号的唯一标识 timestamp: timestamp, // 必填,生成签名的时间戳 nonceStr: nonceStr, // 必填,生成签名的随机串 signature: signature, // 必填,签名 jsApiList: ['scanQRCode', 'checkJsApi'], // 必填,需要使用的JS接口列表 }); wx.ready(() => { console.log('配置完成,扫码前准备完成') }) wx.error(function (res) { alert('出错了:' + res.errMsg); //wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。 }); }, }步骤三:触发事件实现扫码功能 // 点击扫码 区分普通扫码和H5扫码 scan() { const that = this // #ifndef H5 uni.scanCode({ success: function (res) { console.log("进来了1") console.log('条码res:' + res); console.log('条码类型:' + res.scanType); console.log('条码内容:' + res.result); }, fail: error => { console.log("暂不支持1") } }); // #endif // #ifdef H5 // this.log("暂不支持H5扫码 走onScan这个方法") this.onScan() // #endif }, // h5扫描二维码并解析 onScan() { const that = this; wx.scanQRCode({ needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果, scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码,默认二者都有 success: function (res) { var result = res.resultStr; // 当 needResult 为 1 时,扫码返回的结果 var resultArr = result.split(','); // 扫描结果以逗号分割数组 var codeContent = resultArr[resultArr.length - 1]; // 获取数组最后一个元素,也就是最终的内容 }, fail: function (response) { console.log("调用扫码失败") that.$toast(response); alert(' wx.scanQRCode失败') }, }); },注意事项 在调用后端接口获取config信息的时候 1.后端提供的接口 端口号使用wx代替 2.传给后端的url参数,记得一定是网页域名 const url = location.href.split(‘#’)[0] 3.可以提醒后端把jsapi_ticket的值也返回,便于在自行使用工具校验签名算法的时候输入 4.可以提醒后端把timestamp把后三位数去掉,因为签名校验中的timestamp最多只能输入10位 |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |