微信H5授权登录

2,290 阅读1分钟

一、公众号配置域名

回调跳转地址须和公众号配置域名一致,拿到公众号对应appId

二、判断本地是否有存储有openId

localStorage.setItem('openId_xxx','xxxxxxxxxxxxxx')
localStorage.getItem('openId_xxx')
注意:保存openId可根据项目名加上前缀或后缀(比如openId_xxx 避免同一设备登录时openId登录失败)

三、无openId则授权获取code

getCode() {
    let url = window.location.host // 动态抓取域名,避免跟换域名时修改代码
    var str = encodeURIComponent(`https://${url}/hbrp_plat/#/login`);
    goWeChat("wx2766450941903eb4", str); //四个参数appid-公众号id,redirect_uri-回调链接,scope-授权模式,state-重定向将会带上的state参数
}
goWeChat(appid,redirect_uri) {
    let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect
     window.location.href = url
}

四、回调页面截取code值并发送后台换取openId

// 根据code获取微信用户openid
getOpenid() {
    this.urlCode = this.getUrlCode('code')
    if(this.urlCode){
        this.$api.wechatUserInfo({code: this.urlCode}).then(res=>{
            localStorage.openId_xxxx = res.body.openId
        })
    }
}
getUrlCode(name) {
    return (
        decodeURIComponent(
        (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
            location.href
        ) || [, ""])[1].replace(/\+/g, "%20")
        ) || null
    )
}

五、存储openId,进行其他业务处理

localStorage.setItem('openId_xxx','xxxxxxxxxxxxxx')
localStorage.getItem('openId_xxx')
注意:保存openId可根据项目名加上前缀或后缀(比如openId_xxx 避免同一设备登录时openId登录失败