Writing unit tests for stripe webhooks stripe-signature

Viewed 1880

I'm trying to write unit tests for Stripe webhooks. The problem is I'm also verifying the stripe-signature and it fails as expected.

Is there a way to pass a correct signature in tests to the webhook with mock data?

This is the beginning of the webhook route I'm trying to handle

// Retrieve the event by verifying the signature using the raw body and secret.
let event: Stripe.Event;
const signature = headers["stripe-signature"];

try {
  event = stripe.webhooks.constructEvent(
    raw,
    signature,
    context.env.stripeWebhookSecret
  );
} catch (err) {
  throw new ResourceError(RouteErrorCode.STRIPE_WEBHOOK_SIGNATURE_VERIFICATION_FAILD);
}

// Handle event...

And the current test I'm trying to handle, I'm using Jest:

const postData = { MOCK WEBHOOK EVENT DATA }

const result = await request(app.app)
  .post("/webhook/stripe")
  .set('stripe-signature', 'HOW TO GET THIS SIGNATURE?')
  .send(postData);
3 Answers

Stripe now exposes a function in its node library that they recommend for creating signatures for testing:

Testing Webhook signing

You can use stripe.webhooks.generateTestHeaderString to mock webhook events that come from Stripe:

const payload = {
  id: 'evt_test_webhook',
  object: 'event',
};

const payloadString = JSON.stringify(payload, null, 2);
const secret = 'whsec_test_secret';

const header = stripe.webhooks.generateTestHeaderString({
  payload: payloadString,
  secret,
});

const event = stripe.webhooks.constructEvent(payloadString, header, secret);

// Do something with mocked signed event
expect(event.id).to.equal(payload.id);

ref: https://github.com/stripe/stripe-node#webhook-signing

With the help of Nolan I was able to get the signature working. In case anyone else needs help, this is what I did:

import { createHmac } from 'crypto';

const unixtime = Math.floor(new Date().getTime() / 1000);

// Calculate the signature using the UNIX timestamp, postData and webhook secret
const signature = createHmac('sha256', stripeWebhookSecret)
  .update(`${unixtime}.${JSON.stringify(postData)}`, 'utf8')
  .digest('hex');

// Set the stripe-signature header with the v1 signature
// v0 can be any value since its not used in the signature calculation
const result = await request(app.app)
  .post("/webhook/stripe")
  .set('stripe-signature', `t=${unixtime},v1=${signature},v0=ff`)
  .send(postData);

If you are in ruby you can do:

      Stripe::Webhook::Signature.generate_header(
        Time.now,
        Stripe::Webhook::Signature.compute_signature(
          Time.now,
          payload,
          secret
        )
      )
Related