我是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获取帐户电子邮件地址即可将其存储在我的应用中.
谢谢.
$me [’emailils’]是一个数组,而不是哈希.所以添加一个[0]来选择第一个Mailadress:
$correo = ($me['emails'][0]['value']);
现在它应该工作正常……