php - google calendar API事件插入返回403权限不足

时间:2016-11-06 19:59:08

标签: php api google-calendar-api

我修改了 Google Calendar 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 StackOverflow https://stackoverflow.com/questions/10827920/not-receiving-google-oauth-refresh-token
  // $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分享了日历

任何人都知道出了什么问题?

2 个答案:

答案 0 :(得分:2)

尝试删除任何存储的凭据。

在你的情况下'〜/ .credentials / altesGCal.json'。

答案 1 :(得分:0)

确保您还为从Google Developer Console创建的客户电子邮件地址授予适当的权限。我建议遵循OAuth guide.

中列出的步骤