Skip to main content

Command Palette

Search for a command to run...

Payment Integration - Stripe

Published
4 min read
M

As a former 3D Animator with more than 12 years of experience, I have always been fascinated by the intersection of technology and creativity. That's why I recently shifted my career towards MERN stack development and software engineering, where I have been serving since 2021.

With my background in 3D animation, I bring a unique perspective to software development, combining creativity and technical expertise to build innovative and visually engaging applications. I have a passion for learning and staying up-to-date with the latest technologies and best practices, and I enjoy collaborating with cross-functional teams to solve complex problems and create seamless user experiences.

In my current role as a MERN stack developer, I have been responsible for developing and implementing web applications using MongoDB, Express, React, and Node.js. I have also gained experience in Agile development methodologies, version control with Git, and cloud-based deployment using platforms like Heroku and AWS.

I am committed to delivering high-quality work that meets the needs of both clients and end-users, and I am always seeking new challenges and opportunities to grow both personally and professionally.

Stripe Payment Integration: A Beginner's Guide

This guide will walk you through integrating Stripe payment processing into a web application using Node.js, Express.js, and React.js.

Prerequisites

  • Node.js installed

  • Basic knowledge of JavaScript, Node.js, Express.js, and React.js

  • A Stripe account (you can sign up at Stripe)

Step 0: Create a Product and Price in Stripe

Using Stripe Dashboard

  1. Log in to your Stripe Dashboard: Stripe Dashboard.

  2. Navigate to Products: Click on the "Products" tab in the left sidebar.

  3. Create a New Product:

    • Click the "Add product" button.

    • Fill in the product details like name, description, etc., and save it.

  4. Add a Price to the Product:

    • After saving the product, go to the product details page.

    • Click on "Add price".

    • Choose the pricing model (e.g., one-time or recurring).

    • Set the price amount, currency, etc., and save it.

  5. Obtain the Price ID: After saving, note the Price ID (e.g., price_1JXdxZ2eZvKYlo2C5Y1S0hFj).

Step 1: Set Up Stripe

  1. Sign Up for Stripe: Create an account on Stripe and log in to the dashboard.

  2. Get API Keys: Navigate to the Developers section and copy your Publishable Key and Secret Key. These keys are used to authenticate your application with Stripe.

Step 2: Backend Setup (Node.js and Express.js)

  1. Initialize a Node.js Project:

     mkdir stripe-integration
     cd stripe-integration
     npm init -y
    
  2. Install Dependencies:

     npm install express stripe body-parser
    
  3. Create the Express Server: Create a file named server.js:

     const express = require('express');
     const bodyParser = require('body-parser');
     const stripe = require('stripe')('your-secret-key');
    
     const app = express();
     const PORT = process.env.PORT || 5000;
    
     app.use(bodyParser.json());
    
     app.post('/create-checkout-session', async (req, res) => {
       const { priceId } = req.body;
    
       try {
         const session = await stripe.checkout.sessions.create({
           payment_method_types: ['card'],
           line_items: [
             {
               price: priceId,
               quantity: 1,
             },
           ],
           mode: 'payment',
           success_url: 'http://localhost:3000/success',
           cancel_url: 'http://localhost:3000/cancel',
         });
    
         res.status(200).send({
           sessionId: session.id,
         });
       } catch (error) {
         res.status(500).send({ error: error.message });
       }
     });
    
     app.listen(PORT, () => {
       console.log(`Server is running on port ${PORT}`);
     });
    
  4. Replace your-secret-key: Replace 'your-secret-key' with your actual Stripe Secret Key.

  5. Run the Server:

     node server.js
    

Step 3: Frontend Setup (React.js)

  1. Create a React App:

     npx create-react-app stripe-frontend
     cd stripe-frontend
    
  2. Install Stripe.js and React Stripe.js:

     npm install @stripe/react-stripe-js @stripe/stripe-js
    
  3. Create Payment Component: Create a file named Payment.js in the src directory:

     import React, { useState } from 'react';
     import { loadStripe } from '@stripe/stripe-js';
    
     const stripePromise = loadStripe('your-publishable-key');
    
     const Payment = () => {
       const [sessionId, setSessionId] = useState(null);
       const [priceId, setPriceId] = useState('');
    
       const createCheckoutSession = async () => {
         const response = await fetch('http://localhost:5000/create-checkout-session', {
           method: 'POST',
           headers: {
             'Content-Type': 'application/json',
           },
           body: JSON.stringify({ priceId }),
         });
    
         const session = await response.json();
         setSessionId(session.sessionId);
       };
    
       const handleClick = async () => {
         const stripe = await stripePromise;
    
         const { error } = await stripe.redirectToCheckout({
           sessionId,
         });
    
         if (error) {
           console.error('Stripe checkout error:', error);
         }
       };
    
       return (
         <div>
           <h2>Stripe Payment</h2>
           <input
             type="text"
             placeholder="Enter Price ID"
             value={priceId}
             onChange={(e) => setPriceId(e.target.value)}
           />
           <button onClick={createCheckoutSession}>Create Checkout Session</button>
           {sessionId && (
             <button onClick={handleClick}>Go to Checkout</button>
           )}
         </div>
       );
     };
    
     export default Payment;
    
  4. Update App Component: Update the App.js file to use the Payment component:

     import React from 'react';
     import Payment from './Payment';
    
     function App() {
       return (
         <div className="App">
           <header className="App-header">
             <h1>Stripe Payment Integration</h1>
             <Payment />
           </header>
         </div>
       );
     }
    
     export default App;
    
  5. Run the React App:

     npm start
    

Explanation

  1. Backend:

    • We set up an Express server with a single route /create-checkout-session that creates a Checkout Session using Stripe's API. The Checkout Session is used to handle the payment process.

    • We use the Stripe secret key to authenticate API requests.

  2. Frontend:

    • We create a Payment component using @stripe/react-stripe-js to handle payment UI and interactions.

    • The Payment component allows the user to input a Price ID and create a Checkout Session.

    • Once the Checkout Session is created, the user can be redirected to the Stripe Checkout page to complete the payment.

Conclusion

This guide provides a basic understanding of integrating Stripe Checkout Sessions using Node.js, Express.js, and React.js. For more advanced use cases, such as handling different currencies, saving customer details, or managing subscriptions, refer to the official Stripe documentation.

Instructor: Muhammad Sufiyan

Linkedin: https://www.linkedin.com/in/innosufiyan/