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

如何在Strapi中集成Stripe Webhook并配置专属中间件获取原始请求体

配置Strapi中间件仅针对Stripe Webhook路由保留原始请求体

1. 恢复全局Body中间件默认配置

首先修改config/middlewares.js,移除全局的includeUnparsed配置,避免影响所有路由:

module.exports = [
  'strapi::errors',
  'strapi::security',
  'strapi::cors',
  'strapi::poweredBy',
  'strapi::logger',
  'strapi::query',
  'strapi::body', // 恢复默认配置
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
];

2. 为Stripe Webhook路由单独配置中间件

在src/api/stripe-webhook/routes/stripe-webhook.js(无对应目录则新建)中定义Webhook路由,并单独开启该路由的原始请求体保留:

module.exports = {
  routes: [
    {
      method: 'POST',
      path: '/stripe-webhook', // 匹配你的Stripe Webhook回调地址
      handler: 'stripe-webhook.handleWebhook',
      config: {
        middlewares: [
          {
            name: 'strapi::body',
            config: {
              includeUnparsed: true, // 仅此路由生效
            },
          },
        ],
      },
    },
  ],
};

3. 在控制器中获取原始请求体

在对应控制器src/api/stripe-webhook/controllers/stripe-webhook.js里,通过ctx.request.bodyUnparsed获取原始请求体,用于Stripe签名验证:

'use strict';

module.exports = {
  async handleWebhook(ctx) {
    // 读取原始请求体
    const rawBody = ctx.request.bodyUnparsed.toString('utf8');
    const stripeSignature = ctx.request.headers['stripe-signature'];

    // 执行Stripe签名验证与事件处理
    // 示例代码:
    // const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
    // const event = stripe.webhooks.constructEvent(
    //   rawBody,
    //   stripeSignature,
    //   process.env.STRIPE_WEBHOOK_SECRET
    // );

    ctx.status = 200;
    return { received: true };
  },
};

关键注意点

  • 确保Stripe后台配置的Webhook回调路径与你定义的路由路径完全一致
  • 务必在环境变量中存储Stripe的API密钥与Webhook密钥,避免硬编码
  • 该方案适配Strapi v4版本,若使用v3需调整路由与控制器的结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 12:45:22