【问题标题】:How to get email address when user is authenticated with Google Oauth2 and people.me用户通过 Google Oauth2 和 people.me 进行身份验证时如何获取电子邮件地址
【发布时间】:2014-01-30 23:11:42
【问题描述】:

我是 php 和 google api 的新手,我正在尝试在用户使用 Google+ 唱歌时获取电子邮件地址,我使用 $plus->people->get("me" ) 但是当我尝试获取电子邮件地址时,它会失败并出现以下错误:

PHP 注意:未定义索引:值

这是我的代码:

<?php
session_start();

set_include_path(get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] . "/src");

require_once 'Google/Client.php';

require_once 'Google/Service/Plus.php';

$client_id = 'XXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com';
$client_secret = 'XXXXXXXXXXXXXXXXXXX';
$redirect_uri = 'http://www.XXXXXXXXXXXXXX.com/pruebas.php';

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/userinfo.profile");
$client->addScope("https://www.googleapis.com/auth/userinfo.email");

$plus = new Google_Service_Plus($client);

if (isset($_REQUEST['logout'])) {
    unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['access_token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));

}

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    $client->setAccessToken($_SESSION['access_token']);
    $_SESSION['token'] = $client->getAccessToken();

} else {
    $authUrl = $client->createAuthUrl();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Pruebas</title></head>
<body>
<?php if (isset($authUrl)) {
    print "<a class='login' href='$authUrl'><img src='logogoo/Red-signin-Medium-base-32dp.png'></a>";
} else {
    print "<a class='logout' href='pruebas.php?logout'>Cerrar:</a>";
}

if (isset($_SESSION['access_token'])) {
    $me = $plus->people->get("me");

    print "<br>ID: {$me['id']}\n<br>";
    print "Display Name: {$me['displayName']}\n<br>";
    print "Image Url: {$me['image']['url']}\n<br>";
    print "Url: {$me['url']}\n<br>";
    $name3 = $me['name']['givenName'];
    echo "Nombre: $name3 <br>"; //Everything works fine until I try to get the email
    $correo = ($me['emails']['value']);
    echo $correo;
    }
?>
</body>
</html>

我只是从 $me 获取帐户电子邮件地址以将其存储在我的应用程序中。

谢谢。

【问题讨论】:

    标签: php email google-plus google-api-php-client


    【解决方案1】:

    $me['emails'] 是一个数组,而不是一个哈希。所以添加一个 [0] 来选择第一个 Mailadress:

    $correo = ($me['emails'][0]['value']);
    

    现在应该可以正常工作了...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 2018-02-12
      • 2020-01-07
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多