Files
persionalBrand/apps/api/src/wechat-auth.ts
T
que01 d0a0eeea8c
CI / Browser smoke (pull_request) Successful in 58s
CI / Static checks (pull_request) Successful in 1m32s
CI / API integration (pull_request) Successful in 1m27s
CI / Production build (pull_request) Successful in 2m7s
feat: 支持按品牌配置微信登录凭据
2026-10-23 22:07:39 +08:00

86 lines
3.1 KiB
TypeScript

import { Injectable, ServiceUnavailableException, UnauthorizedException } from "@nestjs/common";
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
interface WechatSessionResponse {
openid?: string;
session_key?: string;
unionid?: string;
errcode?: number;
errmsg?: string;
}
export interface WechatSession {
openid: string;
sessionKey: string;
unionid?: string;
}
export interface WechatLoginCredentials {
appId: string;
appSecret: string;
}
/**
* 每个品牌对应自己的小程序,登录凭据必须来自该品牌的后台上传配置。
* 不使用全局环境变量或跨品牌回退,避免把 A 品牌的 OpenID 登录到 B 品牌。
*/
export function resolveWechatLoginCredentials(settings: unknown): WechatLoginCredentials {
const payload =
settings && typeof settings === "object" && !Array.isArray(settings)
? (settings as Record<string, unknown>)
: {};
const appId = typeof payload.appId === "string" ? payload.appId.trim() : "";
if (!appId) throw new ServiceUnavailableException("该品牌尚未配置微信 AppID");
if (!payload.appSecretCredential)
throw new ServiceUnavailableException("该品牌尚未配置微信登录 AppSecret");
let appSecret: string;
try {
appSecret = decryptMiniAppCredential(payload.appSecretCredential);
} catch {
throw new ServiceUnavailableException("该品牌微信登录凭据不可用,请重新保存 AppSecret");
}
if (!appSecret)
throw new ServiceUnavailableException("该品牌微信登录 AppSecret 为空,请重新保存");
return { appId, appSecret };
}
@Injectable()
export class WechatAuthService {
async exchangeCode(code: string, credentials: WechatLoginCredentials): Promise<WechatSession> {
if (!code.trim()) throw new UnauthorizedException("微信登录 code 不能为空");
if (!credentials.appId || !credentials.appSecret)
throw new ServiceUnavailableException("微信登录尚未配置");
const query = new URLSearchParams({
appid: credentials.appId,
secret: credentials.appSecret,
js_code: code,
grant_type: "authorization_code",
});
let response: Response;
try {
response = await fetch(`https://api.weixin.qq.com/sns/jscode2session?${query.toString()}`);
} catch (error) {
console.error(
"wechat session request failed",
error instanceof Error ? error.message : error,
);
throw new ServiceUnavailableException("微信登录服务暂时不可用");
}
if (!response.ok) {
console.error("wechat session http error", response.status);
throw new ServiceUnavailableException("微信登录服务暂时不可用");
}
const result = (await response.json()) as WechatSessionResponse;
if (!result.openid || !result.session_key) {
console.warn("wechat session rejected", { errcode: result.errcode, errmsg: result.errmsg });
throw new UnauthorizedException(result.errmsg ?? "微信登录失败");
}
return {
openid: result.openid,
sessionKey: result.session_key,
...(result.unionid ? { unionid: result.unionid } : {}),
};
}
}