35 lines
1.0 KiB
JavaScript
35 lines
1.0 KiB
JavaScript
|
|
import { postUserWxMiniAuth } from '@/api/user'
|
|||
|
|
import { saveAuthSession } from '@/utils/session'
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 微信小程序:`uni.login` → `/user/wxMiniAuth` → 写入 token
|
|||
|
|
* @param {{ silent?: boolean }} [opts] silent=true:不触发全局 loading、不弹业务/网络失败 Toast(适合 App 启动静默登录)
|
|||
|
|
* @returns {Promise<boolean>} 是否登录成功
|
|||
|
|
*/
|
|||
|
|
export async function tryWxMiniProgramAuth(opts = {}) {
|
|||
|
|
const silent = opts.silent === true
|
|||
|
|
const reqExtra = silent
|
|||
|
|
? { skipLoading: true, skipBizToast: true }
|
|||
|
|
: undefined
|
|||
|
|
|
|||
|
|
const loginRes = await new Promise((resolve, reject) => {
|
|||
|
|
uni.login({
|
|||
|
|
provider: 'weixin',
|
|||
|
|
success: resolve,
|
|||
|
|
fail: reject,
|
|||
|
|
})
|
|||
|
|
})
|
|||
|
|
if (!loginRes?.code) {
|
|||
|
|
if (!silent)
|
|||
|
|
uni.showToast({ title: '未获取到微信登录凭证', icon: 'none' })
|
|||
|
|
return false
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const res = await postUserWxMiniAuth({ code: loginRes.code }, reqExtra)
|
|||
|
|
if (res && res.code === 200 && res.data) {
|
|||
|
|
saveAuthSession(res.data)
|
|||
|
|
return true
|
|||
|
|
}
|
|||
|
|
return false
|
|||
|
|
}
|