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

1 Answer 1

1

The following works for me, with req.rawBody:

const event = stripe.webhooks.constructEvent(req.rawBody, sig, stripeWHEndpointSecret);
Sign up to request clarification or add additional context in comments.

5 Comments

For some reason i don't have a rawBody property for req :error TS2339: Property 'rawBody' does not exist on type 'Request'
i have only this: const event = stripe.webhooks.constructEvent(req.body.rawBody , sig, stripeWHEndpointSecret); which doesn't work
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
I think the property rawBody doesn't exist anymore as of 2024

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.