在PHP中不使用Google_Oauth2Service接收电子邮件地址的原因主要有以下几点:
Google_Oauth2Service是一个用于处理Google OAuth 2.0认证的服务。OAuth 2.0是一种授权协议,允许第三方应用访问用户的资源(如电子邮件地址),而无需获取用户的密码。
可以使用Google People API来获取用户的电子邮件地址。以下是一个简单的示例代码:
<?php
require_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('Your Application Name');
$client->setScopes(Google_Service_PeopleService::CONTACTS_READONLY);
$client->setAuthConfig('path/to/your/client_secret.json');
$client->setAccessType('offline');
$service = new Google_Service_PeopleService($client);
// 获取访问令牌
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$redirectUri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($client->createAuthUrl(), FILTER_SANITIZE_URL));
exit(1);
}
// 获取联系人
$contacts = $service->people->connections->listConnections('people/me', array(
'personFields' => 'names,emailAddresses',
));
foreach ($contacts->getConnections() as $person) {
if ($person->hasEmails()) {
foreach ($person->getEmails() as $email) {
echo $email->getValue() . "\n";
}
}
}
?>
通过使用Google People API,可以更安全、更方便地获取用户的电子邮件地址,并且避免依赖过时的库。
领取专属 10元无门槛券
手把手带您无忧上云