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

 

Further Reading:

  1. Google API Offline Access Using OAuth 2.0 Refresh Token
  2. Authenticating with OAuth 2.0 for Google API Access with PHP

2 Comments

  • February 22, 2012 - 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.

  • chris
    February 22, 2012 - 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;
    }

  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    *

    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


    All comments are moderated.