在CURL中为Google App脚本转换--data-urlencode

时间:2018-02-15 19:25:48

标签: google-apps-script

我正在尝试编写转换此调用的Google Apps脚本

curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/AC82950e7259813d6695afc79412c7a06f/Messages.json'/ 
  --data-urlencode 'To=+441632960675'  \
  --data-urlencode 'MessagingServiceSid=MG9752274e9e519418a7406176694466fa'  \
  --data-urlencode 'Body=Phantom Menace was clearly the best of the prequel trilogy.'  \
  -u AC82950e7259813d6695afc79412c7a06f:auth_token

使用UrlFetchApp.fetch()命令在google app脚本中兼容。

我的代码看起来像这样

    function sendcopilot() {
      var messages_url = "https://api.twilio.com/2010-04-01/Accounts/AC82950e7259813d6695afc79412c7a06f/Messages.json";

      var payload = {
        "To": "+1415555555",
        "MessagingServiceSid":"sidid",
        "Body" : "Phantom Menace"

      };
   var options = {

        "method" : "post",
        "payload" : payload
      };

      options.headers = {
        "Authorization" : "Basic " + Utilities.base64Encode("mytoken:mysecret")
      };

      UrlFetchApp.fetch(messages_url, options);
    }

我一直收到的错误似乎是我没有做“--data-urlencode”这篇文章,但我无法解决如何在Google Apps脚本中进行操作

1 个答案:

答案 0 :(得分:0)

关键是上下文类型是application/x-www-form-urlencoded

这是一个工作示例。

您必须更新凭据:

function sendText(link, from) {
  const TWILIO_ACCOUNT_SID = 'XXX';
  const TWILIO_AUTH_TOKEN = 'YYY';
  const link = 'https://api.twilio.com/2010-04-01/Accounts/' + TWILIO_ACCOUNT_SID + '/Messages.json';
  let formData = {
    'Body': 'See ' + link + '\n\nClick link to see detail and schedule a viewing.\n\nReply STOP to end receiving matches.',
    'From': 'xxx',
    'To': 'xxx',
    'MediaUrl': 'https://demo.twilio.com/owl.png'
  };
  var options =
  {
    'method': 'post',
    'contentType': 'application/x-www-form-urlencoded',
    'payload': formData
  };
  options.headers = { "Authorization": "Basic " + Utilities.base64Encode(TWILIO_ACCOUNT_SID + ":" + TWILIO_AUTH_TOKEN) };
  UrlFetchApp.fetch(link, options);
}