Integrating SSLCOMMERZ Payment Gateway in Node.js

Shejan Mahamud
5 min readJun 18, 2024

In this blog post, we will walk through the process of integrating the SSLCommerz payment gateway into a Node.js application using MongoDB for database operations. This guide will help you set up a secure and efficient payment processing system for your web application.

Credit: Shejan Mahamud

SSLCOMMERZ is a secure and authorized online Payment Gateway platform, developed by SSL Wireless, which has enabled the end-customers of online businesses & E-Commerce merchants to perform secured transactions from the customer’s card, mobile wallet or bank account.. Let’s see some of the core benefits of SSLCOMMERZ-

  • Quick activation with online documentation
  • Easy integration
  • PSO licensed by the Central Bank of Bangladesh
  • 30+ payment schemes
  • Accepts global payment
  • Real-time dashboard reporting
  • High-level security with PCI DSS Compliance

Prerequisites

Before we begin, make sure you have the following:

  1. Node.js: Ensure that Node.js is installed on your machine. You can download it from nodejs.org.
  2. MongoDB: Make sure MongoDB is set up and running.
  3. SSLCommerz Account: You need a SSLCommerz merchant account. You can sign up at sslcommerz.com.

Step 1: Set Up Your Project

First, create a new Node.js project and install the necessary dependencies. Open your terminal and run the following commands:

mkdir sslcommerz-integration
cd sslcommerz-integration
npm init -y
npm install express body-parser dotenv sslcommerz-lts mongodb cors

Step 2: Configure Environment Variables

Create a .env file in the root of your project and add your SSLCommerz credentials. These credentials will be used to authenticate your requests with the SSLCommerz API.

STORE_ID=your_store_id
STORE_PASSWORD=your_store_password
SERVER_API=http://localhost:3030
MONGO_URI = "mongodb+srv://username:password@cluster0.7ctc5qe.mongodb.net/?retryWrites=true&w=majority"

After creating a merchant account, you will receive your STORE_ID and STORE_PASSWORD via email. The SERVER_API is your backend API address, and you can obtain the MONGO_URI from your MongoDB dashboard.

Step 3: Set Up the Express Server

Next, set up your Express server and define the necessary routes for handling payment operations. Create an app.js file and add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const SSLCommerzPayment = require('sslcommerz-lts');
const { MongoClient, ObjectId, ServerApiVersion } = require("mongodb");
const cors = require("cors");
require('dotenv').config();
const mongoURI = process.env.MONGO_URI;

const app = express();
const port = process.env.PORT || 3030;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // To handle form data sent by SSLCommerz

// MongoDB connection
const client = new MongoClient(mongoURI, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});

// Middleware for CORS and JSON parsing
app.use(
cors({
origin: ["http://localhost:5173"],
credentials: true,
})
);
app.use(express.json());

// SSLCommerz configuration
const store_id = process.env.STORE_ID;
const store_passwd = process.env.STORE_PASSWORD;
const is_live = false; // true for live mode, false for sandbox

