管理SDK,目录API,用户:列表-任何PHP示例如何做到这一点


Admin SDK, Directory API, Users: list - Any PHP examples on how to do this?

  1. 谷歌商业应用程序链接到应用程序引擎帐户
  2. 云控制台->已注册的应用程序->{name}->Web应用程序->OAuth 2.0 ClientID
  3. 云控制台->管理员API(打开)
  4. Google应用程序控制台->安全性->API访问(已选中)
  5. "->"->第三方OAuth->API客户端({ClientID}.apps.googleusercontent.com)
  6. "->"->"->API范围(https://www.googleapis.com/auth/admin.directory.user)

,这是我目前所掌握的

require_once 'google/appengine/api/app_identity/AppIdentityService.php';
use 'google'appengine'api'app_identity'AppIdentityService;
function setAuthHeader() {
  $access_token =AppIdentityService::getAccessToken("https://www.googleapis.com/auth/admin.directory.user");
  return [ sprintf("Authorization: OAuth %s", $access_token["access_token"]) ];
}
$get_contacts_url = "https://www.googleapis.com/admin/directory/v1/users?customer=my_customer";
$headers = implode("'n'r", setAuthHeader());
$opts =
  array("http" =>
  ["http" => ["header" => $headers ]]
);
$context = stream_context_create( $opts );
$response = file_get_contents( $get_contacts_url, false, $context );
print_r ($response);

"access_token"通过得很好,但$response返回,

{ "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } }

在页面底部的Users:List示例中,他们显示了如下的"Get"请求,

GET https://www.googleapis.com/admin/directory/v1/users?customer=my_customer&key={YOUR_API_KEY}

什么是{YOUR_API_KEY}?我尝试过每一个云控制台和谷歌应用API,但运气不好。

我完全错了,我应该用一种完全不同的方法吗?我已经为此挣扎了一个多星期了,我喜欢任何形式的回应。感谢

我认为实现这一点最简单的方法是使用PHP客户端库,https://github.com/google/google-api-php-client/,由谷歌提供,它可以很好地为您处理身份验证。如果你自己尝试,JWT的东西会变得非常棘手。我只是给你举了一个这样做的例子,https://gist.github.com/fillup/9fbf5ff35b337b27762a.我用我自己的谷歌应用程序帐户测试了它,并验证了它的工作原理,如果你有问题,请告诉我。

编辑:在这里添加代码示例以方便:

<?php
/**
 * Easiest to use composer to install google-api-php-client and generate autoloader
 * If you dont want to use composer you can manually include any needed files
 */
include_once 'vendor/autoload.php';
/**
 * Client ID from https://console.developers.google.com/
 * Must be added in Google Apps Admin console under Security -> Advanced -> Manage API client     access
 * Requires scope https://www.googleapis.com/auth/admin.directory.user or
 * https://www.googleapis.com/auth/admin.directory.user.readonly
 */
$clientId = 'somelongstring.apps.googleusercontent.com';
/**
 * Service Account Name or "Email Address" as reported on     https://console.developers.google.com/
 */
$serviceAccountName = 'somelongstring@developer.gserviceaccount.com';
/**
 * Email address for admin user that should be used to perform API actions
 * Needs to be created via Google Apps Admin interface and be added to an admin role
 * that has permissions for Admin APIs for Users
 */
$delegatedAdmin = 'delegated-admin@domain.com';
/**
 * This is the .p12 file the Google Developer Console gave you for your app
 */
$keyFile = 'file.p12';
/**
 * Some name you want to use for your app to report to Google with calls, I assume
 * it is used in logging or something
 */
$appName = 'Example App';
/**
 * Array of scopes you need for whatever actions you want to perform
 * See https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
 */
$scopes = array(
    'https://www.googleapis.com/auth/admin.directory.user'
);
/**
 * Create AssertionCredentails object for use with Google_Client
 */
$creds = new Google_Auth_AssertionCredentials(
    $serviceAccountName,
    $scopes,
    file_get_contents($keyFile)
);
/**
 * This piece is critical, API requests must be used with sub account identifying the
 * delegated admin that these requests are to be processed as
 */
$creds->sub = $delegatedAdmin;
/**
 * Create Google_Client for making API calls with
 */
$client = new Google_Client();
$client->setApplicationName($appName);
$client->setClientId($clientId);
$client->setAssertionCredentials($creds);
/**
 * Get an instance of the Directory object for making Directory API related calls
 */
$dir = new Google_Service_Directory($client);
/**
 * Get specific user example
 */
//$account = $dir->users->get('example@domain.com');
//print_r($account);
/**
 * Get list of users example
 * In my testing you must include a domain, even though docs say it is optional
 * I was getting an error 400 without it
 */
$list = $dir->users->listUsers(array('domain' => 'domain.com', 'maxResults' => 100));
print_r($list);

简而言之:您过度简化了OAuth2。

它不像通过一个键发送HTTPGET参数来获取数据那么容易。

我相信您已经读过这篇文章,但您需要了解OAuth2 web流,以及客户端库如何利用它。您应该需要此文件才能使用目录API。

您使用的是最新的PHP库还是不推荐使用的库?对于最新的BETAPHP库,这是与身份验证部分相关的代码部分。

set_include_path("google-api-php-client-master/src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Auth/OAuth2.php';
if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
  // Replace this with the email address from the client.
  $clientEmail,
  // Replace this with the scopes you are requesting.
  array(SCOPES),
  $key
);
$cred->sub = ""; //admin email
$client->setAssertionCredentials($cred);
try {
if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();