访问谷歌日历API擅自通过JavaScript(Accessing Google Calendar

2019-07-04 07:32发布

我试图访问公共日历(从谷歌日历),其中包含国家法定节假日:

calendarId: 'pt_br.brazilian#holiday@group.v.calendar.google.com'

随着日历是公开的,我想我应该能够仅使用API​​密钥来访问它:

function OnLoadCallback() {
    var config = {
        client_id: '32j4lk32j5kj342l5h.googleuser.com', //fake client id
        scope: 'https://www.googleapis.com/auth/calendar.readonly'
    };
    gapi.client.setApiKey('fId345AM20HXXXXXXXXXXXXXXXXgT3f9kyp2REfkaw2'); //fake api key
    gapi.client.load('calendar', 'v3', function() {
        var today = new Date(),
            request;

        request = gapi.client.calendar.calendarList.get({
            calendarId: 'pt_br.brazilian#holiday@group.v.calendar.google.com',
            timeMin: (new Date(today.getFullYear(), today.getMonth(), today.getDay(), 0, 0, 0, 0)).toISOString(),
            timeMax: (new Date(today.getFullYear(), today.getMonth(), today.getDay(), 23, 59, 59, 999)).toISOString(),
            fields: 'items(creator(displayName,email),end,endTimeUnspecified,start,summary)'
        });

        request.execute(function(response) {
            window.alert('length of items: ' + response.items.length);
        });

    });
}

不过,我不断收到以下响应,这是一个401(未授权)错误:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

有人能澄清什么,我试图做的是实现与否?
最后,如果它是可能的 - 我有什么改变提到我当前的代码?

Answer 1:

我是能够做到使用jQuery同样的事情。

var mykey = 'your_api_key'; // typically like Gtg-rtZdsreUr_fLfhgPfgff
var calendarid = 'you_calendar_id'; // will look somewhat like 3ruy234vodf6hf4sdf5sd84f@group.calendar.google.com

$.ajax({
    type: 'GET',
    url: encodeURI('https://www.googleapis.com/calendar/v3/calendars/' + calendarid+ '/events?key=' + mykey),
    dataType: 'json',
    success: function (response) {
        //do whatever you want with each
    },
    error: function (response) {
        //tell that an error has occurred
    }
});

然而,你需要确保你已经做了以下内容: -


1)注册一个项目https://code.google.com/apis/console
2)生成一个简单的API访问键
3)确保日历API是根据服务激活。

更多详情https://developers.google.com/google-apps/calendar/firstapp



文章来源: Accessing Google Calendar API without authorization via JavaScript