Twilio+Node JS: How to send SMS and voice calls using Twilio and Node JS?

Hello everyone, today we will learn how to send SMS/voice call using TWILIO and NODE JS. We know, with the increase in the number of mobile devices around the globe today, and numerous mobile applications available to us, SMS is becoming the de facto standard for verification.

Let's begin our hunt by creating a free account on Twilio, click here

After successful registration go to your dashboard, there you can find your ACCOUNT SID and AUTH TOKEN, 


it is quite simple, right? 👍

Next,
we are going to explore how to use Twilio for sending SMS in a Node.js application.

Prerequisites
Application directory structure


package.json 

A package.json is a JSON file that exists at the root of a Javascript/Node project. It holds metadata relevant to the project and it is used for managing the project's dependencies, scripts, version, and a whole lot more.

{
"name": "node_app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.ts",
"lint": "eslint . --ext .ts"
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/cors": "^2.8.6",
"@types/express": "^4.17.6",
"@types/node": "^14.0.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"ts-node": "^8.10.1",
"twilio": "^3.51.0",
"typescript": "^3.9.2"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^2.34.0",
"@typescript-eslint/parser": "^2.34.0",
"eslint": "^6.8.0",
"eslint-config-airbnb-base": "^14.1.0",
"eslint-plugin-import": "^2.20.2",
"nodemon": "^2.0.3"
}
}


index.ts

index.ts typically handles your app startup, routing, and other functions of your application and does require other modules to add functionality.

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import smsRoute from './routes/sms.routes';
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use('/smsRoute', smsRoute);
app.listen(3000, () => {
// eslint-disable-next-line no-console
console.log('App listening on port 3000!');
});

sms.service.js

our business logic will be here, right?😄

import { Request, Response } from 'express';

var TWILIO_ACCOUNT_SID = 'Your SID',
TWILIO_AUTH_TOKEN = 'your token',
TWILIO_PHONE_NUMBER = 'your twilio phone number';
const twilio = require('twilio');
const client = require('twilio')(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);

export async function sendSms(request: Request, response: Response) {
// Use the REST client to send a text message
client.messages.create({
to: request.body.phoneNumber,
from: TWILIO_PHONE_NUMBER,
body: request.body.message
}).then(function () {
// When we get a response from Twilio, respond to the HTTP POST request
response.send('Message is inbound!');
});
}


export async function call(request: Request, response: Response) {
// Use the REST client to send a text message
client.calls.create({
to: request.body.phoneNumber,
from: TWILIO_PHONE_NUMBER,
url: 'http://demo.twilio.com/docs/voice.xml'
}).then(function() {
response.send('Call incoming!');
});
}

sms.route.js

import {
Router, Request, Response,
} from 'express';
import { sendSms, call } from '../services/sms.service';


const router = Router();

router.post('/sendSms', (req: Request, res: Response) => {
sendSms(req, res);
});
router.post('/call', (req: Request, res: Response) => {
call(req, res);
});
export = router

Test our application using postman or any other API tester

  • localhost:3000/smsRoute/sendSms


  • localhost:3000/smsRoute/call

Download source code:


Run:
  1. npm install
  2. npm start
console output:

> nodemon index.ts
[nodemon] 2.0.6
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node index.ts`
App listening on port 3000!

steps are very simple, right?😊 Don't forget  for Twilio signup 

Hurray, Enjoy coding

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete