uniapp实现使用JSSDK调用微信扫一扫

668 阅读1分钟

业务场景

最近使用uniapp开发H5网页,需要调用微信的扫一扫功能,可是uniapp官网不支持扫码功能

1724308838378.jpg

但是官网也给了解决办法,就是使用微信的JSSDK

1724309091209.jpg

步骤一

首先要把js文件引入到项目中,在main.js中引入

Snipaste_2024-08-22_14-51-03.png

代码如下

var script = document.createElement('script');
script.src = "https://res.wx.qq.com/open/js/jweixin-1.6.0.js";
document.body.appendChild(script);

步骤二 配置config信息

onLoad(optioon) {
  this.getCofig();
},
methods: {
  //判断是ios系统还是安卓系统的路由地址
  getSignUrl() {
   var signLink = ''
   var ua = navigator.userAgent.toLowerCase();
   if (/iphone|ipad|ipod/.test(ua)) {
    signLink = uni.getStorageSync('WxCodeUrl');
    if (!signLink) signLink = location.href
   } else {
    signLink = location.href
   }
   return signLink;
  },
  // 配置信息
  getCofig() {
   const that = this;
   WXgetSignDate({
    url: this.getSignUrl()
   }).then(res => {
    that.wxConfig(
     res.data.appid,
     res.data.timestamp,
     res.data.nonceStr,
     res.data.signature
    );
   }).catch(err => {
    alert(err, '配置信息失败')
   })
  },
  //wx.config的配置
  wxConfig(appId, timestamp, nonceStr, signature) {
   wx.config({
    debug: false,
    appId: appId,
    timestamp: timestamp,
    nonceStr: nonceStr,
    signature: signature,
    jsApiList: ['scanQRCode', 'checkJsApi'],
   });
   wx.ready(() => {
    // alert(' config成功')
   })
   wx.error(function(res) {
    alert( res.errMsg);
   });
  },
}

步骤三 出发事件扫面二维码

  QRcodeBtn() {
   const _that = this;
   wx.scanQRCode({
    needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果
    scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
    success: function(res) {
     // 返回的扫描结果
     var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
     window.location.href = result
    },
    fail: function(res) {
     // 扫描失败后的回调
     _that.res = JSON.stringify(res)
     alert('扫描失败', res)
    }
   });
  },

注意,安卓系统扫码和ios系统不一样,ios可能会报签名失效的问题,请看这篇文章