vue+h5项目中调取微信扫一扫功能
准备工作:
1.引用微信jweixin-module支持,可使用
npm install jweixin-module --save
2.使用微信扫一扫需登录微信公众号->设置-公众号设置->功能设置下的JS接口安全域名
配置安全域名,例如https://dp-scrm.lanlnk.com要配置成dp-scrm.lanlnk.com,无需添加http
使用:
项目中引入:import wx from ‘jweixin-module’;
import wx from 'jweixin-module';
export default {data(){return{}},mounted(){this.isWechat();}methods:{isWechat() {const ua = window.navigator.userAgent.toLowerCase();if (ua.match(/micromessenger/i) == 'micromessenger') {// return true;console.log('微信浏览器');this.scanQRJssdk();} else {console.log('普通浏览器,请在手机微信浏览器打开此页面');return false;}},// 初始化sdk配置async scanQRJssdk() {// alert(`url链接:${window.location.href}`);const u = navigator.userAgent;const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; // Androidconst isIOS = navigator.platform.indexOf('iPhone') != -1;//ioslet url = '';if (isAndroid) {url = location.href;}if (isIOS) {url = location.href.split('#')[0]; // hash模式下,#后面的部分如果带上ios中config会不对}const api = [];// 'qrCode','barCode'api.push('qrCode');api.push('barCode');const resData = await getWeiXinSdk({ api, url }); // 根据接口返回appId,timestamp等数据console.log('获取微信配置结果', resData);if (resData) {// alert(JSON.stringify(resData));wx.config({// beta: true,debug: false,appId: resData.data.result.appId,timestamp: resData.data.result.timestamp,nonceStr: resData.data.result.nonceStr,signature: resData.data.result.signature,jsApiList: ['checkJsApi', 'scanQRCode']});wx.ready(() => {wx.checkJsApi({jsApiList: ['scanQRCode'],success(res) {console.log('aaaa', res);}});});wx.error((res) => {alert(`出错了:${res.errMsg}`);// 这个地方的好处就是wx.config配置错误,会弹出窗口哪里错误,然 后根据微信文档查询即可。});}},OnQRcode() { // 点击的时候调起扫一扫功能呢const that = this;console.log('1');wx.scanQRCode({needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码,默认二者都有success(res) {const resultStrArr = res.resultStr.split(','); // 转为数组时为了避免扫描一维码是返回CODE_128,20180528前面会添加一个CODE_128所以转为数组获 取最后一条就行了console.log(resultStrArr[resultStrArr.length - 1]); // 输出扫码信息that.result = resultStrArr[resultStrArr.length - 1];},fail(res) {console.log('err', res);}});},}
}
注意:
1.配置的公众号appid一定要与config中的appid一致;
2.配置的安全域名要与当前域名一致,否则会报:errMsg : config:invalid url domain错误
3.vue项目单页面应用使用this.$router.push(path)不会刷新当前路由,推荐hash模式
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
