Čamo Čamo - 5 months ago 25
PHP Question

Google+ login via Javascript and PHP

Can you tell me please, how can I get user data(name, email) via Google+ Javascript/Php api? I go according this tutorial, which describes how to get

authResult['code']
via Javascript.

Thats ok I have it. I send it to server via Ajax but I don't know how to get user data like name and email via PHP BUT without any redirects. Here are the samples of code
Javascript:

function googleStart()
{
console.log('googleStart');
gapi.load('auth2', function()
{
auth2 = gapi.auth2.init({
client_id: '811214467813-v3fmui5dfghte5m0kmohsf6dl11ori3tg.apps.googleusercontent.com',
// Scopes to request in addition to 'profile' and 'email'
fetch_basic_profile: false,
scope: 'profile email'
});
});
}

function googleSignIn(authResult)
{
console.log(authResult);

if (authResult['code']) {

console.log(authResult);

// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');

// Send the code to the server
$.ajax({
type: 'POST',
url : "{link :Signgoogle:in}",
accepts : 'json',
// Spýtať sa na DJPW čo to tu je zakomentované
//contentType: 'application/octet-stream; charset=utf-8',
//processData: false,
data : {
'code' : authResult['code'],
'id_token' : authResult.getAuthResponse().id_token
},
...


PHP:

public function actionIn()
{
$code = $_POST['code'];

$client = new \Google_Client();
$client->setClientId(self::APP_ID);
$client->setClientSecret(self::APP_SECRET);
$client->setRedirectUri(self::REDIRECT_URI);

$client->authenticate($code);
$access_token = $client->getAccessToken();
$client->setAccessToken($access_token);

$client->getAuth();


$data = $access_token;

if($data)
{
$this->sendJson(array($data));
}
else
{
$data = array('error' => '$client->verifyIdToken($id) skočil chybou.');
$this->sendJson($data);
}

}
....


PHP retrieves an
access_token
but no users data. Ofcourse it is an ajax call so I can't do any redirects as Google describes on every page. Can you help me please I can't find any solution.

Thank you very much.

Answer

Once you have an authenticated client for the user you will want to make a request to the Google+ people.get API method.

$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setAccessToken($access_token);
$plus = new Google_Service_Plus($client);
$me = $plus->people->get('me');
print "ID: {$me['id']}\n";
print "Display Name: {$me['displayName']}\n";
print "Image Url: {$me['image']['url']}\n";
print "Url: {$me['url']}\n";

For their email you will have to iterate over the $me['emails'] array and find the value with type=account.

Comments