2016-09-26 112 views
0

我正在尝试使用Google日历API来获取我拥有的公共日历的最新事件列表。这是我的客户可以编辑日历,信息将出现在网站上。这是到目前为止我的代码(这是我从谷歌的例子编辑):Google Calendar API:如何在没有用户登录的情况下获取公共日历的活动?

<html> 
    <head> 
    <script type="text/javascript"> 
     // Your Client ID can be retrieved from your project in the Google 
     // Developer Console, https://console.developers.google.com 
     var CLIENT_ID = '<MY-CLIENT-ID>'; 

     var SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]; 

     /** 
     * Check if current user has authorized this application. 
     */ 
     function checkAuth() { 
     gapi.auth.authorize(
      { 
      'client_id': CLIENT_ID, 
      'scope': SCOPES.join(' '), 
      'immediate': true 
      }, handleAuthResult); 
     } 

     /** 
     * Handle response from authorization server. 
     * 
     * @param {Object} authResult Authorization result. 
     */ 
     function handleAuthResult(authResult) { 
     var authorizeDiv = document.getElementById('authorize-div'); 
     if (authResult && !authResult.error) { 
      // Hide auth UI, then load client library. 
      authorizeDiv.style.display = 'none'; 
      loadCalendarApi(); 
     } else { 
      // Show auth UI, allowing the user to initiate authorization by 
      // clicking authorize button. 
      authorizeDiv.style.display = 'inline'; 
     } 
     } 

     /** 
     * Load Google Calendar client library. List upcoming events 
     * once client library is loaded. 
     */ 
     function loadCalendarApi() { 
     gapi.client.load('calendar', 'v3', listUpcomingEvents); 
     } 

     /** 
     * Print the summary and start datetime/date of the next ten events in 
     * the authorized user's calendar. If no events are found an 
     * appropriate message is printed. 
     */ 
     function listUpcomingEvents() { 
     var request = gapi.client.calendar.events.list({ 
      'calendarId': '<MY-PUB-CAL-ID>', 
      'timeMin': (new Date()).toISOString(), 
      'showDeleted': false, 
      'singleEvents': true, 
      'maxResults': 10, 
      'orderBy': 'startTime' 
     }); 

     request.execute(function(resp) { 
      var events = resp.items; 
      appendPre('Upcoming events:'); 

      if (events.length > 0) { 
      for (i = 0; i < events.length; i++) { 
       var event = events[i]; 
       var when = event.start.dateTime; 
       if (!when) { 
       when = event.start.date; 
       } 
       appendPre(event.summary + ' (' + when + ')') 
      } 
      } else { 
      appendPre('No upcoming events found.'); 
      } 

     }); 
     } 

     /** 
     * Append a pre element to the body containing the given message 
     * as its text node. 
     * 
     * @param {string} message Text to be placed in pre element. 
     */ 
     function appendPre(message) { 
     var pre = document.getElementById('output'); 
     var textContent = document.createTextNode(message + '\n'); 
     pre.appendChild(textContent); 
     } 

    </script> 
    <script src="https://apis.google.com/js/client.js?onload=loadCalendarApi"> 
    </script> 
    </head> 
    <body> 
    <div id="authorize-div" style="display: none"> 
     <span>Authorize access to Google Calendar API</span> 
     <!--Button for the user to click to initiate auth sequence --> 
     <button id="authorize-button" onclick="handleAuthClick(event)"> 
     Authorize 
     </button> 
    </div> 
    <pre id="output"></pre> 
    </body> 
</html> 

所以这几乎是工作,但是当我提出这个要求,我得到这个错误:

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

为什么我我没有通过身份验证访问此公共日历为只读?

回答

1

我想通了!我所要做的就是在api客户端加载后设置ApiKey。

<html> 
    <head> 
    <!-- JQuery --> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 

    <script type="text/javascript"> 

     // Your Client ID can be retrieved from your project in the Google 
     // Developer Console, https://console.developers.google.com 
     var CLIENT_ID = '371470665725-hp91oi0t7is0ua9k1fsl1ehfvj0ep6ik.apps.googleusercontent.com'; 
     var API_KEY = 'AIzaSyBlHlhQ-wej20Cnb6gkxh2f4s8rtbJm2sI' 
     var CAL_ID = '[email protected]' 
     var SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]; 


     /** 
     * Load Google Calendar client library. List upcoming events 
     * once client library is loaded. 
     */ 
     function loadCalendarApi() { 
     gapi.client.setApiKey(API_KEY); 
     gapi.client.load('calendar', 'v3', listUpcomingEvents); 
     } 

     /** 
     * Print the summary and start datetime/date of the next ten events in 
     * the authorized user's calendar. If no events are found an 
     * appropriate message is printed. 
     */ 
     function listUpcomingEvents() { 
     var request = gapi.client.calendar.events.list({ 
      'calendarId': CAL_ID, 
      'timeMin': (new Date()).toISOString(), 
      'showDeleted': false, 
      'singleEvents': true, 
      'maxResults': 10, 
      'orderBy': 'startTime' 
     }); 

     request.execute(function(resp) { 
      var events = resp.items; 
      appendPre('Upcoming events:'); 

      if (events.length > 0) { 
      for (i = 0; i < events.length; i++) { 
       var event = events[i]; 
       var when = event.start.dateTime; 
       if (!when) { 
       when = event.start.date; 
       } 
       appendPre(event.summary + ' (' + when + ')') 
      } 
      } else { 
      appendPre('No upcoming events found.'); 
      } 

     }); 
     } 

     /** 
     * Append a pre element to the body containing the given message 
     * as its text node. 
     * 
     * @param {string} message Text to be placed in pre element. 
     */ 
     function appendPre(message) { 
     var pre = document.getElementById('output'); 
     var textContent = document.createTextNode(message + '\n'); 
     pre.appendChild(textContent); 
     } 

    </script> 
    <script src="https://apis.google.com/js/client.js?onload=loadCalendarApi"> 
    </script> 
    </head> 
    <body> 
    <div id="authorize-div" style="display: none"> 
     <span>Authorize access to Google Calendar API</span> 
     <!--Button for the user to click to initiate auth sequence --> 
     <button id="authorize-button" onclick="handleAuthClick(event)"> 
     Authorize 
     </button> 
    </div> 
    <pre id="output"></pre> 
    </body> 
</html> 

所以你可以看到,我添加了一个API_KEY变量和函数loadCalendarApi我设置API_KEY然后让我拉的事件从日历:)

2

您的错误意味着请求的凭据不正确(或缺失)。使用库的http记录功能来检查对Google API服务器的请求和响应。每个请求都应该有一个带有不记名令牌的“授权”头。从thread开始,你需要在你的头文件中通过Authorization: Oauth {access token}

您可以检查此SO职位:How to list Google Calendar Events without User Authentication

What you need to do is use a Service account for this. You will then be able add the service accounts email address as a user to the calendar for your website. The Service account will then be able to access this calendar including the events.

您也可以注册一个开发者控制台,并创建API密钥。那么你可以这样做:

GET https://www.googleapis.com/calendar/v3/calendars/<CALENDAR_EMAIL>/events?key={YOUR_API_KEY} 

希望这有助于!

+0

对不起,我有点糊涂了。所以我去创建了一个应该链接到这个项目的服务账户,并将该账户添加到日历中,以便能够查看它。但我不确定该从哪里出发。 SA有一个密钥ID,但我不确定我是否应该在任何地方使用它。我的代码和我之前发布的时候完全一样,我不确定我应该修改哪些内容:( – Diericx

相关问题