Skip to content

Instantly share code, notes, and snippets.

@tszym
Created July 7, 2014 09:58
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 tszym/465444c45e1918224edc to your computer and use it in GitHub Desktop.
Save tszym/465444c45e1918224edc to your computer and use it in GitHub Desktop.
Google Analytics API - Authentication
<?php
/**
* How to authenticate with OAuth2 by the Google API client
**/
$classLoader = require __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/../vendor/google/apiclient/src/Google/Client.php';
require_once __DIR__.'/../vendor/google/apiclient/src/Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('BunkrTestAnalytics1');
$client->setClientId('my_big_client_id.apps.googleusercontent.com');
$client->setClientSecret('CLIENT_SECRET');
$client->setRedirectUri('http://'. $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF']);
// You need this scope for Analytics
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://'. $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
// Create analytics service object. See next step below.
$analytics = new Google_Service_Analytics($client);
runDemo($analytics);
}
function runDemp($analytics) {
// Here you make requests to the API
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment