一弧械、開發(fā)準(zhǔn)備
1.申請的微信公眾號且選擇類型為服務(wù)號八酒,因為只有服務(wù)號才可以進(jìn)行一下步驟;
2.需要通過備案的域名刃唐,后面在網(wǎng)頁授權(quán)域名配置中會用到羞迷,當(dāng)然在前端訪問域名也是必須的;
二画饥、微信授權(quán)整體邏輯
1.參考微信官方文檔
2.設(shè)計思路:前端授權(quán)獲取code --->上傳給后臺 ---> 后臺通過code 調(diào)用微信后臺換取access_token和使用scope為snsapi_userinfo的方式 獲取到用戶openid和基本信息 ---> 返回到前端---> 將openid作為用戶的唯一標(biāo)識衔瓮。
三、具體步驟
1.將公眾號appid和appSecret交給后臺開發(fā)同學(xué)完成相關(guān)配置抖甘,在開發(fā)---->基本配置热鞍;
2.在公眾號頁面,設(shè)置---> 公眾號設(shè)置 ---> 功能設(shè)置中,設(shè)置網(wǎng)頁授權(quán)回調(diào)域名薇宠;
3.前端實現(xiàn)代碼偷办;
根據(jù)業(yè)務(wù)功能在具體實現(xiàn)過程中,首先在router路由守衛(wèi)中判斷 本地是否存儲用戶openid澄港,如果有進(jìn)入業(yè)務(wù)頁面椒涯,如果沒有重定向到微信授權(quán)頁面。
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)后還會跳到此地址
sessionStorage.setItem('wxRedirectUrl', fullPath)
//請求微信授權(quán),并跳轉(zhuǎn)到 /auth 路由
let appId = '公眾號appid'
let redirectUrl = encodeURIComponent('正式環(huán)境授權(quán)頁面路徑')
//判斷是否為正式環(huán)境
if (window.location.origin.indexOf('正式環(huán)境域名') !== -1) {
redirectUrl = encodeURIComponent('正式環(huán)境授權(quán)頁面路徑')
} else {
redirectUrl = encodeURIComponent('測試環(huán)境授權(quán)頁面路徑')
}
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()
}
})
在頁面目錄中創(chuàng)建一個auth.vue授權(quán)空頁面废岂;
<template>
<div></div>
</template>
<script>
export default {
name: "Auth",
async created() {
// 如果連接中有微信返回的 code,則用此 code 調(diào)用后端接口狱意,向微信服務(wù)器請求用戶信息
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) {
//將一些信息存儲到本地
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ù)頁面
} catch (error) {
console.log(error);
}
} else {
// 如果不是從微信重定向過來的湖苞,沒有帶著微信的 code,則直接進(jìn)入首頁
this.$router.replace("/");
}
}
};
</script>
<style lang="scss" scoped>
</style>
不同的業(yè)務(wù)實現(xiàn)的方式可能不同详囤,可根據(jù)自己具體業(yè)務(wù)邏輯加以調(diào)整袒啼。