Google Calenders API access to use API call calendarList->listCalendarList (PHP)

890 views
Skip to first unread message

Daniel Mulder

unread,
Jul 14, 2016, 6:42:15 AM7/14/16
to Google Calendar API
Hi,

I'm working on a website for a rental car company website with bookings module for rental cars. It's has 30+ cars and I have created a technical design that's simple and effective and is optimal for this client that hasn't a large budget. It will be a WordPress website with a basic WooCommer webshop and a calendar / bookings add on for cars that uses WooCommerce components to modify the order process. It also adds capability to query and use the availability of rental cars in a given period and does this using Google Calendars and a calendar per car for keeping track of availability. I already have made an Woo integration for injecting the FullCalender class into the WordPress / WC pages like the checkout form implemented as a calendar widget for users to select start and end dates with for a car. This class works great and also the Google Calendar API methods build into it. I'm stuck on the calendar and it really puzzles me: the calenderList->listCalcenderList. I have managed to make all examples work from the php api client lib, I can read calendar items from a single calendar with the api client etc but a list. Not so much luck. I need this to create a listing of all Calendars and search those one by one for available time slots. The latter I think a can do, the first not strangely enough. 

Here it works when reading the items for the last 30 or so days:

And here it doesn't work for creating a listing:

Below is the code I have from a tutorial and that works for fetching the data for a single calendar but not for a listing.

Is the anyone who can fill me in on what I need to use and where it needs to be placed? Like what are the proper items and files and what sort of connection object like use setAuthConfigFile and template/base.php. Is it one or the other or both? Etc. I'm not sure where to look at this point. 

Thanks in advanced Daniël


<?php


include_once __DIR__
. '/../vendor/autoload.php';
//include_once "templates/base.php";


$sc
=  '************************************/service-account-credentials.json';
$cs
=  '******************************************/google-api-php-client-2.0.0/client_secret.json';


define
('APPLICATION_NAME', 'Google Calendar API PHP Quickstart');
//define('CREDENTIALS_PATH', __DIR__ . '/../service-account-credentials.json');
define
('CREDENTIALS_PATH', $sc);
define
('CLIENT_SECRET_PATH', $cs);


// 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
->setAuthConfigFile(CLIENT_SECRET_PATH);
 
exit;
  $client
->setAccessType('offline');


 
// Load previously authorized credentials from a file.
  $credentialsPath
= expandHomeDirectory(CREDENTIALS_PATH);
 
if (file_exists($credentialsPath)) {
    $accessToken
= file_get_contents($credentialsPath);
 
} 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->authenticate($authCode);


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


 
// Refresh the token if it's expired.
 
