This is a step by step tutorial on how to implement Africa's Talking airtime API to your Node.js(express) application. Check out the whole project from GitHub.

Africa's Talking (AT) is a unified API platform for software developers in Africa building SMS, USSD, Voice, Payments and Airtime applications. AT is here to ensure that the developer community in Africa is successful at creating, growing and sustaining great businesses, using their solutions.

Prerequisite

  1. Visual Studio Code or IDE of your choice.
  2. Basic knowledge of Node.js.

Account Setup and Launch Simulator

Let's jump right in and login to our AT accounts. If you don't have an account go ahead and create one here.

First, let's launch our sandbox environment. Sandbox is a free test environment that mirrors how users would interact with your application and the API. To learn more about the Sandbox, visit here.

When you login to your account, your dashboard should look like this;

Navigate to the "Go To Sandbox APP", you will be redirected to this page;

Click on launch simulator. Select the country you are developing from and make sure to type in your correct phone number to get accurate results then click on launch.

Generate API key

We'll go back to our dashboard and click on settings. Then click on API key as shown in the image below. You will be redirected to a page where you'll have to key in your AT account password. Make sure you copy and store the API key safely.

Click on API key note the app user name is sandbox

Sending Airtime

Let's get started.

  1. We'll open our project; you can use your favourite Integrated Development Environment (IDE). Create a new file and name it .env . This is where we will store our environment variables. In this case the apikey, username and port. Make sure you use the current generated apikey, use sandbox as the apps username. Use "sandbox" for development in the test environment.
  2. Initialize node using npm init or yarn init.
  3. Let's add some dependencies. Copy either of the two commands to the console in your root directory. npm install express africastalking body-parser dotenv or yarn add express africastalking body-parser dotenv. To handle HTTP POST request in express.js version 4 and above we install body-parser middleware. body-parser extracts the entire body portion of an incoming request stream and exposes it on req.body.  dotenv loads environment variables from the .env file.
  4. In this tutorial we will be using ES6+ syntax and therefore we will have to add babel. To learn more about babel click here. npm i @babel/core babel-cli @babel/preset-env babel-watch --save-dev or yarn add @babel/core babel-cli @babel/preset-env babel-watch --dev.
  5. Now let's create a file in the root directory and name it index.js. Add the following code to the index.js file.
import express from "express";
import dotenv from "dotenv";
const router = express.Router();

dotenv.config();

// Set your app credentials
const credentials = {
    apiKey: process.env.apiKey,
    username: process.env.username
}
// Initialize the SDK
const AfricasTalking = require("africastalking")(credentials)

// Get airtime service
const airtime = AfricasTalking.AIRTIME

// Sending airtime route
router.post("/",(req,res) => {
    const options = {
        recipients: [{
            phoneNumber: req.body.phoneNumber,
            currencyCode: req.body.currencyCode,
            amount: req.body.amount
        }]
    };
    airtime.send(options)
        .then(response => {
            console.log(response);
            res.json(response);
        }).catch(error => {
            console.log(error);
            res.json(error.toString());
        });
    
})

export default router;

dotenv.config() method reads the environment variables. const credentials authenticates our application.  The airtime route sends a request(req) to the AT airtime API. As soon as the request is sent and the data given in the body is accurate, it returns the full response object with res.json(response) as well as logs the response to the console with console.log(response).  In case the request fails, an error message is returned using res.json(error.toString()). The toString() method converts the error to a string. Finally we export our route using  export default router

6. Create another file and name it app.js in the same directory(root directory). Copy the following code to this file;

import express from "express";
import 'babel-polyfill';
import router from "./index";
import dotenv from "dotenv";
import bodyParser, { json } from "body-parser";

dotenv.config();

const app = express();
const port = process.env.port || 3000;

app.listen(port, ()=> console.log(`Listening from ${port}`));

app.use(bodyParser.json());

app.use("/v1", router);

Here we set our live server to run on the port set on the .env file or port 3000. Our application listens from the AT API passing the whole body through bodyParser.json()

7. To run our application we will have to modify our package.json file to look like this;

{
  "name": "send_airtime",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "babel app.js --out-dir build",
    "start": "babel-watch app.js"
  },
  "author": "Cynthia",
  "license": "ISC",
  "dependencies": {
    "africastalking": "^0.5.2",
    "body-parser": "^1.19.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "nodemon": "^2.0.4",
    "save": "^2.4.0"
  },
  "devDependencies": {
    "@babel/core": "^7.11.6",
    "@babel/preset-env": "^7.11.5",
    "babel-cli": "^6.26.0",
    "babel-watch": "^7.0.0",
    "make-runnable": "^1.3.8"
  }
}

Notice that in the script tag we have added "build" and "start" .The script build, builds our application with babel which converts the ES6 syntax to (pre 2015 JS) which the environment understands. In the "start" script we have added babel-watch so that when we edit code it will restart upon new changes.

8. Let's run the application using npm start. You should be able to see in your console Listening from port ${your Port}.

9. Open postman, fill in the body as you can see below and run your application. You should receive airtime  notification in your sandbox environment. Note, no notification will be sent to your mobile phone.

The body is in JSON
You can choose the response you'd like displayed. In our case we returned the whole response object

A message will be sent to your sandbox test environment once the transaction is successful.

Message to your sandbox test environment

You can track your transactions from the AT Airtime transactions dashboards as shown below. It gives you status updates like successful and failed transactions making it easy to manage your application.

You can check your transaction from Africa's Talking dashboard

That's how you send airtime using the Africa's Talking airtime API. Here is the link to the GitHub repository.

Find the code here:

Happy Coding!!!

You've successfully subscribed to Decoded For Devs
Welcome back! You've successfully signed in.
Great! You've successfully signed up.
Your link has expired
Success! Your account is fully activated, you now have access to all content.