微信小程序官方登陆方式修改,要求经过button点击登陆,和你们分享一下个人解决方案。html
原先的登陆逻辑是注册一个全局login方法, login方法中首先调用wx.login静默登陆,获取临时登陆凭证code,在开发者服务器后台调用 api,使用 code 换取 openid 和 session_key 。而后调用wx.getUserInfo获取用户信息。redux
如今的实现逻辑是写一个button中转页,进入小程序wx.getUserInfo获取失败后跳转到button中转页,点击button调用bindgetuserinfo方法,该方法返回的detail数据与wx.getUserInfo方法返回的信息一致,此时也能够获取到用户信息。回调成功后wx.navigateBack({})回原页面。小程序
下面贴上部分代码片断:微信小程序
async bindGetUserInfo(event) {
const { detail } = event;
const isSuccess = detail.errMsg === 'getUserInfo:ok';
if (isSuccess) {
this.authSuccess(detail);
return;
}
// 用户拒绝受权
// 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,
// });
}
复制代码
就酱愉快的重构结束~api