从Google脚本控制台通过环聊API调用POST请求

时间:2018-07-18 14:22:42

标签: google-apps-script google-calendar-api gsuite hangouts-api hangouts-chat

我已经通过环聊API创建了一个漫游器,现在想通过Google脚本控制台向Google Calendar API(Freebusy: query)发送一个POST请求:

function testPOST() {

  var url = "https://www.googleapis.com/calendar/v3/freeBusy";

  var datetimeMin = "2018-02-22T18:00:00.000Z";
  var datetimeMax = "2018-02-22T20:00:00.000Z";

  var payload =
    {
      "timeMin": datetimeMin,
      "timeMax": datetimeMax,
      "timeZone": "Europe/Paris",
      "groupExpansionMax": 2,
      "calendarExpansionMax": 5,
      "items": [
        {
          //I read, that Gmail address is your default calendar ID
          "id": "%my_email@gmail.com%"
        }
      ]
    }

  var options =
    {
      "method": "POST",
      "payload": payload,
      "followRedirects": true,
      "muteHttpExceptions": true
    };

  var result = UrlFetchApp.fetch(url, options);

  if (result.getResponseCode() == 200) {

    var params = JSON.parse(result.getContentText());

    Logger.log(params.name);
    Logger.log(params.blog);

  } else {
    Logger.log(result);
  }
}

在执行期间,resultnullundefined,Google控制台会显示该对象,但它为空。我检查了一下,指定电子邮件的默认日历是公开的。

有人能弄清楚如何通过Google脚本控制台从环聊API发送POST请求吗?

2 个答案:

答案 0 :(得分:2)

Calendar API端点可能期望有效负载是JSON编码的字符串。因此,如下更新您的选项对象:

var options = {
    "method":"POST",
    "contentType":"application/json",
    "payload":JSON.stringify(payload)
}

答案 1 :(得分:1)

实际上,代码存在多个问题:

  1. url没有包含正确的Google Calendar API密钥

  2. 结果尚未解析为JSON

正确的代码:

function testPOST() {

    var url = 'https://www.googleapis.com/calendar/v3/freeBusy?key=%GOOGLE_CALENDAR_API_KEY%';

    var datetimeMin = "2018-02-22T18:00:00.000Z";
    var datetimeMax = "2018-02-22T20:00:00.000Z";

    var payload = {
            "timeMin": datetimeMin,
            "timeMax": datetimeMax,
            "timeZone": "Europe/Paris",
            "groupExpansionMax": 2,
            "calendarExpansionMax": 5,
            "items": [
                {
                    "id": "%my_email@gmail.com%"
                }
            ]
        }

    var options = {
            'method': "POST",
            "payload": payload,
            "muteHttpExceptions": true,
            "payload": JSON.stringify(payload),
            "contentType": 'application/json',
            "timeZone": "CEST",
        };

    var result = UrlFetchApp.fetch(url, options);

    Logger.log(result);

    if (result.getResponseCode() == 200) {

        var params = JSON.parse(result.getContentText());

        Logger.log(params.name);
        Logger.log(params.blog);

    } else {
        Logger.log(result);
    }
}