Google API Requests with OAuth 2.0 Access Token

In the Authenticating with OAuth 2.0 for Google API Access with PHP post, an access token was retrieved for calls to Google APIs for data. In this post, the user’s name will be retrieved from their account.

To do that, the access token needs to be sent as a header param or query param with the call to the userinfo Google API. See Calling a Google API for more information. The header param method is shown below.

A PHP object containing the account info will be returned by a call to “call_api” function with the access token and API URL passed in:

$accountObj = call_api($_SESSION['accessToken'],"https://www.googleapis.com/oauth2/v1/userinfo");

“call_api” calls the api and gets the data:

function call_api($accessToken,$url){
	$curl = curl_init($url);
 
	curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);	
	$curlheader[0] = "Authorization: Bearer " . $accessToken;
	curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader);

	$json_response = curl_exec($curl);
	curl_close($curl);
		
	$responseObj = json_decode($json_response);
	
	return $responseObj;	    
}

From the account object, the name can be accessed;

$your_name =  $accountObj->name;

echo "<p class='successMessage'>The name on your Google account is: " . $your_name . "</p>";

Demo

Download code

Posted in Uncategorized. Permalink. Both comments and trackbacks are closed.

4 Comments

  1. February 23, 2012 at 7:58 am | Permalink

    @Chris

    Looks like you misspelled authorization_code. Should be:

    'grant_type' => 'authorization_code',
    

    With a ‘z’, not an ‘s’.

  2. chris
    February 23, 2012 at 5:50 am | Permalink

    Hi Jen,

    sorry i would have posted more but it was late.

    so i’m sending my parameters ($data), to get my access token:


    $data = array(
    'code' => ,
    'grant_type' => 'authorisation_code',
    'redirect_uri' => ,
    'client_id' => ,
    'client_secret' =>
    );

    But I get a 405 repsonse. Am I sending this information correctly?

  3. February 22, 2012 at 12:25 pm | Permalink

    @Chris

    Are you getting any error messages? Are you getting a valid access token? Honestly, it’s hard to help you unless you provide some more info.

  4. chris
    February 22, 2012 at 12:14 pm | Permalink

    I can’t get this working…


    public function make_request($url, $data)
    {
    echo $url;
    if(is_array($data)) $data = implode('&', $data);

    $curl = curl_init($url);

    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $curlheader[0] = "Authorization: Bearer " . $data;
    curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader);

    $json_response = curl_exec($curl);
    curl_close($curl);

    $responseObj = json_decode($json_response);
    return $responseObj;
    }