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

时间:2016-05-09 12:26:09

标签: google-api google-plus google-api-php-client google-api-client google-oauth2

使用Google API PHP client库我使用以下代码,该代码运行良好并打印有关用户的大量信息,用户通过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&#34; API资源管理器&#34;输入我感兴趣的字段时:

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

1 个答案:

答案 0 :(得分:2)

要指定从G + API获取哪些字段,您只需在options数组中指定fields成员即可。所以实际上你非常接近解决方案:

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

您甚至不必urlencode,因为这是图书馆本身的默认安全功能。

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

您,因为图书馆的用户应该只使用公共成员,例如$me->getPlacesLived()$me->getId()。在开发过程中倾倒整个对象是一个很好的工具,但在生产中调用公共接口是可行的方法。