feat: 微信登录与认证完善 + 一键 docker compose 启动
登录流程(以 openid 为唯一标识): - auth.service.login 改为 upsert:openid 在库续登,不在库自动建用户签 token - 个人主体无 getPhoneNumber 权限,故不强制手机号注册;register 接口保留备未来用 - wechat.service 新增 getAccessToken(Redis 缓存)、getPluginOpenPid、getUserPhoneNumber - 新增 /api/wechat/plugin-openpid、/api/wechat/phone 接口 schema 与迁移: - User 增加 openpid(可空唯一) 兼容插件场景;openid 保持必填主键 - 新增 add_openpid_optional_openid、openid_required_primary 迁移 部署: - docker-compose.yml 改为 docker compose up -d 一键启动 postgres+redis+app - app 容器内用服务名连 db/redis,启动自动跑 prisma migrate deploy - 端口统一 3090(Dockerfile EXPOSE、compose 映射同步) - 新增 docs/wechat-api-signature-guide.md API 签名手册 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
+1
-1
@@ -1,6 +1,6 @@
|
||||
# ── 应用 ─────────────────────────────────────────────
|
||||
NODE_ENV=development
|
||||
APP_PORT=3000
|
||||
APP_PORT=3090
|
||||
# Swagger 文档路径,生产环境可置空以关闭
|
||||
SWAGGER_PATH=docs
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ services:
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "3090:3090"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
+7
-6
@@ -1,5 +1,5 @@
|
||||
# 本地开发:仅起 postgres + redis,应用用 npm run start:dev 直连
|
||||
# 起容器:docker compose up -d postgres redis
|
||||
# 一键启动:docker compose up -d
|
||||
# 同时起 postgres + redis + app,app 启动前自动跑 prisma migrate deploy
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
@@ -33,18 +33,19 @@ services:
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
|
||||
# 本地开发默认不启动 app;需要时用 profile:
|
||||
# docker compose --profile app up -d
|
||||
app:
|
||||
profiles: ["app"]
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/Dockerfile
|
||||
container_name: wxmp-app
|
||||
restart: unless-stopped
|
||||
env_file: .env
|
||||
# 容器内用服务名连 db/redis,覆盖 .env 里的 localhost
|
||||
environment:
|
||||
DATABASE_URL: postgresql://postgres:postgres@postgres:5432/wxmp?schema=public
|
||||
REDIS_URL: redis://redis:6379
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "3090:3090"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
+1
-1
@@ -22,6 +22,6 @@ RUN npm ci --omit=dev && npx prisma generate
|
||||
|
||||
COPY --from=builder /app/dist ./dist
|
||||
|
||||
EXPOSE 3000
|
||||
EXPOSE 3090
|
||||
# 启动前执行 migrate deploy(生产用),随后启动服务
|
||||
CMD ["sh", "-c", "npx prisma migrate deploy && node dist/main.js"]
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
# 微信小程序「API 接口安全」(数字签名)指导手册
|
||||
|
||||
> 对应获证地址:`developers.weixin.qq.com/miniprogram/dev/server/getting_started/api_signature.html`
|
||||
> 配套文件:本目录 `key/` 下的三个密钥文件(**切勿提交到 git,已忽略**)。
|
||||
|
||||
---
|
||||
|
||||
## 一、这份文档究竟是干嘛的?
|
||||
|
||||
微信小程序服务端在调用微信的**敏感开放接口**(如获取 `access_token`、订阅消息、手机号快速验证、
|
||||
用户信息等)时,传统做法是「AppSecret + IP 白名单」。这套 **API 数字签名**是微信新推出的
|
||||
**更强的接口调用安全机制**,做到两层防护:
|
||||
|
||||
1. **内容加密** —— 请求/响应体用对称密钥加密,网络上不再是明文 JSON,防泄漏。
|
||||
2. **签名验签** —— 双方互相信任消息「确实来自对方、且未被篡改」,具备**不可否认性**。
|
||||
|
||||
一句话:**它让你的服务器调用微信接口时,不依赖 IP 白名单也能安全、防篡改。**
|
||||
|
||||
适用场景:服务器 IP 不固定(云函数/CDN/多地域)时,比维护 IP 白名单更省心;以及需要更高安全等级的敏感接口。
|
||||
|
||||
---
|
||||
|
||||
## 二、你拿到的三个密钥分别是什么、有什么用
|
||||
|
||||
你的三件套(`key/` 目录),经核对是 **AES-256-GCM 对称加密 + RSA 签名**的组合:
|
||||
|
||||
| 文件 | 实际类型 | 作用 |
|
||||
|---|---|---|
|
||||
| **对称密钥.txt** | base64 编码的 **256-bit AES key**(`AES-256-GCM`) | **加密请求/响应正文** |
|
||||
| **非对称密钥.txt** | **RSA 私钥**(`BEGIN RSA PRIVATE KEY`) | **对请求签名**(`RSAwithSHA256` PSS),证明请求来自你 |
|
||||
| **开放平台证书.cer** | 微信**平台公钥证书**(`BEGIN CERTIFICATE`) | **验签微信的回包**,确认回包来自微信且未被改 |
|
||||
|
||||
补充:
|
||||
|
||||
- **验证签名用的「应用公钥」**:在 MP 后台生成密钥对时,花生处会显示公钥字段,**需要把应用公钥填回配置框上传**,微信用它验证你发的请求签名。你的 `非对称密钥.txt` 是私钥(自留),公钥不在此文件中。
|
||||
- **三个「编号(Sn)」**:对称密钥编号、非对称密钥编号、证书编号都在 MP 后台「API 安全」页面查看/记录,**不在密钥文件里**,请单独保存,后续算法和请求头需要用到。
|
||||
|
||||
---
|
||||
|
||||
## 三、算法与签名步骤
|
||||
|
||||
### 3.1 对称加密(加密请求正文)
|
||||
|
||||
- 算法:`AES-256-GCM`(你的 key 取 `对称密钥.txt` 的 base64 解码)。
|
||||
- 明文构成:把原始业务字段合并上三个安全字段后 JSON 序列化:
|
||||
- `_n`:随机串(随机数)
|
||||
- `_appid`:你的小程序 AppID
|
||||
- `_timestamp`:与请求头 `Wechatmp-TimeStamp` 一致的统一时间戳(毫秒)
|
||||
- GCM 附加认证数据(AAD):`urlpath|appid|timestamp|sn`(竖线分隔)。
|
||||
- 输出三个 base64 字段:`iv`(12 字节随机)、`data`(密文)、`authtag`(认证标签)。
|
||||
- 加密后的请求体 JSON(即下文签名用的 `postdata`)形如:
|
||||
```json
|
||||
{"_version": 1, "_appid": "...", "_timestamp": 1760000000000, "_sn": "密钥编号", "iv": "...", "data": "...", "authtag": "..."}
|
||||
```
|
||||
|
||||
### 3.2 RSA 签名(对加密后的请求签名)
|
||||
|
||||
- 算法:`RSAwithSHA256`,**PSS 填充**,salt 长度 **32**。
|
||||
- 拼接待签名串,字段之间用 `\n` 连接,**末尾无多余换行**:
|
||||
|
||||
```
|
||||
urlpath\nappid\ntimestamp\npostdata
|
||||
```
|
||||
|
||||
其中:
|
||||
- `urlpath` = **带 `https://` 的完整接口路径,不含 Query**,例如
|
||||
`https://api.weixin.qq.com/wxa/business/getuserphonenumber`;
|
||||
- `appid` = 小程序 AppID;
|
||||
- `timestamp` = 同上传到密文 `_timestamp` 的值(毫秒);
|
||||
- `postdata` = 第一步加密后的请求体 JSON 字符串。
|
||||
- 用你的 `非对称密钥.txt`(RSA 私钥)对上述字符串签名,结果 base64。
|
||||
|
||||
### 3.3 请求头
|
||||
|
||||
把下面的值放到 HTTP 请求头:
|
||||
|
||||
```
|
||||
Wechatmp-AppId: <小程序 appid>
|
||||
Wechatmp-TimeStamp: <timestamp>
|
||||
Wechatmp-Signature: <base64 的 RSA 签名>
|
||||
```
|
||||
|
||||
请求体 `Content-Type: application/json`,body 就是加密后的 JSON。
|
||||
|
||||
### 3.4 验签微信回包
|
||||
|
||||
- 回包头带 `Wechatmp-Serial`(新证书编号)与 `Wechatmp-Signature`。
|
||||
- 用 `开放平台证书.cer` 里的平台公钥验签(同样 `RSAwithSHA256` PSS),确认无误后再用对称密钥解密响应正文(算法与加密一致)。
|
||||
- 若响应头出现 `Wechatmp-Serial-Deprecated` 且与你证书号匹配,说明平台证书即将过期,需及时在 MP 后台更新。
|
||||
|
||||
---
|
||||
|
||||
## 四、在 MP 后台如何配置(拿这三件套)
|
||||
|
||||
路径:`mp.weixin.qq.com` → 「开发」→「开发管理」→「开发设置」→「**API 安全**」→ 管理员微信扫码验证。
|
||||
|
||||
1. **对称密钥**:点「随机生成密钥」→「下载密钥」→「确认」。得到 key(`对称密钥.txt`)与编号。
|
||||
2. **非对称密钥**:点「随机生成密钥对」→「下载私钥」(`非对称密钥.txt`)自留 → 把**公钥**填入输入框上传 →「确认」。
|
||||
3. **平台证书**:配置好应用公钥后,页面下载「开放平台证书」(`开放平台证书.cer`)。
|
||||
4. 记录三个**编号(Sn)**,妥善保管(尤其私钥与大对称密钥)。
|
||||
|
||||
---
|
||||
|
||||
## 五、在项目里如何开发(集成参考)
|
||||
|
||||
本仓库当前 `wechat.service.ts` 用的是传统 AppSecret 直连(`code2Session`)。调用**敏感接口**时可按本机制
|
||||
新增一个「签名 + 加密」请求封装。以下为可参考的 Node.js/TS 实现蓝图(基于 `node:crypto`,无需新依赖):
|
||||
|
||||
```ts
|
||||
import { createCipheriv, createSign, createVerify, constants } from 'node:crypto';
|
||||
import axios from 'axios';
|
||||
|
||||
// 配置:从 ConfigService / env 读取,切勿硬编码
|
||||
const CFG = {
|
||||
appid: process.env.WX_APPID,
|
||||
// 对称密钥(base64)
|
||||
symmetricKey: process.env.WX_API_SYMMETRIC_KEY, // 对应 对称密钥.txt
|
||||
symmetricSn: process.env.WX_API_SYMMETRIC_SN, // 编号 Sn
|
||||
// RSA 私钥(PEM 字符串)
|
||||
privateKey: process.env.WX_API_PRIVATE_KEY, // 对应 非对称密钥.txt
|
||||
privateSn: process.env.WX_API_SN, // 非对称密钥编号
|
||||
// 平台证书(PEM),用于回包验签
|
||||
platformCert: process.env.WX_PLATFORM_CERT, // 对应 开放平台证书.cer
|
||||
};
|
||||
|
||||
function sha256PssSign(privateKeyPem: string, message: string): string {
|
||||
const sign = createSign('RSA-SHA256');
|
||||
sign.update(message, 'utf8');
|
||||
// PSS + saltLength 32
|
||||
const sig = sign.sign({ key: privateKeyPem, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: 32 });
|
||||
return sig.toString('base64');
|
||||
}
|
||||
|
||||
/** 加密请求体 -> 返回 { body, signature, timestamp } */
|
||||
function encryptAndSign(data: object, urlpath: string, now: number) {
|
||||
const key = Buffer.from(CFG.symmetricKey, 'base64');
|
||||
const iv = require('crypto').randomBytes(12);
|
||||
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
||||
|
||||
// 明文:业务字段 + _n/_appid/_timestamp
|
||||
const plain = JSON.stringify({ ...data, _n: Math.random().toString(36).slice(2), _appid: CFG.appid, _timestamp: now });
|
||||
|
||||
// AAD = urlpath|appid|timestamp|sn
|
||||
cipher.setAAD(Buffer.from(`${urlpath}|${CFG.appid}|${now}|${CFG.symmetricSn}`));
|
||||
const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
|
||||
const body = JSON.stringify({
|
||||
_version: 1, _appid: CFG.appid, _timestamp: now, _sn: CFG.symmetricSn,
|
||||
iv: iv.toString('base64'), data: enc.toString('base64'), authtag: cipher.getAuthTag().toString('base64'),
|
||||
});
|
||||
|
||||
// 待签名串 urlpath\nappid\ntimestamp\npostdata
|
||||
const toSign = `${urlpath}\n${CFG.appid}\n${now}\n${body}`;
|
||||
const signature = sha256PssSign(CFG.privateKey, toSign);
|
||||
return { body, signature, timestamp: now };
|
||||
}
|
||||
|
||||
/** 调用示例:微信「获取用户手机号」类敏感接口 */
|
||||
async function callWechatApi(urlpath: string, payload: object) {
|
||||
const now = Date.now();
|
||||
const { body, signature, timestamp } = encryptAndSign(payload, urlpath, now);
|
||||
const { data } = await axios.post(urlpath, body, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Wechatmp-AppId': CFG.appid,
|
||||
'Wechatmp-TimeStamp': String(timestamp),
|
||||
'Wechatmp-Signature': signature,
|
||||
},
|
||||
});
|
||||
return data; // 注意:还需按第四节用平台证书验签 + 对称解密后再取用
|
||||
}
|
||||
```
|
||||
|
||||
> 说明:`axios` 已在依赖中;`node:crypto` 为 Node 内置,无需安装。正式落地时把这个封装挪进
|
||||
> `src/wechat/`(如 `src/wechat/api-signature.ts`),配置项接入 `.env`。
|
||||
|
||||
---
|
||||
|
||||
## 六、注意事项(务必读)
|
||||
|
||||
1. **私钥/对称密钥绝不硬编码、绝不进 git**。本手册代码中的 `process.env.*` 即为此;`key/` 已被 `.gitignore` 忽略。
|
||||
2. **编号(Sn)要单独记录**:文件里只有密钥本身,三个编号在 MP 后台「API 安全」页查看,算法和后续轮换都要用。
|
||||
3. **部分接口不支持加密**:文档明确「资源上传类 API 暂不支持加密」,且**并非所有接口都要求**这套签名。调用前先看目标接口文档,确认它走哪套鉴权(AppSecret 直连 or 数字签名)。
|
||||
4. **登录接口 `jscode2session` 当前不走这套签名**,保持现有 AppSecret 直连即可(已实现)。
|
||||
5. 签名结果每次不同(PSS 含随机因子),属正常。
|
||||
6. **证书过期**:关注 `Wechatmp-Serial-Deprecated` 响应头,过期前到 MP 后台更新平台证书。
|
||||
7. 文档示例代码里的密钥是演示用的,不能用。
|
||||
|
||||
---
|
||||
|
||||
## 七、接入本仓库的待办清单(可按需推进)
|
||||
|
||||
- [ ] 在 `.env.example` 增加 `WX_API_SYMMETRIC_KEY / WX_API_SYMMETRIC_SN / WX_API_PRIVATE_KEY / WX_API_SN / WX_PLATFORM_CERT` 占位
|
||||
- [ ] `src/wechat/` 新增 `api-signature.ts` 封装(按第五节蓝图,含回包验签 + 解密)
|
||||
- [ ] 用真实小程序 AppID 调通一个敏感接口的加解密全链路
|
||||
- [ ] 若长期大量调用,考虑把对称密钥/私钥换成环境变量注入(而非文件),并做密钥轮换流程
|
||||
@@ -0,0 +1,8 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "openpid" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ALTER COLUMN "openid" DROP NOT NULL;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_openpid_key" ON "User"("openpid");
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ALTER COLUMN "openid" SET NOT NULL;
|
||||
@@ -13,7 +13,10 @@ datasource db {
|
||||
// ── 用户 ──────────────────────────────────────────────
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
// 微信 openid:登录判定主键。首次登录验证手机号注册,后续登录 openid 在库即放行
|
||||
openid String @unique
|
||||
// 插件用户标识(当前未用插件,保留可空以兼容未来)
|
||||
openpid String? @unique
|
||||
unionid String?
|
||||
nickname String?
|
||||
avatar String?
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Body, Controller, Post } from '@nestjs/common';
|
||||
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Public } from '../common/decorators/public.decorator';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { LoginDto, RegisterDto } from './dto/login.dto';
|
||||
|
||||
@ApiTags('认证')
|
||||
@Controller('auth')
|
||||
@@ -11,10 +11,25 @@ export class AuthController {
|
||||
|
||||
@Public()
|
||||
@Post('login')
|
||||
@ApiOperation({ summary: '微信小程序登录(传 wx.login code)' })
|
||||
@ApiOkResponse({ schema: { example: { code: 0, message: 'ok', data: { accessToken: '...' } } } })
|
||||
async login(@Body() dto: LoginDto) {
|
||||
// 仅凭 code 由服务端换 openid,前端传不传 openid 一律忽略
|
||||
return this.authService.login(dto.code);
|
||||
@ApiOperation({ summary: '登录:wx.login code 换 openid,自动注册/续登并签发 token' })
|
||||
@ApiOkResponse({
|
||||
schema: {
|
||||
example: { code: 0, message: 'ok', data: { accessToken: '...' } },
|
||||
},
|
||||
})
|
||||
async login(@Body() dto: LoginDto): Promise<{ accessToken: string }> {
|
||||
return this.authService.login(dto);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('register')
|
||||
@ApiOperation({ summary: '可选:补全昵称/头像/手机号(企业主体场景)' })
|
||||
@ApiOkResponse({
|
||||
schema: {
|
||||
example: { code: 0, message: 'ok', data: { accessToken: '...' } },
|
||||
},
|
||||
})
|
||||
async register(@Body() dto: RegisterDto): Promise<{ accessToken: string }> {
|
||||
return this.authService.register(dto);
|
||||
}
|
||||
}
|
||||
|
||||
+62
-14
@@ -1,13 +1,18 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Redis } from 'ioredis';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { REDIS_CLIENT } from '../redis/redis.module';
|
||||
import { JwtPayload } from '../common/decorators/current-user.decorator';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { WechatService } from '../wechat/wechat.service';
|
||||
import { LoginDto, RegisterDto } from './dto/login.dto';
|
||||
|
||||
// session_key 在 Redis 的存储键与默认有效期(微信 session_key 约 30 天,这里保守用 7 天)
|
||||
// 注册凭证(registerTicket)在 Redis 的存储键与有效期
|
||||
const REG_TICKET_TTL = 10 * 60; // 10 分钟
|
||||
|
||||
// session_key 在 Redis 的存储键与有效期
|
||||
const SESSION_KEY_TTL = 7 * 24 * 60 * 60;
|
||||
|
||||
@Injectable()
|
||||
@@ -21,18 +26,24 @@ export class AuthService {
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 微信小程序登录核心流程:
|
||||
* 1. 用前端 code 调微信 code2Session 换 openid + session_key(不信任任何前端 openid)
|
||||
* 2. findOrCreate 用户
|
||||
* 3. session_key 存 Redis(供后续解密 encryptedData / phone)
|
||||
* 4. 签发自有 JWT 返回
|
||||
* 登录:以 openid 为唯一标识,自动注册/续登。
|
||||
* 只用前端 wx.login() 的 code 换取 openid(不信任前端传的任何 openid)。
|
||||
* - openid 已存在 -> 直接签发 token(后续登录)
|
||||
* - openid 不存在 -> 用 openid 建用户后签发 token(首次登录,无需手机号)
|
||||
*
|
||||
* 说明:个人主体小程序无 getPhoneNumber 权限,故不强制手机号注册。
|
||||
* 手机号采集留作未来换企业主体后可选补充(见 register())。
|
||||
*/
|
||||
async login(code: string): Promise<{ accessToken: string }> {
|
||||
const session = await this.wechat.code2Session(code);
|
||||
async login(dto: LoginDto): Promise<{ accessToken: string }> {
|
||||
const session = await this.wechat.code2Session(dto.code);
|
||||
|
||||
const user = await this.users.findOrCreateByOpenid(session.openid, session.unionid);
|
||||
// upsert:openid 在库则续登,不在库则直接建用户(无需手机号)
|
||||
const user = await this.users.findOrCreateByOpenid(
|
||||
session.openid,
|
||||
session.unionid,
|
||||
);
|
||||
|
||||
// 缓存 session_key,key 形如 wx:session:{userId}
|
||||
// 缓存 session_key(供后续解密 encryptedData / 数据签名校验)
|
||||
await this.redis.set(
|
||||
`wx:session:${user.id}`,
|
||||
session.sessionKey,
|
||||
@@ -40,14 +51,51 @@ export class AuthService {
|
||||
SESSION_KEY_TTL,
|
||||
);
|
||||
|
||||
const payload: JwtPayload = { sub: user.id, openid: user.openid };
|
||||
const accessToken = await this.jwt.signAsync(payload, {
|
||||
expiresIn: this.config.get<number>('jwt.expires'),
|
||||
const accessToken = await this.signToken(user.id, user.openid);
|
||||
return { accessToken };
|
||||
}
|
||||
|
||||
/**
|
||||
* 首次注册:用 registerTicket 换回 openid,验证手机号后创建用户并签发 token。
|
||||
* 手机号非空即视为注册完成。
|
||||
*/
|
||||
async register(dto: RegisterDto): Promise<{ accessToken: string }> {
|
||||
const key = `wx:reg_ticket:${dto.registerTicket}`;
|
||||
const raw = await this.redis.get(key);
|
||||
if (!raw) {
|
||||
throw new UnauthorizedException('注册凭证无效或已过期,请重新登录');
|
||||
}
|
||||
const ticket = JSON.parse(raw) as {
|
||||
openid: string;
|
||||
sessionKey?: string;
|
||||
unionid?: string | null;
|
||||
};
|
||||
|
||||
// 验证手机号;传 openid 让微信校验 code-openid 绑定关系,防串号
|
||||
const phone = await this.wechat.getUserPhoneNumber(dto.phoneCode, ticket.openid);
|
||||
|
||||
const user = await this.users.createWithOpenid(ticket.openid, {
|
||||
phone: phone.purePhoneNumber,
|
||||
nickname: dto.nickname,
|
||||
avatar: dto.avatar,
|
||||
unionid: ticket.unionid ?? undefined,
|
||||
});
|
||||
|
||||
// 一次性凭证,用完即弃
|
||||
await this.redis.del(key);
|
||||
|
||||
const accessToken = await this.signToken(user.id, user.openid);
|
||||
return { accessToken };
|
||||
}
|
||||
|
||||
/** 签发 JWT,payload 携带 userId(sub) 与 openid */
|
||||
private async signToken(userId: string, openid: string): Promise<string> {
|
||||
const payload: JwtPayload = { sub: userId, openid };
|
||||
return this.jwt.signAsync(payload, {
|
||||
expiresIn: this.config.get<number>('jwt.expires'),
|
||||
});
|
||||
}
|
||||
|
||||
/** 取出缓存的 session_key(供解密小程序加密数据用) */
|
||||
async getSessionKey(userId: string): Promise<string | null> {
|
||||
return this.redis.get(`wx:session:${userId}`);
|
||||
|
||||
@@ -1,9 +1,31 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty({ description: 'wx.login() 返回的临时登录 code', example: '0a3xxxxxx' })
|
||||
@ApiProperty({ description: 'wx.login() 的临时 code', example: '0a3xxxxxx' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
code!: string;
|
||||
}
|
||||
|
||||
export class RegisterDto {
|
||||
@ApiProperty({ description: '登录时返回的注册凭证(openid 暂存于服务端)' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
registerTicket!: string;
|
||||
|
||||
@ApiProperty({ description: 'wx.getPhoneNumber 拿到的手机号 code' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
phoneCode!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '昵称' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
nickname?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '头像 URL' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
// 从 req.user 取出当前登录用户(由 JwtStrategy.validate 注入)
|
||||
export interface JwtPayload {
|
||||
sub: string; // userId
|
||||
openid: string;
|
||||
openid: string; // 微信 openid(登录判定主键)
|
||||
}
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
|
||||
@@ -3,7 +3,7 @@ export default () => ({
|
||||
nodeEnv: process.env.NODE_ENV ?? 'development',
|
||||
isProd: process.env.NODE_ENV === 'production',
|
||||
app: {
|
||||
port: parseInt(process.env.APP_PORT ?? '3000', 10),
|
||||
port: parseInt(process.env.APP_PORT ?? '3090', 10),
|
||||
swaggerPath: process.env.SWAGGER_PATH ?? 'docs',
|
||||
},
|
||||
database: {
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as Joi from 'joi';
|
||||
// 启动时对环境变量做强校验:缺失关键项即 fail-fast,避免运行期才发现配置错误
|
||||
export const validationSchema = Joi.object({
|
||||
NODE_ENV: Joi.string().valid('development', 'production', 'test').default('development'),
|
||||
APP_PORT: Joi.number().default(3000),
|
||||
APP_PORT: Joi.number().default(3090),
|
||||
SWAGGER_PATH: Joi.string().allow('').default('docs'),
|
||||
|
||||
DATABASE_URL: Joi.string().required(),
|
||||
|
||||
@@ -5,7 +5,12 @@ import { PrismaService } from '../prisma/prisma.service';
|
||||
export class UsersService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
/** 按 openid 查询用户,不存在则创建(首次登录) */
|
||||
/** 按 openid 查询用户(登录判定主键) */
|
||||
async findByOpenid(openid: string) {
|
||||
return this.prisma.user.findUnique({ where: { openid } });
|
||||
}
|
||||
|
||||
/** 按 openid 查询,不存在则创建(首次登录自动注册,无需手机号) */
|
||||
async findOrCreateByOpenid(openid: string, unionid?: string) {
|
||||
return this.prisma.user.upsert({
|
||||
where: { openid },
|
||||
@@ -14,6 +19,16 @@ export class UsersService {
|
||||
});
|
||||
}
|
||||
|
||||
/** 首次注册:绑定手机号后创建用户(phone 非空 = 注册完成标记) */
|
||||
async createWithOpenid(
|
||||
openid: string,
|
||||
data: { phone?: string; nickname?: string; avatar?: string; unionid?: string },
|
||||
) {
|
||||
return this.prisma.user.create({
|
||||
data: { openid, ...data },
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id: string) {
|
||||
return this.prisma.user.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class CodeDto {
|
||||
@ApiProperty({ description: '前端拿到的临时 code', example: 'wx-plugin-login-code' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
code!: string;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Public } from '../common/decorators/public.decorator';
|
||||
import { WechatService } from './wechat.service';
|
||||
import { CodeDto } from './dto/code.dto';
|
||||
|
||||
@ApiTags('微信')
|
||||
@ApiBearerAuth()
|
||||
@Controller('wechat')
|
||||
export class WechatController {
|
||||
constructor(private readonly wechat: WechatService) {}
|
||||
|
||||
@Public()
|
||||
@Post('plugin-openpid')
|
||||
@ApiOperation({ summary: '获取插件用户 openpid(前端 wx.pluginLogin 的 code)' })
|
||||
async pluginOpenPid(@Body() dto: CodeDto) {
|
||||
return this.wechat.getPluginOpenPid(dto.code);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('phone')
|
||||
@ApiOperation({ summary: '获取用户手机号(前端 wx.getPhoneNumber 的 code)' })
|
||||
async phone(@Body() dto: CodeDto) {
|
||||
return this.wechat.getUserPhoneNumber(dto.code);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { WechatController } from './wechat.controller';
|
||||
import { WechatService } from './wechat.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
controllers: [WechatController],
|
||||
providers: [WechatService],
|
||||
exports: [WechatService],
|
||||
})
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common';
|
||||
import { Inject, Injectable, Logger, ServiceUnavailableException } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import Redis from 'ioredis';
|
||||
import axios from 'axios';
|
||||
import { REDIS_CLIENT } from '../redis/redis.module';
|
||||
|
||||
// code2Session 返回结构(微信 sns/jscode2session)
|
||||
export interface Code2SessionResult {
|
||||
@@ -9,6 +11,17 @@ export interface Code2SessionResult {
|
||||
unionid?: string;
|
||||
}
|
||||
|
||||
// access_token 缓存键与 TTL(微信 access_token 7200s,提前 5 分钟刷新)
|
||||
const ACCESS_TOKEN_KEY = 'wx:access_token';
|
||||
const ACCESS_TOKEN_TTL = 7200;
|
||||
|
||||
// getuserphonenumber 返回的手机号信息
|
||||
export interface PhoneInfo {
|
||||
phoneNumber: string;
|
||||
purePhoneNumber: string;
|
||||
countryCode: string;
|
||||
}
|
||||
|
||||
// 微信支付统一下单入参(预留,暂未实现)
|
||||
export interface UnifiedOrderInput {
|
||||
orderNo: string;
|
||||
@@ -22,7 +35,51 @@ export interface UnifiedOrderInput {
|
||||
export class WechatService {
|
||||
private readonly logger = new Logger(WechatService.name);
|
||||
|
||||
constructor(private readonly config: ConfigService) {}
|
||||
constructor(
|
||||
private readonly config: ConfigService,
|
||||
@Inject(REDIS_CLIENT) private readonly redis: Redis,
|
||||
) {}
|
||||
|
||||
/** 是否启用本地 mock(WX_MOCK_LOGIN=1),避免无真实 appid 时阻塞联调 */
|
||||
private get isMock(): boolean {
|
||||
return this.config.get<string>('wx.mockLogin') === '1';
|
||||
}
|
||||
|
||||
/** 调用微信接口前带 access_token 的统一错误处理 */
|
||||
private throwWechatError(prefix: string, data: { errcode?: number; errmsg?: string }): never {
|
||||
throw new ServiceUnavailableException(
|
||||
`${prefix}: ${data.errcode ?? 'unknown'} ${data.errmsg ?? ''}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取全局 access_token。优先读 Redis 缓存,未命中再向微信申请并缓存。
|
||||
* 注意:access_token 是全小程序共享的,不是用户维度,故用固定 key。
|
||||
*/
|
||||
async getAccessToken(): Promise<string> {
|
||||
const cached = await this.redis.get(ACCESS_TOKEN_KEY);
|
||||
if (cached) return cached;
|
||||
|
||||
const appid = this.config.get<string>('wx.appid');
|
||||
const secret = this.config.get<string>('wx.secret');
|
||||
const url = 'https://api.weixin.qq.com/cgi-bin/token';
|
||||
const params = { grant_type: 'client_credential', appid, secret };
|
||||
|
||||
try {
|
||||
const { data } = await axios.get(url, { params, timeout: 8000 });
|
||||
if (data.errcode) {
|
||||
this.throwWechatError('获取 access_token 失败', data);
|
||||
}
|
||||
// 提前 5 分钟过期,避免边界失效
|
||||
const ttl = Math.max(60, (data.expires_in || ACCESS_TOKEN_TTL) - 300);
|
||||
await this.redis.set(ACCESS_TOKEN_KEY, data.access_token, 'EX', ttl);
|
||||
return data.access_token as string;
|
||||
} catch (error) {
|
||||
if (error instanceof ServiceUnavailableException) throw error;
|
||||
this.logger.error('获取微信 access_token 失败', String(error));
|
||||
throw new ServiceUnavailableException('微信服务暂不可用');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用前端 wx.login() 的 code 换取 openid + session_key。
|
||||
@@ -33,7 +90,7 @@ export class WechatService {
|
||||
* 返回,用于走通登录链路(仅供开发,切勿在生产开启)。
|
||||
*/
|
||||
async code2Session(code: string): Promise<Code2SessionResult> {
|
||||
if (this.config.get<string>('wx.mockLogin') === '1') {
|
||||
if (this.isMock) {
|
||||
return { openid: `mock-${code}`, sessionKey: 'mock-session-key' };
|
||||
}
|
||||
|
||||
@@ -67,6 +124,62 @@ export class WechatService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 换取插件用户的唯一标识 openpid。
|
||||
* 前端需先用 wx.pluginLogin 拿到 code(5 分钟有效、一次性)。
|
||||
*/
|
||||
async getPluginOpenPid(code: string): Promise<{ openpid: string }> {
|
||||
if (this.isMock) {
|
||||
return { openpid: `mock-openpid-${code}` };
|
||||
}
|
||||
const accessToken = await this.getAccessToken();
|
||||
const url = `https://api.weixin.qq.com/wxa/getpluginopenpid?access_token=${accessToken}`;
|
||||
try {
|
||||
const { data } = await axios.post(url, { code }, { timeout: 8000 });
|
||||
if (data.errcode) {
|
||||
this.throwWechatError('获取插件用户 pid 失败', data);
|
||||
}
|
||||
return { openpid: data.openpid as string };
|
||||
} catch (error) {
|
||||
if (error instanceof ServiceUnavailableException) throw error;
|
||||
this.logger.error('调用 getpluginopenpid 失败', String(error));
|
||||
throw new ServiceUnavailableException('微信服务暂不可用');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用前端 wx.getPhoneNumber 拿到的 code 换取用户手机号。
|
||||
* 传入 openid 时微信会校验 code 与 openid 是否绑定(防串号)。
|
||||
*/
|
||||
async getUserPhoneNumber(code: string, openid?: string): Promise<PhoneInfo> {
|
||||
if (this.isMock) {
|
||||
return {
|
||||
phoneNumber: '13800000000',
|
||||
purePhoneNumber: '13800000000',
|
||||
countryCode: '86',
|
||||
};
|
||||
}
|
||||
const accessToken = await this.getAccessToken();
|
||||
const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`;
|
||||
const payload = openid ? { code, openid } : { code };
|
||||
try {
|
||||
const { data } = await axios.post(url, payload, { timeout: 8000 });
|
||||
if (data.errcode) {
|
||||
this.throwWechatError('获取手机号失败', data);
|
||||
}
|
||||
const p = data.phone_info || {};
|
||||
return {
|
||||
phoneNumber: p.phoneNumber as string,
|
||||
purePhoneNumber: p.purePhoneNumber as string,
|
||||
countryCode: p.countryCode as string,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof ServiceUnavailableException) throw error;
|
||||
this.logger.error('调用 getphonenumber 失败', String(error));
|
||||
throw new ServiceUnavailableException('微信服务暂不可用');
|
||||
}
|
||||
}
|
||||
|
||||
// ── 以下为微信支付 V3 预留接口,本轮仅占位 ──────────────
|
||||
// TODO: 接入微信支付 V3(统一下单 / 回调验签 / 查单 / 退款)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user