简体   繁体   中英

Twilio statusCallback implementation running into trouble

I am a beginner to Twilio. I understand that I can get the status of the SMS send by having a statusCallback, so that the POST will happen to the callbackurl with the status of the message. But I am having troubles in creating that particular POST endpoint. Here is what I have :

  // Twilio API CALL
    client.sendMessage({
            to:userId, 
            from: metadata.myTwilioNumber,
            body: message, 
            StatusCallback:'POST URL'
                }, function(err, responseData) {
              if (!err) { 

               } else {
                 logger.info(err);
              }

My POST endpoint is a simple node js (request, response) endpoint.

    var server = http.createServer ( function(request,response){
          response.writeHead(200,{"Content-Type":"text\plain"});
        if(request.method == "GET")
            {
                response.end("received GET request.")
            }
        else if(request.method == "POST")
            {

                console.log(request.CallStatus);
    console.log(response);
                console.log('receivedRequest');
                response.end("received POST request.");
            }
        else
            {
                response.end("Undefined request .");
            }
    });

server.listen(4445);

Can someone help me in getting the status and messageID of the response? Currently, the POST is getting invoked but i am unable to get the message details and status.

Twilio developer evangelist here.

You are using the basic Node.js standard library http module which is going to make it a lot of work to extract the information from the POST request. Can I recommend you try something like express with body-parser instead.

You can do so by installing the two modules with npm:

npm install express body-parser

Then you can rewrite your incoming message application like this:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));

app.post('/', (req, res) => {
  console.log(req.body.CallStatus);
  res.sendStatus(200);
});

app.listen(4445, () => {
  console.log('Application running on localhost:4445');
});

All the parameters that Twilio sends will be available on the req.body object.

Check out this tutorial on receiving SMS messages with Twilio in Node for a bit more detail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM