Defaultblog

Raw Body for Stripe Webhooks using Firebase Cloud Functions

coding firebase stripe software development

So today, I was implementing a Stripe Webhook for a Firebase application. The webhook would be implemented as a cloud function and I wanted to implement the code to verify that the request was securely coming from the proper Stripe servers.

The Stripe team has great documentation on how to do this with application like Node and Ruby. It's all documented here.

I was using Javascript in Firebase Cloud Functions so I followed the Node.js example. At one point in the documentation, they talk about verifying the authenticity of the request by calling stripe.webhooks.constructEvent and passing in a secret key, the payload from request.body, and a signature header.

However, every time I tried it, I kept getting an error about the payload not matching the signature. I was even pointed to this documentation that gave me a hint about the using the Raw Data here.

So I tried to JSON.stringify the incoming request body with no luck.

Luckily, shortly after, I realized you can easily get the rawBody contents:

exports.stripeWebhook = functions.https.onRequest((request, response) => {
  const stripeWebhookSecretKey = functions.config().stripe.webhook_secret_key;

  let event;

  ...
  const payloadData = request.rawBody;
  const payloadString = payloadData.toString();
  const webhookStripeSignatureHeader = request.headers['stripe-signature'];

  event = stripe.webhooks.constructEvent(payloadString, webhookStripeSignatureHeader, stripeWebhookSecretKey);
  ...
});

By calling request.rawBody.toString(), you can get exactly what stripe.webhooks.constructEvent needs.

Caseyli
Casey Li
CEO & Founder, BiteSite