1

There are hundreds of examaple files for Google Calendar API and I have been stuck a couple of days now and i'm getting a lot of errors. I downloaded the https://github.com/google/google-api-php-client/releases/tag/v2.0.3 lib and tried to add a event in my Google Calendar. It would be great if you could give us an up to date solution for us newbies here on stackoverflow. The code is running on hostinger.com and the files is in the same dir.

Is there any up to date ready to use example that creates events? Like new version of this.

Isn't client_secret.json' same as '/calendar-php-quickstart.json'?

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


define('APPLICATION_NAME', 'Google Calendar API PHP Quickstart');
define('CREDENTIALS_PATH', '/calendar-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-php-quickstart.json
define('SCOPES', implode(' ', array(
 Google_Service_Calendar::CALENDAR_READONLY)
));

 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');

 // 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.
 if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
 }
 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();


 $event = new Google_Service_Calendar_Event(array(
  'summary' => 'Google I/O 2015',
 'location' => '800 Howard St., San Francisco, CA 94103',
 'description' => 'A chance to hear more about Google\'s developer   products.',
 'start' => array(
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
 ),
 'end' => array(
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
 ),
    'recurrence' => array(
   'RRULE:FREQ=DAILY;COUNT=2'
    ),
  'attendees' => array(
   array('email' => 'lpage@example.com'),
   array('email' => 'sbrin@example.com'),
  ),
   'reminders' => array(
   'useDefault' => FALSE,
    'overrides' => array(
     array('method' => 'email', 'minutes' => 24 * 60),
     array('method' => 'popup', 'minutes' => 10),
    ),
    ),
    ));

$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
Community
  • 1
  • 1
David
  • 11
  • 4
  • [i wonder if the solutions here are helpful](http://stackoverflow.com/questions/34130068/fatal-error-class-google-auth-assertioncredentials-not-found) – WEBjuju Dec 09 '16 at 13:25
  • Thanks for the url! They used the 2.0.0-RC2 and it is from 2015. Is this still useful? @WEBjuju – David Dec 09 '16 at 13:27
  • you should be using v3, but note they had issues with mixing old and new code. if that's not an issue for you, that's not an issue. – WEBjuju Dec 09 '16 at 13:29
  • this is probably more updated example it uses the .json service account file instead of the p12. You will have to alter it for calendar though https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-php Sorry I haven't been keeping the PHP examples on my site up to date anymore since most of the google samples work. assuming you know where to look :) – Linda Lawton - DaImTo Dec 09 '16 at 13:31
  • 1
    [according to this](https://github.com/google/google-api-php-client/blob/master/UPGRADING.md) Google_Auth_AssertionCredentials has been removed at 2.0. – WEBjuju Dec 09 '16 at 13:32
  • Ohh I got this wrong. I thought the code from @DaImTo was for google calender but it's for analytics.. – David Dec 09 '16 at 13:35
  • Question is updated @WEBjuju – David Dec 09 '16 at 13:41
  • 1
    @David you will need to ad some code to show what you have tried or your question is just please link me / give me code which is not a valid question on stack. – Linda Lawton - DaImTo Dec 09 '16 at 13:45

1 Answers1

0

This is the example Google gives for php inserting a calendar event in v3:

Note that for v3 you must use OAuth 2.0, but the best way to do that is with the google-api-php-client using this example called "idtoken"

// Refer to the PHP quickstart on how to setup the environment:
// https://developers.google.com/google-apps/calendar/quickstart/php
// Change the scope to Google_Service_Calendar::CALENDAR and delete any stored
// credentials.

$event = new Google_Service_Calendar_Event(array(
  'summary' => 'Google I/O 2015',
  'location' => '800 Howard St., San Francisco, CA 94103',
  'description' => 'A chance to hear more about Google\'s developer products.',
  'start' => array(
    'dateTime' => '2015-05-28T09:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'end' => array(
    'dateTime' => '2015-05-28T17:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'recurrence' => array(
    'RRULE:FREQ=DAILY;COUNT=2'
  ),
  'attendees' => array(
    array('email' => 'lpage@example.com'),
    array('email' => 'sbrin@example.com'),
  ),
  'reminders' => array(
    'useDefault' => FALSE,
    'overrides' => array(
      array('method' => 'email', 'minutes' => 24 * 60),
      array('method' => 'popup', 'minutes' => 10),
    ),
  ),
));

$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
WEBjuju
  • 5,797
  • 4
  • 27
  • 36
  • I tried with Google's Quikstart.php but got the error. "Fatal error: Uncaught exception 'Exception' with message 'This application must be run on the command line.' " – David Dec 09 '16 at 14:35
  • you will need to ad some code to show what you have tried – WEBjuju Dec 09 '16 at 14:36
  • be sure to add the error you are getting :) but for [This application must be run on the command line](http://stackoverflow.com/questions/32902777/facing-error-fatal-error-uncaught-exception-google-auth-exception-with-messa) there are answers out there. – WEBjuju Dec 09 '16 at 14:49
  • So I can't let the server take care of this? I need to use command line? – David Dec 09 '16 at 15:14
  • [You will have to authenticate the user the first time via a webpage. There is no way to work around that. Once you have the refresh token everything else can be automated to run command line](http://techno-outlet.eu/index.php?q=aHR0cDovL3RlY2huby1vdXRsZXQuZXUvaW5kZXgucGhwP3E9YUhSMGNEb3ZMM04wWVdOcmIzWmxjbVpzYjNjdVkyOXRMM0YxWlhOMGFXOXVjeTgwTURrM016SXpOaTluYjI5bmJHVXRZMkZzWlc1a1lYSXRZWEJwTFhCb2NDMXphMmx3TFhSb1pTMWpiR2xsYm5RdGMybGtaUzFoZFhSb1pXNTBhV05oZEdsdmJpMWhibVF0ZEhWeWJpMWxkbVZ5ZVhSb2FXNW4) says @DaImTo – WEBjuju Dec 09 '16 at 15:18
  • Automated to run command line? Why can't I user a Service account? Why do I need a command line? I think the best solution is tol build my own PHP calender.. – David Dec 09 '16 at 15:25
  • Are you posting to the users' calendars or are you posting to a "site" calendar? – WEBjuju Dec 09 '16 at 15:28
  • A "site" calender so I wan't the webapplication to handle everything. Was that clear? – David Dec 09 '16 at 23:00
  • If you would follow the tutorial - [Google Calendar API with PHP – Service Account](http://www.daimto.com/google-calendar-api-with-php-service-account/) this will explain how to use Calendar API and integrate it using service account, which would still be applicable to use in the present Calendar version. – Mr.Rebot Dec 11 '16 at 14:47
  • client_secret.json is not the same to calendar-php-quickstart.json. The first file is the credentials containing the [client ID, client secret, and other OAuth 2.0 parameters](https://developers.google.com/api-client-library/python/guide/aaa_client_secrets) while the second file is where the saved credentials are stored. In the tutorial, it is stated "using a service account removes the need to prompt a user to give your application access, as long as the application email has access in the Google calendar this script will work without authentication prompt." Hope this helps. – Mr.Rebot Dec 11 '16 at 14:47