DEV Community

Suneel Kumar
Suneel Kumar

Posted on • Updated on

How to Create a Stripe Subscription with React and Node.js

How to Create a Stripe Subscription with React and Node.js

Stripe is a popular payment gateway that allows businesses to accept payments online. In this article, we'll explore how to create a subscription system using React and Node.js. Subscriptions allow businesses to charge customers recurring fees, such as monthly or annual fees, for access to their products or services.

Before we begin, it's important to note that you'll need to have a Stripe account set up and a basic understanding of React and Node.js.

Setting up the Backend with Node.js

We'll start by setting up the backend using Node.js. We'll use the Express framework to build our API, and the Stripe npm package to interact with the Stripe API.

To get started, create a new Node.js project and install the necessary packages:

$ mkdir my-subscription-app
$ cd my-subscription-app
$ npm init -y
$ npm install express stripe

Next, create an index.js file in the root of your project and add the following code:

const express = require("express");
const stripe = require("stripe")("<your_stripe_secret_key>");

const app = express();
app.use(express.json());

app.post("/create-subscription", async (req, res) => {
  const customer = await stripe.customers.create({
    email: req.body.email,
    source: req.body.stripeToken,
  });

  const subscription = await stripe.subscriptions.create({
    customer: customer.id,
    items: [{ plan: req.body.plan }],
  });

  res.json({ subscription });
});

app.listen(3000,() => {
console.log("Server running on port 3000");
});
Enter fullscreen mode Exit fullscreen mode

In the code above, we've created an endpoint at /create-subscription that will create a new customer and a new subscription in Stripe when a POST request is made to this endpoint.

2. Setting up the Frontend with React

Next, we'll set up the frontend using React. We'll use the react-stripe-elements library to easily integrate Stripe's payment form into our React app.

To get started, create a new React project and install the necessary packages:

$ npx create-react-app my-subscription-app-frontend
$ cd my-subscription-app-frontend
$ npm install @stripe/react-stripe-js @stripe/stripe-js react-stripe-elements
Enter fullscreen mode Exit fullscreen mode

Next, create a SubscriptionForm.js file in your React project and add the following code:

import React, { useState } from "react";
import { useStripe, useElements, CardElement } from "@stripe/react-stripe-js";
import { createSubscription } from "./api";

const SubscriptionForm = () => {
const [error, setError] = useState(null);
const [success, setSuccess] = useState(false);
const stripe = useStripe();
const elements = useElements();

const handleSubmit = async (event) => {
event.preventDefault();
if (!stripe || !elements) {
  return;
}

const cardElement = elements.getElement(CardElement);

try {
  const { error, paymentMethod }
= await stripe.createPaymentMethod({
type: "card",
card: cardElement,
});
  if (error) {
    setError(error.message);
    return;
  }

  const { id } = paymentMethod;
  const response = await createSubscription({
    email: event.target.email.value,
    plan: event.target.plan.value,
    stripeToken: id,
  });

  if (response.error) {
    setError(response.error);
    return;
  }

  setSuccess(true);
} catch (error) {
  setError(error.message);
}
};

return (
<form onSubmit={handleSubmit}>
<input type="email" name="email" placeholder="Email" required />
<select name="plan" required>
<option value="plan_1">Plan 1</option>
<option value="plan_2">Plan 2</option>
<option value="plan_3">Plan 3</option>
</select>
<CardElement />
{error && <p style={{ color: "red" }}>{error}</p>}
{success && <p style={{ color: "green" }}>Subscription created!</p>}
<button type="submit" disabled={!stripe}>
Subscribe
</button>
</form>
);
};

export default SubscriptionForm;

Enter fullscreen mode Exit fullscreen mode

In the code above, we've created a form that allows a user to enter their email, select a plan, and enter their payment information. When the form is submitted, the payment information is passed to the Stripe API to create a payment method, and then passed to our Node.js API to create a new customer and subscription.

  1. Putting it all together

Finally, we'll need to bring the frontend and backend together by making the API call from the React app to the Node.js API.

Create a new file api.js in your React project and add the following code:

export const createSubscription = async (data) => {
const response = await fetch("http://localhost:3000/create-subscription", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});

return response.json();
};
Enter fullscreen mode Exit fullscreen mode

In this code, we're using the fetch API to make a POST request to the /create-subscription endpoint in our Node.js API.

Now, import the SubscriptionForm component into your React app's main file and render it to the screen.

And that's it! You now have a working subscription system using React and Node.js with Stripe. Of course, there are many other features and optimizations you can add, but this should give you a solid foundation to build upon.

please follow me on https://codingmoze.com/

I hope you found this article helpful. If you have any questions or comments, please feel free to reach out!

Top comments (0)