JS 微信接口:扫描二维码

注意:引用微信JS

 <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

        //二维码扫描
        var isReady = false;
        var canUseScanApi = false;
        var latitude =0, longitude = 0;
        function InitPage() {
            var v = encodeURI(window.location.href);
            $.ajax({
                url: "../ajax/GetJSSignature.ashx",
                type: 'Get',
                dataType: 'json',
                data: { "url": v, "id": '<%= afid %>' },
                    success: function (data) {
                        data = listToObj(data);

                        wx.config({
                            debug: false,
                            appId: data.appId,
                            timestamp: data.timeStamp,
                            nonceStr: data.nonceStr,
                            signature: data.signature,
                            jsApiList: ['scanQRCode', 'getLocation']
                        });
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
        }

        function checkQrCode() {
            console.log("扫码,我进来了!");
            if (!isReady) {
                alert("向微信注册失败了.");

            } else if (!canUseScanApi) {
                alert("获取微信api能力失败");
            } else {
                doScanQRCode();
            }

        }

        function doScanQRCode() {
            wx.scanQRCode({
                needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
                scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
                success: function (res) {
                    var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果

                    window.location.href = result;
                }
            })
        }

        function listToObj(arr) {
            var obj = {};
            if (arr && arr.length > 0) {
                for (var i = 0; i < arr.length; i++) {
                    obj[arr[i].Key] = arr[i].Value;
                }
            }
            return obj;
        }

        wx.ready(function () {
            isReady = true;
            wx.checkJsApi({
                jsApiList: ['scanQRCode'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
                success: function (res) {
                    // 以键值对的形式返回,可用的api值true,不可用为false
                    // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                    canUseScanApi = res.checkResult.scanQRCode;
                }
            });
        });


        wx.error(function () {
            isReady = false;
            alert("向微信注册失败了");
        });

        InitPage();

 

posted @ 2021-07-26 11:36  哈哈咖咖  阅读(339)  评论(0)    收藏  举报