NestJS集成Stripe Webhook遇rawBody未定义问题求助
解决Nest.js中Stripe Webhook无法获取rawBody的问题
以下是针对你遇到的req.rawBody为undefined导致Stripe签名验证失败的解决方案:
1. 手动配置body-parser保留原始请求体
直接在main.ts中配置body-parser的verify方法,针对Webhook路由单独保留原始请求体:
import { json } from 'body-parser'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // 配置body-parser,为Webhook路由保留rawBody app.use(json({ verify: (req, res, buf) => { // 匹配你的Webhook路由路径 if (req.originalUrl.startsWith('/panier/webhook')) { (req as any).rawBody = buf.toString(); } }, })); await app.listen(3000); } bootstrap();
2. 使用Nest.js内置@RawBody装饰器(Nest.js 9+)
如果你的Nest.js版本是9或以上,直接用@RawBody()装饰器获取原始请求体,无需手动操作req对象:
import { Controller, Post, Headers, RawBody, BadRequestException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import Stripe from 'stripe'; @Controller('panier') export class PanierController { private stripe: Stripe; constructor(private config: ConfigService) { this.stripe = new Stripe(this.config.get('STRIPE_SECRET')); } @Post('webhook') async incomingEvents( @Headers('stripe-signature') signature: string, @RawBody() rawBody: Buffer ) { const webhookSecret = this.config.get('STRIPE_WEBHOOK_SECRET'); if (!signature) { throw new BadRequestException('Missing stripe signature'); } let event; try { event = this.stripe.webhooks.constructEvent(rawBody, signature, webhookSecret); } catch (err) { console.error(err.message); throw new Error('Webhook signature verification failed.'); } console.log(event); } }
3. 排查全局中间件/拦截器干扰
如果项目中存在全局拦截器、管道或中间件,检查是否有提前解析并修改请求体的逻辑。可以针对Webhook路由跳过这些处理:
- 在全局中间件中判断路由路径,跳过Webhook的请求体解析
- 在控制器方法上使用
@UseInterceptors()或@UsePipes()显式排除全局处理
4. 对齐依赖版本
确保@nestjs/platform-express、@types/express和stripe版本兼容,更新依赖:
npm install @nestjs/platform-express@latest @types/express@latest stripe@latest
问题原因说明
直接设置rawBody: true无效通常是因为:
- 默认的
body-parser会解析请求体并丢弃原始数据,需手动配置保留 - 全局中间件或拦截器提前处理了请求,覆盖或清除了
rawBody - 旧版本Nest.js对
rawBody的支持不完善,需用装饰器或手动配置
内容的提问来源于stack exchange,提问作者Ibrahim Yahyaoui
相关产品推荐
相关产品推荐

