h5拉取微信登录

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('微信登录请求出错')
    })
},

猜你喜欢

转载自www.cnblogs.com/huihuihero/p/12118062.html