Skip to content

Instantly share code, notes, and snippets.

@natmchugh
Created September 11, 2013 22:46
Show Gist options
  • Save natmchugh/6530830 to your computer and use it in GitHub Desktop.
Save natmchugh/6530830 to your computer and use it in GitHub Desktop.
<?php
require (__DIR__.'/../vendor/autoload.php');
use Guzzle\Http\Client;
use Fishtrap\Guzzle\Plugin\OAuth2Plugin;
use Guzzle\Log\MessageFormatter;
$clientId = '709587747215-XXXXXXXXXXXX.apps.googleusercontent.com';
$redirectURL = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$scope = 'https://www.googleapis.com/auth/userinfo.email '.
'https://www.googleapis.com/auth/userinfo.profile';
$clientSecret = 'XXXXXXX-XXXXXX';
if (empty($_GET['state']) || $_GET['state'] != 'loggedin') {
$params = array(
'scope' => $scope,
'state' => 'loggedin',
'redirect_uri' => $redirectURL,
'response_type' => 'code',
'client_id' => $clientId ,
'access_type' => 'offline',
'approval_prompt' => 'force',
// 'login_hint' => ''
);
$url = 'https://accounts.google.com/o/oauth2/auth?';
header('Location: '.$url.http_build_query($params));
}
$client = new Client('https://www.googleapis.com');
$oauth = new Oauth2Plugin(array(
'consumer_key' => $clientId ,
'consumer_secret' => 'zREZ7zWFxxKJJc-XXXXXXX',
'token_secret' => 'XXXXXXX',
'redirect_uri' => $redirectURL,
'code' => $_GET['code'],
'auth_url' => 'https://accounts.google.com/o/oauth2/token',
));
$client->addSubscriber($oauth);
$request = $client->get('/oauth2/v1/userinfo');
// try {
$response = $request->send();
// } catch (Guzzle\Http\Exception\ClientErrorResponseException $e) {
// var_dump($e->getMessage());
// $_SESSION['access_token'] = refreshToken($clientId, $clientSecret, $redirectURL);
// die;
// }
var_dump($request->getHeaders());
var_dump((string) $response->getBody());
function refreshToken($clientId, $clientSecret, $redirectURL)
{
$client = new Client('https://accounts.google.com');
$refresh_token = file_get_contents('/tmp/refresh_token');
$params = array(
'client_id' => $clientId,
'client_secret' => $clientSecret,
'refresh_token' => $refresh_token,
'grant_type' => 'refresh_token',
);
echo '<br/>------------Refreshing Token---------------<br/>';
try {
$request = $client->post('/o/oauth2/token')
->addPostFields($params);
$data = (array) $request->send()->json();
} catch (Guzzle\Http\Exception\ClientErrorResponseException $e) {
var_dump($e->getMessage());
getAccessToken($clientId, $clientSecret, $redirectURL);
die;
}
var_dump($data);
return $data['access_token'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment