Stripe Webhooks: How to configure

Hey guys,

I am implementing Stripe Checkout on my app and need to configure a webhook for an event. However, after following all documentation and forum posts I could find, I still couldn’t get anywhere.

Can someone please give me a short explanation on how to get this done?

What I have done so far:

  • Declared a server-side route (my endpoint) using meteorhacks:picker and parsed incoming data with body-parser
  • Created a test webhook on the Stripe dashboard
  • Downloaded and configured ngrok to test webhooks on localhost
  • Read the MeteorChef tutorials (not working, probably too old)

What I would like to learn:

  • How to get the data from the endpoint route and do something with it?
  • Stripe mentions the need to “verify the webhook signature” using their official libraries. How do I do this on Meteor?

If you have some boilerplate code I could simply adapt, it would be awesome…

Thanks a lot!

Ours looks like this:


import stripe from "stripe";

const bound = Meteor.bindEnvironment(callback => callback());

WebApp.rawConnectHandlers.use("/payment", (req, res, next) => {
  const sig = req.headers["stripe-signature"];
  const endpointSecret = Meteor.settings.STRIPE_WEBHOOK_SK;
  const stripeObj = stripe(Meteor.settings.STRIPE_SK);
  if (req.method === "POST") {
    let body = "";
    req.on("data", data => bound(() => {
      body += data;
    }));
    req.on("end", () => bound(() => {
      try {
        const eventObj = stripeObj.webhooks.constructEvent(body, sig, endpointSecret);
        const eventData = eventObj.data;
        const result = invokeStripeEvent(eventObj, eventData.object);
        res.writeHead(200);
        res.end(result);
      }
      catch (error) {
        res.writeHead(500);
        console.warn("[Payment Gateway Exception]: ", error);
        if (error.type && error.type === "StripeSignatureVerificationError") {
          res.end("We caught you -_-");
        }
        else {
          res.end(JSON.stringify(error, Object.getOwnPropertyNames(error)));
        }
      }
    }));
  }
  else {
    next();
  }
});
6 Likes

I also like to verify the origin ip against https://stripe.com/docs/ips#webhook-ip-addresses so that you can halt the request more quickly if you know it’s bad data.

4 Likes

Thanks for the code, can you please tell me what invokeStripeEvent(eventObj, eventData.object) is doing?

That’s where the magic happens - highly app specific (and obviously proprietary)

Ah I see. :slight_smile:
I was just wondering if stripe needs a response to the hook and how this result should look like?

The response is a HTTP response code - I think anything except 200 will cause stripe to retry (though this is probably documented somewhere).

1 Like

Thanks man, your code saved my week :v: