Create A Subscription Service with Stripe in NodeJS & Express
Here’s how to create a backend service for recurring charges for your customers with Stripe.
With subscriptions, customers can make recurring payments for access to a product. Subscriptions are not so different from one-time purchases — only that they are recurring and requires you to hold onto your customers’ information so you can charge them automatically.
This tutorial will guide you to setup a backend application in NodeJS and Express to setup a subscription service.
Navigate to your project folder and create a file named index.js. Once you’re done, install Express, HTTP, Body-Parser, and Stripe.
npm i express
npm i http
npm i body-parser
npm i stripe
We’ll next code for our server to use routes and body parser to handle data.
const express = require("express");
const app = express();
const routes = require('./stripe-module/route');
const bodyParser = require('body-parser')
const http = require('http');app.use(cors());
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));const port = 8001;
app.set('port', port);
app.use(routes);const server = http.createServer(app);
server.listen(port, () => {
console.log(`Express server listening on port ${port}`);
});
To keep things organized, let’s create a folder to hold the service , controller, and route javascript files. Name it stripe-module.
Create a file named service.js. Inside we’ll write a function that sends a request to Stripe. The required parameters for this to work is a customer’s ID and an array of price items the customer is subscribing for.
Note: Remember to add your stripe key for this work!
const stripe = require('stripe')('sk_test_key_here');
const service = {};service.createSubscription = (customerId, items) => {
return stripe.subscriptions.create({
customer: customerId,
items: items
});
}module.exports = service;
We’ll next create a controller that acquires data from the request and sends it over to the service. Create a file named controller.js and write the following code.
const service = require('./service');
const controller = {};controller.createSubscription = async(req, res) => {
const { customerId, items } = req.body;
try {
const subscription =
await service.createSubscription(customerId, items);
res.json({ response: subscription });
} catch (error) {
console.error(error);
return res.status(400).json({ error: error.message });
}
};module.exports = controller;
Lastly, let’s setup the route that trigger the subscription request. Create a file named router.js and write the following code in it.
const router = require('express').Router();
const controller = require('./controller');const subscriptionMiddleware = [
controller.createSubscription
];
router.post('/subscribe', subscriptionMiddleware)module.exports = router;
That’s it! Run the app with npm run start or node index.js and send a request using Postman.
Remember to add the customerId and items — as an array — to the body of this post request. Below is an example of how I did that using JSON.
Thanks for reading & Happy Coding! 🚀