FacebookTwitterGoogle+Share

Pulling data from Google Calendar

I track my hours on Google calendar. I know, high-tech, right?

Like a savage, at the end of every month I’d count up the hours for billing — but no more! That’s for the machines.

If getting a list of events from Google’s Calendar API between a specified date range seems useful to you — well, here, have some code:

// The API was installed by composer
require 'vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfigFile('/path/to/config.json'); // Replace this with your JSON file
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
$client->setRedirectUri('http://location/of/oauth2callback.php'); // Replace this with your callback URL

// This is my timezone
date_default_timezone_set('America/Los_Angeles');

// Connect to a google account
session_start();
if (!array_key_exists( 'accessToken', $_SESSION ) ) {
	$auth_url = $client->createAuthUrl();
	header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
	die();
} 


$accessToken = $_SESSION['accessToken'];
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
	if (!array_key_exists( 'refreshToken', $_SESSION ) ) {
		$auth_url = $client->createAuthUrl();
		header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
		die();
	} 
	
	$client->refreshToken($session['refreshToken']);
	$session['accessToken'] = $client->getAccessToken();
}


// Retrieve data
$service = new Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();
$calendarId = 'calendar/id'; // Replace this with your calendar ID

// Check the current month
$start = date('Y-m-01');
$end = date('Y-m-').date("t");

$optParams = array(
  'maxResults' => 2500, 
  'orderBy' => 'startTime',
  'singleEvents' => TRUE,
  'timeMin' => dateconv($start),
  'timeMax' => dateconv($end, true)
);
try {
	$events = $service->events->listEvents($calendarId, $optParams);
} catch( Exception $e ) {
	print_r( $e );
}


while(true) {
	try {
		foreach ($events->getItems() as $event) {
			$name = $event->getSummary();
			$delta = strtotime($event->getEnd()['dateTime']) - strtotime($event->getStart()['dateTime']);
			$hours =  $delta/(60*60);
		}
	} catch( Exception $e ) {
		print_r( $e );
	}
	$pageToken = $events->getNextPageToken();
	if ($pageToken) {
		$optParams['pageToken'] = $pageToken;
		$events = $service->events->listEvents($calendarId, $optParams);
	} else {
		break;
	}
}

You’ll need to specify your calendar ID. You can get a list of all of them like this:


while(true) {
	foreach ($calendarList->getItems() as $e) {
		echo $e->getId().": ".$e->getSummary()."\n";
  	}
	$pageToken = $calendarList->getNextPageToken();
	if ($pageToken) {
		$optParams = array('pageToken' => $pageToken);
		$calendarList = $service->calendarList->listCalendarList($optParams);
	} else {
		break;
	}
}

But wait, what’s this oauth2callback.php? Basically it’s the location google hits when you confirm the site should be allowed to access your account.

require 'vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfigFile('/path/to/config.json'); // Replace this with your JSON file
$client->setRedirectUri('http://location/of/oauth2callback.php'); // Replace this with your callback URL
session_start();
if ( array_key_exists( 'code', $_REQUEST ) ) {
	$_SESSION['accessToken'] = $client->authenticate($_REQUEST['code']);
	$_SESSION['refreshToken'] = $client->getRefreshToken();
	header('location: index.php');
} else {
	echo "error";
}

Now, you may be wondering where this config.json comes from. Basically you have to blah blah the api and create a new client id under credentials blah blah. It’s probably just about as confusing as they could make it, but here’s a link to their wizard and, probably more useful, a link to their PHP quickstart guide. The Step 1: Enable the Google Calendar API section is the one you’re looking for.

 

Comments

You must be logged in to post a comment.