在 G Suite 域中创建辅助日历

Creating Secondary Calendars In a GSuite Domain

我正在尝试在 redu-admin@redu.club 帐户下创建辅助日历。这是我的代码:

putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/redu-service-account.json');

define('SCOPES', Google_Service_Calendar::CALENDAR);

function createCalendar()
{
    try {
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->setApplicationName('Redu');
        $client->useApplicationDefaultCredentials();
        $client->addScope([SCOPES]);
        $client->setAccessType('offline');
        $service = new Google_Service_Calendar($client);

        // Calendar creation
        $calendar = new Google_Service_Calendar_Calendar();

        $calendar->setSummary('test');
        $calendar->setTimeZone('America/Los_Angeles');

        $createdCalendar = $service->calendars->insert($calendar);

        // Make the newly created calendar public
        $rule = new Google_Service_Calendar_AclRule();
        $scope = new Google_Service_Calendar_AclRuleScope();

        $scope->setType("default");
        $scope->setValue("");
        $rule->setScope($scope);
        $rule->setRole("reader");

        $createdRule = $service->acl->insert($createdCalendar->getId(), $rule);

        return $createdCalendar->getId();
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

此代码创建了一个日历,但是当我转到 redu-admin@redu.club 的日历时,我看不到它。我的猜测是它在服务帐户下创建了一个日历。当我尝试添加行时 $this->client->setSubject('redu-admin@redu.club');,我得到的错误是:

Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
  "error": "unauthorized_client",
  "error_description": "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."

非常感谢任何帮助。

如果您想为用户创建辅助日历,您需要模拟该用户

您已经正确尝试过:

        $client = new Google_Client();
        $client->setApplicationName('Redu');
        $client->useApplicationDefaultCredentials();
        $client->addScope([SCOPES]);
        $client->setAccessType('offline');
        $client->setSubject('redu-admin@redu.club');
        $service = new Google_Service_Calendar($client);

但是之前需要遵循两个重要步骤:

  1. 为服务帐户启用全域委派in the GCP console
  2. Admin console
  3. 中为服务帐户提供必要的委派范围