微信小程序登錄方式的修改解決方案
微信小程序官方登錄方式修改,要求通過button點(diǎn)擊登錄,和大家分享一下解決方案。

原先的登錄邏輯是注冊(cè)一個(gè)全局login方法, login方法中首先調(diào)用wx.login靜默登錄,獲取臨時(shí)登錄憑證code,在開發(fā)者服務(wù)器后臺(tái)調(diào)用 api,使用 code 換取 openid 和 session_key 。然后調(diào)用wx.getUserInfo獲取用戶信息。
現(xiàn)在的實(shí)現(xiàn)邏輯是寫一個(gè)button中轉(zhuǎn)頁,進(jìn)入小程序wx.getUserInfo獲取失敗后跳轉(zhuǎn)到button中轉(zhuǎn)頁,點(diǎn)擊button調(diào)用bindgetuserinfo方法,該方法返回的detail數(shù)據(jù)與wx.getUserInfo方法返回的信息一致,此時(shí)也可以獲取到用戶信息?;卣{(diào)成功后wx.navigateBack({})回原頁面。
下面貼上部分代碼片段:
async bindGetUserInfo(event) {
const { detail } = event;
const isSuccess = detail.errMsg === 'getUserInfo:ok';
if (isSuccess) {
this.authSuccess(detail);
return;
}
// 用戶拒絕授權(quán)
// wx.navigateBack({});
}
async authSuccess(detail) {
await this.getToken(detail);
wx.navigateBack({});
// this.nextHander();
}
保存用戶信息
async getToken(detail) {
console.log('getToken', detail);
const session_key = wx.getStorageSync('session_key');
const { encryptedData: encrypted_data, iv } = detail;
const that = this;
// 保存用戶信息到服務(wù)器
const { data: { user, up_token, token, is_created } } = await this.fetch({
url: '/api/artisan/wechat/login',
data: {
session_key,
encrypted_data,
iv,
},
method: 'POST',
});
wx.setStorageSync('user', user);
this.$root.$parent.store.set('up_token', up_token, 30);
// 存儲(chǔ)用戶標(biāo)識(shí)符到本地
this.$root.$parent.store.set('token', token, 30);
this.$root.$parent.store.set('is_created', is_created, 30);
// redux
// store.dispatch({
// type: 'SET_IS_CREATED',
// payload: is_created,
// });
}
就醬愉快的重構(gòu)結(jié)束~

立即掃碼關(guān)注

多門店/直營/加盟連鎖管理系統(tǒng)