2022-11-27 23:54:26 +08:00

64 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import message from "./message"
/**
* 执行wx.login 返回 用户登录凭证 code
* @param timeout
*/
export function login(timeout = 10000) {
return new Promise<string>((resolve, reject) => {
wx.login({
timeout, // 超时为10s
success: (res) => {
if (res.code) resolve(res.code)
else {
message.toast('登录失败,' + res.errMsg, 'error')
reject('登录失败,' + res.errMsg)
}
},
fail: (e) => {
message.toast('登录失败,请重新登录', 'error')
reject('登录失败,' + e.errMsg)
}
})
})
}
type UserProfileData = {
/**
* 包括敏感数据在内的完整用户信息的加密数据(BASE64)
*/
encryptedData: string
/**
* 加密算法的初始向量(BASE64)
*/
iv: string
/**
* 用户登录凭证(有效期五分钟)。开发者需要在开发者服务器后台调用 auth.code2Session
* 使用 code 换取 openid、unionid、session_key 等信息
*/
code?: string
}
export function getUserProfile() {
return new Promise<UserProfileData>(async (resolve, reject) => {
// wx.login 必须在获取用户数据之前
wx.getUserProfile({
desc: '展示用户信息并参与相关活动',
success: (res) => {
if (res.errMsg == 'getUserProfile:ok' && res.encryptedData) {
resolve({
encryptedData: res.encryptedData,
iv: res.iv
})
} else {
message.toast('登录失败,请重新登录', 'error')
reject('登录失败,' + res.errMsg)
}
},
fail: (e) => {
message.toast('登录失败,请重新登录', 'error')
reject('登录失败,' + e.errMsg)
}
})
});
}