feat: 支持按品牌配置微信登录凭据
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

This commit is contained in:
que01 committed 2026-10-23 22:07:39 +08:00
1 parent e75c524343
commit d0a0eeea8c
23 files changed
+460 -62

No files matched your search

+35 -6
View File
@@ -1,4 +1,5 @@
import { Injectable, ServiceUnavailableException, UnauthorizedException } from "@nestjs/common";
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
interface WechatSessionResponse {
openid?: string;
@@ -14,17 +15,45 @@ export interface WechatSession {
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): Promise<WechatSession> {
async exchangeCode(code: string, credentials: WechatLoginCredentials): Promise<WechatSession> {
if (!code.trim()) throw new UnauthorizedException("微信登录 code 不能为空");
const appId = process.env.WECHAT_APP_ID;
const appSecret = process.env.WECHAT_APP_SECRET;
if (!appId || !appSecret) throw new ServiceUnavailableException("微信登录尚未配置");
if (!credentials.appId || !credentials.appSecret)
throw new ServiceUnavailableException("微信登录尚未配置");
const query = new URLSearchParams({
appid: appId,
secret: appSecret,
appid: credentials.appId,
secret: credentials.appSecret,
js_code: code,
grant_type: "authorization_code",
});