0

我通过 Hangouts API 创建了一个机器人,现在想通过 Google Scripts 控制台POST向 Google Calendar API ( Freebusy: query ) 发送请求:

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);
  }
}

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

有人可以弄清楚如何POST通过 Google Scripts 控制台从 Hangouts API 发送 -request 吗?

4

2 回答 2

2

日历 API 端点可能期望有效负载是 JSON 编码的字符串。所以更新你的选项对象如下:

var options = {
    "method":"POST",
    "contentType":"application/json",
    "payload":JSON.stringify(payload)
}
于 2018-07-18T17:56:52.210 回答
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);
    }
}
于 2018-07-18T18:10:56.040 回答