Building a Secure Payment Gateway with Node.js and TypeScript Using SeerBit

Building a Secure Payment Gateway with Node.js and TypeScript Using SeerBit

Securing online payment systems is a critical concern for businesses. Payment gateways must be robust and reliable to ensure online transactions are processed safely.

This article will guide you through building a secure payment gateway using Node.js and TypeScript, integrating SeerBit, a leading payment processor tailored for the African market. We’ll cover setting up the project, implementing a payment link generator, using the system design pattern, and testing the payment link in your browser.

Prerequisites

Before you start building the payment gateway, ensure you have the following:

  1. Node.js and npm should be installed on your machine.
  2. TypeScript installed globally:
   npm install -g typescript
  1. SeerBit Account: Sign up or sign in on SeerBit to get your Public Key and Secret Key. These keys will be required to authenticate your API requests.
  2. Axios: For making HTTP requests to SeerBit’s API.
  3. JSON Web Tokens (JWT): For secure authentication and authorization.

Getting the SeerBit API Keys:

SeerBit Log in form screenshot
  • Here, you will find your Test Public Key and Secret Key. Copy these keys for later use in your application.
SEERBIT TEST KEYS SCREENSHOTS

Key Components of a Payment Gateway

Before diving into the implementation, it’s crucial to understand the key components of a payment gateway and how they work together to process payments securely.

  1. Payment Flow:
  • User: The individual who initiates the payment by providing their payment details.
  • Merchant: The business that receives the payment for goods or services.
  • Payment Processor: A service like SeerBit that facilitates the transfer of payment information between the user and the merchant’s bank.

Building the Payment Gateway

Let’s start by setting up the project using Node.js and TypeScript, and implementing a feature to create a payment link that can be used by customers to make payments.

1. Setting Up the Project

First, create a new Node.js project and initialize TypeScript.

mkdir secure-payment-gateway
cd secure-payment-gateway
npm init -y
npm install typescript ts-node express axios
npm install @types/express
npx tsc --init

Next, set up the basic structure for your application:

mkdir src
touch src/index.ts

In src/index.ts, set up a simple Express server with the payment link creation feature:

import express from 'express';
import axios from 'axios';

const app = express();
app.use(express.json());

app.post('/create-payment-link', async (req, res) => {
    const paymentLinkData = {
        publicKey: process.env.publicKey, 
        amount: "5000",
        currency: "NGN",
        country: "NG",
        paymentReference: "payment",
        email: "test@examples.com",
        fullName: "Halil TSS",
        tokenize: "false",
        callbackUrl: "https://seerbit.com"
    };

    try {
        const response = await axios.post('https://seerbitapi.com/api/v2/payments', paymentLinkData, {
            headers: {
                'Authorization': `Bearer ${process.env.bearerToken}`, 
                'Content-Type': 'application/json'
            }
        });

        res.json(response.data);
    } catch (error: any) {
        console.log("Error creating payment link");
        console.log(error.response?.data);
        res.status(500).json({ message: 'Payment link creation failed', error: error.response?.data });
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

System Design Pattern: Singleton Pattern

In this payment gateway implementation, we’ve employed the Singleton Design Pattern for managing the configuration and connection to SeerBit’s API.

Why Singleton Pattern?

  1. Single Instance: The Singleton Pattern ensures that only one instance of the configuration and connection setup is created throughout the lifecycle of the application. This is crucial for a payment gateway where consistency and reliability are paramount.
  2. Controlled Access: Since the API keys and connection configurations are sensitive, the Singleton Pattern allows us to control access to these resources, ensuring they are not accidentally altered or duplicated.
  3. Global Access Point: The Singleton Pattern provides a single global access point to the configuration and connection objects, making it easy to manage and maintain the connection across different parts of the application.

Here’s how the Singleton Pattern is applied:

class SeerBitConnection {
    private static instance: SeerBitConnection;
    private publicKey: string;
    private bearerToken: string;

    private constructor() {
        this.publicKey = process.env.PUBLIC_KEY || '';
        this.bearerToken = process.env.BEARER_TOKEN || '';
    }

    public static getInstance(): SeerBitConnection {
        if (!SeerBitConnection.instance) {
            SeerBitConnection.instance = new SeerBitConnection();
        }
        return SeerBitConnection.instance;
    }

    public getPaymentLinkData() {
        return {
            publicKey: this.publicKey,
            bearerToken: this.bearerToken,
        };
    }
}

In the SeerBitConnection class:

  • Private Constructor: Prevents direct instantiation of the class, ensuring that only one instance exists.
  • getInstance Method: Provides a global access point to the single instance of SeerBitConnection.
  • getPaymentLinkData Method: Returns the API keys required for making requests to SeerBit, ensuring they are securely managed and accessed consistently.

The use of the Singleton Pattern here ensures that the configuration and connection to SeerBit’s API are secure, consistent, and efficiently managed.

Testing the Payment Link

Once the code is set up, follow these steps to test the payment link creation and verify its functionality in a web browser.

1. Start the Server

Open your terminal (Command Prompt for Windows, Terminal for macOS/Linux), navigate to the project directory, and run:

npx ts-node src/index.ts

This command will start the Express server, and it will be running on http://localhost:3000.

Download the source code here.

2. Create a Payment Link Using Postman

  • Open Postman and create a new POST request to http://localhost:3000/create-payment-link.
  • Send the request and check the response. It should return a payment link.
SEERBIT POSTMAN TEST PAYMENT API SCREENSHOT

3. Test the Payment Link in a Browser

  • Copy the payment link generated in the Postman response.
  • Open your preferred web browser (e.g., Chrome, Firefox, Safari).
  • Paste the payment link into the address bar and press Enter.
  • The browser will load the payment page, where you can proceed with a test payment.
SEERBIT PAYMENT INITIALIZATION SCREENSHOT
SEERBIT PAYMENT AUTHORIZATION SCREENSHOT
SCREENSHOT OF A SUCCESSFUL SEERBIT TRANSACTION

Conclusion

In this article, we walked through setting up a secure payment gateway using Node.js and TypeScript, integrating with SeerBit for payment processing. We implemented a feature to generate payment links, discussed how to test this functionality using Postman, and provided instructions for testing the payment link in a web browser.

The use of the Singleton Design Pattern ensures that the configuration and connection to SeerBit’s API are managed efficiently, with a single, consistent instance throughout the application’s lifecycle. This approach helps maintain the integrity and security of your payment gateway.

By following these steps, you can build a reliable and secure payment gateway tailored to your business needs.

Thanks for reading…

Happy Coding!