How to send an SMS using Node JS
Africa’s Talking is a company that was founded in 2010, Africa’s Talking has grown to be a company that is fueled by the need to empower developers building for Africa. Over the years, they have worked on creating a platform that fully supports a growing community of over 25,000 developers, spread across the continent and beyond.
The company has remained among the top companies offering SMS, and USSD preferred by programmers. It also offers other services such as Voice calls, Airtime, and Internet of Things(IoT).
We need to send SMSs everyday from our systems to mobile phones, be it OTP, verification codes, notifications, etc.
We will be using Node Js as our backend programming language to send SMSs to mobile phone using Africa’s Talking restless gateway.
What do we need to send SMS?
- A laptop with installed Node Js. Download Node Js Here.
- An account at Africa’s Talking. Visit here to register.
- Visual Studio Code Editor: Download Here
- A cup of coffee. (:
Let us get started.
- Create a blank directory in your laptop/pc.
- Open VS Code and navigate to file, open folder. Locate the folder/directory you had created.
- Initialize your application by running the following command on the console.
npm init -y
A new file “package.json” will be created inside the folder.
4. Install the following required dependencies by running the commands on the console.
npm i express request ejs
Below is how our new “package.json” file will be looking like:
{
"name": "folder-name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.1",
"request": "^2.88.2"
}
}
5. Create a new file “index.js” and add the following content in it.
const app = require("express")();
const express = require("express");
const path = require("path");
const request = require("request");
const http = require("http").Server(app);
const PORT = 3000; //the port our app will be running on
const base_url ='http://localhost';
const africas_username='xxxxxxx'; // the username obtained from africa's talking account
const africas_api_key = 'xxxxxxxxxx';// An API key obtained from africa's talking account
app.set("view engine", "ejs");// set our view engine to ejs
app.set("views", path.join(__dirname, "views"));//the directory containing the views files
app.use(express.json({limit: "1mb",})); //allow json post requests
app.use(express.urlencoded({limit: "1mb", extended: true }));// allow other post request
//get the initial/home route and redirect it to the main view
app.get("/", (req, res) => {
res.render("main");
});
//handle post request on the main view
app.post("/", function(req, res) {
//set output to JSON
res.writeHead(200, {
"Content-Type": "application/json",
});
var phone = req.body.smsPhone; //get posted phone number
var message = req.body.smsMessage;//get posted message
//Initialize ptions to sent sms message by africa's talking
const options = {
url: "https://api.africastalking.com/restless/send?username=" + africas_username + "&Apikey=" + africas_api_key + "&to=+" + phone + "&message=" + message,
method: "GET",
headers: {
Accept: "application/json",
"Accept-Charset": "utf-8",
},
};
//submitting the request
request(options, function (err, sms_res, body) {
if (err) {
//when an error occurs
let result = {sent:0, message:err};
res.end(JSON.stringify(result));
} else {
if (body.toString().includes("requirement failed")) {
//request sent but an error occurred
let result = {sent:0, message:body};
res.end(JSON.stringify(result));
} else {
var bd = JSON.parse(body);
if(bd){
var status = bd.SMSMessageData.Recipients[0].statusCode;
if (status == 100 || status == 101 || status == 102) {
//request sent successfully and message sent
let result = {sent:1, message:body};
res.end(JSON.stringify(result));
}else{
//request sent but sms not sent
let result = {sent:0, message:bd.SMSMessageData.Recipients[0].status};
res.end(JSON.stringify(result));
}
}
}
}
});
});
http.listen(PORT, () => {
console.log(`server running at ${base_url}:${PORT}`);
});
6. Create a new file “main.ejs” inside the “views” folder and add the following content.
SEND SMS BY NODE JS THROUGH AFRICA'S TALKING GATEWAY
Enter details to send SMS
Run the following command on the console. Open your browser and visit http://localhost:3000, enter your phone number, message and hit submit. Wait for the magic!
Download the source code from https://github.com/alboom25/node-send-sms-africas-talking
HAPPY CODING!!!