項目描述:pc端+公眾號頁面(移動端)
登陸方式:pc端微信掃碼登陸武翎,公眾號內(nèi)授權(quán)登陸
pc端實現(xiàn)方式:將公眾號開發(fā)功能生成的登陸鏈接(回調(diào)code由后端接收)+前端uuid生成二維碼渊抽,循環(huán)獲取后端掃碼接口(參數(shù)為uuid)欣喧,成功后獲取用戶信息晕城,登陸成功。
移動端實現(xiàn)方式:不支持瀏覽器打開牡拇,只能在微信內(nèi)打開頁面怎囚,點擊使用微信登陸,首先檢測路徑中是否帶參(code)诫惭,有的話證明已回調(diào)成功翁锡,使用code請求接口登陸。沒有的話夕土,重定向微信登陸鏈接(回調(diào)地址為?window.location.href.split('?')[0];)接收code馆衔。
代碼如下:
created() {
// 從 window.location.href 中截取 code 并且賦值
if (window.location.href.indexOf('code') !== -1) { // 此方法僅供參考!T剐濉角溃!
this.code = window.location.href.split('?')[1].split('=')[1].split('&')[0];
}
if (this.code) { // 存在 code 直接調(diào)用接口
this.handGetUserInfo(this.code);
}
},
methods: {
handLogin() {
// 重定向地址重定到當(dāng)前頁面,在路徑獲取 code
const hrefUrl = window.location.href.split('?')[0];
if (this.code === '') {
window.location.href =
`
https://open.weixin.qq.com/connect/oauth2/authorize
?appid=wxdb6e943
&redirect_uri=${encodeURIComponent(hrefUrl)}
&response_type=code
&scope=snsapi_userinfo
`
}
},
// 提交微信登陸code
handGetUserInfo(code) {
this.$http
.post('/Client-User/Code/Login', {
code:code
})
.then((res) => {
if (res.success) {
localStorage.setItem('ClientToken', res.data.token);
this.getUserInfo();
}
})
.catch((err) => {
console.info(err)
})
},
// 獲取用戶信息
getUserInfo() {
this.$http
.get('Client-User/Cur', {})
.then((res) => {
if (res.success) {
localStorage.setItem('userInfo', JSON.stringify(res.data));
this.$store.commit('setUserInfo', res.data);
if (res.data.filledInfo === 1) {
this.$message({
message: '登陸成功篮撑,為您跳轉(zhuǎn)至引導(dǎo)頁',
type: 'success'
});
this.$router.push({ name: 'guide' });
} else if (res.data.filledInfo === 0) {
this.$router.push({ name: 'registered' });
}
}
})
.catch((err) => {
console.info(err)
})
}
附注:公眾號頁面微信登陸本地開發(fā)測試方式减细。
首先在vue.config.js將項目端口號改成80(微信回調(diào)地址只支持80端口),其次在C:\Windows\System32\drivers\etc赢笨,hosts中修改本機域名未蝌,最后在公眾號中將本機域名填到回調(diào)域名白名單中。
最最后茧妒,在微信開發(fā)者工具>公眾號網(wǎng)頁調(diào)試萧吠,使用域名訪問項目即可。