h5拉取微信登錄


流程:
① 請求微信接口(攜帶指定參數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('微信登錄請求出錯')
    })
},


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM