如何在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
相关产品推荐
相关产品推荐

