DEV Community

FOLASAYO SAMUEL OLAYEMI
FOLASAYO SAMUEL OLAYEMI

Posted on

Accepting Credit Card Payments in Node.js using BudPay's API

Introduction

Accepting credit card payments is a crucial functionality for many businesses operating online. In this comprehensive guide, we will explore how to integrate BudPay's API into a Node.js application to seamlessly process credit card payments.

BudPay offers a secure and reliable payment gateway that simplifies the payment processing workflow. By the end of this tutorial, you will have a clear understanding of how to leverage BudPay's API to accept credit card payments in your Node.js application.

Prerequisites:

To follow along with this tutorial, you will need:

  • Comprehensive knowledge of Javascript

  • Node.js installed on your local machine

  • A BudPay merchant account (Sign up at BudPay website)

  • To begin utilising BudPay’s APIs, it is essential to complete the setup process. If you need help doing this, here is an article that guides you on Setting Up BudPay As A Payment System

Step 1: Setting Up the Node.js Project:

  • Create a new directory for your project and navigate to it in your terminal.

  • Initialize a new Node.js project by running the following command:

npm init -y
Enter fullscreen mode Exit fullscreen mode
  • Install the required dependencies:
npm install express axios
Enter fullscreen mode Exit fullscreen mode

In this article, we incorporate the Express framework to establish a robust server, while utilizing the Axios library to facilitate seamless communication with the BudPay API.

Step 2: Configuring the BudPay API Credentials:

To get started with the BudPay API, you need to obtain API credentials consisting of a public key and a secret key. These credentials are essential for authenticating your requests to the API. Here's a step-by-step guide on how to obtain your BudPay API credentials:

  • Sign up or log in: If you don't have an account, sign up for a new account. If you already have an account, log in using your credentials.

  • Click on account settings: Once you're logged in, setup your account by clicking on the "Account Settings" button. Provide all the required profile details and click "Save Changes".

Image description

  • Generate API credentials: After updating your profile details, navigate to the "API Keys" section. Here, you'll find your Your API Keys for Integration and also, an option to generate new API Keys.

BudPay API Key Page Screenshot

  • Create a new file named config.js in the project root and add the following code:
module.exports = {
  apiPublicKey: 'YOUR_API_PUBLIC_KEY',
  apiSecretKey: 'YOUR_API_SECRET_KEY',
};
Enter fullscreen mode Exit fullscreen mode

In the above code, we declared a configuration module that exports an object with two properties: apiPublicKey and apiSecretKeywith the corresponding keys provided by BudPay.

Step 3: Creating the Express Server:

  • Create a new file named server.js in your root directory and set up a basic Express server with the following code:
const express = require('express');
const axios = require('axios');
const { apiPublicKey, apiSecretKey } = require('./config');

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

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

This code sets up an Express server using the Express framework and initializes an instance of the server. It also imports the Axios library for making HTTP requests. The apiPublicKey and apiSecretKey variables are imported from the config.js file. The server is configured to parse JSON data using express.json(). The PORT variable is set to either the value of the process.env.PORT environment variable or 3000 as the default port. The server then listens on the specified port and logs a message to the console indicating that the server is running.

Step 4: Implementing the Credit Card Payment Route:

  • Add the following code to server.js to implement the credit card payment route:
app.post("/api/v1/initialize-transaction", async (req, res) => {
  try {
    const { amount, cardNumber, cardExpMonth, cardExpYear, cardCvv, reference, email, currency } = req.body;

    const response = await axios.post(
      "https://api.budpay.com/api/v2/transaction/initialize",
      {
        amount,
        cardNumber,
        cardExpMonth,
        cardExpYear,
        cardCvv,
        reference,
        email,
        currency,
      },
      {
        headers: {
          "Content-Type": "application/json",
          "X-API-Key": apiPublicKey,
          "X-API-Secret": apiSecretKey,
        },
      }
    );

    if (response.data.success) {
      res.json({ success: true, message: "Payment successful!" });
    } else {
      res.json({ success: false, message: "Payment failed." });
    }
  } catch (error) {
    console.error("Error processing payment:", error);
    res.status(500).json({
      success: false,
      message: "An error occurred while processing the payment.",
    });
  }
});
Enter fullscreen mode Exit fullscreen mode

The provided code sample above demonstrates the implementation of a POST request to the /api/v1/initialize-transaction endpoint. Within this code, the request body parameters are destructured, and an API call is made to BudPay's API to initialize a transaction. The necessary headers are set, and the response is handled based on the success or failure of the payment, as well as any potential errors encountered during the process.

The /api/v1/initialize-transaction endpoint is specific to the implementation of this application. The endpoint path itself is arbitrary and can be defined according to the needs and conventions of the application you're working with.

You can define your own endpoints based on the functionality you want to expose or the resources they want to interact with. In this case, the /api/v1/initialize-transaction endpoint is created to handle the initialization of a transaction for credit card payments using the BudPay API.

By sending a POST request to this endpoint, the server executes the code within the corresponding route handler. The app.post function is used to define the route and specify the callback function to be executed when a POST request is made to /api/v1/initialize-transaction.

Step 5: Testing the Credit Card Payment Route:

  • Start the Node.js server by running node server.js in your terminal.

  • Use an HTTP client tool like cURL or Postman to send a POST request to http://localhost:5000/api/v1/initialize-transaction with the following JSON payload:

{
        "amount":500.0,
        "cardNumber":"4111111111111111",
        "cardExpMonth":"12",
        "cardExpYear":"25",
        "cardCvv":"123",
        "reference":"ORDER_123",
        "email":"test@gmail.com",
        "currency":"NGN"
}
Enter fullscreen mode Exit fullscreen mode
  • Inspect the response to verify the payment status.

Output

Image description

Conclusion:

In this tutorial, we have explored how to accept credit card payments in a Node.js application using BudPay's API. By integrating the BudPay payment gateway, you can securely process credit card transactions in your application. We covered the steps from setting up the Node.js project to implementing the credit card payment route, demonstrating how to make API calls to BudPay's payment endpoint. You can now leverage this knowledge to enhance your own Node.js applications with seamless credit card payment processing using BudPay's robust API.

Remember to handle errors, perform input validation, and customize the implementation based on your specific application requirements. BudPay's comprehensive API documentation and support resources will assist you in extending the functionality further.

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

Thank you for reading!

Happy coding and secure payment processing with BudPay!

Top comments (0)