Node.js Implementation of Stripe Checkout Subscriptions and Webhooks

Posted by


In this tutorial, we will walk through setting up a subscription-based payment system using Stripe Checkout and Webhooks with Node.js. Stripe Checkout makes it easy to design and customize a checkout experience while webhooks allow you to receive real-time notifications on various events in your Stripe account.

Prerequisites:

  1. Node.js installed on your machine
  2. Basic knowledge of JavaScript and Node.js
  3. A Stripe account (if you don’t already have one, sign up at https://stripe.com/)

Step 1: Setting up a Node.js project
First, create a new Node.js project by running the following commands in your terminal:

mkdir stripe-subscription
cd stripe-subscription
npm init -y

Next, install the stripe and express packages by running:

npm install stripe express

Step 2: Setting up Stripe API keys
Log in to your Stripe account and navigate to the Developers section. Under the API keys tab, you will find your publishable and secret API keys. Copy these keys and store them in a .env file in the root of your project directory:

STRIPE_PUBLISHABLE_KEY=your_stripe_publishable_key
STRIPE_SECRET_KEY=your_stripe_secret_key

Step 3: Setting up an Express server
Create a new file named server.js in your project directory. Add the following code to set up an Express server and configure it to use the Stripe API keys from the .env file:

require('dotenv').config();
const express = require('express');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

const app = express();

app.use(express.static('public'));
app.use(express.json());

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

Step 4: Creating a Stripe Checkout session
Next, we will create a route to handle creating a new Stripe Checkout session for a subscription. Add the following code to your server.js file:

app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
      {
        price: 'price_1IwSHqLKpys1qP7fNLyy2mwa', // Replace with your price ID
        quantity: 1
      }
    ],
    mode: 'subscription',
    success_url: 'http://localhost:3000/success.html',
    cancel_url: 'http://localhost:3000/cancel.html'
  });

  res.json({ sessionId: session.id });
});

In this code, we are creating a new Stripe Checkout session with a single subscription item. Replace the price value with your own price ID.

Step 5: Setting up a success and cancel page
Create two HTML files named success.html and cancel.html in a public directory in your project. Add some simple messages to each file to indicate success and cancellation of the subscription.

Step 6: Handling webhook events
To handle webhook events such as successful payments and cancellations, we need to set up a webhook endpoint in our Node.js server. Add the following code to your server.js file:

const endpointSecret = 'whsec_...'; // Replace with your webhook secret

app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
  const sig = req.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
  } catch (err) {
    res.status(400).send(`Webhook Error: ${err.message}`);
    return;
  }

  switch (event.type) {
    case 'payment_intent.succeeded':
      // Handle successful payment
      break;
    case 'checkout.session.completed':
      // Handle completed checkout session
      break;
    case 'customer.subscription.deleted':
      // Handle deleted subscription
      break;
    default:
      // Handle other events
      break;
  }

  res.status(200).send();
});

In this code, we are verifying the webhook signature, parsing the event, and handling different event types. Replace the endpointSecret value with your own webhook signing secret.

Step 7: Testing the setup
Start your Express server by running node server.js in your terminal. Visit http://localhost:3000 in your browser and trigger the payment flow to test the subscription creation process.

You can test webhook events by using the Stripe CLI or triggering events from your Stripe Dashboard. Make sure to replace the endpointSecret value with the actual signing secret from your webhook settings.

That’s it! You have successfully set up a subscription-based payment system with Stripe Checkout and Webhooks using Node.js. Feel free to customize and expand upon this setup to fit your specific needs.

0 0 votes
Article Rating

Leave a Reply

19 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@VidaAlexandru
2 hours ago

Very good tutorial, thank you for this!

@ArmyBhadaja
2 hours ago

After subscription expire it will auto renew? What can we do for auto pay according this

@SouravRooj
2 hours ago

Thanks a lot. Sometime ago, I didn't have knowledge about the Stripe payment gateway system. After watching both of your videos, I learned so many things about Stripe and subscriptions. Thanks, man. Love you from India.

@Karrnfr
2 hours ago

Hey man. Thank you for this

@vinhbuihoang2871
2 hours ago

Thanks you a lot.

@condra1332
2 hours ago

Thank you very much. Very long time before I started to understand this. Now I got it .

@rossp87
2 hours ago

How does it work if someone wants to upgrade part way through the month? Ie get more licenses or something

@the-code-provider
2 hours ago

Thank you a lot, it's the first time I found a 1 hour tutorial video REALLY interesting and well built !
I didn't lost my time, your lesson is pure gold, thanks again !

@Superuser-r1y
2 hours ago

Have you also explain subscription plan changed event in this toturial?

@Jake-r9s
2 hours ago

This was perfect. -exactly what I was looking for

@Jake-r9s
2 hours ago

THANK YOU

@Jake-r9s
2 hours ago

THANK YOU

@onicar
2 hours ago

I just want to add a comment for the algorithm so more people see this video. Searched for many guides and this is the one.

@luliboluli4109
2 hours ago

I'm loving this video hopefully I will be able to integrate this code I'm using html,css,javascript and node.js I put my product id's on my plan buttons on html, use them on javascript and parse them to the server . I'm new in this gateway technology I might needsome help can you be a point of contact? Other than that I love your work keep it up

@RR-et6zp
2 hours ago

really looking forward to a stripe connect standard vid if possible (for a marketplace like uber, where the app takes eg. 10%)

@radhescript
2 hours ago

Node js video streaming app

@dharsanr6504
2 hours ago

Need full production grade projects from you , and congrats keep going 💪💪

@aneeshbakshi7200
2 hours ago

You are awesome. I just had a project requirement to build a subscription payment gateway. Thanks a lot.

@Marvelous71
2 hours ago

There is no courses on stripe on ytb clearly ty man ❤

19
0
Would love your thoughts, please comment.x
()
x