我正在尝试使用谷歌的OAuth2 API。在他们的通用文档中,他们提到了一个名为UserInfo: http://code.google.com/apis/accounts/docs/OAuth2Login.html#userinfocall的调用,它将允许我检索用户id,电子邮件,姓名和其他基本内容。
但是我无法在他们的PHP客户端库中找到它:https://code.google.com/p/google-api-php-client/
它在哪里?
Google OAuth2 API发生了变化——以下是现在获取用户信息的方式:
<?php
require_once('google-api-php-client-1.1.7/src/Google/autoload.php');
const TITLE = 'My amazing app';
const REDIRECT = 'https://example.com/myapp/';
session_start();
$client = new Google_Client();
$client->setApplicationName(TITLE);
$client->setClientId('REPLACE_ME.apps.googleusercontent.com');
$client->setClientSecret('REPLACE_ME');
$client->setRedirectUri(REDIRECT);
$client->setScopes(array(Google_Service_Plus::PLUS_ME));
$plus = new Google_Service_Plus($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
error_log('The session state did not match.');
exit(1);
}
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . REDIRECT);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken() && !$client->isAccessTokenExpired()) {
try {
$me = $plus->people->get('me');
$body = '<PRE>' . print_r($me, TRUE) . '</PRE>';
} catch (Google_Exception $e) {
error_log($e);
$body = htmlspecialchars($e->getMessage());
}
# the access token may have been updated lazily
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$body = sprintf('<P><A HREF="%s">Login</A></P>',
$client->createAuthUrl());
}
?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE><?= TITLE ?></TITLE>
</HEAD>
<BODY>
<?= $body ?>
<P><A HREF="<?= REDIRECT ?>?logout">Logout</A></P>
</BODY>
</HTML>
别忘了-
- 在Google API控制台获取web客户端id和secret
- 在同一地点授权
https://example.com/myapp/
你可以在Youtube GitHub找到官方示例。
PHP客户端已更新:https://code.google.com/p/google-api-php-client/issues/detail?id=43
我已经发布了一个解决方案,适用于我,一个补丁到谷歌PHP客户端库检索UserInfo,在这个类似的问题:如何识别一个谷歌OAuth2用户?