如何为 $plus->people->get('me') 调用指定字段?

问题描述 投票:0回答:1

使用 Google API PHP 客户端 库,我使用以下代码,该代码运行良好,并打印有关通过 OAuth2 授权我的应用程序的用户的大量信息:

<?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'); # HOW TO SPECIFY FIELDS?
                $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>

但是我需要的信息比上面脚本返回的信息要少。

仅在 People: get“API explorer”中输入我感兴趣的字段时:

id,gender,name,image,placesLived

screenshot 1

这再次运行良好并且仅打印指定的字段:

screenshot 2

我的问题:

如何指定上面

$me = $plus->people->get('me');
调用中的字段?

学习1.1.7/src/Google/Service/Plus.php后使用代码:

/**
 * Get a person's profile. If your app uses scope
 * https://www.googleapis.com/auth/plus.login, this method is 
 * guaranteed to return ageRange and language. (people.get)
 *
 * @param string $userId The ID of the person to get the profile for. The
 * special value "me" can be used to indicate the authenticated user.
 * @param array $optParams Optional parameters.
 * @return Google_Service_Plus_Person
 */
public function get($userId, $optParams = array())
{
  $params = array('userId' => $userId);
  $params = array_merge($params, $optParams);
  return $this->call('get', array($params), "Google_Service_Plus_Person");
}

我尝试过以下 PHP 代码:

const FIELDS = 'id,gender,name,image,placesLived';

$me = $plus->people->get('me', array('fields' => urlencode(FIELDS)));

但由于某种原因它打印了很多

:protected
字符串:

Google_Service_Plus_Person Object
(
    [collection_key:protected] => urls
    [internal_gapi_mappings:protected] => Array
        (
        )

    [aboutMe] => 
    [ageRangeType:protected] => Google_Service_Plus_PersonAgeRange
    [ageRangeDataType:protected] => 
    [birthday] => 
    [braggingRights] => 
    [circledByCount] => 
    [coverType:protected] => Google_Service_Plus_PersonCover
    [coverDataType:protected] => 
    [currentLocation] => 
    [displayName] => 
    [domain] => 
    [emailsType:protected] => Google_Service_Plus_PersonEmails
    [emailsDataType:protected] => array
    [etag] => 
    [gender] => male
    ...

我也尝试过在

me
:

之后附加字段
$me = $plus->people->get('me?fields=' . urlencode(FIELDS)));

但是收到 404 错误:

调用 GET 时出错 https://www.googleapis.com/plus/v1/people/me%3Ffields%3Did%252Cgender%252Cname%252Cimage%252CplacesLived: (404) 未找到

更新:我在 GitHUb 创建了Issue #948

php google-api google-oauth google-plus google-api-php-client
1个回答
2
投票

要指定从 G+ API 获取哪些字段,您只需在选项数组中指定一个

fields
成员。所以实际上你已经非常接近解决方案了:

$me = $plus->people->get('me', array('fields' => 'id,gender,name,image,placesLived'));

您甚至不必

urlencode
,因为这是库本身的默认安全功能。

可能欺骗您的是,

Google_Service_Plus_Person
类包含受保护成员的所有可能字段,而不考虑 API 发送的实际字段。未包含的字段在对象中将为空。与往常一样,类的用户不应以任何方式使用受保护的成员。

作为图书馆的用户,您只能使用公共成员,例如

$me->getPlacesLived()
$me->getId()
。在开发过程中转储整个对象是一个很好的工具,但在生产中调用公共接口才是正确的方法。

© www.soinside.com 2019 - 2024. All rights reserved.