Created
July 7, 2014 09:58
-
-
Save tszym/465444c45e1918224edc to your computer and use it in GitHub Desktop.
Google Analytics API - Authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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