微信小程序官方登錄方式修改,要求通過button點擊登錄,和大家分享一下我的解決方案。
原先的登錄邏輯是注冊一個全局login方法, login方法中首先調(diào)用wx.login靜默登錄,獲取臨時登錄憑證code,在開發(fā)者服務器后臺調(diào)用 api,使用 code 換取 openid 和 session_key 。然后調(diào)用wx.getUserInfo獲取用戶信息。
現(xiàn)在的實現(xiàn)邏輯是寫一個button中轉(zhuǎn)頁,進入小程序wx.getUserInfo獲取失敗后跳轉(zhuǎn)到button中轉(zhuǎn)頁,點擊button調(diào)用bindgetuserinfo方法,該方法返回的detail數(shù)據(jù)與wx.getUserInfo方法返回的信息一致,此時也可以獲取到用戶信息?;卣{(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;
// 保存用戶信息到服務器
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);
// 存儲用戶標識符到本地
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,
// });
}