如何通过Google Oauth2和people.me对用户进行身份验证后获取电子邮件地址

时间:2014-01-30 23:11:43

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

我是php和google api的新用户,当用户在使用Google+时,我正在尝试获取电子邮件地址,我使用$ plus-> people->获取所有用户信息(“我“)但是当我尝试获取电子邮件地址时,它失败并出现此错误:

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获取帐户电子邮件地址即可将其存储在我的应用中。

感谢。

1 个答案:

答案 0 :(得分:6)

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

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

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