Implementing One-Time Payments with BudPay and Node.js
Tags: webdev, javascript, budpay, tutorial
Published: 2023-07-05 23:11:01

## 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](https://nodejs.dev/learn/how-to-install-nodejs) set up on your computer. 

- A BudPay account. If you don't already have an account, create one on the [BudPay website](https://www.budpay.com).

- 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](https://dev.to/fataj/setting-up-budpay-as-a-payment-system-2d49) 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](https://merchant.budpay.com/merchant/register) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ydo5u0bu4a2edvr9m3up.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vx0dxsasjkh8yhto22s5.png)

## 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
```

- Initialize a new Node.js project and answer the prompts:

```
npm init
```

- Install the necessary dependencies:

```
npm install express axios dotenv
```
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;
```
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;
  }
}
```
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
```

- 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"
}
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hkatk63346euiquk2sra.png)

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

![Postman result for the API test](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eqib74awyguiava6qffo.png)

## 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);
  }
});
```
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"
    }
}
```

![Postman result for the API test](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nmhusb476dcb1t6jjrzv.png)

![Postman result for the API test](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cpnxgsmd2ysfec7mwsfl.png)

## Conclusion
In this article, we learned how to implement one-time payments using BudPay and Node.js. We used the [Axios library](https://axios-http.com/docs/intro) to interact with the [BudPay API](apis.budpay.ng), creating a payment intent and generating a payment URL for users.

For a complete reference and source code, you can visit the [GitHub repository](https://github.com/Folasayo-Samuel/One-Time-Payments-with-BudPay) 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](https://devs.budpay.com/) for comprehensive information on integrating BudPay into your Node.js application.

Thanks for reading...
**Happy Coding!**