Google PHP 客户端 API - 错误 400 Admin SDK

Google PHP Client API - Error 400 Admin SDK


我正在尝试获取用户在 google GSuite for Education 上关联的组。 我已经开始按照教程列出与关联相关的所有用户,但我得到:错误 400 - "message":“输入无效。
到目前为止,我已经创建了一个带有服务帐户的项目,因为我需要没有用户交互,因为提取必须自动完成。 之后,我将帐户设置为启用了 G Suite 全域委派,并将其放入具有 https://www.googleapis.com/auth/admin.directory.group.readonly and https://www.googleapis.com/auth/admin.directory.user.readonly 域的授权 API 客户端,但是当我 运行 代码时,我得到了上面的错误
这是代码:

<?php
  require_once './google-api/vendor/autoload.php';
  putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/Culturalia.json');

  function getGoogleClient() {
    return getServiceAccountClient();
  }

  function getServiceAccountClient() {
    try {
        // Create and configure a new client object.
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
  }

  $client = getGoogleClient();
  $service = new Google_Service_Directory($client);


  // Print the first 10 users in the domain.
  $optParams = array(
    'customer' => 'my_customer',
    'maxResults' => 10,
    'orderBy' => 'email',
  );
  $results = $service->users->listUsers($optParams);


  if (count($results->getUsers()) == 0) {
    print "No users found.\n";
  } else {
    print "Users:\n";
    foreach ($results->getUsers() as $user) {
      printf("%s (%s)\n", $user->getPrimaryEmail(),
          $user->getName()->getFullName());
    }
  }
?>

但我猜这更有可能是我在某处遗漏的授权,我们将不胜感激。

问题:

您可能已将域范围的委托授予服务帐户(仔细检查您是否已使用 this guide 完成),但您没有使用此委托来模拟 域中的任何帐户。那是你缺少的部分。

授予全域委派的目的是让服务帐户能够代表您域中的任何帐户访问资源。但是,您需要指定要模拟的帐户;否则,您就没有冒充任何人,服务帐户就好像您根本没有授予域范围的授权一样

由于服务帐户在技术上不是域的一部分,因此您在尝试列出域用户时遇到错误。

解决方案:

要模拟帐户,您需要在设置 client 时指定其电子邮件地址,如下所示:

$user = "email-address@your-domain";
$client->setSubject($user);

参考: