在公司开发微信红包过程中用过一些函数

// 阻止在非微信打开
var isWeixin=function(ua) {
    ua = ua || navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
    } else {
        return false;
    }
}

;(function(){
    if(isWeixin()) return;
    window.location.replace("/61redbag/open_error.html");
})();



if (typeof(rbFn) == "undefined") var rbFn = {};

rbFn={
    errorUrl:"/622redbag/getError.html",
    shareImg:"https://wxtest.zhimajinrong.com/622redbag/images/shareIcon.jpg",
    getQuery: function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null && decodeURIComponent(r[2])!=="" ) return decodeURIComponent(r[2]);
        return null;
    },
    toQueryString: function(o) {
        if (typeof(o) !== "object") return;
        var c = [];
        c.add = function(a, b) {
            this.push(encodeURIComponent(a) + "=" + encodeURIComponent(b))
        };
        for (var x in o) {
            c.add(x, o[x]);
        }
        return c.join("&");
    },
    submitGetForm: function(btn, data, async) {
        var data = data || $(this).serialize();
        $.ajax({
            beforeSend: function() {
                (btn !== null) && rbFn.setBtn(btn, false);
            },
            url: "/zm_bonus/unlimitedGetBonus",
            data: data,
            type: "post",
            dataType: "json",
            async: async !== !1,
            success: function(r) {
                if(r){
                    var url="/622redbag/shareBonus.html?"+rbFn.toQueryString(r);
                    window.location.replace(url);
                }else{
                    alert("未知错误请重试!")
                    (btn !== null) && rbFn.setBtn(btn, true);
                }
            },
            error: function() {
                alert("网络错误请重试!");
                (btn !== null) && rbFn.setBtn(btn, true);
            }
        });
    },
    submitForm: function(btn, data, async) {
        // code 
        // -1 手机号码不能为空
        // -2 请输入正确的手机号码
        // -3 该手机号码已被绑定,请选择别的手机号码
        // -4 红包组唯一标识不存在
        // -5 红包组已过期
        // -6 红包组里的红包已抢完
        // -7 您已经抢过一次了,不能再抢了
        // -8 出现内部错误了
        // 0 成功
        var data = data || $(this).serialize();
        // alert(data);
        $.ajax({
            beforeSend: function() {
                (btn !== null) && rbFn.setBtn(btn, false);
            },
            url: "/zm_bonus/hongbao/grabBonus",
            data: data,
            type: "post",
            dataType: "json",
            async: async !== !1,
            success: function(r) {
                var code = r.code,
                    msg = r.msg,
                    _code = String(Math.abs(code) - 1),
                    tips = {};
                    
                Array.prototype.push.call(tips, "请填写手机号", "请填写正确的手机号码", "该手机号码已被绑定,请选择别的手机号码");

                if (_code in tips) {
                    (btn !== null) ? (dealFn(tips[_code]), rbFn.setBtn(btn, true)) : void 0;
                } else {
                    //成功 0 getBonus.html
                    //已过期 -5 tocreatBonus.html
                    //已抢光 -6 getBonusOver.html
                    //已抢过 -7 getBonusGeted.html
                    //-4 红包组唯一标识不存在 // 内部错误 -8 rbFn.errorUrl
                    var config = {
                        "0": "getBonus",
                        "-5": "tocreatBonus",
                        "-6": "getBonusOver",
                        "-7": "getBonusGeted"
                    },
                    $code=String(code);
                    /*
                    if(isNaN(code)||code==-4||code==-8){
                        // 出错
                        window.location.replace(rbFn.errorUrl);
                    }else */

                    if($code in config){
                        var _url = "/622redbag/"+config[$code]+".html";
                            _url += window.location.search + "&userPhone=" + msg.userPhone + "&bonusMoney=" + msg.bonusMoney;
                            // "&expireTime=" + msg.expireTime;
                        window.location.replace(_url);
                    }else{
                        window.location.replace(rbFn.errorUrl);
                    }
                }
            },
            error: function() {
                alert("网络错误请重试");
                (btn !== null) && rbFn.setBtn(btn, true);
            }
        });
    },
    shareFn:function(returnObj,callback,data){
        var _data=$.extend({},{"url":window.location.href.split("#")[0]},data);
        // alert(JSON.stringify(_data));
        $.ajax({
            url:"/zm_bonus/getConfigInfo",
            type:"post",
            dataType:"json",
            async:false,
            data:_data,
            success:function(r){
                wx.config({
                    //debug: true,  //开启调试模式
                    appId: r.msg.appId, // 必填,公众号的唯一标识
                    timestamp: r.msg.timestamp, // 必填,生成签名的时间戳
                    nonceStr: r.msg.nonceStr, // 必填,生成签名的随机串
                    signature: r.msg.signature,// 必填,签名,见附录1
                    // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
                    jsApiList: [
                        'checkJsApi',
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage',
                        'onMenuShareQQ',
                        'onMenuShareWeibo',
                        'getNetworkType',
                        'previewImage',
                        'hideOptionMenu',
                        'showOptionMenu'
                    ]
                });

                wx.ready(function(){
                    wx.showOptionMenu();
                    /*var obj={
                        title:"全民降暑,芝麻金融送你千万高温补贴。",
                        desc: "戳!"+ (r.msg.nickname?"帮"+r.msg.nickname:"")+"抢高温补贴红包。快来一起降温!",
                        link: r.msg.oauthUrl+"?bonusGroupId="+rbFn.getQuery("bonusGroupId"),
                        imgUrl:"https://app.zhimajinrong.com/61redbag/images/share_icon.jpg",
                        success:function(){},
                        cancel:function(){},
                        fail:function(){alert("分享失败请重试!");}
                    };*/

                    var obj=returnObj.call(null,r);
                    
                    wx.onMenuShareAppMessage(obj);
                    wx.onMenuShareTimeline(obj);
                    wx.onMenuShareWeibo(obj);
                    wx.onMenuShareQQ(obj);
                    wx.showMenuItems({
                        menuList: [
                            "menuItem:share:appMessage",
                            "menuItem:share:timeline",
                            "menuItem:share:qq",
                            "menuItem:share:weiboApp",
                            "menuItem:share:QZone"
                        ]
                    });

                    callback.call(null);
                });

                wx.error(function(res){
                    //var obj= (typeof(res)==="object") ? JSON.stringify(res) : res.toString();
                    alert("系统错误,请重试!");
                });
            },
            error:function(){
                alert("网络错误请重试");
            }
        });
            
    },
    toshareFn:function(link,callback,data){
        rbFn.shareFn(function(r){
            var _link= (typeof(link)==="function") ? link.call(null,r) : link,
                nickname=r.msg.nickname;
            return {
                title:"财神踏云来 我用红包表达爱",
                desc: ((typeof(nickname)!=="undefined")&&(nickname!=="")) ? nickname+"化身最萌财神,百元红包送友人" : "芝麻财神驾到,百元红包任性发",
                link: _link,
                imgUrl:rbFn.shareImg,
                success:function(){},
                cancel:function(){},
                fail:function(){alert("分享失败请重试!");}
            }
        },function(){
            callback&&callback.call(null);
        },data);
    },
    setBtn: function(btn, f , ff) {
        var t=ff?"修改":"抢红包",tt=ff?"提交中...":"疯抢中...";
        f ? btn.val(t).prop("disabled", !1) : btn.val(tt).prop("disabled", !0);
    },
    getPage: function() {
        return (document.getElementById("get-page") && document.getElementById("get-page").value.replace(/.+-/igm, "")) || null;
    },
    mask: function() {
        var mask = $(".rb_cover");
        return {
            open: function() {
                mask.show();
            },
            close: function(f,t) {
                var time=t||200;
                if(f){
                    rbFn.imgLoad(function(){
                        window.setTimeout(function(){
                            mask.hide();
                        }, time);
                    });
                }else{
                    window.setTimeout(function(){
                        mask.hide();
                    }, time);
                }
            }
        }
    },
    imgLoad:function(fn){
        var imgs=document.querySelectorAll("img"),l=imgs.length;
        for(var i=0;i<l;i++){
            var img=new Image();
            img.src=imgs[i].src;
            img.onload=function(){
                if(!--l){
                    fn.call(null);
                }
            }
        }
    },
    imgLoadFn:function(Img,callback){
        var img=new Image();
        img.src=$(Img)[0].src;
        img.onload=function(){
            callback.call(null);
        }
    },
    debug:function(r){
        var debug=$('<div class="debug"></div>');
            debug.append(r);
            $("body").append(debug);
    },
    setPos:function(opts){
        var def={
            "wrap":".pos-wrap",
            "posImg":".pos-img",
            "ele":".pos-ele",
            "callback":"",
            "pos":[]
        },
        obj=$.extend({},def,opts);

        var wrap=$(obj.wrap),
            posImg=wrap.find(obj.posImg),
            ele=wrap.find(obj.ele),
            img=new Image(),
            rePos=function(){
                var w=img.width,
                    h=img.height,
                    _w=wrap.width(),
                    _h=wrap.height(),
                    iw=_w/w,
                    ih=_h/h;

                ele.each(function(i,v){
                    var v=$(v),
                        pos=obj.pos[i];
                    v.css({
                        "width":pos[0]*iw,
                        "height":pos[1]*ih,
                        "left":pos[2]*iw,
                        "top":pos[3]*ih           
                    });
                });
            }

        img.src=posImg.attr("src");

        img.onload=function(){
            rePos();
            if(typeof(obj.callback)==="function") obj.callback.call(null);
        }

        $(window).on("resize",rePos);
    },
    creatBonus:function(){
        var userPhone=rbFn.getQuery("userPhone"),
            link="/zm_bonus/unlimitedGetBonusGotoOauth?redBagType=2"+(userPhone?"&"+window.location.search.substr(1):"");
        window.location.replace(link);
        // alert(link);
    }
}
//测试平台功能
var checkPlat={
    isAndroid: function (ua) {
        ua = ua || navigator.userAgent;
        return ua.toLowerCase().indexOf('android') > -1;
    },

    isIOS: function (platform) {
      if (navigator && navigator.platform) {
        platform = platform || navigator.platform;
        // return /iP(?:hone|od|ad)/.test(platform);
        return /iP(?:hone|od|ad)/.test(navigator.userAgent);
      } else {
        return false;
      }
    },

    isWeixin: function (ua) {
        ua = ua || navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            return true;
        } else {
            return false;
        }
    }
}

 

转载于:https://www.cnblogs.com/anson0415/p/4606915.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值