我正在尝试使用Google的OAuth2 API。在他们的通用文档中,他们提到了一个名为UserInfo的调用:http://code.google.com/apis/accounts/docs/OAuth2Login.html#userinfocall,它允许我检索用户ID,电子邮件,名称和其他基本内容。
但是我在他们的PHP客户端库中找不到它:https://code.google.com/p/google-api-php-client/
它在哪里?
答案 0 :(得分:2)
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>
别忘了 -
https://example.com/myapp/
您可以在Youtube GitHub找到官方示例。
答案 1 :(得分:1)
答案 2 :(得分:0)
我发布了一个适用于我的解决方案,这是一个针对Google PHP客户端库的补丁,用于检索UserInfo,在这个类似的问题中:How to identify a Google OAuth2 user?