h5拉取微信登陆

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

一、获取网页受权(官方文档: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`
    },

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

一、提取微信返回的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")

二、将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('微信登陆请求出错')
    })
},
相关文章
相关标签/搜索