LOADING STUFF...

H5微信授权登录

网络技术4年前 (2020)发布 fdadmin
1,775 0 0

流程:
① 请求微信接口(携带指定参数appid,scope等。及一个回调地址redirect_uri)
② 微信收到请求后会跳转到回调地址redirect_uri,并在该回调地址上携带相关回调参数
③ 提取相关回调参数传给后台即可

1、获取网页授权

(官方文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html)

wxLogin(){     // ① 
    window.location.href=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx666b1e66bbd57c4c&redirect_uri=http%3a%2f%2fm.test.demo.com%2fuser%2fwxLogin&response_type=code&scope=snsapi_userinfo&state=mlogin#wechat_redirect`
    },

2、在以上请求后跳转回的页面:redirect_uri/?code=CODE&state=STATE进行以下操作 // ②

1、提取微信返回的url的code和state   // ③
getQueryString(name){  
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
    let r = window.location.search.substr(1).match(reg);  
    if (r != null) return unescape(r[2]); 
    return null;              
}, 
如·获取code:
let code=this.getQueryString("code")

2、将code传给后端获取相关数据
getWxLogin(){
    let code=this.getQueryString("code")
    this.$axios.post(`${common.userApi}/wxMLogin?code=${code}`).then(res=>{
        if(res.data.code==200){
            this.$toast("登录成功")
        }else if(res.data.code==201){
            this.$toast("请先关注公众号")  //下判断用户有没有关注公众号
        }else if(res.data.code==202){
            this.$toast("请绑定账号或注册新的账号")  //提示用户将账号与微信号绑定起来,若用户之前未注册过我们的账号,则提示其直接注册新的公众号账号
            this.openid=res.data.data   //若后端判断出用户未绑定账号或未注册,则会返回openid给前端。前端拿到openid再加上userid传给后端即可完成绑定。或者前端拿到openid再加上用户名,用户手机号等各种信息传给后端完成注册。(接口使用FormData格式)
        }else if(res.data.code==500){
            this.$toast(res.data.msg)
        }
    }).catch(err=>{
        this.$toast('微信登录请求出错')
    })
},
© 版权声明

相关文章

暂无评论

暂无评论...