58 lines
1.7 KiB
TypeScript
58 lines
1.7 KiB
TypeScript
import type { WechatLoginResult } from '@dukang/shared-types';
|
|
import { isWechatEnv, weixinSdk } from './weixin';
|
|
import { request, saveAuth, type ShopSessionPayload } from './api';
|
|
|
|
export type ShopAccountProfile = {
|
|
id: string;
|
|
storeId: string;
|
|
name: string;
|
|
phone: string;
|
|
wxOpenId?: string | null;
|
|
store?: { name: string };
|
|
};
|
|
|
|
export async function fetchShopAccount(): Promise<ShopAccountProfile> {
|
|
return request<ShopAccountProfile>('SHOP_H5', '/shop/auth/me');
|
|
}
|
|
|
|
export function needsWechatAuth(profile: ShopAccountProfile | null): boolean {
|
|
return isWechatEnv() && !!profile && !profile.wxOpenId;
|
|
}
|
|
|
|
export function sessionFromWechatLogin(result: WechatLoginResult): ShopSessionPayload | null {
|
|
if (!result.accessToken || !result.refreshToken) return null;
|
|
const store = result.store;
|
|
return {
|
|
accessToken: result.accessToken,
|
|
refreshToken: result.refreshToken,
|
|
store: store
|
|
? {
|
|
id: String(store.id ?? ''),
|
|
storeId: String(store.storeId ?? ''),
|
|
name: String(store.name ?? ''),
|
|
phone: String(store.phone ?? ''),
|
|
storeName: String(store.storeName ?? store.name ?? ''),
|
|
}
|
|
: undefined,
|
|
};
|
|
}
|
|
|
|
export function saveShopWechatAuth(result: WechatLoginResult): boolean {
|
|
const session = sessionFromWechatLogin(result);
|
|
if (!session) return false;
|
|
saveAuth(session);
|
|
return true;
|
|
}
|
|
|
|
export async function authorizeShopWechat(): Promise<WechatLoginResult | void> {
|
|
if (!isWechatEnv()) {
|
|
throw new Error('请在微信内打开以完成授权');
|
|
}
|
|
return weixinSdk.login();
|
|
}
|
|
|
|
export async function handleShopWechatCallback(): Promise<WechatLoginResult | null> {
|
|
if (!isWechatEnv()) return null;
|
|
return weixinSdk.handleOAuthCallback();
|
|
}
|