发布于 3年前

VUE history路由模式下的微信扫一扫

// 扫一扫事件
   scannerFun: async function() { // 这是一个封装的axios(post)的异步请求接口
      if (!this.isWeixinBrowser()) {
        this.showToast(1500, "请在微信内使用");
      } else {
        let result = await this.http.post("***/***/***", { // 后台接口
          url: location.href // 当前页面的路由,需要在公共号里配置白名单。
        });
        if (result) { // 等有结果以后才配置信息,否则配置失败
          wx.config({
            debug: false,
            appId: result.appid,
            timestamp: result.timestamp,
            nonceStr: result.nonceStr,
            signature: result.signature,
            jsApiList: ["scanQRCode"]
          });
          this.readyFun();
        }
      }
    },
    readyFun: function() {
      let that = this; // 要用到vue的路由,但是在wx的方法里this指的是wx对象。所以这里就将vue的对象保存在一个that的变量上;
      wx.ready(function() {
        wx.scanQRCode({
          needResult: 1,
          success: function(res) {
            //扫码后获取结果参数赋值给Input
            let url = res.resultStr;
            let queryUrlPar = function(thisUrl) {
              let reg = /([^?=&]+)=([^?=&]+)/g;
              let obj = {};
              thisUrl.replace(reg, function() {
                obj[arguments[1]] = arguments[2];
              });
              return obj;
            };
            if (queryUrlPar(url).money) {
              this.thisInMoney = queryUrlPar(url).money;
            } else {
              // 如果金额没有设定,则在转账页面可以输入;
              this.thisInMoney = false;
            }
            if (queryUrlPar(url).name && queryUrlPar(url).mobile) { // 这是这个二维码必传的参数,如果没有则说明二维码不是我们要扫的二维码,则有相应的提示信息
              this.inName = queryUrlPar(url).name;
              this.inMobile = queryUrlPar(url).mobile;
              that.$router.push({
                name: "inputAmount",
                params: {
                  fromType: "scanQRCode",
                  money: this.thisInMoney,
                  inName: this.inName,
                  inMobile: this.inMobile,
                  type: "false",
                  orderId: "false"
                }
              });
            } else { // 错误提示信息
              that.showToast(1500, "请扫描本应用收款二维码");
            }
          }
        });
      });
    },
    // 判断是否微信内置环境
    isWeixinBrowser: function() {
      let ua = navigator.userAgent.toLowerCase();
      return /micromessenger/.test(ua) ? true : false;
    }

注意不同路由模式下,路由的截取方式不一样。
1、白名单设置的是:
http://www.************/mp

2、当前的路径是:
http://www.************/mp/index.html#/my(hash模式)
http://www.************/mp/my (history模式)
url处理方法:
url: location.href.split('#')[0] (hash模式)
location.href (history模式)
处理后的路径是:(一下路径都可以注意和白名单对比)
http://www.***********.com/mp/index.html
http://www.************/mp/my

注意的是:
1、这个传过去的参数URL必须是当前页面的URL,如果是hash模式下的路由URL后面的#号部分要去掉。如果是history模式下的路由直接location.href获取就可以了。
2、这个参数URL路径,和微信公共号上配置的JS接口安全域名(白名单)的不同和必须一致的地方。

扫一扫错误文档,仔细阅读:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

Vue
©2020 edoou.com   京ICP备16001874号-3