66 lines
2.1 KiB
TypeScript
66 lines
2.1 KiB
TypeScript
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<PartnerProfile> {
|
|
return request<PartnerProfile>('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<WechatLoginResult | null> {
|
|
if (!isWechatEnv()) return null;
|
|
return weixinSdk.handleOAuthCallback();
|
|
}
|
|
|
|
/**
|
|
* 微信授权登录(对齐 C 端:仅微信内置浏览器走 OAuth)。
|
|
* 返回 true = 已登录;void = 已跳转授权页等待回调。
|
|
*/
|
|
export async function loginPartnerWithWechat(): Promise<boolean | void> {
|
|
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<void> {
|
|
if (!isWechatEnv()) return;
|
|
await weixinSdk.login();
|
|
}
|
|
|
|
export async function authorizePartnerWechat(): Promise<WechatLoginResult | void> {
|
|
if (!isWechatEnv()) {
|
|
throw new Error(WECHAT_INAPP_REQUIRED_MSG);
|
|
}
|
|
return weixinSdk.login();
|
|
}
|
|
|
|
/** @deprecated 使用 handlePartnerWechatLoginResult */
|
|
export function savePartnerWechatAuth(result: WechatLoginResult): boolean {
|
|
return handlePartnerWechatLoginResult(result);
|
|
}
|