59 lines
1.9 KiB
TypeScript
59 lines
1.9 KiB
TypeScript
import type { WechatLoginResult } from '@dukang/shared-types';
|
|
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
|
import { isWechatEnv, weixinSdk } from './weixin';
|
|
import {
|
|
authorizeWechatForPay,
|
|
fetchClientConfig,
|
|
fetchUserProfile,
|
|
needsWechatAuthForPay,
|
|
saveWechatLoginResult,
|
|
} from './pay-wechat';
|
|
|
|
export type WechatAuthEnsureResult =
|
|
| { ok: true }
|
|
| { ok: false; redirecting: true }
|
|
| { ok: false; needBindPhone: true; wxSessionKey: string };
|
|
|
|
export async function checkNeedsWechatAuth(): Promise<boolean> {
|
|
const [config, profile] = await Promise.all([fetchClientConfig(), fetchUserProfile()]);
|
|
return needsWechatAuthForPay(config, profile);
|
|
}
|
|
|
|
/** 真实微信支付前确保已绑定微信;OAuth 跳转时返回 redirecting */
|
|
export async function ensureWechatAuthForPay(): Promise<WechatAuthEnsureResult> {
|
|
if (!isWechatEnv()) return { ok: true };
|
|
if (!(await checkNeedsWechatAuth())) return { ok: true };
|
|
|
|
const result = await authorizeWechatForPay();
|
|
if (!result) return { ok: false, redirecting: true };
|
|
|
|
if (result.needBindPhone && result.wxSessionKey) {
|
|
return { ok: false, needBindPhone: true, wxSessionKey: result.wxSessionKey };
|
|
}
|
|
|
|
if (saveWechatLoginResult(result)) {
|
|
return { ok: true };
|
|
}
|
|
return { ok: false, redirecting: true };
|
|
}
|
|
|
|
export async function handleWechatAuthCallback(): Promise<WechatLoginResult | null> {
|
|
if (!isWechatEnv()) return null;
|
|
const config = await fetchClientConfig();
|
|
if (!isWxAuthorizeEnabled(config)) return null;
|
|
return weixinSdk.handleOAuthCallback();
|
|
}
|
|
|
|
export async function loginWithWechatSdk(): Promise<WechatLoginResult | void> {
|
|
const config = await fetchClientConfig();
|
|
if (!isWxAuthorizeEnabled(config)) return;
|
|
if (!isWechatEnv()) {
|
|
throw new Error('请在微信内打开以使用微信一键授权');
|
|
}
|
|
return weixinSdk.login();
|
|
}
|
|
|
|
export function applyWechatLoginResult(result: WechatLoginResult): boolean {
|
|
return saveWechatLoginResult(result);
|
|
}
|