Using Google+ API for PHP — Need to get the users email

扶醉桌前 提交于 2020-01-13 04:28:06

问题


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?


回答1:


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.




回答2:


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.



回答3:


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": "fred.example@gmail.com",
 "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>";
}


来源:https://stackoverflow.com/questions/8706288/using-google-api-for-php-need-to-get-the-users-email

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!