Get raw request body in custom controller

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!

7 Likes