You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fastify中获取原始请求体用于Stripe签名验证失败求助

Fastify中Stripe Webhook签名验证失败:无法获取原始请求体及多解析器配置问题

我在Fastify中对接Stripe Webhook时,需要获取原始请求体完成签名验证,但尝试了多种方法(包括Stack Overflow上的多数解决方案)均无效。

路由注册代码

export const paymentRoutes = (app: FastifyInstance, _opts: any, done: Function) => {
app.register(rawbody, {
  field: 'rawBody',
  global: false,
  encoding: 'utf8',
  runFirst: true,
});
app.route({
  method: ['GET', 'POST'],
  url: '/webhook',
  config: {
    rawBody: true,
  },
  handler: subscriptionWebhook,
});
})

Fastify服务初始化代码

export default class App {
  public app: any;
  public port: number;

  constructor(port ?: number) {
    this.app = fastify({
      querystringParser: (query: string) => qs.parse(query),
    });
    this.port = port || config.app.port;
    this.setup();
  }

  public setup() {
    this.app.register(helmet);
    this.app.register(cors, {
      credentials: true,
      origin: ['https://localhost:3000'],
      'Access-Control-Allow-Origin': true,
      'Access-Control-Allow-Methods': 'PUT,GET,POST,DELETE,PATCH',
    });

    //Content Parser : that I cannot remove from every route. Is there any way to add 2 different parsers one on specific route and other one on rest of the routes

    this.app.addContentTypeParser(
      'application/json', {
        parseAs: 'string',
        bodyLimit: 120000000
      },
      (_: any, body: any, done: any) => {
        try {
          const json = JSON.parse(body as string);
          done(null, json);
        } catch (e: any) {
          e.statusCode = 400;
          done(e);
        }
      },
    );

  }
}

错误信息

调用stripe.webhooks.constructEvent(body, sig, endpointSecret)时,无论传入rawBody还是body,均抛出错误:

reason: StripeSignatureVerificationError: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?

疑问

我无法移除全局的内容解析器,请问能否为特定路由和其余路由配置不同的内容解析器?

内容的提问来源于stack exchange,提问作者Joy Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:33:21