Here we will learn how to integrate textlocal in our project.

First thing that we need to do is we have to register our self to Textlocal. Now what we will need from textlocal is username and sender information that we have registered and it will provide one hash key which we will need to integrate into our code.

Now below is the code for how to integrate textlocal in our application and how we can use that service.

Node.js has a built-in module called “http” and “urlencoded” which you have to install from npm.

To install “urlencoded” run below command in your terminal:

$ npm install urlencode

//Code starts

var http = require(‘http’);
var urlencode = require(‘urlencode’);
var username = ‘info@commonapp.com’;     //username is required to register with textlocal
var hash = ‘abcdefghijklmnopqrstuvwxyz’;    // you will get a hashcode from textlocal
var sender = ‘COMMONAPP’;                      //sender is required to register with textlocal (this will display on receiver’s phone as a sender)
//Send message function starts
exports.sendMessage = function (toNumber, message) {
try {
varmsg=urlencode(message);
vardata=’username=’+username+’&hash=’+hash+’&sender=’+sender+’&numbers=’+toNumber+’&message=’+msg;
varoptions= {
host:’api.textlocal.in’, path:’/send?’+data
};
returnnewPromise((resolve, reject) => {
returnhttp.request(options, function (response) {
varstr=”;//another chunk of data has been recieved, so append it to `str`
response.on(‘data’, function (chunk) {
str+=chunk;
});//the whole response has been recieved, so we just print it out here
response.on(‘end’, function () {
letdata=JSON.parse(str);
if (data.errors) {
reject(data);
}
else {
resolve(data);
}
// return str;
});
response.on(‘error’, function () {
reject(str);
// return str;
});
}).end();
})
} catch (err) {
throwError(err);
}
}
callback = function (response) {
varstr=”;//another chunk of data has been recieved, so append it to `str`
response.on(‘data’, function (chunk) {
str+=chunk;
});//the whole response has been recieved, so we just print it out here
response.on(‘end’, function () {
console.log(str);
returnstr;
});
}
Now above is the send message function which we have created now how do we need to call that function in our application that we will learn below:
//here we are importing that service in our application js file and assuming that you know how to import file in NodeJS
const messageService = require(‘../../services/sendMessage.service’)
//In our controller where we want to send message, We will use this function
//Here we are pushing mobile numbers into one array and that array we wil use in our function
userList.forEach(user => {
phoneNumber.push(user.phoneNumber);
});
var message = ‘Dear user, Here you define a message which you want to send.’
//Calling send message function
await messageService.sendMessage(phoneNumber, `${message}`)

You may also like

Leave a Reply