vue 微信扫一扫(多个站点项目统一使用一个扫码页面)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_36710522/article/details/100037624

微信内扫码功能很多人都会在项目中用到,使用扫码微信公众号的配置也比较严格,需要你的网页有签名,而签名生成需要有一个微信公众号的appkey和APPsecret,然而要有这两项得注册个微信公众号,并且公众号还需要认证。微信白名单的限制总不能每次开发一次项目有用到微信码就要配置一遍微信公众号,写一遍扫码功能吧?
终极解决方案:
写一个扫码功能的页面放在服务器,所有的项目都往这个扫码页面跳转,然后带着扫码结果返回到扫码之前项目去处理。这样就实现了多项目轻松调用微信扫码功能。
好了,吐槽完了,直接上扫码功能代码(开箱即用):

<template>
    <div class="content">
        <van-loading size="40px" type="spinner">加载中...</van-loading>
    </div>
</template>

<script>
import wx from "weixin-js-sdk";
import axios from "axios";
export default {
  data() {
    return {
      redirect_uri:''
    };
  },
  created() {
      this.scan_enter();
      this.redirect_uri = this.$route.query.redirect_uri; //获取从某个项目中跳转过来的域名或者Ip
  },
  methods: {
    //  微信扫码
    scan_enter() {
      axios.get("你的请求微信配置参数接口地址").then(res => {
        wx.config({
          debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
          //以下参数后端接口返回
          appId: res.data.data.appId, // 必填,公众号的唯一标识
          timestamp: res.data.data.timestamp,  // 必填,生成签名的时间戳
          nonceStr: res.data.data.nonceStr, // 必填,生成签名的随机串
          signature: res.data.data.signature, // 必填,签名
          jsApiList: ["checkJsApi", "scanQRCode"] // 必填,需要使用的JS接口列表,所有JS接口列表
        });
      });

      wx.error(function(res) {
        alert("出错了:" + res.errMsg); //这个地方的好处就是wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。
      });
      var _this = this;
      wx.ready(function() {
        wx.checkJsApi({
          jsApiList: ["scanQRCode"],
          success: function(res) {}
        });
        wx.scanQRCode({
          needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果
          scanType: ["qrCode"], // 可以指定扫二维码还是一维码,默认二者都有
          success: function(res) {
            var result = res.resultStr;
            console.log(result, "扫描结果");
            window.location.href = _this.redirect_uri +'?'+ 'result=' +result; //前面跳转过来的地址,拿到扫码结果再跳转回去
          }
        });
      });
    },
  },
  mounted() {
  }
};
</script>

<style lang='scss' scoped>
    .content{
        width:100%;
        height:100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }
</style>

猜你喜欢

转载自blog.csdn.net/qq_36710522/article/details/100037624