Stripe Events with Webhooks

Implement Stripe Webhooks in your subscription system with Express js.

Denisse Avatar

By:

Denisse Abreu
May 23, 2022 8pm ET

Eng/Spa 3-min

Hello 🖐🏼, this is the third part of our guide, Build a subscription system with Stripe and Express js. In this tutorial, We'll connect the Stripe Webhook to our subscription system. Webhooks are an integral part of any subscription system. When people subscribe, change and cancel their subscription, your system needs to listen for these events on-demand and update your database to grant or reject access to your service. For this project, I'm using Express. If you don't have a project, you can copy mine here: Vue Stripe Subscriptions.

1. Set Up Stripe.

Install the Stripe package and the Stripe CLI according to your operating system. Stripe CLI installation Guide.


  npm install stripe --save
  
  • Create a .env file in the project root; please, don't expose your keys directly in the code!
.env

Configure a middleware to separate webhook events from other post requests that your app may have. This is because webhooks can't be parsed as JSON objects.

server/index.js

2. Start the Stripe CLI console.

Open your terminal and type stripe -v to check the Stripe installation. If the Stripe CLI is not installed on your computer, go to Get started with the Stripe CLI, then type stripe login and stripe listen --forward-to localhost:3000/api/posts/webhook to redirect the webhook triggers to your node js server. If you want to use your secret key, use the --api-key flag. Ensure your pairing code is the same in the Stripe Browser; If the pairing code is correct, you will receive your webhook secret, insert this secret in your .env file and restart your server. For more information about setting up the Stripe CLI, check this example Listen to Stripe events.

Command Prompt

  • Start listening for events inside the webhook endpoint; if everything is good, you will receive 200 ok responses from Stripe.

Command Prompt Stripe Response

  • Alternately, you can trigger different events using the Stripe Shell

Stripe Shell

  • Stripe switch cases from the console logs; Remember to delete the console logs and use the dataObject.status to manipulate your database.

Vscode Terminal

3. Start your Stripe integration testing.

The following code is the complete webhook route; instead of logging each case, query your database to grant, update or cancel subscription services. Consult Stripe subscriptions event list for more switch cases.

server/posts.js