import type { WechatLoginResult } from '@dukang/shared-types'; import { WECHAT_INAPP_REQUIRED_MSG } from '@dukang/weixin-sdk'; import { isWechatEnv, weixinSdk } from './weixin'; import { request, saveAuth } from './api'; export type PartnerProfile = { id: string; name: string; phone: string; companyName: string; hasWechat?: boolean; }; export async function fetchPartnerProfile(): Promise { return request('PARTNER_H5', '/partner/me'); } /** 微信内上传照片前需完成公众号授权绑定 */ export function needsWechatAuth(profile: PartnerProfile | null): boolean { return isWechatEnv() && !!profile && !profile.hasWechat; } /** 处理微信登录/绑定结果,返回是否已拿到 token 可进入首页 */ export function handlePartnerWechatLoginResult(result: WechatLoginResult): boolean { if (!result.accessToken) return false; saveAuth({ accessToken: result.accessToken }); return true; } export async function handlePartnerWechatCallback(): Promise { if (!isWechatEnv()) return null; return weixinSdk.handleOAuthCallback(); } /** * 微信授权登录(对齐 C 端:仅微信内置浏览器走 OAuth)。 * 返回 true = 已登录;void = 已跳转授权页等待回调。 */ export async function loginPartnerWithWechat(): Promise { if (!isWechatEnv()) { throw new Error(WECHAT_INAPP_REQUIRED_MSG); } const result = await weixinSdk.login(); if (result) return handlePartnerWechatLoginResult(result); } /** * 短信登录成功后于微信内自动发起 OAuth,将 openId 绑定到当前合伙人账号(便于同一微信后续免登)。 */ export async function bindPartnerWechatAfterSmsLogin(): Promise { if (!isWechatEnv()) return; await weixinSdk.login(); } export async function authorizePartnerWechat(): Promise { if (!isWechatEnv()) { throw new Error(WECHAT_INAPP_REQUIRED_MSG); } return weixinSdk.login(); } /** @deprecated 使用 handlePartnerWechatLoginResult */ export function savePartnerWechatAuth(result: WechatLoginResult): boolean { return handlePartnerWechatLoginResult(result); }