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