Setting Up an SMS Server Using Africa's Talking SMS API with Node.js

Setting Up an SMS Server Using Africa's Talking SMS API with Node.js

Jul 31, 2024·

3 min read

In the digital age, SMS remains a powerful tool for communication, especially in regions where internet access might be limited. Africa’s Talking offers a robust SMS API that allows developers to integrate SMS functionality into their applications effortlessly. In this guide, we will walk through setting up an SMS server using the Africa’s Talking SMS API with Node.js.

Prerequisites

  1. Node.js and npm: Make sure Node.js and npm (Node Package Manager) are installed on your system. You can download and install 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 sms-server
cd sms-server

Initialize a new Node.js project:

npm init -y

This command 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

Step 3: Set Up Your SMS Server

Create an index.js file in your project directory:

touch index.js

Open index.js and add the following code:

javascriptCopy codeconst express = require('express');
const AfricaTalking = require('africastalking');

// Initialize Express
const app = express();
app.use(express.json()); // To parse JSON 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 });

// SMS service
const sms = africasTalking.SMS;

// Endpoint to send SMS
app.post('/send-sms', async (req, res) => {
    try {
        const { to, message } = req.body;

        if (!to || !message) {
            return res.status(400).json({ error: 'Missing "to" or "message" in request body' });
        }

        const response = await sms.send({
            to,
            message,
            from: 'YOUR_SHORTCODE' // Replace with your Africa's Talking short code
        });

        res.status(200).json(response);
    } catch (error) {
        console.error('Error sending SMS:', error);
        res.status(500).json({ error: 'Failed to send SMS' });
    }
});

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

Step 4: 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 5: Testing Your SMS Server

You can test your SMS server using tools like Postman or cURL. Send a POST request to http://localhost:3000/send-sms with the following JSON body:

jsonCopy code{
    "to": "+254XXXXXXXXX", // Replace with the recipient's phone number
    "message": "Hello from Africa's Talking SMS API!"
}

If everything is set up correctly, you should receive a JSON response from Africa’s Talking with details about the SMS sent.

Conclusion

Setting up an SMS server using Africa’s Talking SMS API with Node.js is straightforward. With just a few lines of code, you can integrate SMS functionality into your application. This setup can be enhanced further based on your needs, such as adding more endpoints, handling incoming SMS, or integrating with a database.

I will be releasing a similar python version and ussd article soon, stay tuned!

Feel free to modify and expand this example according to your requirements. Happy coding!