【发布时间】:2012-12-10 01:29:24
【问题描述】:
我正在尝试使用 Google Oauth API 来获取用户信息。 它非常适用于 Google Plus API,但我正在尝试创建一个备份,以防用户没有 google plus 帐户。 身份验证过程是正确的,我什至得到了 $userinfo 对象,但我究竟如何访问这些属性。我试过 $userinfo->get() 但它只返回用户的 id。
我做错了吗?这是我正在使用的代码...
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
// Visit https://code.google.com/apis/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setClientId('*********************');
$client->setClientSecret('**************');
$client->setRedirectUri('***************');
$client->setDeveloperKey('**************');
$plus = new Google_Oauth2Service($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$userinfo = $plus->userinfo;
print_r($userinfo->get());
} else
{
$authUrl = $client->createAuthUrl();
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel='stylesheet' href='style.css' />
</head>
<body>
<header><h1>Google+ Sample App</h1></header>
<div class="box">
<?php if(isset($personMarkup)): ?>
<div class="me"><?php print $personMarkup ?></div>
<?php endif ?>
<?php
if(isset($authUrl)) {
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
print "<a class='logout' href='?logout'>Logout</a>";
}
?>
</div>
</body>
</html>
谢谢...
**编辑*** 缺少范围--已添加
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
现在可以使用...
【问题讨论】:
-
你遇到了什么错误?
-
我没有收到任何错误,我只是不确定我是否正确使用了对象 [$userinfo = $plus->userinfo;]。在此之后,我如何从 $userinfo 对象访问用户信息。我试过 $userinfo->get() 但只返回 ID
-
在哪里添加缺少的范围?
-
创建客户端对象后 $client = Google_OAUTH_Client_Class::getGoogleClient(); $client->setScopes(array(......));
标签: php google-api oauth-2.0 google-api-php-client