2016-09-26 3 views
0

Google 캘린더 API를 사용하여 내가 소유 한 공개 캘린더의 최신 이벤트 목록을 가져 오려고합니다. 내 고객이 캘린더를 편집 할 수 있고 정보가 웹 사이트에 표시됩니다. 여기 내 코드는 (내가 Google의 예에서 편집하는) 지금까지입니다 :Google 캘린더 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에서 나는 다음 날 일정에서 이벤트를 당겨 :

2

오류는 요청의 자격 증명이 올바르지 않거나 누락되었음을 의미합니다. 라이브러리의 http 기록 기능을 사용하여 Google API 서버에 대한 요청 및 응답을 검사하십시오. 각 요청에는 베어러 토큰이있는 "Authorization"헤더가 있어야합니다. 이 thread에서 헤더에 Authorization: Oauth {access token}을 전달해야합니다. 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 키를 만듭니다

이 SO 게시물에 확인할 수 있습니다. 그런 다음 할 수 있습니다.

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

희망이 있습니다.

+0

미안 해요, 난 조금 혼란 스러워요의를하자 API_KEY을 설정합니다. 그래서 나는이 프로젝트에 연결되어야하는 서비스 계정을 만들고 캘린더에 해당 계정을 추가하여 볼 수있게했습니다. 그러나 나는 거기에서 어디로 가야할지 모르겠습니다. SA에는 키 ID가 있지만 어디서나 사용하도록되어 있는지 확실하지 않습니다. 내 코드는 이전에 게시 한 것과 정확히 동일하므로 수정해야하는 것이 무엇인지 잘 모르겠습니다. ( – Diericx

관련 문제