How to use Stripe Payments in Node.js Using Express ?

How to use Stripe Payments in Node.js Using Express ?


Published at - Aug 13, 2021

In this post, we will learn how to integrate Stripe payment gateway in our application using Node Js and Express and I am going to create a basic app to make payment where users can submit payment in testing mode using test card details.

Github repo for stripe payment gateway with nodejs – https://github.com/harendra21/stripe-nodejs

Steps

  • Create Stripe account

To integrate stripe payment gateway in our application first thing we required a stripe account to getting started. You can create your account by clicking on the following links (Log in if you already have an account) Login or Register.

  •  Get your Tokens

You can get tokens by navigating to `Developers -> API Keys` from the sidebar of your dashboard.

  • Code Setup

To start coding we have to set up the directory structure of our application provided below.

  • Change tokens

Change your token in views/card.js and server.js file.

  • Install Packages

npm i body-parser ejs express nodemon stripe

  • Serve Aplication

node server.js

Project Strecture

  • main_application
    • views
      • card.js
      • index.html
      • complete.html
    • server.js

Code

server.js

This file is the main file for our server which loads all views and handle payment request. It contains a stripe library for process payment at the backend.

const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')
const stripe = require('stripe')('YOUR_SECRET_KEY_HERE')

const app = express()
app.use(bodyParser.urlencoded({ extended: true }))

app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

app.use(express.static(path.join(__dirname, './views')));

app.get('/', (req,res) => {
	res.render('index.html');
})

app.post('/charge', (req, res) => {
    try {
        stripe.customers.create({
            name: req.body.name,
            email: req.body.email,
            source: req.body.stripeToken
        }).then(customer => stripe.charges.create({
            amount: req.body.amount * 100,
            currency: 'usd',
            customer: customer.id,
            description: 'Thank you for your generous donation.'
        })).then(() => res.render('complete.html'))
            .catch(err => console.log(err))
    } catch (err) { res.send(err) }
})


const port = process.env.PORT || 3000
app.listen(port, () => console.log('Server is running...'))

card.js

This file is used at the frontend to validate card information entered by the user and this file is using stripe client-side library to process validation of your personal and card information.

const stripe = Stripe('Publishable_key_here');
const elements = stripe.elements();

var style = {
    base: {
        color: "#fff"
    }
}
const card = elements.create('card', { style });
card.mount('#card-element');

const form = document.querySelector('form');
const errorEl = document.querySelector('#card-errors');

const stripeTokenHandler = token => {
    const hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);

    console.log(form)
    form.submit();
}

form.addEventListener('submit', e => {
    e.preventDefault();

    stripe.createToken(card).then(res => {
        if (res.error) errorEl.textContent = res.error.message;
        else {
            console.log(res.token)
            stripeTokenHandler(res.token);
        }
    })
})

index.html

It is the main homepage of the application which is used to providing an interface to enter the required information to make payment.

homepage
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://unpkg.com/[email protected]^1.0/dist/tailwind.min.css" rel="stylesheet">
    <title>Stripe Node App</title>
</head>

<body class="bg-gray-900">
    <nav class="bg-purple-900 h-20 flex justify-center">
        <h1 class="text-white text-5xl">Stripe Node App</h1>
    </nav>

    <div class="flex justify-center mt-32">
        <form action="/charge" method="POST" class="flex flex-col w-1/3">
            <input class="bg-transparent text-white p-2 h-10 mb-4" type="text" name="name" placeholder="Name">
            <input type="email" class="bg-transparent text-white p-2 h-10 mb-4" name="email" placeholder="Email">
            <input class="bg-transparent text-white p-2 h-10 mb-4" type="text" name="amount" placeholder="Amount">

            <div id="card-element" class="bg-transparent text-white p-2 h-10 mb-4"></div>
            <div id="card-errors" role="alert"></div>
            <button class="text-white bg-purple-900 p-4 rounded">Submit Payment</button>
        </form>
    </div>
</body>

<script src="https://js.stripe.com/v3/"></script>
<script src="card.js"></script>

</html>

complete.html

It is the success page of our application that comes after payment is done.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://unpkg.com/[email protected]^1.0/dist/tailwind.min.css" rel="stylesheet">
    <title> Completed</title>
</head>

<body class="bg-gray-900">
    <nav class="bg-purple-900 h-20 flex justify-center">
        <h1 class="text-white text-5xl">Stripe Node App</h1>
    </nav>
    <div class="flex flex-col items-center mt-32 text-white text-2xl">
        <p>Thank you for your generous donation.</p>
        <p>Your payment has been received.</p>
        <a href="/"><button class="bg-blue-700 rounded p-4 mt-3">Return</button></a>
    </div>
</body>

</html>

Test card details

You can use below card number for test mode and for expiry date you have enter any date greater than today’s date for cvv number use any 3 digit number it will work and in zip code box you have to enter your zip code.

Card number – 4242 4242 4242 4242 of click here

Github repo – https://github.com/harendra21/stripe-nodejs

Download Code

Thank you for reading stripe payment gateway with nodejs !





About author

Harendra
Harendra Kanojiya

Hello, I am Harendra Kumar Kanojiya - Owner of this website and a Fullstack web developer. I have expertise in full-stack web development using Angular, PHP, Node JS, Python, Laravel, Codeigniter and, Other web technologies. I also love to write blogs on the latest web technology to keep me and others updated. Thank you for reading the articles.



Follow Us

Follow us on facebook Click Here

Facebook QR
Scan from mobile
Join our telegram channel Click Here
Telegram QR
Scan from mobile