Skip to content

Instantly share code, notes, and snippets.

@jveldboom
Created September 8, 2013 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jveldboom/6481874 to your computer and use it in GitHub Desktop.
Save jveldboom/6481874 to your computer and use it in GitHub Desktop.
quick example
<?php
require_once app_path().'/libraries/google-api-php-client/src/Google_Client.php';
require_once app_path().'/libraries/google-api-php-client/src/contrib/Google_AnalyticsService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google Analytics PHP Starter Application");
// Visit https://code.google.com/apis/console?api=analytics to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('xxxxxxxx');
$client->setClientSecret('xxxxxxxxxxx');
$client->setRedirectUri('http://localhost');
$client->setDeveloperKey('xxxxxxxxxx');
$service = new Google_AnalyticsService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken())
{
$analytics = $service->data_ga->get('ga:(viewid)', '2012-01-01', date("Y-m-d"), 'ga:visits,ga:pageviews');
echo '<pre>'.print_r($analytics,true).'</pre>';
// you'll need to save the access and refresh token to the database to access without user action
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
//echo '<pre>'.print_r($_SESSION,true).'</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment