Adam Freymiller
Adam Freymiller

Reputation: 1939

Handling inbound Twilio messages using node.js

I'm reading through portions of the Twilio documentation (https://www.twilio.com/help/faq/why-does-my-twilio-number-respond-with-thanks-for-the-message-configure-your-numbers-sms-url-to-change-this-message) pertinent to SMS messaging responses, and am trying to build a node.js app which will allow me to respond to inbound SMS messages with programmatic responses.

I've been trying to emulate this SO post which deals with a similar problem (How can I respond to incoming Twilio calls and SMS messages using node.js?) and have the following code:

var AUTH_TOKEN = "*********************";
var twilio = require('twilio');
var express = require('express');
var http = require('http');

var app = express();

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());


app.post('/welcome/sms/reply/', function(req, res) {
    //Validate that this request really came from Twilio...
    if (twilio.validateExpressRequest(req, AUTH_TOKEN)) {
        var twiml = new twilio.TwimlResponse();
        twiml.say('Hi!  Thanks for checking out my app!');
        res.type('text/xml');
        res.send(twiml.toString());
    }
    else {
        res.send('you are not twilio.  Buzz off.');
    }
});

http.createServer(app).listen(3000);

Calling the POST request /welcome/sms/reply through a REST client yields the else statement, and I'm not sure why since the AUTH_TOKEN is exactly what I have in my account dashboard.

Upvotes: 1

Views: 429

Answers (2)

philnash
philnash

Reputation: 73029

Twilio developer evangelist here.

If you're trying to call your own endpoint there using a REST client and you are validating requests (twilio.validateExpressRequest) then you will need to construct your request the same as Twilio does. Crucially this includes a X-Twilio-Signature header, read more at that link for more details.

If you test your code with Twilio, it should work and be a valid request.

Upvotes: 1

Adam Freymiller
Adam Freymiller

Reputation: 1939

See this post for reference in incorporating ngrok + Express. https://www.twilio.com/blog/2015/09/monitoring-call-progress-events-with-node-js-and-express.html

Upvotes: 0

Related Questions