Build a subscription system with Stripe and Express js.
May 08, 2022 12pm ET
1. Set Up Stripe And Express.
- First, Install the corresponding libraries.
Install through npm
npm install express npm install stripe --save
- Create a .env file in the project root; please, don't expose your keys directly in the code!
Next, create Index.js; this file will be the data entry point. Create a middleware that will check if the HTTP request is directed to the webhook; if it is, let the request pass without parsing it as a JSON object; otherwise, parse the data and redirect it to the Express router. If you parse the webhook data, Stripe will reject it. We will implement the webhook in a separate blog due to its complexity.
Create the Express router file, and start by importing Stripe and the secret key; the first HTTP method is a router post. This method will create the customer using the email and full name. If the customer creation is susccesful, send back to the frontend the customer id. In production, collect more parameters from the customer, the address and phone number; here, you can check the list of parameters that you can send to Stripe.
The second router post method is subscription creation. Destruct the request body and extract the customer id and the price id, send them to Stripe using the subscription create function. If the create subscription function is successful; retrieve the subscription id and the client secret; Send them back to the front end as a JSON object.
The last router method is the subscription delete route. In order to delete the subscription, we need the subscription id, create a login system in your application to let the users delete their subscriptions, and retrieve the subscription id from your local database.