I will change the approach and I am going to use OAuth2 with PHP for both Facebook and Google+ authentication, but for now let's focus on using OAuth 2.0 to Access Google APIs.
After following the registration process of the application, I ended having the oauth2_client_id, oauth2_client_secret, and a place to receive the access_token at oauth2_redirect_uri.
Like I mentioned before I am using the PHP Library - the information and sample are pretty good. I have chosen my redirect_uri to coincide with the initial uri and check if the user it is logged in and if it has already granted access to my application or not. Here is the resulted index.php, just add your oauth2 information.
<?php
require_once 'google-api-php-client/src/apiClient.php';
require_once 'google-api-php-client/src/contrib/apiPlusService.php';
//start sessionsession_start();
$client = new apiClient();
$client->setApplicationName("Memory");
//Visit https://code.google.com/apis/console to generate your//oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setClientId('yourClientID');
$client->setClientSecret('yourClientSecret');
$client->setRedirectUri('youRedirectUri');
$client->setDeveloperKey('...');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
//init the required service Books, Buzz, Customsearch, Tasks, etc. - I am using Plus$plus = new apiPlusService($client);//if the user is not logged in, propmpt him to do so
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
//acquire the access tokenif (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
//if the user has granted access before, get the access token//else pop-up the auth dialog
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
//The access token may have been updated lazily.
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
//provide a way to revoke the token since there is no authorization manager on Google+ yetif (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
?>
<!doctype html>
<html>
<head></head>
<body>
<header><h1>Google+ Test</h1></header>
<div>
<?php if(isset($me)): ?>
<div>
<href="<?php echo $me['url'] ?>">
<?php print $me['displayName'] ?></a>
<div><img src="<?php echo $me['image']['url'];?>" /></div>
</div>
<?php endif ?>
<?php
if(isset($authUrl)) {
print "<a href='$authUrl'>Login!</a>";
} else {
print "<a href='?logout'>Logout</a>";
}
?>
</div>
</body>
</html>
Hack around with var_dump to get more information from the access token and use it as required.
No comments:
Post a Comment