【问题标题】:Node and Twilio integration节点和 Twilio 集成
【发布时间】:2018-09-11 05:42:54
【问题描述】:

我在 nodejs 中使用 Twilio 编写了一个可编程的 SMS 功能。我有一条消息可供选择,当用户发回任何响应时,我想使用 twilio 发送自动响应。

我已完成所有操作,除了处理用户的回复后,我的自动回复没有发送给用户。

我不断从我的 twilio 仪表板中获得更多信息。

这是我的响应处理程序代码..

 app.post('/ui/sms',function(req, res) {
    //req.headers['Content-type'] = 'text/xml';
    //req.headers['Accept'] = 'text/xml';
    try {
        console.log('Processing Response', req.headers);
        const MessagingResponse = require('twilio').twiml.MessagingResponse;
        const twiml = new MessagingResponse();
        const fromTwilio = isFromTwilio(req);
        console.log('isFromTwilio: ', fromTwilio);
        if (fromTwilio) {
            let msg = req.body.Body||'';
            if (msg.indexOf('1')>-1) {
                twiml.message('Thanks for confirming your appointment.');
            } else if (msg.indexOf('2')>-1) {
                twiml.message('Please call 408-xxx-xxxx to reschedule.');
            } else if (msg.indexOf('3')>-1) {
                twiml.message('We will call you to follow up.');
            } else {
                twiml.message(
                    'Unknown option, please call 408-xxx-xxxx to talk with us.'
                );
            }
            res.writeHead(200, { 'Content-Type': 'text/xml' });
            res.end(twiml.toString());
        }
        else {
            // we don't expect these
            res.status(500).json({ error: 'Cannot process your request.' });
        }
        /*processSMSResponse(req, function(response) {
            res.json(response);
        });*/
    } catch(e) {
        res.json(e);
    }
});


function isFromTwilio(req) {
console.log('REQ HEADER:::::::::\n', req);
// Get twilio-node from twilio.com/docs/libraries/node
const client = require('twilio');

// Your Auth Token from twilio.com/console
const authToken = 'xxxxxxxxxxxxxxxxx';

// The Twilio request URL
//const url = 'https://mycompany.com/myapp.php?foo=1&bar=2';
const url = 'https://xxxx.com/ui/sms';
var reqUrl = 'https://xxxx.com/ui/sms'
// The post variables in Twilio's request
//const params = {
    //CallSid: 'CA1234567890ABCDE',
    //Caller: '+14158675310',
    //Digits: '1234',
    //From: '+14158675310',
    //To: '+18005551212',
//};
const params = req.body;
console.log('post params: ', params);

// The X-Twilio-Signature header attached to the request
try{
    Object.keys(params).sort().forEach(function(key) {
        reqUrl = reqUrl + key + params[key];
    });

    var twilioSignature = crypto.createHmac('sha1', authToken).update(Buffer.from(reqUrl, 'utf-8')).digest('base64');
    //const twilioSignature = req.header('HTTP_X_TWILIO_SIGNATURE');
    console.log('twilioSignature: ', twilioSignature);
} catch(e){
    console.log(e);
}
return client.validateRequest(
                authToken, 
                twilioSignature, 
                url, 
                params
            );
}

我已明确尝试设置标题但没有用。我不太了解 twilio 对我的期望或如何修改标题。

{
 "status": "Error",
 "error": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response><Message>Please call 408-xxx-xxxx to reschedule.</Message></Response>"
}

我在 Twilio 控制台中将其视为正文,它具有我需要但无法作为消息发送的响应..

【问题讨论】:

  • 你的内容类型错误,twilio.com/docs/api/errors/12300
  • 尝试使用 res.set() 方法和状态码设置内容类型,并使用 res.statusCode() 和 res.send() 发送正文。 res.end() 不是发送响应的正确方法。
  • 试过没用..

标签: node.js twilio


【解决方案1】:

这里是 Twilio 开发人员宣传员。

通过查看您的代码并亲自尝试,我看不出它有什么问题。不过,这里有两个潜在的失败点:

1) 我看不到你的isFromTwilio 函数。如果那个失败,它可能会导致错误,然后在错误处理程序上返回 JSON 而不是 XML。我不知道为什么它会在那个 JSON 中回复 TwiML。

2) 我可以重现的其他行为(除了 TwiML 没有在响应正文中发送)是当我没有在中间件链中包含 body-parser 时。这将导致 req.body 未定义,因此 req.body.Body 将抛出一个错误,然后被捕获并返回 JSON。

您是否已将body-parser 包含并正确包含为中间件?你可以这样做:

const { urlencoded } = require('body-parser');
app.use(urlencoded({ extended: false });

或者如果您只想将它​​用于这个端点,您可以在请求处理程序之前添加 urlencoded({ extended: false }) 作为参数:

app.post('/ui/sms', urlencoded({ extended: false }), function(req, res) {

我希望这会有所帮助。

干杯,

多米尼克

【讨论】:

  • 是的,我在 server.js 文件中有它,但 urlencoded({extended: false }) 默认设置为 true。
  • 我添加了额外的函数,如果 X-Twilio-Signature 有效,它会返回 true。
  • 嗯,这很奇怪。似乎显然抛出了一些错误。我建议使用 Chrome 或 VS Code 直接将调试器附加到它,或者首先使用我们内置的 Express 中间件替换您自己的 isFromTwilio 函数:github.com/twilio/twilio-node/blob/master/lib/webhooks/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-08
  • 2017-01-30
  • 2017-12-12
相关资源
最近更新 更多