Node.JS Express Stripe 3D Card Secure Authentication Subscription Payment Checkout Example in HTML5 & Javascript

You are currently viewing Node.JS Express Stripe 3D Card Secure Authentication Subscription Payment Checkout Example in HTML5 & Javascript

Node.js Express Stripe 3D Card Secure Authentication Subscription Payment Checkout Example in HTML5 & Javascript

const bodyParser = require("body-parser");
const express = require("express");
const Stripe = require("./stripe");
const session = require("express-session");
var MemoryStore = require("memorystore")(session);
 
const app = express();
 
const productToPriceMap = {
  BASIC: "##basicpriceid####",
  PRO: "###propriceid###",
};
app.use(
  session({
    saveUninitialized: false,
    cookie: { maxAge: 86400000 },
    store: new MemoryStore({
      checkPeriod: 86400000,
    }),
    resave: false,
    secret: "keyboard cat",
  })
);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
 
app.use(express.static("public"));
app.engine("html", require("ejs").renderFile);
 
app.get("/", async function (req, res, next) {
  res.status(200).render("login.ejs");
});
app.post("/login", async (req, res) => {
  const { email } = req.body;
  const customer = await Stripe.addNewCustomer(email);
  req.session.customerID = customer;
  req.session.email = email;
  res.redirect("/account");
});
app.get("/account", async function (req, res) {
  res.render("account.ejs");
});
app.post("/checkout", async (req, res) => {
  console.log(req.body.product)
  if (req.body.product == "PRO") {
    product = productToPriceMap.PRO
  }
  else {
    product = productToPriceMap.BASIC
  }
  const { customer } = req.session;
  const session = await Stripe.createCheckoutSession(
    customer,
    product
  );
 
  console.log(session);
  res.send({ sessionId: session.id });
});
 
app.get("/success", (req, res) => {
  res.send("Payment successful");
});
 
app.get("/failed", (req, res) => {
  res.send("Payment failed");
});
const port = 4242;
 
app.listen(port, () => console.log(`Listening on port ${port}!`));

const stripe = require("stripe");
const STRIPE_SECRET_KEY = "##stripesecretkey##";
 
const Stripe = stripe(STRIPE_SECRET_KEY, {
  apiVersion: "2020-08-27",
});
 
const addNewCustomer = async (email) => {
  const customer = await Stripe.customers.create({
    email,
    description: "New Customer",
  });
 
  return customer;
};
 
const createCheckoutSession = async (customer, price) => {
  const session = await Stripe.checkout.sessions.create({
    mode: "subscription",
    payment_method_types: ["card"],
    customer,
    line_items: [
      {
        price,
        quantity: 1,
      },
    ],
    subscription_data:{
      trial_period_days:14
    },
    success_url: `http://localhost:4242/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `http://localhost:4242/failed`,
  });
 
  return session;
};
 
const getCustomerByID = async (id) => {
  const customer = await Stripe.customers.retrieve(id);
  return customer;
};
 
module.exports = {
  addNewCustomer,
  getCustomerByID,
  createCheckoutSession,
};

<html lang="en">
  <body class="text-center">
    <form class="form-login" action="/login" method="post">
  
      <h1>Log in</h1>
<input
        type="email"
        name="email"
        placeholder="Email address"
        required
      />
      <button type="submit">
        Sign in
      </button>
    </form>
 
    <script
      src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
      integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
      crossorigin="anonymous"
    ></script>
  </body>
</html>

<html>
<head>
</head>
<body>
<input type="radio" id="basic" name="product" value="BASIC" />
        <label for="basic">Basic for $15</label><br />
        <input type="radio" id="pro" name="product" value="PRO" />
        <label for="pro">Pro for $30</label><br />
 
<button class="btn btn-primary" id="checkout-button" type="submit">
          Buy now
        </button>
 
<script
      src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
      integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
      crossorigin="anonymous"
    ></script>
  <script type="text/javascript" src="https://js.stripe.com/v3/"></script>
<script type="text/javascript" src="./js/account.js"></script>
</body>
<html>

$(document).ready(function () {
  const PUBLISHABLE_KEY = "##stripepublishablekey##";
 
  const stripe = Stripe(PUBLISHABLE_KEY);
  const checkoutButton = $("#checkout-button");
 
  checkoutButton.click(function () {
    const product = $('input[name="product"]:checked').val();
    console.log(product)
    fetch("/checkout", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        product,
      }),
    })
      .then((result) => result.json())
      .then(({ sessionId }) => stripe.redirectToCheckout({ sessionId }));
  });
});

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply