Get raw request body in custom controller

System Information
  • Strapi Version:
  • Operating System:
  • Database:
  • Node Version:
  • NPM Version:
  • Yarn Version:

Hello Friends,

I am trying to integrate Stripe Payment Gateway’s Webhook in my Strapi setup. Webhook is working and being called remotely. But Stripe requires the raw body content to construct the event which fails saying that:

‘No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? GitHub - stripe/stripe-node: Node.js library for the Stripe API.

I am sure you guys have gone through the issue if implemented the Stripe. Can help on this?
P.S. I am using version 4.0.1

Thanks.

1 Like

Hello, I was trying to integrate with Stripe as well and I was running into the same problem. It seems like nobody answered it and the docs are not detailing this, but you can configure your middlewares.

If your ./config/middlewares.js looks reads the following:

module.exports = [
        'strapi::errors',
        'strapi::security',
        'strapi::poweredBy',
        'strapi::logger',
        'strapi::query',
        { name: 'strapi::body', config: { includeUnparsed: true } },
        'strapi::session',
        'strapi::favicon',
        'strapi::public',
    ]

basically, replacing the default strapi::body for the one with the config set.

Then, from your endpoint you can run:

const unparsed = require('koa-body/unparsed.js');

module.exports = {
    async webhook(ctx) {
        const unparsedBody = ctx.prequest.body[unparsed];
        const signature = ctx.request.headers['stripe-signature'];
        let event;

        try {
            event = stripe.webhooks.constructEvent(
                unparsedBody,
                signature,
                endpointSecret
            );
        } catch (err) {
            return ctx.badRequest(`Webhook Error: ${err.message}`);
        }

        // Return a response to acknowledge receipt of the event
        return { received: true };

I hope it helps!

2 Likes

Thank you for this solution! I’ve looked for hours and this one worked for Strapi v4. Bumping for the search algorithm or any others that are lost.