DEV Community

FOLASAYO SAMUEL OLAYEMI
FOLASAYO SAMUEL OLAYEMI

Posted on • Edited on

Implementing One-Time Payments with BudPay and Node.js

Introduction

One-time payments are a crucial component of many applications and services, allowing users to make single transactions without the need for recurring subscriptions.

In this article, we will explore how to implement one-time payments using BudPay, a popular payment gateway, and Node.js, a powerful JavaScript runtime environment.

Prerequisites

You will need the following in order to follow along with this tutorial:

  • Node.js and JavaScript fundamentals are required.

  • You have Node.js set up on your computer.

  • A BudPay account. If you don't already have an account, create one on the BudPay website.

  • The setup process must be finished in order to use BudPay's APIs. Here is an article that will walk you through setting up BudPay as a payment system if you need assistance.

Configuring the BudPay API Credentials:

You need to receive API credentials, which include a public key and a secret key, in order to use the BudPay API. Your requests to the API must be authenticated using these credentials. The following steps will show you how to get your BudPay API credentials:

  • Register or log in: Create a new account if you don't already have one. Use your login information to access your account if you already have one.

  • Account settings: After logging in, go to the "Account Settings" button to set up your account. Click "Save Changes" after entering all the necessary profile information.

Image description

  • Create API credentials by going to the "API Keys" section after updating your profile information. Your API Keys for Integration can be found here, along with a button to create new API Keys.

BudPay API Key Page Screenshot

Setting up the Project

Let's start by setting up a new Node.js project. Open your terminal or command prompt and follow these steps:

  • Create a new project directory:
mkdir budpay-one-time-payments
cd budpay-one-time-payments
Enter fullscreen mode Exit fullscreen mode
  • Initialize a new Node.js project and answer the prompts:
npm init
Enter fullscreen mode Exit fullscreen mode
  • Install the necessary dependencies:
npm install express axios dotenv
Enter fullscreen mode Exit fullscreen mode

This code sample demonstrates the utilization of the express framework for creating a robust server, leveraging axios for seamless communication with the BudPay API to simplify HTTP request handling and response management. Additionally, the dotenv library is installed to securely manage the BudPay API Keys.

Implement BudPay One-Time Payment

After successfully setting up your project and installing the required dependencies as described previously, we can proceed to create a one-time payment. Create a new file called index.js in your project directory and open it in your favorite text editor.

In the index.js file, start by importing Express and also, importing the Axios library and initializing it with your BudPay API credentials:

const express = require("express");
const app = express();
const axios = require("axios");
require("dotenv").config();

app.use(express.json());

const secretKey = process.env.BUDPAY_SECRET_KEY;
Enter fullscreen mode Exit fullscreen mode

We initialize an Express server, configure it to parse JSON requests, and set up environment variables for the BudPay API key.

Next, let's create a function that handles the one-time payment process:

async function processPayment() {
  try {
    const paymentUrl = await createPaymentLink();
    console.log("Payment URL:", paymentUrl);
    return paymentUrl;
  } catch (error) {
    console.error("Payment failed:", error.message);
  }
}

async function createPaymentLink() {
  const url = "https://api.budpay.com/api/v2/create_payment_link";

  const requestData = {
    amount: "2500",
    currency: "NGN",
    name: "Folasayo Samuel",
    description: "my description",
    redirect: "https://www.google.com",
  };

  const headers = {
    Authorization: `Bearer ${secretKey}`,
    "Content-Type": "application/json",
  };

  try {
    const response = await axios.post(url, requestData, { headers });
    const responseData = response.data;
    const { ref_id, payment_link } = responseData.data;
    return { ref_id, payment_link };
  } catch (error) {
    console.error("Error creating payment link:", error.message);
    throw error;
  }
}
Enter fullscreen mode Exit fullscreen mode

In the code sample above, we define two asynchronous functions.
The createPaymentLink function sends a POST request to the Budpay API to create a payment link, using the provided request data and headers. It extracts the ref_id and payment_link from the response data and returns them as an object.

The processPayment function calls the createPaymentLink function and awaits the result. It logs the payment URL and returns it if successful, or logs the payment failure if an error occurs during the process.

Testing the Payment Process

To test the payment process, save the index.js file and run the following command in your terminal or command prompt:

node index.js
Enter fullscreen mode Exit fullscreen mode
  • Use an HTTP client tool like cURL or Postman to send a POST request to http://3000/process-payment with the following JSON payload:
{
      "amount": "2500",
      "currency": "NGN",
      "name": "Folasayo Samuel",
      "description": "my description",
      "redirect": "https://www.google.com"
}
Enter fullscreen mode Exit fullscreen mode

If everything is set up correctly, you should see the payment URL logged to the console. Open the URL in a web browser to complete the payment process.

Postman result for the API test

  • Alternatively, you can copy the URL from your terminal and manually paste it into your web browser.

Postman result for the API test

Handling Payment Notifications

After a successful payment, you may receive a payment notification from BudPay. To handle these notifications, you need to expose an endpoint in your Node.js application that BudPay can call.

Let's create an endpoint that handles the payment notification. Modify the index.js file as follows:

app.post("/payment-notification", (req, res) => {
  try {
    const { notify, notifyType, data } = req.body;

    if (notify === "transaction" && notifyType === "successful") {
      console.log("Successful transaction notification:", data);
    }

    res.status(200).send({ message: "Notification received successfully" });
  } catch (error) {
    console.error("Error processing notification:", error.message);
    res.status(500).send(error.message);
  }
});
Enter fullscreen mode Exit fullscreen mode

In the code above, we define an endpoint /payment-notification that handles incoming notifications. It destructure the notification data from the request body, checks if it is a successful transaction, logs the data if it is, and sends a success response; otherwise, it logs an error and sends an error response.

Use an HTTP client tool like cURL or Postman to send a POST request to http://3000/payment-notification with the following JSON payload:

{

    "notify": "transaction",
    "notifyType": "successful",
      "data": {
          "description": "my description",
          "redirect": "https://www.google.com",
          "amount": "2500",
          "currency": "NGN",
          "name": "Folasayo Samuel",
          "message": "Payment processing initiated",
          "ref_id": "4422542404645mhkl17a39c31b86x",
          "payment_link": "https://budpay.com/paymentlink/4422542404645mhkl17a39c31b86x"
    }
}
Enter fullscreen mode Exit fullscreen mode

Postman result for the API test

Postman result for the API test

Conclusion

In this article, we learned how to implement one-time payments using BudPay and Node.js. We used the Axios library to interact with the BudPay API, creating a payment intent and generating a payment URL for users.

For a complete reference and source code, you can visit the GitHub repository associated with this integration.

Remember to handle payment notifications securely and perform necessary validations and verifications to ensure the integrity of your payment process. The provided example serves as a starting point, and you should refer to BudPay's documentation for comprehensive information on integrating BudPay into your Node.js application.

Thanks for reading...
Happy Coding!

Top comments (0)