使用Google+ API for PHP - 需要向用户发送电子邮件

Thr*_*ead 4 php google-api

我正在使用Google PHP API.文档相当平淡...我希望允许用户连接他们的Google+信息,并使用它来在我的数据库中签署用户.为此,我需要获取他们用于Google帐户的电子邮件.我似乎无法弄清楚如何.当用户连接到我的应用程序时,通过强制许可在Facebook上很容易.任何人都有任何想法?这是我用来抓取用户google +个人资料的代码,它工作正常,除非用户可能没有列出他们的电子邮件.

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>";
}
Run Code Online (Sandbox Code Playgroud)

如果没有用户的电子邮件地址,就会失去允许用户注册Google+的目的.任何更熟悉Google API的人都知道如何获得它?

Chi*_*hah 10

Google API PHP客户端现在支持UserInfo API.

以下是一个小型示例应用程序:http: //code.google.com/p/google-api-php-client/source/browse/trunk/examples/userinfo/index.php

样本的重要部分在这里:

  $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;
Run Code Online (Sandbox Code Playgroud)

我假设这个片段是用包含授权码的GET请求调用的.请记住包含或要求apiOauth2Service.php才能使其正常工作.在我的情况下是这样的:

  require_once 'google-api-php-client/apiClient.php';
  require_once 'google-api-php-client/contrib/apiOauth2Service.php';
Run Code Online (Sandbox Code Playgroud)

祝好运.


Joe*_*vin 7

更新了今天的API:

$googlePlus = new Google_Service_Plus($client);
$userProfile = $googlePlus->people->get('me');
$emails = $userProfile->getEmails();
Run Code Online (Sandbox Code Playgroud)

这假设如下:

  1. 您已使用适当的范围对当前用户进行了身份验证.
  2. 您已使用client_id和client_secret设置$ client.