HomeBlogWeb DevelopmentHow to Integrate Stripe Payment Gateway in Node.js App?

How to Integrate Stripe Payment Gateway in Node.js App?

Published
02nd Jul, 2024
Views
view count loader
Read it in
13 Mins
In this article
    How to Integrate Stripe Payment Gateway in Node.js App?

    Integrating Stripe's APIs into Node.js has marked a significant leap forward in online payment processing for me. Stripe, with its robust and intuitive platform, simplifies financial transactions on the web, offering tools for one-time fees and subscription models. Node.js, a potent JavaScript runtime, is praised for its effectiveness and scalability in managing server-side operations. 

    This blend of Stripe's flexible payment infrastructure and Node.js's performance-driven design allows developers to integrate the Stripe Payment Gateway and create secure, dependable, and smooth payment experiences. If you’re looking to enter Web Development, enroll in our course to learn Node.js. This article is helpful for those looking to integrate Stripe Payment Gateway into Node.js applications. 

    How to Integrate Stripe Payments in Node.js App?

    Payment gateways make it easier for you to stripe integration in Node JS into your app and for users to pay through it. There are multiple payment gateways in the market, including Paytm, Razorpay, and others. But Stripe is one of the most often used gateways. Integrate Stripe payment gateway into your app to utilize its powerful software and APIs, which are used by millions of companies, from small startups to major corporations, to collect payments, send payouts, and manage their businesses online. Not only does Stripe help with payment, but it also helps you to send invoices to your customers after the payments using Stripe invoice.

    Stripe has very clean API documentation to get started. In this article, we’ll use React and Node.js to create our application and integrate Stripe payments in Node.js into it. Explore our Full Stack Developer Bootcamp to work on similar live projects while learning. 

    Here is a listicle of the steps on how to integrate stripe payments in Node.js: 

    • Step 1: Create Stripe Account
    • Step 2: Get Tokens
    • Step 3: Setting up the Node.js Server
    • Step 4: Create the Server
    • Step 5: Code Setup - Create React App
    • Step 6: Setting Up the Frontend
    • Step 7: Test Card Details

    Before getting started, make sure you have Node.js installed in your system. Alternatively, you can install it from here. 

    Step 1: Create Stripe Account

    In order to use Stripe, you need to register yourself on Stripe.

    Create Stripe Account
    AppStudio  If you have already registered, you can sign in using the link below Create Account button.  

    Stripe Requirements  

    Once you sign in to your Stripe account, you may be required to go through some necessary steps in order to activate payments. Make sure you go through it. After you’re done, you’ll be redirected to the Stripe Dashboard similar to below. 

    stripe dashboard
    Stripe Support 

    On the top left of the dashboard, you’ll find an option to create a new account. Click on New Account, add your Account Name and Country of Operation and click on Create account.  

    Once you create a new account, you’ll be required to activate the payments again for this account.  

    Step 2: Get Tokens

    Once you’re done with all the steps mentioned above, click on the Developers button on the top-right of the dashboard. Then click on the API Keys to go to the page where you’ll get your Standard Keys to authenticate API requests. 

    Get Tokens
    ContinuousCare  

    These keys are test data and cannot be used in actual payments. Once you activate your account, you can enable live keys as well. 

    Step 3: Setting up the Node.js Server 

    Before jumping to the front-end, you’re going to create the Node.js server that will interact with Stripe and handle the payments. For the sake of simplicity, we’ll use as few dependencies as required. The dependencies required for the backend are as follows: 

    • cors: You’ll require cors middleware because you will be making requests to the Stripe server. 
    • express: You’ll use express to create the backend server. 
    • stripe: The stripe npm dependency will help you access the Stripe API from your server. 
    • dotenv: This dependency will help you manage your environment variables and store your secret keys. 
    • nodemon: This dependency automatically restarts the Node.js application when file changes are detected in the directory. 

    While you’ll create a simple application in this article, you can create a far better web application as you learn Node.js at KnowledgeHut.

    Project Initialization

    Before getting started, create a folder named backend, where you can store all your backend code right here. Now, fire up your terminal in this directory and follow along. 

    To create a Node project, use the below command: 

    >> npm init 

    It will ask you for some details, which are not that important for the sake of this article. 

    After you’re done, you will find a package.json file in your backend directory. Now, open this directory in your favorite code editor and create a file named index.js inside it. Make sure the filename is the same as the entry point you have set during the project initialization. 

    Now, use the command below to install all the dependencies mentioned above: 

    >> npm i cors express stripe dotenv nodemon 

    Let us also add the script to start the Node.js server in the package.json file. 

    { 
      "name""backend", 
      "version""1.0.0", 
      "description""Sample backend server for integrating Stripe payments", 
      "main""index.js", 
      "scripts": { 
        "start""nodemon index.js" 
      }, 
      "author""Ashutosh Krishna", 
      "license""ISC", 
      "dependencies": { 
        "cors""^2.8.5", 
        "dotenv""^16.0.1", 
        "express""^4.18.1", 
        "nodemon""^2.0.19", 
        "stripe""^9.14.0", 
        "uuid""^8.3.2" 
      } 
    }  

    Now, create a file named .env where you will store your secret keys. The contents of the file should be similar to the below: 

    STRIPE_PUBLISHABLE_KEY=your-publishable-key-here 
    STRIPE_SECRET_KEY=your-secret-key-here 

    We can load these environment variables using the dotenv dependency and then access them as process.env.KEY_NAME. 

    Step 4: Create the Server  

    Now let us create our server in the index.js file. 

    In the script below, we’ll import the required dependencies first. Then, create an app using express. The required middleware is also defined. A sample route is created, which just responds with a Hello World message. The server listens on port 8000. 

    Notice how we load the environment variables using the dotenv dependency and used them. 

    const cors = require("cors"); 
    const express = require("express"); 
    require("dotenv").config(); 
     
    const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY); 
     
    const app = express(); 
     
    // Middlewares here 
    app.use(express.json()); 
    app.use(cors()); 
     
    // Routes here 
    app.get("/", (req, res) => { 
      res.send("Hello World"); 
    }); 
     
    // Listen 
    app.listen(8000, () => { 
      console.log("Server started at port 8000"); 
    }); 

    Once you run the server using the npm start command, you can go to http://localhost:8000 on your browser, and you will find your Hello World message there. 

    Now you need a POST route that can be hit by the front-end. In this route, you’ll create a customer and will charge the amount. Let us create this route now. 

    app.post("/api/create-checkout-session"async (req, res) => { 
      const { product } = req.body; 
      const session = await stripe.checkout.sessions.create({ 
        payment_method_types: ["card"], 
        line_items: [ 
          { 
            price_data: { 
              currency: "inr", 
              product_data: { 
                name: product.name, 
              }, 
              unit_amount: product.price * 100, 
            }, 
            quantity: product.quantity, 
          }, 
        ], 
        mode: "payment", 
        success_url: "http://localhost:3000/success", 
        cancel_url: "http://localhost:3000/cancel", 
      }); 
      res.json({ id: session.id }); 
    }); 

    In the above script, an asynchronous “/api/create-session-checkout” POST route is created. Inside the function, the product is fetched from the request's body. This product shall be passed from the front end. Next, you’re creating a Stripe checkout session where you declare the payment method type as card, the price and product details, the mode, and the success and cancel URLs. You can add more details about the product if you wish to. Integrate Stripe payment gateway to streamline this process. Refer to the Stripe documentation to learn more about this. The function responds with an id, that is, the session's id. This id is used by Stripe later. That’s pretty much about the backend part of our application. 

    Step 5: Code Setup - Create React App  

    Now that you have a backend server ready, it’s time to create a React app that can make use of the backend server. When you install npm, you get npx too. For the sake of the article, you’re going to create a React app named frontend. To create a React app, you can use the below command: 

    >> npx create-react-app frontend 

    The command will set up a sample React app. To see if the setup is working fine, you can run the npm start command. If you see the below output, your setup is ready. 

    npx create-react-app frontend
    Visual Studio Code  

    Installing dependencies  

    Now, before you start working on the front-end of the application, you need to install a few dependencies here too. They are: 

    • react-router-dom: This dependency is used to create single-page applications, and will help you in routing. 
    • @stripe/stripe-js: This dependency helps you use Stripe.js as an ES module.  
    • react-bootstrap: This is an optional dependency you’re going to use for styling your application using Bootstrap. 

    Now, as always, to install the above-mentioned dependencies, you need to run the following command: 

    >> npm i react-router-dom @stripe/stripe-js react-bootstrap 

    Step 6: Setting Up the Frontend 

    Here comes the main frontend task now. You’re going to create three components - one for the checkout page where you’ll have a simple product card with a pay button, one for the success page and the final one for the cancel page. These all components will be present inside a components directory inside the src folder.  

    Checkout Page 

    Inside the components directory, create a file named StripePayment.js. Let us import all the dependencies we’d be using in the component: 

    import React, { useState } from "react"; 
    import "bootstrap/dist/css/bootstrap.min.css"; 
    import Button from "react-bootstrap/Button"; 
    import Card from "react-bootstrap/Card"; 
    import { loadStripe } from "@stripe/stripe-js"; 

    Now, create an empty function called StripePayment and export it as below: 

    function StripePayment() { 
    } 
    export default StripePayment; 

    Now, we will require something to buy. Let us create a simple product with few details in the function as below: 

    function StripePayment() { 
      const [product, setProduct] = useState({ 
        name: "Go FullStack with KnowledgeHut", 
        price: 1000, 
        productOwner: "KnowledgeHut", 
        description: "This beginner-friendly Full-Stack Web Development Course is offered online in blended learning mode, and also in an on-demand self-paced format.", 
        quantity: 1, 
      }); 
    } 
    export default StripePayment; 

    To create a product, we have used the useState() function. The product contains few details such as name, price, productOwner, description and quantity. Now, let us create a product card using react-bootstrap inside the function.  

    import React, { useState } from "react"; 
    import "bootstrap/dist/css/bootstrap.min.css"; 
    import Button from "react-bootstrap/Button"; 
    import Card from "react-bootstrap/Card"; 
     
    function StripePayment() { 
      const [product, setProduct] = useState({ 
        name: "Go FullStack with KnowledgeHut", 
        price: 1000, 
        productOwner: "KnowledgeHut", 
        description: 
          "This beginner-friendly Full-Stack Web Development Course is offered online in blended learning mode, and also in an on-demand self-paced format.", 
        quantity: 1, 
      }); 
     
      return ( 
        <Card style={{ width: "20rem" }}> 
          <Card.Img 
            variant="top" src="https://images.pexels.com/photos/12428359/pexels-photo-12428359.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" 
          /> 
          <Card.Body> 
            <Card.Title>{product.name}</Card.Title> 
            <Card.Text>{product.description}</Card.Text> 
            <Button variant="primary" onClick={makePayment}> 
              Buy Now for {product.price} 
            </Button> 
          </Card.Body> 
        </Card> 
      ); 
    }  
    export default StripePayment; 

    The above script is pretty easy to understand where you have created a Bootstrap card with top-image, card title, card body text and a button. We have also added an onClick parameter on the button, which calls a makePayment function. Let us create the makePayment function now. 

    const makePayment = async () => { 
        const stripe = await loadStripe("your-publishable-key"); 
        const body = { product }; 
        const headers = { 
          "Content-Type""application/json", 
        }; 
     
        const response = await fetch( 
          "http://localhost:8000/api/create-checkout-session", 
          { 
            method: "POST", 
            headers: headers, 
            body: JSON.stringify(body), 
          } 
        ); 
     
        const session = await response.json(); 
     
        const result = stripe.redirectToCheckout({ 
          sessionId: session.id, 
        }); 
     
        if (result.error) { 
          console.log(result.error); 
        } 
      }; 

    The makePayment is an asynchronous function that makes requests to our backend server. An instance of Stripe is loaded using the loadStripe function. The product is added in the body of the request. Do you remember we sent a session id in the response from the backend? This session id is then extracted from the response and provided to the redirectToCheckout function from the stripe dependency.  

    Success and Cancel Pages

    In addition to the checkout page, you’ll create two other pages for success and canceled transactions. Inside the components directory, create two files - Success.js and Cancel.js. 

    Success.js 
    import React from "react"; 
     
    function Success() { 
      return ( 
        <> 
          <h2>Thanks for your order!</h2> 
          <h4>Your payment is successful.</h4> 
          <p> 
            We appreciate your business! If you have any questions, please email us 
            at 
            <a href="mailto:orders@example.com">orders@example.com</a>. 
          </p> 
          <div> 
          </div> 
        </> 
      ); 
    } 
     
    export default Success; 
    Cancel.js 
    import React from "react"; 
     
    function Cancel() { 
      return ( 
        <> 
          <h4>Oops! Your payment has been cancelled.</h4> 
          <p> 
            We appreciate your business! If you have any questions, please email us 
            at 
            <a href="mailto:orders@example.com">orders@example.com</a>. 
          </p> 
          <div> 
            <button> Go to Home page</button> 
          </div> 
        </> 
      ); 
    } 
     
    export default Cancel; 

    Routing the Components   

    Now that all the components are ready, you’ll need to route them as below: 

    • “/” : Checkout Page 
    • “/success” : Success Page 
    • “/cancel” : Cancel Page 

    To route the pages, you’re going to use react-router-dom as below: 

    import React from "react"; 
    import { BrowserRouter, Routes, Route } from "react-router-dom"; 
    import StripePayment from "./components/StripePayment"; 
    import Success from "./components/Success"; 
    import Cancel from "./components/Cancel"; 
     
    function App() { 
      return ( 
        <BrowserRouter> 
          <Routes> 
            <Route path="/success" element={<Success />} /> 
            <Route path="/cancel" element={<Cancel />} /> 
            <Route path="/" element={<StripePayment />} /> 
          </Routes> 
        </BrowserRouter> 
      ); 
    }  
    export default App; 

    With this, the frontend of the application is ready too. It might not look that good, but it fulfills its purpose. You can run your backend and frontend of the application using the npm start command. 

    Step 7: Test Card Details

    In order to test your integration, you’re not going to use real cards for sure. To help you with this, Stripe provides you with test cards. 

    Test cards let you simulate several scenarios: 

    • Successful payments by card brand or country 
    • Card errors due to declines, fraud, or invalid data 
    • Disputes and refunds 
    • Authentication with 3D Secure and PINs 

    The test cards can only be used when you’re using Stripe Test Keys. You can find a lot of cards on this page. 

    Best Practices for Integrate Stripe Payment Gateway in Node JS 

    Here are the best practices for integrating Stripe payment gateway summarized in a pointwise format:

    1. Secure API key storage: Securely store your Stripe API key away from your codebase and limit access to authorized personnel only.  
    2. Server-side validation uses server-side validation and sanitization of user input to prevent bad data from being sent to the server. 
    3. Leverage Webhooks: Use webhooks to provide instant notifications of critical events, increasing delivery time and execution. 
    4. Flag sensitive information: Reduce PCI compliance by using Stripe's client library to flag sensitive payment information. 
    5. Error handling and handling: Use appropriate error handling and handling to detect and control any errors or malfunctions during the Stripe payment gateway integration process. 
    6. Stay current: Regularly review and update Stripe information and best practices to stay up to date on new features and improvements. 
    7. Install Stripe Node.js Package: Use npm to install the Stripe package in your Node.js application for efficient payment integration. 
    8. Create a Basic Node.js Server: Set up a server for Stripe integration, handling payment processing, subscriptions, webhooks, etc. 
    9. Integrate Stripe Checkout: Configure your Node.js server to handle Stripe Checkout integration, creating checkout sessions and handling success/cancel URLs. 
    10. Implement Payment Gateway: Use the Stripe API to manage charges, payment methods, and subscriptions, ensuring secure payment processing. 
    11. Create Subscriptions and Plans: Manage recurring payments and offer subscription-based services using Stripe’s subscription and plan creation methods. 
    12. Handle Stripe Webhooks: Set up a route in your Node.js server to receive and authenticate webhook events from Stripe, implementing custom logic for specific events. 
    13. Test Your Integration: Use Stripe’s test mode and API keys for testing, developing unit tests, and creating mock implementations of Stripe API calls. 

    These practices ensure secure, reliable, and optimized Stripe integration with your Node.js application. 

    Looking to level up your coding skills? Join our Python course training and unlock endless possibilities. From web development to data analysis, Python is the language of the future. Don't miss out on this opportunity to become a Python pro!

    Summary  

    In conclusion, the integration of stripe API’s with Node.js marks a significant milestone in the evolution of online payment solutions this combination offers a robust secure and scalable framework for handling financial transactions catering to a wide range of business needs. By leveraging Stripe's comprehensive payment processing capabilities alongside the efficiency and flexibility of Node.js, developers can integrate Stripe payment in Node.js to create seamless, user-friendly payment experiences.

    This integration not only simplifies the complexities associated with online payments but also ensures a high level of security and compliance which is paramount in today’s digital landscape as ecommerce and online services continue to grow the synergy between stripe and node.js will undoubtedly play a pivotal role in shaping the future of online transactions making them more accessible efficient and secure for businesses and consumers alike. 

    Frequently Asked Questions (FAQs)

    1How do you integrate Stripe payment gateway in React JS?

    Stripe provides you with a dependency called @stripe/stripe-js that helps you use Stripe.js as an ES module. You need to have a backend server to interact with Stripe APIs. In addition to that, there are several third-party dependencies available on npmjs.org too, that can help you integrate Stripe payments easily in your application. One of the most popular is react-stripe-checkout. 

    2What is Stripe payment gateway?

    Payment gateways make it easier for you to integrate payments into your app and for users to pay through it. Stripe payment gateway is one of them. It is used by millions of companies of all kinds, from small startups to major corporations, to collect payments, send payouts, and manage their businesses online. 

    3How does Stripe.js work?

    Stripe.js is a Javascript library that helps you interact with Stripe APIs. When the user fills the details on the checkout form, Stripe.js passes the card details to the Stripe server, where it is verified and stored if it is correct. It then sends a temporary token and the personal details to your server. By using Stripe.js, your server doesn’t need to handle any card data, and hence it’s secure. 

    Profile

    Ashutosh Krishna

    Author

    Ashutosh is an Application Developer at Thoughtworks. Apart from his love for Backend Development and DevOps, he has a keen interest in writing technical blogs and articles. 

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon