Setting Up an USSD Service Using Africa's Talking API with Node.js

Setting Up an USSD Service Using Africa's Talking API with Node.js

Jul 31, 2024·

3 min read

USSD (Unstructured Supplementary Service Data) is a protocol used by GSM cellular telephones to communicate with the network. It is often used for services such as balance inquiries, mobile banking, and more. Africa’s Talking provides an API to handle USSD services, allowing developers to build and manage USSD applications efficiently. This guide will walk you through setting up a basic USSD service using the Africa's Talking API with Node.js.

Prerequisites

  1. Node.js and npm: Ensure Node.js and npm are installed on your system. You can download them from nodejs.org.

  2. Africa's Talking Account: Sign up for an account on Africa’s Talking and obtain your API key and short code.

  3. A Text Editor: Use a text editor or an IDE like Visual Studio Code for coding.

Step 1: Create a New Node.js Project

First, create a new directory for your project and navigate into it:

mkdir ussd-server
cd ussd-server

Initialize a new Node.js project:

npm init -y

This will create a package.json file with default settings.

Step 2: Install Required Packages

Install the necessary npm packages:

  • africastalking: The Africa’s Talking Node.js SDK.

  • express: A minimal web framework for Node.js.

Run the following command:

npm install africastalking express body-parser

Step 3: Set Up Your USSD Server

Create an index.js file in your project directory:

touch index.js

Open index.js and add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const AfricaTalking = require('africastalking');

// Initialize Express
const app = express();
app.use(bodyParser.urlencoded({ extended: true })); // To parse URL-encoded bodies

// Africa's Talking credentials
const username = 'YOUR_AFRICAS_TALKING_USERNAME'; // Replace with your Africa's Talking username
const apiKey = 'YOUR_AFRICAS_TALKING_API_KEY'; // Replace with your Africa's Talking API key

// Initialize Africa's Talking
const africasTalking = AfricaTalking({ apiKey, username });

// USSD service
const ussd = africasTalking.USSD;

// Handle USSD requests
app.post('/ussd', (req, res) => {
    const { phoneNumber, text } = req.body;

    if (!phoneNumber || !text) {
        return res.status(400).send('Missing "phoneNumber" or "text" in request body');
    }

    // Process the USSD request
    let response;
    const parts = text.split('*');
    const userInput = parts[parts.length - 1];

    switch (userInput) {
        case '':
            response = 'CON Welcome to My USSD Service\n1. Check Balance\n2. Send Money';
            break;
        case '1':
            response = 'END Your balance is $100';
            break;
        case '2':
            response = 'CON Enter amount to send';
            break;
        default:
            response = 'END Invalid option';
            break;
    }

    // Send response
    res.send(response);
});

// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Step 4: Configure Your Africa's Talking USSD Application

Log in to your Africa’s Talking account and navigate to the USSD section. Set the USSD code and point it to your server’s /ussd endpoint. For example, if your server is running on http://example.com, you should configure your USSD code to point to http://example.com/ussd.

Step 5: Run Your Server

Start your server with Node.js:

node index.js

You should see a message indicating that the server is running on port 3000.

Step 6: Testing Your USSD Service

To test your USSD service, dial the USSD code you configured on your mobile phone. Follow the menu options and verify that your responses are handled correctly.

Conclusion

Setting up a USSD service using Africa’s Talking API with Node.js allows you to create interactive applications that can be accessed through simple phone dial-ins. This setup can be expanded to include more complex functionalities such as mobile payments, interactive surveys, and more. Modify and extend this example based on your specific needs and business requirements.

Happy coding, and may your USSD service bring seamless communication to your users!