Search code examples
apigoogle-calendar-apigoogle-oauth

Google OAuth 2.0 Service Account - Calendar API (PHP Client)


I have a Google Apps account. I am trying to manipulate a users Calendar within this account.

  • I have created the Project, added the Calendar API service and created a Service Account OAuth 2.0 Client ID through the API console.
  • I have added that generated Email address to the Calendar through the Calendar settings to share the calendar.
  • I have followed the steps suggested to Manage the API access. The client name is the same domain that the Google Apps account is on, and the scope is "https://www.googleapis.com/auth/calendar".
  • Through various sources I was able to compile a script that allows me to read the nominated calendars events and add events to it.

What I cant do is create a sub calendar. I have read through, https://developers.google.com/accounts/docs/OAuth2ServiceAccount, and am attempting to send through the "prn".

This is where the script fails with; Error refreshing the OAuth2 token, message: '{ "error" : "access_denied" }'. If I remove the prn, then all is "good". The calendars just get created under the developer email. Code:

<?
ini_set('display_errors', 1);

session_start();

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';


const CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com';
const MY_EMAIL  = '[email protected]';
const KEY_FILE = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12';

$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setApplicationName("My App");
$client->setAccessType('offline');
$client->setUseObjects(true);

if (isset($_SESSION['token'])) {
 $client->setAccessToken($_SESSION['token']);
}

$key = file_get_contents(KEY_FILE);

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
} else {
    $client->setAssertionCredentials(new Google_AssertionCredentials(
        SERVICE_ACCOUNT_NAME,
        array('https://www.googleapis.com/auth/calendar'),
        $key,
        'notasecret',
        'http://oauth.net/grant_type/jwt/1.0/bearer',
        MY_EMAIL)
    );  
}

// even tried setting the email here
$client->setClientId(MY_EMAIL);

$calendar = new Google_Calendar();
$calendar->setSummary('calendarx');
$calendar->setTimeZone('Australia/Brisbane');
$createdCalendar = $cal->calendars->insert($calendar);
?>

Any help would be greatly appreciated.


Solution

  • The prn field works only with hosted domains, if the domain administrator enabled your application (based on client id) to impersonate users.