I need some help with Google API Oauth 2.0

Hello everyone,

I’m trying to pull my list of Google contacts and display on a page the name and phone number.
I found an interesting post made by Lorna Jane and tried her code. I get a token returned, but every time I revisit the page, it asks me to authenticate again. With current code, no data array is pulled:

$id = 'secret.apps.googleusercontent.com';
$scope = 'https://www.google.com/m8/feeds/default/full/';
$uri = 'http://localhost/callback.php';

$params = array(
	'response_type'	=> 'code',
	'client_id'	=> $id,
	'redirect_uri'	=> $uri,
	'scope'		=> $scope
);
$query = 'https://accounts.google.com/o/oauth2/auth?' . http_build_query($params);
header('Location: ' . filter_var($query, FILTER_SANITIZE_URL));
if (isset($_GET['code']))
{
	$code = $_GET['code'];
	$token = 'https://accounts.google.com/o/oauth2/token';
	$params = array(
		'code'		=> $code,
		'client_id'	=> $id,
		'client_secret'	=> 'clientsecret',
		'redirect_uri'	=> $uri,
		'grant_type'	=> 'authorization_code'
	);
	$request = new HttpRequest($token, HttpRequest::METH_POST);
	$request->setPostFields($params);
	$request->send();
	$responseObj = json_decode($request->getResponseBody());
	var_dump($responseObj);
}

Please let me know what I’m missing. I prefer the pecl_http implementation, over the Google API library.

Hi,

When the script runs, its redirecting to Google for authorization. Once you authorize the request it redirects you back to the same script and the process starts again, so you get caught in a loop. What you need to do is separate out the callback code into a separate script, or at least include some kind of check that will skip the authorization redirect once you have a code from Google:


if (isset($_GET['code']))
{
    $code = $_GET['code'];
    $token = 'https://accounts.google.com/o/oauth2/token';
    $params = array(
        'code'		=> $code,
        'client_id'	=> $id,
        'client_secret'	=> 'clientsecret',
        'redirect_uri'	=> $uri,
        'grant_type'	=> 'authorization_code'
    );
    $request = new HttpRequest($token, HttpRequest::METH_POST);
    $request->setPostFields($params);
    $request->send();
    $responseObj = json_decode($request->getResponseBody());
    var_dump($responseObj);
} else {
    $id = 'secret.apps.googleusercontent.com';
    $scope = 'https://www.google.com/m8/feeds/default/full/';
    $uri = 'http://localhost/callback.php';

    $params = array(
        'response_type'	=> 'code',
        'client_id'	=> $id,
        'redirect_uri'	=> $uri,
        'scope'		=> $scope
    );
    $query = 'https://accounts.google.com/o/oauth2/auth?' . http_build_query($params);
    header('Location: ' . filter_var($query, FILTER_SANITIZE_URL));
}