寫在前面~
- 一般正常的授權(quán)時,用戶在第二次進來,需要做用戶是否授權(quán)的判斷,不然頁面會重復(fù)出現(xiàn)登錄狀態(tài)。如果沒有授權(quán)就需要去進行授權(quán)登錄了。
- OpenID 對于多平臺來說不是唯一值,UnionID是絕對唯一的。比如當這個用戶在公眾號網(wǎng)頁里面去授權(quán)登錄之后,當前用戶的openid為1,那么這個用戶再去登錄與這個公眾號有關(guān)聯(lián)的小程序,那么小程序的授權(quán)登錄后,openid為2。兩個平臺能識別同一個用戶就要用到unionid,這個值是相同的。(自己理解的)
//第一部分
//如果授權(quán)登錄成功之后,將openid存在緩存中,下次在進入頁面要判斷是否存在openid。如果沒有openid就走第二部分,否則就正常執(zhí)行~
//這一部分就不寫了
//第二部執(zhí)行方法(要判斷是不是重定向回來的頁面)
appif() {
let _this = this;
const AppId = "wxxxxx232323dfdfdf";//AppId 是每個公眾號都有的
//如果當前頁面是重定向回來的地址,那么地址中是會有code值的
let appIdCode = utilFun.geturlp("code");//utilFun.geturlp方法為 取地址欄中名字為code的內(nèi)容
if (appIdCode != null) {
//存code
localStorage.setItem("takeFoodCode", appIdCode);
_this.code = localStorage.getItem("takeFoodCode");//輸出
}
//這一塊開始判斷,當前用戶是否授權(quán)登錄過,以緩存中是否有code值
_this.code = localStorage.getItem("takeFoodCode");
if (_this.code != null) {
console.log('code不為空')
//這個時候code不為空,就可以拿code去和后端換取用戶的openid了~
_this.appidFun();
}else{
//進行用戶的登錄授權(quán)操作
const formalUrl = 'http://www.www.cn/mall/';//微信授權(quán)登錄之后 重定向頁面地址(登錄之后微信那邊跳轉(zhuǎn)回來的地址)
const url_oauth2 = "https://open.weixin.qq.com/connect/oauth2/authorize" //微信授權(quán)登錄的地址
_this.redirect_uri = encodeURIComponent(formalUrl);//對重定向地址處理一下
//以下為微信授權(quán)登錄過程中,需要拼接的地址,官方文檔上面有具體內(nèi)容
url_oauth2 = url_oauth2 + "?appid=" + AppId + "&redirect_uri=" + this.redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
window.location.replace(_this.url_oauth2);
}
},
//第三步-用code換取用戶的openid
async appidFun() {
let _this = this;
const openidUrl = 'https://接口';
let dataCode = {
authCode: _this.code
};
const res= await this.$axios(openidUrl, dataCode);
if(res.data == "000000"){
_this.openId = res.data.openId;
localStorage.setItem("userOpenId", _this.openId); //存入 參數(shù): 1.調(diào)用的值 2.所要存入的數(shù)據(jù)
_this.openId = localStorage.getItem("userAppId");//輸出
console.log('獲取到openid了~') //然后執(zhí)行同第一部分,用戶緩存存在openid之后,執(zhí)行相同的事件即可。
}
}
大概這個樣子~
存?zhèn)€記錄~
溜了~
~~