Introduction
BudPay is a payment gateway API that allows businesses to securely process online payments. In addition to generating a Bearer Token, BudPay also provides a standard checkout approach where you can generate a checkout link for a particular transaction. In this tutorial, we will walk through the process of integrating BudPay API using the standard checkout approach in a web application.
Prerequisites
Before we begin, make sure you have the following prerequisites in place:
1.BudPay API credentials (public key and secret key).
2.A basic understanding of web development technologies such as (HTML, CSS, and JavaScript).
3.A server-side technology of your choice. For this tutorial, we will use Node.js and Express.js, but you can use any backend technology of your preference.
How to Get Started
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:
1.Visit the BudPay website: Go to the BudPay website
2.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.
3.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".
4.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.
5.Keep your credentials secure: Make sure to securely store your API credentials. Avoid exposing them in publicly accessible code repositories or sharing them with unauthorized individuals.
With your BudPay API credentials in hand, you can now proceed to integrate the BudPay API into your web development project. It's important to have a basic understanding of web development technologies such as HTML, CSS, and JavaScript, as well as a server-side technology like Node.js and Express.js for this tutorial.
Step 1: Set up your client side folder
- Create a new directory where you store your HTML file, and name it
client
, then create a file namedindex.html
and copy and paste the code below in the file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BudPay Payment Web Application</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Welcome to BudPay web application!</h1>
<button id="generateTokenBtn" class="btn btn-primary">Generate Token</button>
<form id="checkoutForm">
<div class="mb-3">
<label for="emailInput" class="form-label">Email</label>
<input type="email" class="form-control" id="emailInput" required>
</div>
<div class="mb-3">
<label for="amountInput" class="form-label">Amount</label>
<input type="number" class="form-control" id="amountInput" required>
</div>
<div class="mb-3">
<label for="currencyInput" class="form-label">Currency</label>
<input type="text" class="form-control" id="currencyInput" required>
</div>
<button type="submit" class="btn btn-primary">Checkout</button>
</form>
<div id="checkoutResult"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="script.js"></script>
</body>
</html>
2.Create another file named script.js
where you perform all your JavaScript logic.
document.addEventListener("DOMContentLoaded", () => {
const generateTokenBtn = document.getElementById("generateTokenBtn");
const checkoutForm = document.getElementById("checkoutForm");
const checkoutResult = document.getElementById("checkoutResult");
generateTokenBtn.addEventListener("click", async () => {
try {
const response = await axios.get("http://localhost:5000/generate-token");
const token = response.data;
// Show the generated token
checkoutResult.innerHTML = `<p>Generated Token: ${token}</p>`;
} catch (error) {
console.error(error);
checkoutResult.innerHTML =
"<p>An error occurred while generating the token.</p>";
}
});
checkoutForm.addEventListener("submit", async (event) => {
event.preventDefault();
const email = document.getElementById("emailInput").value;
const amount = document.getElementById("amountInput").value;
const currency = document.getElementById("currencyInput").value;
try {
const response = await axios.post("http://localhost:5000/checkout", {
email,
amount,
currency,
});
// Show the checkout link
checkoutResult.innerHTML = response.data;
} catch (error) {
console.error(error);
checkoutResult.innerHTML =
"<p>An error occurred while initializing the transaction.</p>";
}
});
});
Brief explanations to the HTML and JavaScript code above:
The provided code is an HTML document that represents a web page for a BudPay payment web application. The JavaScript code at the end of the HTML document adds functionality to the web application. Let's break down the functions of the code:
1.document.addEventListener("DOMContentLoaded", () => {...})
:
This code listens for the DOMContentLoaded event, which is fired when the HTML document has finished loading and parsed. The callback function inside this event listener is executed when the event occurs.
2.const generateTokenBtn = document.getElementById("generateTokenBtn");
:
This line retrieves the element with the ID "generateTokenBtn" from the document. It assigns the element to the generateTokenBtn constant, allowing further operations.
3.const checkoutForm = document.getElementById("checkoutForm");
:
This line retrieves the form element with the ID "checkoutForm" from the document. It assigns the element to the checkoutForm constant.
4.const checkoutResult = document.getElementById("checkoutResult");
:
This line retrieves the element with the ID "checkoutResult" from the document. It assigns the element to the checkoutResult constant.
5.generateTokenBtn.addEventListener("click", async () => {...})
:
This code adds a "click" event listener to the generateTokenBtn button. When the button is clicked, the callback function inside the event listener is executed.
- The code inside the
try
block makes an HTTP GET request to a "/generate-token" endpoint using the Axios library. It expects to receive a token in the response.
In the provided code snippet, the token generation happens on the backend in the /generate-token
endpoint, not on the frontend when the generateToken
button is clicked. The frontend code makes an HTTP GET request to the /generate-token
endpoint, and the backend generates and returns the token as a response to that request.
The purpose of generating and displaying the token on the frontend is not merely for the reader/user to see what the token looks like. The token serves as a crucial piece of information that represents a generated token value associated with a specific transaction or user. It is typically used to authenticate and authorize subsequent requests or operations related to that specific transaction.
Displaying the generated token on the frontend can serve various purposes, including providing feedback to the user, allowing them to verify the token, or presenting it for further processing, such as initiating a payment or including it in subsequent API calls. The specific use and purpose of the token in the application would depend on the implementation and requirements of the system utilizing the BudPay API.
If the request is successful, the received token is displayed in the checkoutResult element using the innerHTML property.
If an error occurs during the request, the error is logged to the console, and an error message is displayed in the checkoutResult element.
6.checkoutForm.addEventListener("submit", async (event) => {...})
:
This code adds a "submit" event listener to the checkoutForm form. When the form is submitted, the callback function inside the event listener is executed.
event.preventDefault();
:
This line prevents the default form submission behavior, which would refresh the page.The code inside the
try
block retrieves the values entered in the email, amount, and currency input fields.It then makes an HTTP POST request to a "/checkout" endpoint using the Axios library, sending the entered email, amount, and currency as data in the request body.
If the request is successful, the response data, likely a checkout link, is displayed in the
checkoutResult
element using theinnerHTML
property.If an error occurs during the request, the error is logged to the console, and an error message is displayed in the
checkoutResult
element.
The JavaScript code adds event listeners to the "Generate Token" button and the payment form's submit event. It makes HTTP requests to specific endpoints ("/generate-token" and "/checkout") and updates the checkoutResult
element based on the responses received.
Step 2: Set up a Node.js Project
1.Create a new directory for your project and navigate to it using the command line.
2.Run npm init
to initialize a new Node.js project. Follow the prompts to set up the project.
Step 3: Install Dependencies
1.Install Express.js, a popular Node.js web application framework, by running npm install express
in the command line.
2.Install other dependencies like axios
, and any other libraries you may require for your web application.
Step 4: Create an Express.js Server
1.Create a new file called server.js
and require the necessary dependencies:
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
2.Set up a basic route to handle incoming requests:
app.get('/', (req, res) => {
res.send('Welcome to my web application!');
});
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT});
});
Step 5: Generate Bearer Token
1.Create a new route to generate the Bearer Token:
app.get('/generate-token', async (req, res) => {
try {
// Pass your public key and secret key to generate a Bearer Token
const response = await axios.post('https://apis.budpay.ng/api/v2/encrypt/key', {
publicKey: 'YOUR_PUBLIC_KEY',
secretKey: 'YOUR_SECRET_KEY'
});
// Extract the token from the response
const { token } = response.data;
// Send the token as the response
res.send(token);
} catch (error) {
console.error(error);
if(error.code === "ETIMEDOUT"){
res.status(500).send("Connection to BudPay API timed out. Please try again later.");
}else{
res.status(500).send("An error occurred while generating the token.");
}
res.status(500).send('An error occurred while generating the token.');
}
});
Make sure to replace 'YOUR_PUBLIC_KEY' and 'YOUR_SECRET_KEY' with your actual BudPay API credentials.
Step 6: Implement BudPay Integration
1.Create a new route to handle the checkout request:
app.post('/checkout', async (req, res) => {
try {
// Retrieve customer details from the request body
const { email, amount, currency } = req.body;
// Generate a Bearer Token by making a request to the '/generate-token' endpoint
const tokenResponse = await axios.get('http://localhost:5000/generate-token');
const token = tokenResponse.data;
// Make a request to BudPay API to initialize the transaction and get the checkout link
const response = await axios.post('https://api.budpay.ng/api/v2/transactions/initialize', {
email,
amount,
currency
}, {
headers: {
'Authorization': `Bearer ${token}`
}
});
// Handle the response from BudPay API
const { checkoutLink } = response.data;
res.send(`Click <a href="${checkoutLink}">here</a> to complete the payment.`);
} catch (error) {
console.error(error);
res.send('An error occurred while initializing the transaction.');
}
});
2.Modify the client-side of your web application to send a checkout request to your server when the customer clicks on the checkout button. You can achieve this using AJAX, fetch()
, or any other client-side HTTP library.
Step 7: Test the Integration
1.Start your Node.js server by running node server.js
in the command line.
2.Open your web application in a web browser.
3.Make a checkout request through your web application and verify the response. The response will include a clickable link for the customer to complete the payment.
Congratulations! You have successfully integrated BudPay API using the standard checkout approach with your web application. Customers can now click on the generated checkout link to complete their payment securely using the BudPay payment gateway.
How to make payment using BudPay Checkout:
- Select the payment option that best suits your preference.
- Please proceed with the payment for the requested amount. Kindly note that the screenshot below reflects the usage of the test mode. You have the flexibility to switch to the live mode based on your preference and requirements.
Conclusion:
In this tutorial, we covered the step-by-step process of integrating BudPay API using the standard checkout approach in a web application. We set up a Node.js server, generated a Bearer Token using the public and secret keys, implemented BudPay integration using the initialize transaction API, and tested the integration. Remember to handle errors appropriately and ensure the security of sensitive user information during the payment process.
Remember to refer to the BudPay API documentation for further details on API endpoints, response formats, and any additional features or requirements specific to the BudPay payment gateway.
Download the source code here...
Thanks for reading...
Happy Coding!
Top comments (0)