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 { 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", }); 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 } : {}), }; } }