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:
@@ -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