• JavaScript-Tool:wechatHelper.js


    ylbtech-JavaScript-Tool:wechatHelper.js
    1.返回顶部
    1、wechatHelper.js
    !function(a,b){"function"==typeof define&&(define.amd||define.cmd)?define(function(){return b(a)}):b(a,!0)}(this,function(a,b)
    
    {function c(b,c,d){a.WeixinJSBridge?WeixinJSBridge.invoke(b,e(c),function(a){h(b,a,d)}):k(b,d)}function d(b,c,d){a.WeixinJSBridge?
    
    WeixinJSBridge.on(b,function(a){d&&d.trigger&&d.trigger(a),h(b,a,c)}):d?k(b,d):k(b,c)}function e(a){return a=a||
    
    {},a.appId=D.appId,a.verifyAppId=D.appId,a.verifySignType="sha1",a.verifyTimestamp=D.timestamp
    
    +"",a.verifyNonceStr=D.nonceStr,a.verifySignature=D.signature,a}function f(a){return{timeStamp:a.timestamp
    
    +"",nonceStr:a.nonceStr,"package":a["package"],paySign:a.paySign,signType:a.signType||"SHA1"}}function g(a){return 
    
    a.postalCode=a.addressPostalCode,delete a.addressPostalCode,a.provinceName=a.proviceFirstStageName,delete 
    
    a.proviceFirstStageName,a.cityName=a.addressCitySecondStageName,delete 
    
    a.addressCitySecondStageName,a.countryName=a.addressCountiesThirdStageName,delete 
    
    a.addressCountiesThirdStageName,a.detailInfo=a.addressDetailInfo,delete a.addressDetailInfo,a}function h(a,b,c)
    
    {"openEnterpriseChat"==a&&(b.errCode=b.err_code),delete b.err_code,delete b.err_desc,delete b.err_detail;var d=b.errMsg;d||
    
    (d=b.err_msg,delete b.err_msg,d=i(a,d),b.errMsg=d),c=c||{},c._complete&&(c._complete(b),delete c._complete),d=b.errMsg||"",D.debug&&!
    
    c.isInnerInvoke&&alert(JSON.stringify(b));var e=d.indexOf(":"),f=d.substring(e+1);switch(f){case"ok":c.success&&c.success
    
    (b);break;case"cancel":c.cancel&&c.cancel(b);break;default:c.fail&&c.fail(b)}c.complete&&c.complete(b)}function i(a,b){var c=a,d=q
    
    [c];d&&(c=d);var e="ok";if(b){var f=b.indexOf(":");e=b.substring(f+1),"confirm"==e&&(e="ok"),"failed"==e&&(e="fail"),-1!=e.indexOf
    
    ("failed_")&&(e=e.substring(7)),-1!=e.indexOf("fail_")&&(e=e.substring(5)),e=e.replace(/_/g," "),e=e.toLowerCase(),("access 
    
    denied"==e||"no permission to execute"==e)&&(e="permission denied"),"config"==c&&"function not exist"==e&&(e="ok"),""==e&&(e="fail")}
    
    return b=c+":"+e}function j(a){if(a){for(var b=0,c=a.length;c>b;++b){var d=a[b],e=p[d];e&&(a[b]=e)}return a}}function k(a,b){if(!(!
    
    D.debug||b&&b.isInnerInvoke)){var c=q[a];c&&(a=c),b&&b._complete&&delete b._complete,console.log('"'+a+'",',b||"")}}function l(a){if
    
    (!(v||w||D.debug||"6.0.2">A||C.systemType<0)){var b=new Image;C.appId=D.appId,C.initTime=B.initEndTime-
    
    B.initStartTime,C.preVerifyTime=B.preVerifyEndTime-B.preVerifyStartTime,I.getNetworkType({isInnerInvoke:!0,success:function(a)
    
    {C.networkType=a.networkType;var c="https://open.weixin.qq.com/sdk/report?v="+C.version+"&o="+C.isPreVerifyOk+"&s="+C.systemType
    
    +"&c="+C.clientVersion+"&a="+C.appId+"&n="+C.networkType+"&i="+C.initTime+"&p="+C.preVerifyTime+"&u="+C.url;b.src=c}})}}function m()
    
    {return(new Date).getTime()}function n(b){x&&(a.WeixinJSBridge?b():r.addEventListener&&r.addEventListener("WeixinJSBridgeReady",b,!
    
    1))}function o(){I.invoke||(I.invoke=function(b,c,d){a.WeixinJSBridge&&WeixinJSBridge.invoke(b,e(c),d)},I.on=function(b,c)
    
    {a.WeixinJSBridge&&WeixinJSBridge.on(b,c)})}if(!a.jWeixin){var p=
    
    {config:"preVerifyJSAPI",onMenuShareTimeline:"menu:share:timeline",onMenuShareAppMessage:"menu:share:appmessage",onMenuShareQQ:"menu:s
    
    hare:qq",onMenuShareWeibo:"menu:share:weiboApp",onMenuShareQZone:"menu:share:QZone",previewImage:"imagePreview",getLocation:"geoLocati
    
    on",openProductSpecificView:"openProductViewWithPid",addCard:"batchAddCard",openCard:"batchViewCard",chooseWXPay:"getBrandWCPayRequest
    
    ",openEnterpriseRedPacket:"getRecevieBizHongBaoRequest",startSearchBeacons:"startMonitoringBeacons",stopSearchBeacons:"stopMonitoringB
    
    eacons",onSearchBeacons:"onBeaconsInRange",consumeAndShareCard:"consumedShareCard",openAddress:"editAddress"},q=function(){var a=
    
    {};for(var b in p)a[p[b]]=b;return a}(),r=a.document,s=r.title,t=navigator.userAgent.toLowerCase(),u=navigator.platform.toLowerCase
    
    (),v=!(!u.match("mac")&&!u.match("win")),w=-1!=t.indexOf("wxdebugger"),x=-1!=t.indexOf("micromessenger"),y=-1!=t.indexOf
    
    ("android"),z=-1!=t.indexOf("iphone")||-1!=t.indexOf("ipad"),A=function(){var a=t.match(/micromessenger/(d+.d+.d+)/)||t.match
    
    (/micromessenger/(d+.d+)/);return a?a[1]:""}(),B={initStartTime:m(),initEndTime:0,preVerifyStartTime:0,preVerifyEndTime:0},C=
    
    {version:1,appId:"",initTime:0,preVerifyTime:0,networkType:"",isPreVerifyOk:1,systemType:z?1:y?2:-
    
    1,clientVersion:A,url:encodeURIComponent(location.href)},D={},E={_completes:[]},F={state:0,data:{}};n(function(){B.initEndTime=m
    
    ()});var G=!1,H=[],I={config:function(a){D=a,k("config",a);var b=D.check===!1?!1:!0;n(function(){if(b)c(p.config,{verifyJsApiList:j
    
    (D.jsApiList)},function(){E._complete=function(a){B.preVerifyEndTime=m(),F.state=1,F.data=a},E.success=function(a)
    
    {C.isPreVerifyOk=0},E.fail=function(a){E._fail?E._fail(a):F.state=-1};var a=E._completes;return a.push(function(){l
    
    ()}),E.complete=function(b){for(var c=0,d=a.length;d>c;++c)a[c]();E._completes=[]},E}()),B.preVerifyStartTime=m();else{F.state=1;for
    
    (var a=E._completes,d=0,e=a.length;e>d;++d)a[d]();E._completes=[]}}),D.beta&&o()},ready:function(a){0!=F.state?a():(E._completes.push
    
    (a),!x&&D.debug&&a())},error:function(a){"6.0.2">A||(-1==F.state?a(F.data):E._fail=a)},checkJsApi:function(a){var b=function(a){var 
    
    b=a.checkResult;for(var c in b){var d=q[c];d&&(b[d]=b[c],delete b[c])}return a};c("checkJsApi",{jsApiList:j(a.jsApiList)},function()
    
    {return a._complete=function(a){if(y){var c=a.checkResult;c&&(a.checkResult=JSON.parse(c))}a=b(a)},a}
    
    ())},onMenuShareTimeline:function(a){d(p.onMenuShareTimeline,{complete:function(){c("shareTimeline",{title:a.title||s,desc:a.title||
    
    s,img_url:a.imgUrl||"",link:a.link||location.href,type:a.type||"link",data_url:a.dataUrl||""},a)}},a)},onMenuShareAppMessage:function
    
    (a){d(p.onMenuShareAppMessage,{complete:function(){c("sendAppMessage",{title:a.title||s,desc:a.desc||"",link:a.link||
    
    location.href,img_url:a.imgUrl||"",type:a.type||"link",data_url:a.dataUrl||""},a)}},a)},onMenuShareQQ:function(a){d(p.onMenuShareQQ,
    
    {complete:function(){c("shareQQ",{title:a.title||s,desc:a.desc||"",img_url:a.imgUrl||"",link:a.link||
    
    location.href},a)}},a)},onMenuShareWeibo:function(a){d(p.onMenuShareWeibo,{complete:function(){c("shareWeiboApp",{title:a.title||
    
    s,desc:a.desc||"",img_url:a.imgUrl||"",link:a.link||location.href},a)}},a)},onMenuShareQZone:function(a){d(p.onMenuShareQZone,
    
    {complete:function(){c("shareQZone",{title:a.title||s,desc:a.desc||"",img_url:a.imgUrl||"",link:a.link||
    
    location.href},a)}},a)},startRecord:function(a){c("startRecord",{},a)},stopRecord:function(a){c("stopRecord",
    
    {},a)},onVoiceRecordEnd:function(a){d("onVoiceRecordEnd",a)},playVoice:function(a){c("playVoice",
    
    {localId:a.localId},a)},pauseVoice:function(a){c("pauseVoice",{localId:a.localId},a)},stopVoice:function(a){c("stopVoice",
    
    {localId:a.localId},a)},onVoicePlayEnd:function(a){d("onVoicePlayEnd",a)},uploadVoice:function(a){c("uploadVoice",
    
    {localId:a.localId,isShowProgressTips:0==a.isShowProgressTips?0:1},a)},downloadVoice:function(a){c("downloadVoice",
    
    {serverId:a.serverId,isShowProgressTips:0==a.isShowProgressTips?0:1},a)},translateVoice:function(a){c("translateVoice",
    
    {localId:a.localId,isShowProgressTips:0==a.isShowProgressTips?0:1},a)},chooseImage:function(a){c("chooseImage",{scene:"1|
    
    2",count:a.count||9,sizeType:a.sizeType||["original","compressed"],sourceType:a.sourceType||["album","camera"]},function(){return 
    
    a._complete=function(a){if(y){var b=a.localIds;b&&(a.localIds=JSON.parse(b))}},a}())},getLocation:function(a){},previewImage:function
    
    (a){c(p.previewImage,{current:a.current,urls:a.urls},a)},uploadImage:function(a){c("uploadImage",
    
    {localId:a.localId,isShowProgressTips:0==a.isShowProgressTips?0:1},a)},downloadImage:function(a){c("downloadImage",
    
    {serverId:a.serverId,isShowProgressTips:0==a.isShowProgressTips?0:1},a)},getLocalImgData:function(a){G===!1?(G=!0,c
    
    ("getLocalImgData",{localId:a.localId},function(){return a._complete=function(a){if(G=!1,H.length>0){var b=H.shift
    
    ();wx.getLocalImgData(b)}},a}())):H.push(a)},getNetworkType:function(a){var b=function(a){var 
    
    b=a.errMsg;a.errMsg="getNetworkType:ok";var c=a.subtype;if(delete a.subtype,c)a.networkType=c;else{var d=b.indexOf(":"),e=b.substring
    
    (d+1);switch(e){case"wifi":case"edge":case"wwan":a.networkType=e;break;default:a.errMsg="getNetworkType:fail"}}return a};c
    
    ("getNetworkType",{},function(){return a._complete=function(a){a=b(a)},a}())},openLocation:function(a){c("openLocation",
    
    {latitude:a.latitude,longitude:a.longitude,name:a.name||"",address:a.address||"",scale:a.scale||
    
    28,infoUrl:a.infoUrl||""},a)},getLocation:function(a){a=a||{},c(p.getLocation,{type:a.type||"wgs84"},function(){return 
    
    a._complete=function(a){delete a.type},a}())},hideOptionMenu:function(a){c("hideOptionMenu",{},a)},showOptionMenu:function(a){c
    
    ("showOptionMenu",{},a)},closeWindow:function(a){a=a||{},c("closeWindow",{},a)},hideMenuItems:function(a){c("hideMenuItems",
    
    {menuList:a.menuList},a)},showMenuItems:function(a){c("showMenuItems",{menuList:a.menuList},a)},hideAllNonBaseMenuItem:function(a){c
    
    ("hideAllNonBaseMenuItem",{},a)},showAllNonBaseMenuItem:function(a){c("showAllNonBaseMenuItem",{},a)},scanQRCode:function(a){a=a||
    
    {},c("scanQRCode",{needResult:a.needResult||0,scanType:a.scanType||["qrCode","barCode"]},function(){return a._complete=function(a){if
    
    (z){var b=a.resultStr;if(b){var c=JSON.parse(b);a.resultStr=c&&c.scan_code&&c.scan_code.scan_result}}},a}())},openAddress:function(a)
    
    {c(p.openAddress,{},function(){return a._complete=function(a){a=g(a)},a}())},openProductSpecificView:function(a){c
    
    (p.openProductSpecificView,{pid:a.productId,view_type:a.viewType||0,ext_info:a.extInfo},a)},addCard:function(a){for(var 
    
    b=a.cardList,d=[],e=0,f=b.length;f>e;++e){var g=b[e],h={card_id:g.cardId,card_ext:g.cardExt};d.push(h)}c(p.addCard,
    
    {card_list:d},function(){return a._complete=function(a){var b=a.card_list;if(b){b=JSON.parse(b);for(var c=0,d=b.length;d>c;++c){var 
    
    e=b[c];e.cardId=e.card_id,e.cardExt=e.card_ext,e.isSuccess=e.is_succ?!0:!1,delete e.card_id,delete e.card_ext,delete e.is_succ}
    
    a.cardList=b,delete a.card_list}},a}())},chooseCard:function(a){c("chooseCard",
    
    {app_id:D.appId,location_id:a.shopId||"",sign_type:a.signType||"SHA1",card_id:a.cardId||"",card_type:a.cardType||"",card_sign:a.cardSi
    
    gn,time_stamp:a.timestamp+"",nonce_str:a.nonceStr},function(){return a._complete=function(a){a.cardList=a.choose_card_info,delete 
    
    a.choose_card_info},a}())},openCard:function(a){for(var b=a.cardList,d=[],e=0,f=b.length;f>e;++e){var g=b[e],h=
    
    {card_id:g.cardId,code:g.code};d.push(h)}c(p.openCard,{card_list:d},a)},consumeAndShareCard:function(a){c(p.consumeAndShareCard,
    
    {consumedCardId:a.cardId,consumedCode:a.code},a)},chooseWXPay:function(a){c(p.chooseWXPay,f(a),a)},openEnterpriseRedPacket:function
    
    (a){c(p.openEnterpriseRedPacket,f(a),a)},startSearchBeacons:function(a){c(p.startSearchBeacons,
    
    {ticket:a.ticket},a)},stopSearchBeacons:function(a){c(p.stopSearchBeacons,{},a)},onSearchBeacons:function(a){d
    
    (p.onSearchBeacons,a)},openEnterpriseChat:function(a){c("openEnterpriseChat",{useridlist:a.userIds,chatname:a.groupName},a)}},J=1,K=
    
    {};return r.addEventListener("error",function(a){if(!y){var b=a.target,c=b.tagName,d=b.src;if
    
    ("IMG"==c||"VIDEO"==c||"AUDIO"==c||"SOURCE"==c){var e=-1!=d.indexOf("wxlocalresource://");if(e){a.preventDefault(),a.stopPropagation
    
    ();var f=b["wx-id"];if(f||(f=J++,b["wx-id"]=f),K[f])return;K[f]=!0,wx.ready(function(){wx.getLocalImgData({localId:d,success:function
    
    (a){b.src=a.localData}})})}}}},!0),r.addEventListener("load",function(a){if(!y){var b=a.target,c=b.tagName;b.src;if
    
    ("IMG"==c||"VIDEO"==c||"AUDIO"==c||"SOURCE"==c){var d=b["wx-id"];d&&(K[d]=!1)}}},!0),b&&(a.wx=a.jWeixin=I),I}});
    
    ;(function () {
        function noop() {
        }
    
        function removeUrlParameter(url, parameter) {
            //prefer to use l.search if you have a location/link object
            var urlparts = url.split('?');
            if (urlparts.length >= 2) {
    
                var prefix = encodeURIComponent(parameter) + '=';
                var pars = urlparts[1].split(/[&;]/g);
    
                //reverse iteration as may be destructive
                for (var i = pars.length; i-- > 0;) {
                    //idiom for string.startsWith
                    if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                        pars.splice(i, 1);
                    }
                }
    
                url = urlparts[0] + '?' + pars.join('&');
                return url;
            } else {
                return url;
            }
        }
    
        function isWeiXin() {
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == "micromessenger") {
                return true;
            } else {
                return false;
            }
        }
    
        function getPagePureUrl() {
            return location.origin + location.pathname + location.search;
        }
    
        function getQueryString(name) {
            name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
            var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
            return results == null ? "" : decodeURIComponent(results[1].replace(/+/g, " "));
        }
    
        function wechatHelper(options) {
            options = $.extend({}, wechatHelper.defaultOptions, options);
            this.options = options;
            this.wxCache = {
                readyFns: [],
                readyNeedWxFns: [],
                userid: null,
                code: null
            };
        }
    
        function getHashValue(hash, name) {
            name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
            var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
                results = regex.exec(hash);
            return results == null ? "" : decodeURIComponent(results[1].replace(/+/g, " "));
        }
    
        $.extend(wechatHelper.prototype, {
            isWeiXin: isWeiXin,
            removeUrlParameter: removeUrlParameter,
            getPagePureUrl: getPagePureUrl,
            getQueryString: getQueryString,
            getType: function () {
                return 0;
            },
            getOauth2Url: function (originalUrl) {
                if (!originalUrl) {
                    originalUrl = this.getPagePureUrl();
                }
                var state = this.options.getState() || '0';
                state = state + '_' + Math.floor(Math.random() * 100000000);
                var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + this.options.appId + '&redirect_uri=' + 
    
    encodeURIComponent(originalUrl) + '&response_type=code&scope=snsapi_base&state=' + state + '#wechat_redirect';
                return url;
            },
            /**
             * 页面加载完成回调
             * @param {function} fn
             * @param {int} status 执行级别
             * @returns {void}
             * @remark status:
             * 0:页面加载完成就执行
             * 1或不传:微信jssdk初始化完成执行
             */
            onPageReady: function (fn, status) {
                status = status || 1;
                if (!status || status == 0) {
                    if ('$' in window) {
                        $(document).ready(function () {
                            fn && fn();
                        });
                    } else {
                        fn && fn();
                    }
                }
                else if (fn) {
                    if (status == 1) {
                        if ('wx' in window) {
                            wx.ready(function () {
                                fn && fn();
                            });
                        }
                        else {
                            this.wxCache.readyNeedWxFns.push(fn);
                        }
                    }
                }
            },
            /**
             * 预览图片
             * @param {string[]} urlArray url列表
             * @param {string=null} currentUrl 当前url
             */
            wxPreviewImage: function (urlArray, currentUrl) {
                wx && wx.previewImage({
                    current: currentUrl || '',
                    urls: urlArray
                });
            },
            /**
             * 拍摄图片
             * @param {function} callback 选取图片后的回调函数
             */
            wxCaptureImage: function (callback, isUpload, opts) {
                var self = this;
                wx && wx.chooseImage({
                    count: 1,
                    sizeType: ['compressed'],
                    sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有
                    success: function (images) {
                        setTimeout(function () {
                            var serverId;
                            wx.uploadImage({
                                localId: images.localIds[0],
                                success: function (res) {
                                    serverId = res.serverId;
                                    if ("undefined" === typeof isUpload) {
                                        var params = {
                                            mediaIds: serverId,
                                            accesstoken: $.cookie("token")
                                        };
                                        if (opts) {
                                            if (opts.TargetEntityType) {
                                                params.TargetEntityType = opts.TargetEntityType;
                                            }
                                            if (opts.GroupID) {
                                                params.GroupID = opts.GroupID;
                                            }
                                            if (opts.ProjectID) {
                                                params.ProjectID = opts.ProjectID;
                                            }
                                        }
                                        $.post('http://www.dtglzj.com/WxFileUploader.ashx', params, function (d) {
                                            if (!d.Data.IsError) {
                                                d.Data[0].DownloadUrl = images.localIds[0];
                                                callback && callback(d);
                                            } else {
                                                mui.toast(d.Msg)
                                            }
    
                                        });
                                    } else {
                                        callback && callback({
                                            IsError: false,
                                            Msg: "",
                                            mediaId: serverId,
                                            image: images.localIds[0]
                                        });
                                    }
                                },
                                fail: function (res) {
                                    if (offset >= total) {
                                        callback({IsError: true, Msg: '上传失败'});
                                    }
                                }
                            });
                        }, 100);
                    }
                });
            },
            /**
             * 选取图片
             * @param {function} callback 选取图片后的回调函数
             * @param {number=9} count 选择图片数量,默认9
             */
            wxChooseImage: function (source, callback, count, opts) {
                var self = this;
                wx && wx.chooseImage({
                    count: count || 9,
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
                    sourceType: source || ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
                    success: function (images) {
                        var offset = 0, total = images.localIds.length;
                        var serverIdArray = [];
    
                        function exchangeFileIds() {
                            if (!serverIdArray.length) {
                                callback && callback([]);
                                return;
                            }
    
                            var params = {
                                mediaIds: serverIdArray.join(","),
                                accesstoken: $.cookie("token")
                            };
                            if (opts) {
                                if (opts.TargetEntityType) {
                                    params.TargetEntityType = opts.TargetEntityType;
                                }
                                if (opts.GroupID) {
                                    params.GroupID = opts.GroupID;
                                }
                                if (opts.ProjectID) {
                                    params.ProjectID = opts.ProjectID;
                                }
                            }
                            mui.alert(JSON.stringify(params));
                            $.post('http://www.dtglzj.com/WxFileUploader.ashx', params, function (data) {
                                mui.alert("WxFileUploader==" + JSON.stringify(data));
                            }).always(function (d) {
                                //var result = [];
                                if (d.IsError) {
                                    mui.toast(d.Msg);
                                    callback(d);
                                    return;
                                }
                                else {
                                    mui.alert("upload==" + JSON.stringify(d));
                                    $(d.Data).each(function (i, med) {
                                        med.DownloadUrl = images.localIds[i];
                                    });
                                    callback(d);
                                }
                            }, function () {
                                callback([]);
                            });
                        }
    
                        function doUpload() {
                            wx.uploadImage({
                                localId: images.localIds[offset],
                                success: function (res) {
                                    mui.alert("success==" + JSON.stringify(res));
                                    offset++;
                                    serverIdArray.push(res.serverId);
                                    if (offset < total) {
                                        doUpload();
                                    } else {
                                        exchangeFileIds();
                                    }
                                },
                                fail: function (res) {
                                    mui.alert("fail==" + JSON.stringify(res));
                                    if (offset >= total) {
                                        exchangeFileIds();
                                    }
                                }
                            });
                        }
    
                        doUpload();
                    }
                });
            },
            /**
             * 获取地理位置
             * @param {function} callback 获取地理位置后的回调函数
             */
            /**
             * 获取地理位置
             * @param {function} callback 获取地理位置后的回调函数
             */
            wxGetPosition: function (callback) {
                var that = this;
                wx && wx.getLocation({
                    type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
                    success: function (res) {
                        if ('res' in res) {
                            res = res.res;
                        }
                        var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
                        var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
                        var speed = res.speed; // 速度,以米/每秒计
                        var accuracy = res.accuracy; // 位置精度
    
                        var keyPool = that.options.txMaKeys.slice(0, that.options.txMaKeys.length);
                        var tryTimes = -1;
    
                        function retryFunc() {
                            tryTimes++;
                            if (tryTimes > 5 || keyPool.length == 0) {
                                callback && callback(latitude, longitude);
                                return;
                            }
                            var key = keyPool[Math.random() * keyPool.length >> 0];
                            var index = keyPool.indexOf(key);
                            keyPool.splice(index, 1);
                            $.ajax({
                                type: 'GET',
                                url: 'http://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude + '&key=' + key + 
    
    '&output=jsonp',
                                dataType: 'jsonp',
                                jsonp: 'callback',
                                success: function (d) {
                                    if (d) {
                                        if (d.status == 0) {
                                            callback && callback(latitude, longitude, d.result.formatted_addresses.recommend);
                                        }
                                        else {
                                            retryFunc();
                                            //callback && callback(latitude, longitude);
                                        }
                                    }
                                    else {
                                        retryFunc();
                                        //callback && callback(latitude, longitude);
                                    }
                                },
                                error: function () {
                                    retryFunc();
                                    //callback && callback(latitude, longitude);
                                }
                            });
                        }
    
                        retryFunc();
                    }
                });
            },
            wxEnvInit: function (cb) {
                if (!('wx' in window)) {
                    return;
                }
                var state = this.getQueryString('state');
                // if (!state) {
                //     window.location.href = this.getOauth2Url();
                //     return;
                // }
                var code = this.getQueryString('code');
                var redirect = this.getQueryString('redirect');
                this.wxCache.state = state;
                this.wxCache.code = code;
                this.wxCache.redirect = redirect;
    
                var self = this;
    
                utils.getRequest('wxapi/gpc', {
                    url: self.getPagePureUrl(),
                    code: code,
                    token: self.options.getToken()
                }, function (resp) {
                    if (resp.IsError) {
                        var originalUrl = self.getPagePureUrl();
                        originalUrl = self.removeUrlParameter(originalUrl, 'code');
                        originalUrl = self.removeUrlParameter(originalUrl, 'state');
                        location.href = self.getOauth2Url(originalUrl);
                        return;
                    } else {
                        cb && cb(resp);
                        self.wxCache.name = resp.Data.name;
                        self.wxCache.sid = resp.Data.sid;
                        self.wxCache.isSubscrib = resp.Data.isSubscrib;
                        wx.error(function (res) {
                        });
                        wx.ready(function () {
                            if (window.onWxInitialized) {
                                window.onWxInitialized();
                            }
                            for (var i in self.wxCache.readyNeedWxFns) {
                                var fn = self.wxCache.readyNeedWxFns[i];
                                fn.call(this);
                            }
                            if (self.wxCache.redirect) {
                                //window.location.hash = '#' + self.wxCache.redirect;
                            }
                        });
                        wx.config({
                            debug: self.options.debugEnabled,
                            appId: self.options.appId,
                            timestamp: resp.Data.timestamp,
                            nonceStr: resp.Data.nonce,
                            signature: resp.Data.signature,
                            jsApiList: [
                                'checkJsApi',
                                'chooseWXPay',
                                'previewImage',
                                "onMenuShareTimeline",
                                "onMenuShareAppMessage",
                                "onMenuShareQQ",
                                "onMenuShareWeibo",
                                "onMenuShareQZone",
                                'hideOptionMenu',
                                'getLocation',
                                'openLocation',
                                'chooseImage',
                                'uploadImage',
                                'closeWindow',
                                'scanQRCode'
                            ]
                        });
                    }
                }, true, function (d) {
                    if (utils.isNull($.cookie("token"))) {
                        //location.href = "/index.html";
                    } else {
                        var originalUrl = self.getPagePureUrl();
                        originalUrl = self.removeUrlParameter(originalUrl, 'code');
                        originalUrl = self.removeUrlParameter(originalUrl, 'state');
                        location.href = self.getOauth2Url(originalUrl);
                    }
                });
            },
            closeWindow: function () {
                wx && wx.closeWindow();
            },
            checkJsApi: function (apis, callBack) {
                wx && wx.checkJsApi({
                    jsApiList: apis, // 需要检测的JS接口列表,所有JS接口列表见附录2,
                    success: function (res) {
                        // 以键值对的形式返回,可用的api值true,不可用为false
                        // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                        if (callBack) {
                            callBack(res);
                        }
                    }
                });
            },
            scanQRCode: function (cb) {
                wx && wx.scanQRCode({
                    needResult: 1,
                    scanType: ["qrCode", "barCode"],
                    success: function (res) {
                        var result = res.resultStr;
                        cb && cb(result);
                    }
                });
            }
        });
    
        wechatHelper.defaultOptions = {
            appId: 'wx1077xxxxxxxxx7',
            debugEnabled: false,
            getState: noop,
            getToken: noop,
            jsApiList: [],
            txMaKeys: [
                'xxxxx-6BY2U-BX4VD-B4X6M-6KKJZ-WPFBK',
                'xxxxx-MMZ6J-ST7FF-FGZNU-FHRL3-Z3BWB',
                'xxxxx-TZXLI-PF3GZ-5V7H7-MVYT2-GTFUN',
                'xxxxx-LXDEI-QK3GL-5TQXH-4WPTE-KGFM4',
                'xxxxx-ZVX6J-35RFS-KZ26F-VDVRF-JWFB4'
            ]
        };
    
        window.createWechatHelper = function (options) {
            return new wechatHelper(options);
        }
    
    })();
    2、
    2.返回顶部
     
    3.返回顶部
     
    4.返回顶部
     
    5.返回顶部
     
     
    6.返回顶部
     
    warn 作者:ylbtech
    出处:http://ylbtech.cnblogs.com/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    ImageView的功能和使用
    时钟AnalogClock和DigitalClock
    开发自定义View
    二十二、android中application标签说明
    二十一、Android上常见度量单位【xdpi、hdpi、mdpi、ldpi】解读
    二十、Android -- SDcard文件读取和保存
    十九、android中判断sim卡状态和读取联系人资料的方法
    十八、Android引导界面
    十七、Android学习笔记_Android 使用 搜索框
    十六、Android 滑动效果汇总
  • 原文地址:https://www.cnblogs.com/storebook/p/9007947.html
Copyright © 2020-2023  润新知