import type { ClientRuntimeConfig, WechatLoginResult } from '@dukang/shared-types'; import { isWxAuthorizeEnabled } from '@dukang/shared-types'; import { isWechatEnv, weixinSdk } from './weixin'; import { request, saveSession, type UserProfile } from './api'; const WECHAT_AUTH_REQUIRED = 'WECHAT_AUTH_REQUIRED'; export function isWechatAuthRequiredError(err: unknown): boolean { return err instanceof Error && err.message === WECHAT_AUTH_REQUIRED; } export async function fetchClientConfig(): Promise { return request('USER_H5', '/common/client-config'); } export async function fetchUserProfile(): Promise { return request('USER_H5', '/auth/me'); } /** 真实微信支付且未绑定微信时需要授权 */ export function needsWechatAuthForPay( config: ClientRuntimeConfig, profile: UserProfile | null, ): boolean { if (!isWxAuthorizeEnabled(config)) return false; return !config.mockPay && config.wechatPayEnabled && isWechatEnv() && !profile?.hasWechat; } export function saveWechatLoginResult(result: WechatLoginResult): boolean { if (!result.accessToken) return false; saveSession({ accessToken: result.accessToken, refreshToken: result.refreshToken ?? '', deviceKey: result.deviceKey, phoneVerified: !!result.phoneVerified, user: result.user as never, }); return true; } export async function authorizeWechatForPay(): Promise { const config = await fetchClientConfig(); if (!isWxAuthorizeEnabled(config)) return; if (!isWechatEnv()) { throw new Error('请在微信内打开以完成授权'); } return weixinSdk.login(); } export function buildLoginReturnUrl(pathname: string, search: string) { return `/login?return=${encodeURIComponent(`${pathname}${search}`)}`; }