congfeicong

1、H5页面是运行在微信浏览器的

2、需要与公众号关联(即需要openid)

3、判断需求是否需要弹窗告知用户授权操作

4、获取地址栏参数判断是否有\'code\',有的话直接传给后台换取openid,没有就跳转微信提供的获取code的链接

5、获取到的openid做本地存储,判断没有openid进行获取openid操作

6、这边的操作是不需要弹出授权框,且code不能重复使用,所以做了关注二维码弹窗且不能关闭弹窗操作

// 强制关注公众号,获取openid
getCode = function () {
    if (sessionStorage.getItem("openid")&&sessionStorage.getItem("openid")!="undefined") {
        return false;
    }
    var code = getUrlParam(\'code\') // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openId
    var local = window.location.href;
    var APPID = \'xxx\';
    if (code == null || code === \'\') {
        window.location.href = \'https://open.weixin.qq.com/connect/oauth2/authorize?appid=\' + APPID + \'&redirect_uri=\' + encodeURIComponent(local) + \'&response_type=code&scope=snsapi_base&state=#wechat_redirect\'
    } else {
        getOpenId(code) //把code传给后台获取用户信息
    }
}
//把code传给后台,得到openid
getOpenId = function (code) {
    $.ajax({
        type: \'POST\',
        dataType: \'json\',
        url: \'xxx\',
        data: { code: code },
        success: function (res) {
            if (res.status == -1) {
                // 提示没有关注公众号 没有关注公众号跳转到关注公众号页面
                console.log(\'您还未关注公众号喔\');
                //二维码弹窗
                $(\'.openPopup\').click();
                return;
            } else {
                // 本地存储这个openid,并刷新页面
                sessionStorage.setItem("openid", res.data.openid);
                location.reload();
            }
        }
    });
}
//获取地址栏的参数
getUrlParam= function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
}
//页面执行调用
getCode();

 

分类:

技术点:

相关文章: