feat: add official wechat session exchange boundary

This commit is contained in:
que01 committed 2026-09-18 15:27:02 +08:00
1 parent 5e71b89e95
commit de8f989083
3 files changed
+79 -2

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
import { Injectable, ServiceUnavailableException, UnauthorizedException } from "@nestjs/common";
interface WechatSessionResponse {
openid?: string;
session_key?: string;
unionid?: string;
errcode?: number;
errmsg?: string;
}
export interface WechatSession {
openid: string;
sessionKey: string;
unionid?: string;
}
@Injectable()
export class WechatAuthService {
async exchangeCode(code: string): 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("微信登录尚未配置");
const query = new URLSearchParams({
appid: appId,
secret: appSecret,
js_code: code,
grant_type: "authorization_code",
});
const response = await fetch(
`https://api.weixin.qq.com/sns/jscode2session?${query.toString()}`,
);
if (!response.ok) throw new ServiceUnavailableException("微信登录服务暂时不可用");
const result = (await response.json()) as WechatSessionResponse;
if (!result.openid || !result.session_key)
throw new UnauthorizedException(result.errmsg ?? "微信登录失败");
return {
openid: result.openid,
sessionKey: result.session_key,
...(result.unionid ? { unionid: result.unionid } : {}),
};
}
}