Skip to content

Instantly share code, notes, and snippets.

@tszym
Created July 3, 2014 08:38
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/8fa89575c2fc8bac36d4 to your computer and use it in GitHub Desktop.
Save tszym/8fa89575c2fc8bac36d4 to your computer and use it in GitHub Desktop.
Youtube 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/YouTubeAnalytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('TestingYoutube');
$client->setClientId('my_big_id.apps.googleusercontent.com');
$client->setClientSecret('CLIENT_SECRET');
$client->setRedirectUri('http://'. $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF']);
$client->setScopes(array(
'https://www.googleapis.com/auth/yt-analytics.readonly',
'https://www.googleapis.com/auth/yt-analytics-monetary.readonly',
'https://www.googleapis.com/auth/youtube.readonly'
));
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match');
}
$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()) {
// Now we can use the client to query the API
$youtube = new Google_Service_YouTubeAnalytics($client);
try {
// Do work here
} catch (Google_ServiceException $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = '<h3>Authorization Required</h3> <p>You need to <a href="' . $authUrl . '">authorize access</a> before proceeding.<p>';
}
?>
<!doctype html>
<html>
<head>
<title>Use Youtube Analytics API</title>
<meta charset="UTF-8">
</head>
<body>
<?php echo $htmlBody; ?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment