Search code examples
google-oauthgoogle-api-php-client

How to retrieve user "basic profile" and email information for Google authenticated user


I'm working on a simple Google login integration for a website. I need a user to be able to click a button, authenticate with Google, and then retrieve some basic information - name, ID, and email address. I'm using PHP for this task as it's my only real option for the site.

I've been trying to use the beta PHP API found here and for the most part have gotten it to work by employing the example laid out here. The example tries to get user authorization for the application to access Drive file meta data, so I needed to change the scope to be more appropriate for the information we need. I made the following adjustment and it appeared to work fine:

Out:

$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

In:

$client->addScope("email");

After authenticating with Google I'm prompted to authorize the application for both basic profile information and email access. The problem I have now is getting the application to actually retrieve the information it has been authorized to access. I haven't been able to locate an example similar to my scenario, using the version of the PHP API I'm using or the example that Google itself provides.

Essentially I need to replace this:

$drive_service = new Google_Service_Drive($client);
$files_list = $drive_service->files->listFiles(array())->getItems();
echo json_encode($files_list);

With commands that can grab the name, ID, and email of the user that's authenticated with Google via our app.

Edit: Received answer below. Had to make some small edits to get it to work just right.

$google_oauthV2 = new Google_Service_Oauth2($client); [Added 'new' before Google_Service_Oauth2]

print_r($google_oauthV2->userinfo->get()); [Didn't like dump(), changed it to print_r to blast out the results]


Solution

  • Just from digging around the source code, I found Github - Google_Service_Oauth2.php

    $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email',
              'https://www.googleapis.com/auth/plus.me'));
    $google_oauthV2 = Google_Service_Oauth2($client);
    dump($google_oauthV2->userinfo->get());