一、開(kāi)發(fā)準(zhǔn)備
1.申請(qǐng)的微信公眾號(hào)且選擇類(lèi)型為服務(wù)號(hào),因?yàn)橹挥蟹?wù)號(hào)才可以進(jìn)行一下步驟;
2.需要通過(guò)備案的域名,后面在網(wǎng)頁(yè)授權(quán)域名配置中會(huì)用到,當(dāng)然在前端訪問(wèn)域名也是必須的;
二、微信授權(quán)整體邏輯
1.參考微信官方文檔
2.設(shè)計(jì)思路:前端授權(quán)獲取code --->上傳給后臺(tái) ---> 后臺(tái)通過(guò)code 調(diào)用微信后臺(tái)換取access_token和使用scope為snsapi_userinfo的方式 獲取到用戶(hù)openid和基本信息 ---> 返回到前端---> 將openid作為用戶(hù)的唯一標(biāo)識(shí)。
三、具體步驟
1.將公眾號(hào)appid和appSecret交給后臺(tái)開(kāi)發(fā)同學(xué)完成相關(guān)配置,在開(kāi)發(fā)---->基本配置;

image.png
2.在公眾號(hào)頁(yè)面,設(shè)置---> 公眾號(hào)設(shè)置 ---> 功能設(shè)置中,設(shè)置網(wǎng)頁(yè)授權(quán)回調(diào)域名;

image.png
3.前端實(shí)現(xiàn)代碼;
根據(jù)業(yè)務(wù)功能在具體實(shí)現(xiàn)過(guò)程中,首先在router路由守衛(wèi)中判斷 本地是否存儲(chǔ)用戶(hù)openid,如果有進(jìn)入業(yè)務(wù)頁(yè)面,如果沒(méi)有重定向到微信授權(quán)頁(yè)面。
router.beforeEach((to,from,next) => {
let fullPath = to.fullPath
if (to.name === 'Auth') {
next()
return
}
let openId = localStorage.getItem('openId');
if (!openId) {
//保存當(dāng)前路由地址,授權(quán)后還會(huì)跳到此地址
sessionStorage.setItem('wxRedirectUrl', fullPath)
//請(qǐng)求微信授權(quán),并跳轉(zhuǎn)到 /auth 路由
let appId = '公眾號(hào)appid'
let redirectUrl = encodeURIComponent('正式環(huán)境授權(quán)頁(yè)面路徑')
//判斷是否為正式環(huán)境
if (window.location.origin.indexOf('正式環(huán)境域名') !== -1) {
redirectUrl = encodeURIComponent('正式環(huán)境授權(quán)頁(yè)面路徑')
} else {
redirectUrl = encodeURIComponent('測(cè)試環(huán)境授權(quán)頁(yè)面路徑')
}
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize? appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&connect_redirect=1`
} else {
next()
}
})
在頁(yè)面目錄中創(chuàng)建一個(gè)auth.vue授權(quán)空頁(yè)面;
<template>
<div></div>
</template>
<script>
export default {
name: "Auth",
async created() {
// 如果連接中有微信返回的 code,則用此 code 調(diào)用后端接口,向微信服務(wù)器請(qǐng)求用戶(hù)信息
if (this.$route.query.code) {
try {
let redirectUrl = sessionStorage.getItem("wxRedirectUrl");
let res = await this.$api.getWxUserInfo({
wxCode: this.$route.query.code
});
if (res.data.code == 200) {
//將一些信息存儲(chǔ)到本地
const token = res.headers['accesstoken']
localStorage.setItem('token', token)
localStorage.setItem("wxUserInfo", JSON.stringify(res.data.root));
localStorage.setItem("openId", res.data.root.openId);
}
this.$router.replace(redirectUrl);//跳轉(zhuǎn)到業(yè)務(wù)頁(yè)面
} catch (error) {
console.log(error);
}
} else {
// 如果不是從微信重定向過(guò)來(lái)的,沒(méi)有帶著微信的 code,則直接進(jìn)入首頁(yè)
this.$router.replace("/");
}
}
};
</script>
<style lang="scss" scoped>
</style>
不同的業(yè)務(wù)實(shí)現(xiàn)的方式可能不同,可根據(jù)自己具體業(yè)務(wù)邏輯加以調(diào)整。