Calendarlist使用服务帐户返回空结果集

时间:2019-05-15 09:16:08

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

我正在尝试使Google Calendar帐户与Google Calendar API之间建立联系,以根据Google Calendar包含的事件更新MySQL数据库。看来我的客户已经设置好了,现在我必须获取CalendarList,但是我在这里遇到了麻烦。

我从quickstart.php中所做的事情以及Google文档中说明的内容中汲取了灵感,尝试了一些测试。

  

问题是,当我使用getItems();方法时,我所有的请求都返回空结果。

我的代码:

function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Calendar API PHP synchroniser');
    $client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
    $client->setAuthConfig('Path/To/My/AccountService/File.json');
    $client->setAccessType('online');
    $client->setPrompt('MyCalendarWithMyData');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    /*
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            //I don't know what to put here.
        }
    }
    */
    return $client;
}

$client = getClient(); // based on quickstart.php

$service = new Google_Service_Calendar($client);// from the sample on documentation

$calendarList = $service->calendarList->listCalendarList();
$calendars=$calendarList->getItems();
var_dump($calendars);

我的目标是当我获得日历列表以获取相对于日历列表中每个日历的每个事件以更新数据库时。 谢谢 G.G

1 个答案:

答案 0 :(得分:0)

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

如果您进行

$calendar = $service->calendars->get('primary');
echo $calendar->getSummary();

您将看到实际上您的服务帐户中确实有一个日历。默认情况下,它的日历列表中没有任何内容。

如果您希望它可以访问您的个人Google日历,则需要访问google日历网站,并与服务帐户的电子邮件地址共享日历。那么它应该能够执行以下操作,确保您在设置时记下与之共享的日历的日历ID。

$calendar = $service->calendars->get('calendarid');

echo $calendar->getSummary();

如果您确实要在日历列表中添加它,则可以添加它。

$calendarListEntry = new Google_Service_Calendar_CalendarListEntry();
$calendarListEntry->setId("calendarId");

$createdCalendarListEntry = $service->calendarList->insert($calendarListEntry);

echo $createdCalendarListEntry->getSummary();

设置服务帐户

我已经提到过,服务帐户需要预先授权。您需要转到Google日历网站,并在您要使其能够访问的日历的设置下,需要与它共享日历,如图所示

enter image description here

有用的链接