Send & Recieve SMS messages in Node.JS using Nexmo
SiDarthVader
11.7K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Receive an SMS
Enter your apiKey & apiSecret below. Then, press 'Run My Code' to spin up the server. Copy the source of the viewer below and enter it as the Webhook URL for Inbound Messages on the Nexmo dashboard.
Listen for incoming SMS messages
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const Nexmo = require('nexmo'); //nexmo node lib
const express = require('express'); //expressJS (server)
const bodyParser = require('body-parser'); //body parser to parse the incoming http request
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//initialize nexmo client w/ your apikey & secret
const nexmo = new Nexmo({
apiKey: "",
apiSecret: ""
});
// Handle both GET and POST requests
app.get('/inbound', (req, res) => {
handleParams(req.query, res);
});
app.post('/inbound', (req, res) => {
handleParams(req.body, res);
});
function handleParams(params, res) {
if (!params.to || !params.msisdn) { //doesn't have the to # or from # -> usually hit when verifiying the endpoint (callback)
console.log('This is not a valid inbound SMS message!');
} else { //has to & from aka is a text
console.log('Incoming Text:');
console.log('---------------------');
let incomingData = {
messageId: params.messageId,
from: params.msisdn,
text: params.text,
type: params.type,
timestamp: params['message-timestamp']
};
console.log('Message ID: ' + incomingData.messageId);
console.log('Message From: ' + incomingData.from);
console.log('Message Text: ' + incomingData.text);
console.log('Message Type: ' + incomingData.type);
res.send(incomingData);
}
res.status(200).end();
}
module.exports = app;
Enter to Rename, Shift+Enter to Preview
1
chmod +x ./bin/server.js
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content