In this article we discuss how to use the Monnify Nodejs library to interact with the Monnify Reserved Account API.
A customer reserved account is a feature that facilitates businesses with the ability to generate permanent personalized account numbers for their customers, giving them the ability to make payments to the business anytime and anywhere.
With a reserved account, customers are assured of owning account numbers that belong to them alone — just like their usual bank account number that isn't shared among different persons.
We will demonstrate how the Nodejs library can be used to simplify interacting with Monnify reserved account APIs, handling access token management and providing proper validation messages and API responses.
Prerequisites
- Node and NPM are installed. Run npm init to initialize the project.
- A use case that involves wallet functionality: an account number is reserved for each customer's wallet to enable top-ups. Examples: Super Agents, Investment Applications, Betting Platforms, Logistics Applications.
Project Setup
1{
2 "name": "monnify-node",
3 "version": "1.0.0",
4 "description": "A sample usage of the monnify nodejs lib",
5 "main": "index.js",
6 "scripts": {
7 "test": "echo \"Error: no test specified\" && exit 1"
8 },
9 "author": "benji",
10 "license": "ISC"
11}Install Dependencies
1npm install monnify-nodejs-lib express body-parser cors cryptoCreate two folders in the root directory called service and controller — service for managing service-level requests and controller for managing request handlers.
Configure index.js as the entry point for the Express server:
1import router from "./router.js"
2import express from 'express'
3import bodyParser from "body-parser";
4
5const requestRouter = router
6
7const notFound = (req, res, next) => {
8 res.status(404);
9 res.json({ status: 404, msg: "Resource was not found" });
10};
11
12const handleError = (error, req, res, next) => {
13 console.log(error);
14 res.status(error.status || 500);
15 res.json({ status: "failed", responseBody: "An error occurred while processing your request" });
16};
17
18const app = express()
19app.use(bodyParser.urlencoded({ extended: true }))
20app.use(bodyParser.json())
21app.use("/api/v1", requestRouter)
22app.use(notFound);
23app.use(handleError);
24
25const PORT = process.env.PORT || 4111;
26app.listen(PORT, console.log("Server started at port: " + PORT))Service Layer — Reserved Account Management
In service/apiService.js, handle instantiation of the Monnify nodejs lib and implementation for reserved account creation, details retrieval and deallocation:
1import { MonnifyAPI } from "monnify-nodejs-lib"
2
3const config = {
4 MONNIFY_APIKEY: process.env.MONNIFY_APIKEY,
5 MONNIFY_SECRET: process.env.MONNIFY_SECRET,
6}
7
8config.env = process.env.API_ENVIRONMENT; // "SANDBOX" or "LIVE"
9const monnifyClient = new MonnifyAPI(config)
10
11async function getAccessToken() {
12 try {
13 const response = await monnifyClient.getToken()
14 if (response[0] === 200) {
15 return response[1]
16 } else {
17 throw new Error(JSON.stringify(response[1]))
18 }
19 } catch(err) {
20 console.log(err)
21 return false
22 }
23}
24
25async function createVirtualAccount(payload) {
26 try {
27 const authToken = await getAccessToken()
28 if (!authToken) {
29 throw new Error("Could not create virtual account: token unavailable")
30 }
31
32 const response = await monnifyClient.reservedAccount.createReservedAccount(authToken, payload)
33 if (response[0] === 200) {
34 return response[1]
35 } else if (response[0] >= 400 && response[0] < 500) {
36 return response[1]
37 } else {
38 throw new Error(JSON.stringify(response[1]))
39 }
40 } catch(err) {
41 console.log(err)
42 return false
43 }
44}
45
46export default { createVirtualAccount }Controller Layer
1import apiService from "../services/apiService.js"
2
3async function generateReservedAccount(req, res, next) {
4 try {
5 const resp = await apiService.createVirtualAccount(req.body)
6 if (resp) {
7 if (resp.requestSuccessful === true) {
8 return res.status(200).send({ status: "success", responseBody: resp.responseBody })
9 } else {
10 return res.status(400).send({ status: "failed", responseBody: resp.responseMessage })
11 }
12 } else {
13 return res.status(500).send({ status: "failed", responseBody: "Service is currently unavailable" })
14 }
15 } catch(err) {
16 console.log(err)
17 next(err)
18 }
19}
20
21export default { generateReservedAccount }Router Configuration
1import { Router } from "express"
2const router = new Router()
3import trx from "./controllers/trxController.js"
4
5router.post("/trx/reservedAccount", trx.generateReservedAccount)
6router.get("/trx/reservedAccount/:accountReference", trx.getReservedAccount)
7router.delete("/trx/reservedAccount/:accountReference", trx.deallocateReservedAccount)
8
9export default router;With the Monnify nodejs lib, access token generation is cached and expiration time is managed automatically. As shown above, we instantiate the library with the API and Secret Key, and the library provides a reserved account class with a createReservedAccount method.
You can see a full implementation of the code sample at: https://github.com/Monnify/ReservedAccount-Sample
