Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the raw body on a custom made endpoint on strapi?

Tags:

strapi

I'm building a custom endpoint on Strapi. For this endpoint, I need to have the raw body content. Is it possible to obtain it from the ctx variable?

stripe : async(ctx) => {
    // Handle the event
    const sig = ctx.request.headers['stripe-signature']
    
    let event = null
    try {
      // ctx.request.body needs to be the original raw body
      event = stripe.webhooks.constructEvent(ctx.request.body,sig, endpointSecret)
    }catch (e) {
      ctx.badRequest(null,e)
      return
    }
like image 704
Rui Figueiredo Avatar asked Oct 03 '19 14:10

Rui Figueiredo


2 Answers

Create a middleware (/config/middleware.js) and update it to the following

module.exports = {
  settings: {
    cors: {
      enabled: true,
    },
    parser: {
      enabled: true,
      multipart: true,
      includeUnparsed: true,
    },
  },
};

In the controller (/api/<model>/controllers/<model>.js):

const unparsed = require("koa-body/unparsed.js");
const unparsedBody = ctx.request.body[unparsed];
like image 159
Abhishek E H Avatar answered Nov 15 '22 18:11

Abhishek E H


The official koa-bodyparser package actually does this out of the box. See: https://github.com/koajs/bodyparser#raw-body

Here is a small example:

import Koa from 'koa';
import KoaRouter from '@koa/router';
import koaBodyParser from 'koa-bodyparser';

const app = new Koa();
const router = new KoaRouter();

const stripeCheckout = (ctx, next) => {
  const sig = ctx.request.header['stripe-signature'];
  
  let event;
  
  if (!process.env.STRIPE_ENDPOINT_SECRET) {
    throw new Error('Missing Stripe endpoint secret.');
  }
  
  try {
    event = stripe.webhooks.constructEvent(
      ctx.request.rawBody,
      sig,
      endpointSecret: process.env.STRIPE_ENDPOINT_SECRET
    );
  } catch (err) {
    logger('error', err);
    
    ctx.status = 400;
    ctx.body = `Webhook Error: ${err.message}`;
    
    return next();
  }
  
  // ... do something with the event
  
  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;
    
    // ... do something with the checkout session
  }
  
  // return a response to acknowledge receipt of the event
  ctx.status = 200;
  ctx.body = { received: true };
  
  return next();
};

// POST
router.post('/stripe-checkout', stripeCheckout);

app.use(koaBodyParser());

app.use(router.routes());
app.use(router.allowedMethods());

app.listen(port, () => {
  logger('log', `✅  Done! Server is listening on http://localhost:${port}`);
});
like image 22
Zino Hofmann Avatar answered Nov 15 '22 20:11

Zino Hofmann