微信4.13更新后,对用户登录逻辑做了接口调整
import {
wxGetUserProfile, wxHide, wxLoading, wxLogin, wxModal} from "../utils/wxPromise";
export const basic = Behavior({
methods: {
$emit(name, detail, options) {
this.triggerEvent(name, detail, options);
},
set(data) {
this.setData(data);
return new Promise((resolve) => wx.nextTick(resolve));
},
/**
* 验证是否登录
*/
$isLogin() {
let token = wx.getStorageSync('token')
return !!token
},
$login() {
return new Promise((resolve) => {
if (this.$isLogin()) {
resolve()
} else {
wxLoading('正在登录')
wxLogin().then(res => {
//这里替换后台登录接口,后台接口逻辑如下:
//调用微信接口: https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code
//微信接口调用成功,可以获取到openid unionId sessionKey,
//通过openid或unionId查询数据库是否有此用户,如果有返回用户信息,如果没有,则注册并返回注册后的用户信息
return Promise.resolve({
openid: '123456',
unionId: '123456',
id: '123456',
avatar: '',//头像,注册是没有头像等用户信息,需要前端调用wx.getUserProfile完善
})
}).then(res => {
wxHide()
//这里后台登录接口返回注册成功后的用户信息,
wx.setStorageSync('userInfo', res)
wx.setStorageSync('token', res.id)
if (res.avatar) {
//已经有了用户信息
resolve()
return Promise.reject('登录成功')//截断promise的链式操作
} else {
return wxModal({
title: '完善信息',
showCancel: false,
confirmText: '立即完善'
})
}
}).then(() => {
wxLoading('正在登录')
return wxGetUserProfile()
}).then(res => {
return Promise.resolve(res) //这里调用后台接口,完善用户信息
}).then(res => {
//这里后台更新成功后的用户信息,
wx.setStorageSync('userInfo', res)
wx.setStorageSync('token', res.id)
resolve()
}).catch((err) => {
console.log(err);
wxHide()
resolve()
})
}
})
},
页面使用
import {
basic } from 'path/basic.js'
Component({
behaviors: [basic],
methods: {
onLoad: function() {
this.$login()
}
}
})
对wxApi进行二次封装
//wxPromise.js
/**
* 授权检测
* @param authStr
* @param msg
* @returns {Promise<unknown>}
*/
function authorize(authStr, msg = '是否去权限管理页打开授权') {
return new Promise((resolve, reject) => {
wx.getSetting({
success(res) {
if (res.authSetting[authStr]) {
//已经授权
resolve()
} else if (res.authSetting[authStr] === undefined) {
//未授权
wx.authorize({
scope: authStr,
success: res => {
//同意授权
resolve(res)
},
fail: res => {
//拒绝授权
reject(res)
}
})
} else if (res.authSetting[authStr] === false) {
//已拒绝授权,弹框让用户去授权管理页打开
wxModal({
title: '权限管理',
content: msg
}).then(() => {
wx.openSetting({
//打开授权管理页
success(res)</