DEV Community

naval
naval

Posted on

How to test Stripe webhook handlers without a Stripe account

Webhook bugs rarely show up when you click through a checkout once. They show up when events arrive twice, late, or out of order. Here is a way to replay those on your machine with no Stripe account, no network and no Docker.

1. Sign your own test events

The Stripe SDK can generate a valid signature header for any payload:

import Stripe from 'stripe';

const stripe = new Stripe('sk_test_never_used');
const secret = 'whsec_test_secret';

async function deliver(handler, event) {
  const payload = JSON.stringify(event);
  const header = stripe.webhooks.generateTestHeaderString({ payload, secret });
  const res = await handler(new Request('http://localhost/api/stripe/webhook', {
    method: 'POST',
    headers: { 'stripe-signature': header },
    body: payload,
  }));
  return res.status;
}
Enter fullscreen mode Exit fullscreen mode

Signatures are checked against the raw body, so don't parse the JSON first. Any non-2xx status makes Stripe retry, so what you return decides whether an event gets another chance.

2. Replace Stripe's API with a map

If your handler re-fetches the subscription (it should, since an event can be older than the current state):

const state = new Map();
const fakeStripe = {
  async retrieveSubscription(id) {
    return structuredClone(state.get(id));
  },
};
Enter fullscreen mode Exit fullscreen mode

Now you control what "Stripe says right now".

3. Use a real Postgres

Concurrency and constraint bugs don't show up against a mock. The embedded-postgres package starts a throwaway Postgres from a script.

4. Test the cases that break handlers

  • Same event twice: the row should be written once, and both calls should return 200.
  • Late event after a cancel: set the state to canceled and deliver the deleted event. Then set the state back to active, which is what a stale read looks like, and deliver an older updated event. The row should stay canceled.
  • Event before the user exists: answer with an error so Stripe retries, and check that nothing was written. Answering 200 and dropping it leaves a customer who paid and stays on the free plan, with no alert.

What this doesn't cover

A fake Stripe won't catch changes in Stripe's real API. Keep one test that runs against test mode.

A working version

I put these three cases in a script: npm run demo in https://github.com/navalpro8-lgtm/stripe-subscription-sync (MIT), file scripts/demo.mjs. If there's a case it should cover and doesn't, I'd like to hear it.

Top comments (2)

Collapse
 
krusenas profile image
Karolis •

Stripe stops retrying after about three days in live mode, so 'answer with an error so it retries' only covers short outages. Down longer than that and the event's gone, your app has no way to know. fwiw that's why I built Webhook Relay, it stores every delivery and replays the failed ones once your endpoint's back.

Collapse
 
navalpro8lgtm profile image
naval •

fair point, "error so it retries" only covers short outages. after about 3 days the event is just gone. thats what the scheduled reconcile is for, it compares stripe's subscriptions with the db instead of waiting for a redelivery