if ($client->isAccessTokenExpired()) {
    $client
->refreshToken($client->getRefreshToken());
    file_put_contents
($credentialsPath, $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();
$service
= new Google_Service_Calendar($client);


// Print the next 10 events on the user's calendar.
$calendarId
= 'primary';
$optParams
= array(
 
'maxResults' => 10,
 
'orderBy' => 'startTime',
 
'singleEvents' => TRUE,
 
'timeMin' => date('c'),
);
$results
= $service->events->listEvents($calendarId, $optParams);


if (count($results->getItems()) == 0) {
 
print "No upcoming events found.\n";
} else {
 
print "Upcoming events:\n";
 
foreach ($results->getItems() as $event) {
    $start
= $event->start->dateTime;
   
if (empty($start)) {
      $start
= $event->start->date;
   
}
    printf
("%s (%s)\n", $event->getSummary(), $start);
 
}
}


echo pageHeader
("Service Account Access");


//TELL GOOGLE WHAT WE'RE DOING
$client
= new Google_Client();
$client
->setApplicationName("My Calendar"); //DON'T THINK THIS MATTERS
$client
->setDeveloperKey('***************************************'); //GET AT AT DEVELOPERS.GOOGLE.COM
$cal
= new Google_Service_Calendar($client);


//THE CALENDAR ID, FOUND IN CALENDAR SETTINGS. IF YOUR CALENDAR IS THROUGH GOOGLE APPS
//YOU MAY NEED TO CHANGE THE CENTRAL SHARING SETTINGS. THE CALENDAR FOR THIS SCRIPT
//MUST HAVE ALL EVENTS VIEWABLE IN SHARING SETTINGS.


//$calendarId = '****************************************************';


$calendarList
= $cal->calendarList->listCalendarList();


while(true) {
 
foreach ($calendarList->getItems() as $calendarListEntry) {
    echo $calendarListEntry
->getSummary();
 
}
  $pageToken
= $calendarList->getNextPageToken();
 
if ($pageToken) {
    $optParams
= array('pageToken' => $pageToken);
    $calendarList
= $service->calendarList->listCalendarList($optParams);
 
} else {
   
break;
 
}
}


?>


<?php pageFooter(__FILE__); ?>


This is a proof of concept code I used at the very beginning and uses the FullCalendar with Google Calenders like described and works. 



Daniel Mulder

unread,
Jul 14, 2016, 6:51:28 AM7/14/16
to Google Calendar API
Sorry, was to hasty with the code I included. I cleanded it up and this is it.

<?php

include_once __DIR__ . '/../vendor/autoload.php';
//include_once "templates/base.php";

$sc =  '**********************************************************************/service-account-credentials.json';
$cs =  '**********************************************************************/client_secret.json';
//echo pageHeader("Service Account Access");

//TELL GOOGLE WHAT WE'RE DOING
$client = new Google_Client();
$client->setApplicationName("My Calendar"); //DON'T THINK THIS MATTERS
$client->setDeveloperKey('***************************************'); //GET AT AT DEVELOPERS.GOOGLE.COM
$cal = new Google_Service_Calendar($client);

//THE CALENDAR ID, FOUND IN CALENDAR SETTINGS. IF YOUR CALENDAR IS THROUGH GOOGLE APPS
//YOU MAY NEED TO CHANGE THE CENTRAL SHARING SETTINGS. THE CALENDAR FOR THIS SCRIPT
//MUST HAVE ALL EVENTS VIEWABLE IN SHARING SETTINGS.

//$calendarList = $cal->calendarList;

$calendarList = $cal->calendarList->listCalendarList();

while(true) {
  foreach ($calendarList->getItems() as $calendarListEntry) {
    echo $calendarListEntry->getSummary();
  }
  $pageToken = $calendarList->getNextPageToken();
  if ($pageToken) {
    $optParams = array('pageToken' => $pageToken);
    $calendarList = $service->calendarList->listCalendarList($optParams);
  } else {
    break;
  }
}

?>

<?php pageFooter(__FILE__); ?>


Daniel Mulder

unread,
Jul 17, 2016, 6:33:14 AM7/17/16
to Google Calendar API
Hi

For those interested, I figured it out for myself now. This file is in the 2.0.1 lib api-client/examples folder. I call checkServiceAccountCredentialsFile() after spawning a new API client because in this function I also set the environment var GOOGLE_APPLICATION_CREDENTIALS as a temp way to make sure it's set. This function is in examples/templates/base.php. 

Gr


function checkServiceAccountCredentialsFile()
{
  // service account creds
  //$application_creds = __DIR__ . '/../../service-account-credentials.json';
  $application_creds = 'GOOGLE_APPLICATION_CREDENTIALS=' . API_CREDENTIALS_PATH . '/service-account-credentials.json';
  putenv( $application_creds );
  return file_exists($application_creds) ? $application_creds : false;
}



<?php
include_once __DIR__ . '/../vendor/autoload.php';
include_once "templates/base.php"; 

echo pageHeader("Calendar List");

/*************************************************
 * Ensure you've downloaded your oauth credentials
 ************************************************/
if (!$oauth_credentials = getOAuthCredentialsFile()) {
  echo missingOAuth2CredentialsWarning();
  return;
}

/************************************************
 * The redirect URI is to the current page, e.g:
 ************************************************/
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

$client = new Google_Client();
checkServiceAccountCredentialsFile();
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$service = new Google_Service_Calendar($client);

// add "?logout" to the URL to remove a token from the session
if (isset($_REQUEST['logout'])) {
  unset($_SESSION['calendar_token']);
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

/************************************************
 * If we have a code back from the OAuth 2.0 flow,
 * we need to exchange that with the
 * Google_Client::fetchAccessTokenWithAuthCode()
 * function. We store the resultant access token
 * bundle in the session, and redirect to ourself.
 ************************************************/
if (isset($_GET['code'])) {
  $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
  $client->setAccessToken($token);

  // store in the session also
  $_SESSION['calendar_token'] = $token;

  // redirect back to the example
  if (!headers_sent()) {
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
  }
}

// set the access token as part of the client
if (!empty($_SESSION['calendar_token'])) {
  $client->setAccessToken($_SESSION['calendar_token']);
  if ($client->isAccessTokenExpired()) {
    unset($_SESSION['calendar_token']);
  }
} else {
  $authUrl = $client->createAuthUrl();
}

$request = array_merge($_GET, $_POST);
if(isset($request['timeMin'])): 
    $date = new DateTime($request['timeMin']);
    $time['timeMin'] = $date->format(DateTime::ATOM);
else:
    $date = new DateTime();
    $time['timeMin'] = $date->format(DateTime::ATOM);
endif;
if(isset($request['timeMax'])): 
    $date = new DateTime($request['timeMax']);
    $time['timeMax'] = $date->format(DateTime::ATOM);
else:
    $date = new DateTime();
    $time['timeMax'] = $date->format(DateTime::ATOM);
endif;

?>

<div class="box" style="max-width: 900px; width: 98%;">
<?php if (isset($authUrl) ){ ?>
  <div class="request">
    <a class='login' href='<?= $authUrl ?>'>Connect Me!</a>
  </div>
<?php }elseif( isset($_GET['code']) && $_GET['code'] != '' ){ ?>
  <div>
    <p>Your call was successful!</p>
  
    
    <a class='logout' href='?logout'>Logout</a>
    
  </div>
<?php }else{?>
    
    <div class="result" style="max-width: 900px; width: 98%;">

        <?php
        /************************************************
         * If we're signed in then lets try to upload our
         * file.
         ************************************************/


            $calendarList = $service->calendarList->listCalendarList();

            while(true) {
                foreach ($calendarList->getItems() as $calendarListEntry) {
                  $summary = $calendarListEntry->getSummary();
                  if($summary != '') echo '<span>' . $calendarListEntry->id .': '. $calendarListEntry->getSummary() .'</span>' ."<br />";
                }
                $pageToken = $calendarList->getNextPageToken();
                if ($pageToken) {
                  $optParams = array('pageToken' => $pageToken);
                  $calendarList = $service->calendarList->listCalendarList($optParams);
                } else {
                  break;
                }
            }

            echo "<p><a class='logout' href='?logout'>Logout</a></p>";
        }
        ?>
        
    </div>
    
</div>



On Thursday, 14 July 2016 12:42:15 UTC+2, Daniel Mulder wrote:
Reply all
Reply to author
Forward
0 new messages