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

Harendra Kumar Kanojiya - Mar 19 '21 - - Dev Community

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.

  1. Get Tokens — You can get tokens by navigating to Developers -> API Keys from the sidebar of your dashboard.

  2. Code Setup — In order to start coding we have to setup the directory structure of our application provided below.

server.js — This file is the main file for our server which loads all views and handle payment request.

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...'))
Enter fullscreen mode Exit fullscreen mode

card.js — This file is used at the frontend to validate card information entered by the user.

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);
        }
    })
})
Enter fullscreen mode Exit fullscreen mode

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.

<!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/tailwindcss@^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>
Enter fullscreen mode Exit fullscreen mode

complete.html — It is the success page of our application which comes after payment 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/tailwindcss@^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>
Enter fullscreen mode Exit fullscreen mode
  1. Change tokens — Change your token in views/card.js and server.js file.

  2. Install Packages — npm i body-parser ejs express nodemon stripe

  3. Serve Application — node server.js

Test card details -
Card number — 4242 4242 4242 4242

Buy me a coffee

Github repo


Follow me on Twitter

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player