const run = async () => {
try {
// Connect to the database
await client.connect();

// Collection for saving orders
const ordersCollection = client.db("test").collection("orders");

// POST request for creating a payment
app.post("/plans", async (req, res) => {
// Plan details sent from client side
const planDetails = req.body;

// Convert price into an integer
const price = parseInt(planDetails.price);

// Create a transaction ID using ObjectId
const tran_id = new ObjectId().toString();

// Payment data to send to SSLCommerz
const data = {
total_amount: price,
currency: "BDT",
tran_id: tran_id,
success_url: `${process.env.SERVER_API}/payment/success`,
fail_url: `${process.env.SERVER_API}/payment/fail`,
cancel_url: `${process.env.SERVER_API}/payment/cancel`,
ipn_url: `${process.env.SERVER_API}/payment/ipn`,
shipping_method: "Courier",
product_name: planDetails.plan,
product_category: "Electronic",
product_profile: "general",
cus_name: "Customer Name",
cus_email: planDetails.user_email,
cus_add1: "Dhaka",
cus_add2: "Dhaka",
cus_city: "Dhaka",
cus_state: "Dhaka",
cus_postcode: "1000",
cus_country: "Bangladesh",
cus_phone: "01711111111",
cus_fax: "01711111111",
ship_name: "Customer Name",
ship_add1: "Dhaka",
ship_add2: "Dhaka",
ship_city: "Dhaka",
ship_state: "Dhaka",
ship_postcode: 1000,
ship_country: "Bangladesh"
};

// Initialize SSLCommerz payment
const sslcz = new SSLCommerzPayment(store_id, store_passwd, is_live);
sslcz.init(data).then((apiResponse) => {
// Get the payment gateway URL
let GatewayPageURL = apiResponse.GatewayPageURL;
res.send({ url: GatewayPageURL });

// Insert order details into the database
const order = { ...planDetails, tran_id, status: 'pending'};
const result = ordersCollection.insertOne(order);
});

// POST request for handling successful payment
app.post("/payment/success", async (req, res) => {

// Update order status in the database to successful
const result = await ordersCollection.updateOne(
{ tran_id },
{ $set: { status: 'success'} }
);
//redirect to payment success page in client
res.redirect("http://localhost:5173/payment/success");
});

// POST request for handling failed payment
app.post("/payment/fail", async (req, res) => {

// Update order status in the database to failed
const result = await ordersCollection.updateOne(
{ tran_id },
{ $set: { status: 'failed'} }
);
//redirect to payment failed page in client
res.redirect("http://localhost:5173/payment/fail");
});

// POST request for handling canceled payment
app.post("/payment/cancel", async (req, res) => {

// Update order status in the database to canceled
const result = await ordersCollection.updateOne(
{ tran_id },
{ $set: { status: 'canceled'} }
);
//redirect to payment cancel page in client
res.redirect("http://localhost:5173/payment/cancel");
});

// POST request for handling IPN (Instant Payment Notification)
app.post("/payment/ipn", async (req, res) => {

// Update order status in the database based on IPN notification
const result = await ordersCollection.updateOne(
{ tran_id },
{ $set: { status: status === "VALID" } }
);
res.send({ message: "IPN received" });
});
});
} finally {
// Ensuring the server keeps running
}
};

// Run the server
run().catch(console.dir);

// Simple route to check if server is running
app.get('/', async (req, res) => {
res.send({ server_status: "Running" });
});

// Start the Express server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Explanation

  1. Express Server Setup: The Express server is set up and configured to use the body-parser middleware to handle JSON requests.
  2. MongoDB Connection: A connection to MongoDB is established using the MongoClient from the mongodb package.
  3. SSLCommerz Configuration: The SSLCommerz payment gateway is configured with the store ID and password from environment variables.
  4. POST /plans Route: This route handles the creation of a payment session. It receives the plan details from the frontend, generates a unique transaction ID, and initializes a payment session with SSLCommerz. The user is then redirected to the SSLCommerz payment page.
  5. POST /payment/success, /payment/cancel, /payment/fail Route: This route handles the success,fail and cancel callback from SSLCommerz. It updates the order status in the database and updates the user’s plan details.

Step 4: Handle Frontend Integration

To trigger the payment process from your frontend, you can use the following code snippet. This code sends a POST request to the /plans endpoint and redirects the user to the SSLCommerz payment page.

const handlePlans = async () => {
const { data } = await axios.post('/plans', {
user_email: user.email,
plan: plan,
price: price,
purchase_date: purchaseDate,
expiration_date: expirationDate,
currency: 'BDT',
payment_method: 'SSLCOMMERZ'
});
//redirect to url which is you send from server
window.location.replace(data.url);
};

Explanation

  1. handlePlans Function: This function sends a POST request to the /plans endpoint with the necessary plan details.
  2. Redirection: Upon receiving the response, the user is redirected to the SSLCommerz payment page using window.location.replace.

Conclusion

In this blog post, we have successfully integrated the SSLCommerz payment gateway into a Node.js application using raw MongoDB for database operations. This integration allows you to securely process payments and update your database accordingly.

Key Points

  • SSLCommerz Setup: Ensure you have a merchant account with SSLCommerz and obtain your store ID and password.
  • Environment Variables: Store your credentials securely in environment variables.
  • MongoDB Operations: Use MongoDB for database operations to keep track of orders and update user plans.

By following these steps, you can set up a robust and secure payment processing system in your Node.js application. Happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Shejan Mahamud
Shejan Mahamud

Written by Shejan Mahamud

Aspiring web developer passionate about MERN stack. Eager to create innovative and user-friendly web applications.

No responses yet

Write a response