php - google 日历 API 事件插入 returns 403 权限不足

php - google calendar API event insert returns 403 Insufficient Permission

我修改了 Google 日历 API 快速入门以创建

$myEvent = $service->events->insert($calendarId, $myEvent);

出现错误:

PHP Fatal error:  Uncaught Google_Service_Exception: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "insufficientPermissions",
    "message": "Insufficient Permission"
   }
  ],
  "code": 403,
  "message": "Insufficient Permission"
 }
}

这是我的代码:

<?php
require_once __DIR__ . '/vendor/autoload.php';


define('APPLICATION_NAME', 'gCal2phposteo');
define('CREDENTIALS_PATH', '~/.credentials/altesGCal.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/altesGCal.json
define('SCOPES', implode(' ', array(
  Google_Service_Calendar::CALENDAR)
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');
  //pk, from Whosebug 
  // $client->setApprovalPrompt('force');     // needed if you loose the refreshToken

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  //pk, BUG: refresh token is not saved
  if ($client->isAccessTokenExpired()) {
    $refreshToken = $client->getRefreshToken();
    $client->fetchAccessTokenWithRefreshToken($refreshToken);     // loosing the refresh token here !
    $myAccess = $client->getAccessToken();
    $myAccess['refresh_token'] = $refreshToken;
    file_put_contents($credentialsPath, json_encode($myAccess));
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);

$calendarId = 'primary';

$myEvent = new Google_Service_Calendar_Event(
  array(
    'summary'     => 'pk4test Summary',
    'location'    => 'Village-Neuf, 1 rue des alouettes',
    'description' => 'Consultation d\'ostéopathie.',
    'start'       => array(
      'dateTime'  => '2016-11-07T18:15:00.000+01:00',
      'timeZone'  => 'Europe/Paris',
    ),
    'end'         => array(
      'dateTime'  => '2016-11-07T19:00:00.000+01:00',
      'timeZone'  => 'Europe/Paris',
    ),
    'attendees'   => array(
      array(
        'email'     => 'osteo@kienner.fr',
        'organizer' => true
      ),
      # array('email'   => 'xx@domain.fr', 'resource' => true),
    ),
    'creator'     => array(
      'email'       => 'osteo@kienner.fr',
      'displayName' => 'Cabinet d\'ostéopathie Kienner Mireille',
      'self'        => true
    ),
    'guestsCanInviteOthers'   => false,
    'guestsCanModify'         => false,
    'guestsCanSeeOtherGuests' => false,
  )
);

$myEvent = $service->events->insert($calendarId, $myEvent);

printf('Event created: %s', $myEvent->htmlLink);

我看到 3 个帖子说我应该与自动创建的服务帐户共享我的日历:

POST 1: 403 Forbidden message when calling the v3 Google Calendar API using a Service Account via OAuth 2.0

POST 2: Edit Google calendar events from Google service account: 403.

我找到了 2 个已创建的帐户,尽管我认为我必须与 XXXXXXXX@developer.gserviceaccount.com 共享日历,但我还与 myProjectName@@appspot.gserviceaccount.com

共享了日历

有人知道哪里出了问题吗?

确保您还向从 Google 开发人员控制台创建的客户端电子邮件地址授予了适当的权限。我的建议是按照 OAuth guide.

中概述的步骤进行操作

尝试删除所有存储的凭据。

在你的例子中'~/.credentials/altesGCal.json'.