使用PHP客户端库获取Google Apps帐户的所有用户

时间:2016-05-29 04:08:29

标签: php google-api-php-client

我目前正在尝试获取域内所有用户的列表,而我使用的逻辑如下:

$service = new Google_Service_Directory($client);

$optParams = array(
    'customer' => 'my_customer',
    'maxResults' => 500,
    'orderBy' => 'email',
    );

$results = $service->users->listUsers($optParams);
$users = $results->getUsers();

    foreach($users as $user) {
    $usersemails = $user->getPrimaryEmail();
    echo $usersemails.'<br>';
   }

问题是我最多只能获得500个用户。我发现我必须使用下一页令牌,所以我尝试了这个:

$service = new Google_Service_Directory($client);

$optParams = array(
  'customer' => 'my_customer',
  'maxResults' => 500,
  'orderBy' => 'email',
  'pageToken' => NULL,
);

$results = $service->users->listUsers($optParams);
$pageToken = $results->getNextPageToken();
$users = $results->getUsers();

while($pageToken); 

  foreach($users as $user) {
    $usersemails = $user->getPrimaryEmail();
    echo $usersemails.'<br>';
}

但我收到以下消息:

  

504网关超时。服务器没有及时回复。

我使用的代码是否存在问题,或者这是服务器的问题?

1 个答案:

答案 0 :(得分:0)

经过多次检查,我发现问题在于我没有正确编写代码。我修改了我的代码,现在它工作正常。如果其他人遇到同样的问题,也许这可能会有所帮助。这是最终的代码:

$service = new Google_Service_Directory($client);

$pageToken = NULL;
$optParams = array(
  'customer' => 'my_customer'
);

try {
  do {
    if ($pageToken){
    $optParams['pageToken'] = $pageToken;   
  }

$results = $service->users->listUsers($optParams);
$pageToken = $results->getNextPageToken();
$users = $results->getUsers();

foreach($users as $user) {
  $usersemails = $user->getPrimaryEmail();
  echo $usersemails.'<br>';
}

} while($pageToken); 

} catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
}