从Google获取Userinfo OAuth 2.0 PHP API

pgky5nke  于 2023-05-21  发布在  PHP
关注(0)|答案(4)|浏览(178)

我正在尝试使用Google Oauth API获取用户信息。它完美地为谷歌加API,但我试图创建一个备份的情况下,用户没有谷歌加帐户。身份验证过程是正确的,我甚至得到了$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'));

现在起作用了

8gsdolmq

8gsdolmq1#

丢失了瞄准镜

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

现在工作起来很有魅力!

b91juud3

b91juud32#

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

$oauth = new Google_Service_Oauth2($googleClient);

        var_dump($oauth->userinfo->get());
gywdnpxw

gywdnpxw3#

Google API PHP client库已更改-以下是获取用户信息的方式:

<?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>

别忘了-
1.获取Google API console上的Web客户端ID和密码
1.在同一位置授权https://example.com/myapp/
你可以在Youtube GitHub找到官方的例子。

2017年更新:

您可以使用以下命令添加要检索的字段:

const FIELDS       = 'id,name,image';
$me = $plus->people->get('me', array('fields' => FIELDS));
xdyibdwo

xdyibdwo4#

2023版:

use Google\Service\Oauth2;
...
$client->addScope([Oauth2::USERINFO_EMAIL]);
$service = new Oauth2($client);
//$service->userinfo->get()->email;

相关问题