Last Updated: December 07, 2017
·
8.144K
· colinm

Be lazy when testing Stripe webhooks

Work smarter, not harder! Time and again I've seen developers ripping out their hair while trying to test their Stripe webhook integrations. Don't involve your controllers. Don't create JSON. Don't fight with WebMock. It doesn't have to be that hard. Stripe loves you.

(And if you're handling webhooks in a controller, move that out to a service object.)

Have you checked out the docs?

Stripe::Event in their Ruby library offers a construct_from constructor which accepts a Hash. Pass in a hash and you get back a Stripe::Event just like the ones you request via the API. For maximum laziness, use symbols for keys instead of strings.

Now you can unit test without the Stripe servers, a network, a controller, or JSON:

describe SomeClass do
  h = {
        id: 'evt_1234567',
        type: 'charge.succeeded',
        other: 'useful',
        data_goes: 'here'
      }
  event = Stripe::Event.construct_from(h)

  it 'has an event id' do
    expect(event.id).to eq('evt_1234567')
  end
end

Not working with Ruby? Similar constructors are available in their other libraries. Take advantage of them!

Important Note: Please don't use this knowledge to shoot yourself in the face. That would make me sad. Even sadder than running integration tests needlessly. DO NOT use construct_from to turn POST data into a Stripe::Event in production.

Follow Stripe's best practices; the data coming in from the webhook should be presumed fraudulent. When working with live data, grab the id from the webhook, discard everything else, and request the event via the Stripe API.

4 Responses
Add your response

Sorry? How is this helpful? If we are using something like stripe_events gem to handle webhooks how does the above actually help us test the functionality of the events?

over 1 year ago ·

This is for testing custom integrations.

If you're using something like stripe_events—which wasn't released at the time I wrote this tip—then obviously you need to work within the constraints of that library. That library's documentation is probably your best bet there.

over 1 year ago ·

Since this post was written Aug 2013, any idea if this still works? Because it does not seem to on the Stripe Node.js library.

over 1 year ago ·

Thank you very much, this makes a great deal of sense to me, simplified my integration... Really don't care Stripe can deliver the event to us successfully, only care to test what we do if we receive an event. Wonderful solution, thank you!

over 1 year ago ·