如何在PHP中使用Google身份验证向用户发送电子邮件?

时间:2015-03-24 13:52:56

标签: php oauth-2.0 google-plus

我已成功在GOOGLE中创建了API注册。要在我的网站上登录,请使用以下链接:

https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=http://www.example.com/goo/gaccess.php&client_id=109717......9-0r0..............avubqdddi5j.....apps.googleusercontent.com&scope=email

点击此链接后,Google会要求您接受是否允许此应用访问您的信息。单击“接受”后,用户重定向到我添加脚本的页面。

<?php
  require_once realpath(dirname(__FILE__) . '/google-api-php-client-master/src/Google/autoload.php'); // or wherever autoload.php is located

if (isset($_GET['code'])) {


echo $access_token = $_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));

}

  ?>

问题是我不知道如何获取用户信息和电子邮件ID。我希望在用户接受将其信息访问权限提供给我的网站后向用户显示。 我现在得到的只是一个代码:

 4/v3Lbc...............o15_kBpgqItOOcR-BAm9FA.ksVbL...............KaDJMaXmAI

我还安装了一个用于访问Google API的PHP客户端库。

1 个答案:

答案 0 :(得分:0)

您可以使用示例项目here

中所述的此代码
if ($client->getAccessToken()) {
$user = $oauth2->userinfo->get();

// These fields are currently filtered through the PHP sanitize filters.
// See http://www.php.net/manual/en/filter.filters.sanitize.php
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
$img = filter_var($user['picture'], FILTER_VALIDATE_URL);
$personMarkup = "$email<div><img src='$img?sz=50'></div>";

// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
}