Use request npm to create a http call.
request-promise —save npm I npm I npm I npm I npm I n
Create a folder called "services" and a file called "TextLocalSMS.js" for the class "TextLocalSMS.js."
var httprequest = require('request-promise');
module.exports = class TextLocalSMS {
constructor() {
}
async callApi(METHOD,URL,BODY){
var options = {
method: METHOD,
uri: URL,
headers:{
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
},
json:true
};
let response= await httprequest(options).then((result)=>{
console.log(`SMS API: ${URL} RESULT =`,result);
return result;
}).catch(function (err) {
console.log(`SMS API: ${URL} ERROR =`,err.message);
return err;
});
return response;
}
async sendSMS(toNumbers,rawMessage){
let url = 'https://api.textlocal.in/send/';
let sender = encodeURIComponent('TXTLCL');
let encoded_message = encodeURIComponent(rawMessage);
let body={
apikey:'API_KEY',
numbers:toNumbers.join(','),
sender:sender,
message:encoded_message
};
let result = await callApi('POST',url,body);
return result;
}
}
Now require this file when you want to use it , suppose in app.js
var TextLocalSMS = require('./services/TextLocalSMS');
app.get('/demo',async (req,res)=>{
// add logic for get user's phone nubmer from database here
// ...
let otp = Math.floor(100000 + Math.random() * 900000);
let text_msg = `MyWebsite.com - OTP : ${otp} for reset your account password .`;
let toNumbers = ['918123456789'];
let smsService = new TextLocalSMS();
let smsSent = await smsService.sendSMS(toNumbers,text_msg);
// database query to store OTP with user_id in your database if otp successfully send to user
// ...
return res.json(smsSent);
})