从Google OAuth 2.0 PHP API获取Userinfo

ksb*_*ksb 25 php google-api oauth-2.0 google-api-php-client

我正在尝试使用Google Oauth API获取userinfo.它适用于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>
Run Code Online (Sandbox Code Playgroud)

谢谢...

**编辑*** 缺少范围 - 已添加

 $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
Run Code Online (Sandbox Code Playgroud)

现在有效......

ksb*_*ksb 23

缺少范围

$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
Run Code Online (Sandbox Code Playgroud)

现在就像魅力一样!


ins*_*ign 17

我不确定它是否有帮助,但自从Google API PHP客户端更新后,我以这种方式获取userinfo:

        $oauth = new Google_Service_Oauth2($googleClient);

        var_dump($oauth->userinfo->get());
Run Code Online (Sandbox Code Playgroud)

  • 我曾经使用过这种方法,但这是在以前的版本中完成的,而不是在当前版本中. (4认同)