longz
2026-07-08 700f9d0da314a4ea701fe9f68d305b67d72ec5fb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import type { ApiError } from '@/api/core/handlers'
import { fetchMiniMe, loginByWx } from '@/api/auth'
import { normalizeLoginProfile, normalizeMeProfile } from '@/types/auth'
import { useMiniAuthStore } from '@/store/auth'
 
export const EMPLOYEE_SUBSCRIBE_TEMPLATE_IDS = [
  'QlNwG99WXWztRDgtlLcE0fHxfY2VwaX8PRMrwGpEync',
  'Wip0ODJgybZpeFpcvev_0GK1wQXEqZw-LHOjS-UyDLw',
]
 
export const MINI_PHONE_AUTH_REQUIRED = 10008
 
export function getApiErrorCode(error: unknown) {
  return typeof error === 'object' && error != null && 'code' in error
    ? Number((error as ApiError).code)
    : NaN
}
 
export async function getWxLoginCode() {
  // #ifdef MP-WEIXIN
  return await new Promise<string>((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: (res) => {
        if (res.code) {
          resolve(res.code)
          return
        }
        reject(new Error('获取微信登录凭证失败'))
      },
      fail: () => reject(new Error('获取微信登录凭证失败')),
    })
  })
  // #endif
  // #ifndef MP-WEIXIN
  throw new Error('当前环境暂不支持微信授权登录')
  // #endif
}
 
export async function requestEmployeeSubscribeAuthorization(userType?: string | null) {
  if (userType !== 'EMPLOYEE') {
    return
  }
  // #ifdef MP-WEIXIN
  try {
    await new Promise<void>((resolve) => {
      uni.requestSubscribeMessage({
        tmplIds: EMPLOYEE_SUBSCRIBE_TEMPLATE_IDS,
        complete: () => resolve(),
      })
    })
  }
  catch (error) {
    console.warn('request employee subscribe message failed', error)
  }
  // #endif
}
 
export async function finishMiniLogin(loginData: Awaited<ReturnType<typeof loginByWx>>) {
  const authStore = useMiniAuthStore()
  authStore.setSession({
    token: loginData.token,
    profile: normalizeLoginProfile(loginData),
  })
 
  try {
    const profile = await fetchMiniMe(loginData.token)
    authStore.setProfile(normalizeMeProfile(profile))
  }
  catch (error) {
    console.warn('load mini profile failed after login', error)
  }
 
  await requestEmployeeSubscribeAuthorization(authStore.profile?.userType)
}