Created
July 3, 2014 10:03
-
-
Save tszym/06f8905d9529803150ae to your computer and use it in GitHub Desktop.
Youtube Data API v3 - 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/YouTube.php'; | |
session_start(); | |
$client = new Google_Client(); | |
$client->setApplicationName('TestingYoutube'); | |
$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 YouTube Data | |
$client->setScopes(array('https://www.googleapis.com/auth/youtube')); | |
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_YouTube($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>My Uploads</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