Files
qncV4uni-app/src/utils/wxMiniAuth.js

35 lines
1.0 KiB
JavaScript
Raw Normal View History

2026-05-16 15:47:07 +08:00
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
}