0

I've been trying to listen to Stripe webhooks with firebase functions:

here is my code:

import * as bodyParser from 'body-parser'
import * as express from 'express';
const app = express();
app.use(bodyParser.raw({ type: '*/*' }));
const stripe = new stripeM("test_token");;
const stripeWHEndpointSecret = 'secret';


app.post('*', (req, res) => {
    const sig = req.headers["stripe-signature"];
    console.log(sig);
    try {
        const event = stripe.webhooks.constructEvent(req.body, sig, stripeWHEndpointSecret);
        console.log(event);

    }
    catch (err) {
        console.log(util.inspect(err));
        res.status(400).end();
    }   
    res.json({received: true});
});
export const stripeWebhooksListener = functions.https.onRequest(app);

and I keep getting this error: SyntaxError: Unexpected token o in JSON at position 1

Now i understand it's a problem with parsing the req.body as it arrives in chunks probably. but, I thought that using the Express with body-parser should solve it.

Any help will be appreciated

Stripe official documentation on how to do it: https://stripe.com/docs/webhooks/signatures

Shahar Wider
  • 447
  • 5
  • 21

1 Answers1

1

The following works for me, with req.rawBody:

const event = stripe.webhooks.constructEvent(req.rawBody, sig, stripeWHEndpointSecret);
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • For some reason i don't have a rawBody property for req :error TS2339: Property 'rawBody' does not exist on type 'Request' – Shahar Wider May 03 '18 at 07:30
  • i have only this: const event = stripe.webhooks.constructEvent(req.body.rawBody , sig, stripeWHEndpointSecret); which doesn't work – Shahar Wider May 03 '18 at 07:43
  • Would this help? https://stackoverflow.com/questions/44383387/typescript-error-property-user-does-not-exist-on-type-request?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa or https://github.com/Microsoft/TypeScript/issues/15199 – Renaud Tarnec May 03 '18 at 08:06
  • The second one doesn't help, the first one suggest extending Request from express... do you suggest extending Request with rawBody? (i'm not sure how will it help me?) Thanks, Shahar – Shahar Wider May 06 '18 at 10:38