美文网首页
微信扫一扫功能实现

微信扫一扫功能实现

作者: 飞鹰_007 | 来源:发表于2020-09-04 10:34 被阅读0次

1.引入微信js-sdk:   npm install --save-dev weixin-js-sdk

2.引入axios:    npm install --save axios

3.组件中使用:

<div @click="scan" ></div>

 created() {

    this.getSign();    //获取签名

  },

  methods: {

    getSign(){

            let params = {

                url: location.href.split('#')[0], // 鉴权url

                h5Source: 'wx' //自己额外的参数

            };

            let config = {

                headers: {

                    'Content-Type': 'application/json; charset=UTF-8'

                }

            };

            axios.post('/baidu-service/weixin/signature',params,config).then((res) => {

                let data = res.data.obj; //这里根据返回值来使用

                wx.config({

                    debug: false, // 开启调试模式

                    appId: data.appId, // 必填,公众号的唯一标识

                    timestamp: data.timestamp, // 必填,生成签名的时间戳

                    nonceStr: data.nonceStr, // 必填,生成签名的随机串

                    signature: data.signature, // 必填,签名,见附录1

                    jsApiList: ['checkJsApi','scanQRCode']

                })

            }).catch((error) => {

                console.log('签名错误',error)

            });

       },

        scan(){

            let that = this;

            wx.ready(function () {

                 wx.scanQRCode({ // 微信扫一扫接口

                    needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,

                    scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码,默认二者都有

                    success: function (res) {

                        let getCode = res.resultStr; // 当needResult 为 1 时,扫码返回的结果

                        that.$router.push({  //跳转到扫描详情界面

                            path: '/detail',

                            query: {

                                id: getCode

                            }

                        });

                    },

                    fail: function (res) {

                        that.showToast('抱歉,当前客户端版本不支持扫一扫');

                    }

                })   

            })

        }

  }

相关文章

网友评论

      本文标题:微信扫一扫功能实现

      本文链接:https://www.haomeiwen.com/subject/brqzsktx.html