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>";
If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.

RSS
Twitter
4 Comments
@Chris
Looks like you misspelled authorization_code. Should be:
With a ‘z’, not an ‘s’.
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?
@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.
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;
}