3

所以,我对这个不是很熟悉,所以我有点困惑。我正在尝试使用 Twilio 函数创建一个函数,将传入的短信发送到第三方 API。一般来说,我会怎么做?

这就是我现在拥有的

exports.handler = function(context, event, callback) {
  var got = require('got');
  var data = event.Body;
  console.log("posting to helpscout: "+requestPayload);
  got.post('https://api.helpscout.net/v1/conversations.json', 
    {
      body: JSON.stringify(data), 
      'auth': {
        'user': process.env.API_KEY,
        'pass': 'x'
      },
      headers: {
        'Content-Type': 'application/json' 
      }, 
      json: true
    })
    .then(function(response) {
     console.log(response.body)
     callback(null, response.body);
    })
    .catch(function(error) {
      callback(error)
    })
}
4

1 回答 1

2

下面是一些可以帮助您入门的内容(Twilio 函数的代码)。这将在 Help Scout 中创建一个新对话。

注意:event参数包含有关 Twilio 函数的特定调用的信息(传入的 sms 消息)。它有诸如event.Body,event.From


const https = require('https');

exports.handler = function(context, event, callback) {

    let twiml = new Twilio.twiml.MessagingResponse();
    twiml.message("Thanks. Your message has been forwarded to Help Scout.");

    let postData = JSON.stringify(
        {
            "type": "email",
            "customer": {
                "email": "customer@example.com"
            },
            "subject": "SMS message from " + String(event.From),
            "mailbox": {
                "id": "000000"
            },
            "status": "active",
            "createdAt": "2017-08-21T12:34:12Z",
            "threads": [
                {
                    "type": "customer",
                    "createdBy": {
                        "email": "customer@example.com",
                        "type": "customer"
                    },
                    "body": String(event.Body),
                    "status": "active",
                    "createdAt": "2017-08-21T12:34:12Z"
                }
            ]
        }
    );


    // replace with your Help Scout values
    let postOptions = {
        host: 'api.helpscout.net',
        port: '443',
        path: '/v1/conversations.json',
        method: 'POST',
        auth: '1234567890abcdef:X',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(postData)
        }
    };

    let req = https.request(postOptions, function(res) {
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
            console.log(chunk);
            callback(null, twiml);
        });
    });

    req.write(postData);
    req.end();

};

文档: https ://www.twilio.com/blog/2017/05/introducing-twilio-functions.html

于 2017-08-21T16:52:26.770 回答