Stripe Webhooks
Learn how NextKit handles Stripe Webhooks in your application
NextKit handles five webhooks from Stripe and stores "just enough" data into the organization's entity to function correctly.
The Stripe's webhooks topics are defined here at app/core/stripe/stripe-webhooks.enum.ts
:
To handle webhooks, we created an API route at app/api/stripe/webhook.ts
.
This route is responsible for:
- Validating that the webhook is coming from Stripe
- Routing the webhook to its handler
Validating Stripe's Webhooks
To validate the webhook, we do the following:
- get the header 'stripe-signature'
- create a Stripe instance
- get the raw body
- call
constructEvent
to validate and build an event object sent by Stripe. When this fails, it will throw an error
Handling Stripe's Webhooks
After validating the webhook, we can now handle the webhook type relative to its topic:
As described above, we handle 5 events:
Completed
: the checkout session was completed (but payment may not have arrived yet if it's asynchronous)SubscriptionDeleted
: the subscription was deleted by the customerSubscriptionUpdated
: the subscription was updated by the customer
Checkout Completed
When a user completes the checkout session, we create the subscription
object on the currently connected user's organization.
The subscription's object has the following interface:
This interface is added to the Organization
object.
Subscription Updated
When a subscription is updated, we rebuild the subscription object and update it in the organization's Database row.
Subscription Deleted
When a subscription is deleted, we simply remove it from the organization entity.
Adding additional webhooks
If you want to add additional webhooks, you can do so by adding a new case in the switch statement.
For example, if you want to handle the customer.subscription.trial_will_end
event, you can do so by adding the following case:
Adding additional data to the subscription object
If you want to add additional data to the subscription object, you can do so by adding the data to the OrganizationSubscription
interface.
For example, if you want to add the quantity
property to the subscription object, you can do so by adding the following property to the interface:
Then you will update the subscription
table in the PostgreSQL database to add the quantity
column.
Finally, you can add the data to the subscription object using the subscriptionMapper
function: