Clojure, Stripe Webhooks & You
Let’s say we have a monolithic RESTful API written in clojure. Let’s also say we want to add stripe subscriptions to it so we can take people’s money.
Stripe is amazing. Worth every penny. Nothing more to say there, let’s talk libraries. There are a few clojure libraries that we could use for calling the api but we’re focused on webhooks so they aren’t going to help us that much.
Stripe has one object for every action in the system: events. The easiest and most naive way (my favorite way) to get this thing going is to just receive the request and dump everything straight into the database. Since we’re using postgres as the database (although I would love to use hitchhiker trees I think… somehow), we’ll need three things:
That’s pretty much it, let’s test it out. There is this thing but sadly it doesn’t support the latest versions of the api. I like to use localtunnel. Install it and then run
lt --port <your port> from the terminal.
Then go to your stripe dashboard and click webhooks, add your localtunnel url, SEND DAT WEBHOOK and watch the 🎩 magic happen.
Seems like we’re finished with the webhooks, but there’s actually quite a bit of work to do still, testing seems like it could be a good idea. Not to mention that stripe also wants you to send a request back to their servers after you receive the webhook request with the id they sent, that way you can verify that stripe actually sent you something and it’s not some crazy PR forging bitcoin miner trying to troll you. So let’s do that.
Aside from the utils reference which uses two functions
flip which both do basically what they sound they like they do, there’s really only one function that stands out:
make-url . This function may be slow, but is very useful if you’ve ever dealt with environment variables or some sort of configuration file where it looks like this
https://api.stripe.com/v1/ and then someone calls a function that looks like this
(get "/events/123") and the
get function naively does string concatenation and results in a url that looks like this
req function uses
make-url and makes a request map with or without a body and puts the stripe token and api url in there as well. The
res function likewise handles the response. The nice thing about this is that making a request map is separate from when the request is made, so there’s easy testing, like so!
Not the best code out there, but that’ll do 🐖. The next step would probably be to actually make the call back to events which would probably look like this
And that is how you receive stripe webhooks in your monolith like a pro or something resembling a pro, maybe.