API with NestJS #39. Reacting to Stripe events with webhooks

JavaScript NestJS TypeScript

This entry is part 39 of 148 in the API with NestJS

So far, in this series, we’ve interacted with Stripe by sending requests. It was either by requesting the Stripe API directly on the frontend, or the backend. With webhooks, Stripe can communicate with us the other way around.

Webhook is a URL in our API  that Stripe can request to send us various events such as information about payments or customer updates. In this article, we explore the idea of Webhooks and implement them into our application to avoid asking Stripe about the status of user’s subscriptions. By doing that, we aim to improve the performance of our application and avoid exceeding rate limits.

Using Stripe webhooks with NestJS

We aim to develop with Stripe webhooks while running the application on localhost. When working with webhooks, we expect Stripe to make requests to our API. By default, our app can’t be accessed from outside while running locally. Because of that, we need an additional step to test webhooks. To perform it, we need Stripe CLI. We can download it here.

We need to forward received events to our local API. To do it, we need to run the following:

Handling webhook signing secret

In response, we receive the webhook signing secret. We will need it in our API to validate requests made to our endpoint.

A valid approach is to keep the webhook secret in our environment variables.

app.module.ts

.env

Accessing the raw body of a request

NestJS uses the body-parser library to parse incoming request bodies. Because of that, we don’t get to access the raw body straightforwardly. The Stripe package that we need to use to work with webhooks requires it, though.

To deal with the above issue, we can create a middleware that attaches the raw body to the request.

rawBody.middleware.ts

If you want to know more about middleware, check out TypeScript Express tutorial #1. Middleware, routing, and controllers

Above, we use the interface. We need to define it.

requestWithRawBody.interface.ts

For the middleware to work, we need to use it in our function.

main.ts

Parsing the webhook request

When Stripe requests our webhook route, we need to parse the request. To do that successfully, we need three things:

  • the webhook secret,
  • the raw request payload,
  • the request header.

With the header we can verify that the events were sent by Stripe and not by some third party.

When we have all of the above, we can use the Stripe library to construct the event data.

stripe.service.ts

The last step in managing the Stripe webhook with NestJS is to create a controller with the route.

stripeWebhook.controller.ts

Tracking the status of subscriptions

One of the things we could do with webhooks is tracking the status of subscriptions. To do that, let’s expand the entity.

user.entity.ts

We also need a way to set the property. To do that, we need a new method in our :

users.service.ts

To use the above logic, we need to expand our :

stripeWebhook.controller.ts

Above, we had to sort out some TypeScript issues. Currently, Stripe recommends casting to deal with them.

In our flow, Stripe calls our endpoint and sends us events. We check if they are connected to subscriptions by checking the property. If that’s the case, we can assume that the property is a subscription. With that knowledge, we can update the property of a user.

Webhook idempotency

According to the Stripe documentation, Stripe might occasionally send the same event more than once. They advise us to create a mechanism to guard the application against processing the same event multiple times and making our event processing idempotent.

One way of doing so would be to keep the id of every processed event in the database.

stripeEvent.entity.ts

Please notice that above we define a primary column that is not auto-generated. We aim to use the event id from Stripe to populate this column.

stripeWebhook.service.ts

A crucial thing to notice is that the throws an error when we try to use an id that already exists in the database. We can use it to improve our .

stripeWebhook.controller.ts

Since our controller keeps growing, let’s move part of the logic to our .

stripeWebhook.service.ts

With the above code, our endpoint throws an error when Stripe sends the same event again.

Deleting old events with cron might be a good idea. If you want to do that, check out API with NestJS #25. Sending scheduled emails with cron and Nodemailer

Summary

In this article, we’ve learned more about Stripe and improved our application by reacting to Stripe events. To do that, we’ve had to implement a webhook that accepts requests from Stripe. When doing so, we’ve started to track changes in the subscription statuses. We’ve also made sure that we don’t parse the same event more than once.

Series Navigation<< API with NestJS #38. Setting up recurring payments via subscriptions with StripeAPI with NestJS #40. Confirming the email address >>
Subscribe
Notify of
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Wiktor
Wiktor
1 year ago

There is so much useful information. Not only in this article but also from others. Thank you!

Last edited 1 year ago by Wiktor
Benjamin
Benjamin
11 months ago

You don’t need a middleware for raw bodies anymore. You can just do this:

Last edited 11 months ago by Benjamin
Ernesto
Ernesto
11 months ago

Cant believe I found the solution here xD thanks for it!

Michał
10 months ago

good article but I think to ensure idempotency we need to run both inserting StripeEvent and changing User’s state as part of db transaction.

Another thing – we shouldn’t throw error when event was already processed because Stripe will retry.

Last edited 10 months ago by Michał