Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm using the Google PHP API. The documentation is rather lackluster... I want to allow users to connect their Google+ information and also use it to sign the users up in my database. In order to do that I need to get the email they use for their google account. I can't seem to figure out how to. It's easy enough in Facebook by forcing the permission when the users connect to my app. Anyone have any idea? This is the code I'm using to grab the users google+ profile and it works fine, except users may not have their email listed there.

include_once("$DOCUMENT_ROOT/../qwiku_src/php/google/initialize.php");

$plus = new apiPlusService($client);
if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
    $me = $plus->people->get('me');
    print "Your Profile: <pre>" . print_r($me, true) . "</pre>";
    // The access token may have been updated lazily.
    $_SESSION['token'] = $client->getAccessToken();
} else {
    $authUrl = $client->createAuthUrl();
    print "<a class='login' href='$authUrl'>Connect Me!</a>";
}

Without the users email address, it sort of defeats the purpose of allowing users to signup with Google+ Anyone more familiar with the Google API know how I can get it?

share|improve this question

3 Answers 3

The UserInfo API is now supported by the Google API PHP Client.

Here's a small sample application: http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/userinfo/index.php

The important bit of the sample is here:

  $client = new apiClient();
  $client->setApplicationName(APP_NAME);
  $client->setClientId(CLIENT_ID);
  $client->setClientSecret(CLIENT_SECRET);
  $client->setRedirectUri(REDIRECT_URI);
  $client->setDeveloperKey(DEVELOPER_KEY);
  $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email',
        'https://www.googleapis.com/auth/plus.me'));      // Important!

  $oauth2 = new apiOauth2Service($client);

  // Authenticate the user, $_GET['code'] is used internally:
  $client->authenticate();

  // Will get id (number), email (string) and verified_email (boolean):
  $user = $oauth2->userinfo->get();
  $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
  print $email;

I'm assuming this snippet was called with a GET request including the authorization code. Remember to include or require apiOauth2Service.php in order for this to work. In my case is something like this:

  require_once 'google-api-php-client/apiClient.php';
  require_once 'google-api-php-client/contrib/apiOauth2Service.php';

Good luck.

share|improve this answer
    
Can you comment on this: stackoverflow.com/questions/11495303/… –  vivek.m Jul 16 '12 at 8:48

Forgive me if I'm missing something, but how do you know what Google account to link them with if you don't have their email address? Usually, you'd prompt the user to enter their Google Account's email in order to find their profile in the first place.

Using OAuth2, you can request permissions through the scope parameter. (Documentation.) I imagine the scopes you want are https://www.googleapis.com/auth/userinfo.email and https://www.googleapis.com/auth/userinfo.profile.

Then, it's a simple matter to get the profile info once you've obtained your access token. (I assume you've been able to redeem the returned authorization code for an access token?) Just make a get request to https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken}, which returns a JSON array of profile data, including email:

{
 "id": "00000000000000",
 "email": "[email protected]",
 "verified_email": true,
 "name": "Fred Example",
 "given_name": "Fred",
 "family_name": "Example",
 "picture": "https://lh5.googleusercontent.com/-2Sv-4bBMLLA/AAAAAAAAAAI/AAAAAAAAABo/bEG4kI2mG0I/photo.jpg",
 "gender": "male",
 "locale": "en-US"
}

There's got to be a method in the PHP library to make that request, but I can't find it. No guarantees, but try this:

$url = "https://www.googleapis.com/oauth2/v1/userinfo";
$request = apiClient::$io->makeRequest($client->sign(new apiHttpRequest($url, 'GET')));

if ((int)$request->getResponseHttpCode() == 200) {
        $response = $request->getResponseBody();
        $decodedResponse = json_decode($response, true);
        //process user info
      } else {
        $response = $request->getResponseBody();
        $decodedResponse = json_decode($response, true);
        if ($decodedResponse != $response && $decodedResponse != null && $decodedResponse['error']) {
          $response = $decodedResponse['error'];
        }
      }
 }

Anyway, in the code you posted, just pass the desired scope to createAuthUrl():

else {
    $authUrl = $client->createAuthUrl("https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile");
    print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
share|improve this answer
1  
I'm using the Google+ service and they OAuth my application just like in Facebook. The only problem is that I can't figure out how to make sure to get an email address so I can enter them into my database. I'll update the code for the full script but omit my "$client" variable that has all my sensitive codes. –  Jacob Jan 3 '12 at 3:35
    
Alright, sounds good. –  benesch Jan 3 '12 at 3:37
    
code.google.com/p/google-api-php-client More info here. –  Jacob Jan 3 '12 at 3:37
    
It appears that there is no easy way to go about this as there is no function. I may have found a workaround by digging around in the Google Group. I'll post the answer if I get this working, which shouldn't be too hard. I'll just have to use an HTTP request it seems. groups.google.com/forum/#!topic/google-api-php-client/… –  Jacob Jan 3 '12 at 3:42
    
Oh no, there definitely is. Give me a minute or two. –  benesch Jan 3 '12 at 3:44

Updated with today's API:

$googlePlus = new Google_Service_Plus($client);
$userProfile = $googlePlus->people->get('me');
$emails = $userProfile->getEmails();

This assumes the following:

  1. You've authenticated the current user with the proper scopes.
  2. You've set up $client with your client_id and client_secret.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.