Google Calendar API,包含服务帐户问题,权限不足

时间:2017-01-19 09:20:36

标签: php google-api google-calendar-api google-api-php-client service-accounts

Google Calendar API显示权限不足的错误。

致命错误:未捕获的异常'Google_Service_Exception',消息'错误调用GET https://www.googleapis.com/calendar/v3/users/me/calendarList :( 403)权限不足'

<?php

  session_start();
  include_once "templates/base.php";

  require_once realpath(dirname(__FILE__)'/../src/Google/autoload.php');

  $client_id = '110224493213908548123'; //Client ID .apps.googleusercontent.com
  $service_account_name = 'test@test-156006.iam.gserviceaccount.com'; //Email Address
  $key_file_location = 'test.p12'; //key.p12

  $client = new Google_Client();
  $client->setApplicationName("Easycarcare");
  $client->addScope("https://www.googleapis.com/auth/calendar");
  //$client->addScope("https://www.googleapis.com/auth/calendar.readonly");
  $service = new Google_Service_Calendar($client);



  if (isset($_SESSION['service_token'])) {
    $client->setAccessToken($_SESSION['service_token']);
  }
  $key = file_get_contents($key_file_location);
  $cred = new Google_Auth_AssertionCredentials(
      $service_account_name,
      array('https://www.googleapis.com/auth/calendar'),
      $key
  );

  $client->setAssertionCredentials($cred);
  if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
  }
  $_SESSION['service_token'] = $client->getAccessToken();


  $calendarList = $service->calendarList->listCalendarList();

  while(true) {
    foreach ($calendarList->getItems() as $calendarListEntry) {
      echo $calendarListEntry->getSummary();
    }
    $pageToken = $calendarList->getNextPageToken();
    if ($pageToken) {
      $optParams = array('pageToken' => $pageToken);
      $calendarList = $service->calendarList->listCalendarList($optParams);
    } else {
      break;
    }
  }

1 个答案:

答案 0 :(得分:0)

您需要记住服务帐户不是您。服务帐户是虚拟用户。它有自己的谷歌日历帐户,自己的谷歌驱动器帐户,可能还有更多。

在您第一次create a calendar之前,您不会在日历列表中看到任何数据,然后将其添加到calendar list

记住日历列表不是用户可以访问日历的日历列表,只是左下角Web视图中的显示。因此,即使您与服务帐户共享了一个个人日历,它也不会出现在服务帐户日历列表中,直到您以编程方式将其添加到该列表中。

答案:您没有看到任何数据,因为服务帐户没有数据。