uniApp微信小程序的登录流程
- 先使用uni.getSetting来判断用户是否曾经授权过,获取到res.authSetting[‘scope.userInfo’],来判断是否有进行过授权操作,授权过为true,未授权为false
async checkWxAuth({ state, dispatch }): Promise<{ auth: boolean }> {
return await new Promise((resolve, reject) => {
uni.getSetting({
success(res) {
if (res.authSetting["scope.userInfo"]) {
console.log("--------scope-----", res)
resolve({ auth: true });
} else {
resolve({ auth: false });
}
},
});
});
},
async checkLogin({ state, dispatch, commit }): Promise<boolean> {
let wxAuth = await dispatch('checkWxAuth')
const token: string | null = uni.getStorageSync("token");
const expire_time: number = uni.getStorageSync("expire_time");
const hasUserInfo: boolean = uni.getStorageSync("hasUserInfo");
if (!wxAuth.auth) {
commit('loginOut')
return false;
}
if (!token) {
commit('loginOut')
return false;
}
const curTimeStamp: number = (new Date()).getTime();
if ((curTimeStamp > expire_time)) {
commit('loginOut')
return false
}
if (!state.isLogin) {
return false
}
if (!String(hasUserInfo)) {
return false
}
return true
},
- 如果为未授权未登录状态,则调用事件getUserProfile来进行授权,会弹出一个授权接口,同意授权后使用uni.login获取用户的code值,来与后端发起请求换取CacheKey,再使用uni.login来获取用户的基本信息,向后端发起请求将所需内容保存到后端
wx.getUserProfile({
desc: " 授权登录",
success: (profile) => {
console.log("--------getUserProfile-----", profile);
uni.login({
success: async (res) => {
console.log("--------loginAction/uni.login-----", res);
console.log(res);
let keyObject = await this.getCacheKey(res.code);
if (keyObject) {
let { cacheKey } = keyObject;
let openid = keyObject.wechatUser.routineOpenId;
uni.getUserInfo({
success: async (res) => {
console.log("--------loginAction/uni.getUserInfo-----", res);
let loginRes = await this.wxLogin({
});
console.log("--------loginRes-----", loginRes);
uni.hideLoading();
this.close();
console.log('用户信息',this.userInfo)
},
fail: () => {
uni.hideLoading();
this.open();
},
});
}
},
});
},
fail: () => {
uni.hideLoading();
this.open();
},
});