Skip to content

Instantly share code, notes, and snippets.

@fillup
Last active November 30, 2022 08:08
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save fillup/9fbf5ff35b337b27762a to your computer and use it in GitHub Desktop.
Save fillup/9fbf5ff35b337b27762a to your computer and use it in GitHub Desktop.
Example of using Google Admin SDK Directory API to get an individual or list of users.
<?php
// Updated 2018-01-24 to work with google/apiclient:^2.0
/*
* 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';
/*
* 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.org';
/*
* 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'
);
/*
* Provide path to JSON credentials file that was downloaded from Google Developer Console
* for Service Account
*/
$authJson = __DIR__ . '/creds.json';
/*
* Create Google_Client for making API calls with
*/
$googleClient = new \Google_Client();
$googleClient->setApplicationName($appName);
$googleClient->setAuthConfig($authJson);
$googleClient->setSubject($delegatedAdmin);
$googleClient->setScopes($scopes);
$googleClient->setAccessType('offline');
/*
* Get an instance of the Directory object for making Directory API related calls
*/
$dir = new \Google_Service_Directory($googleClient);
/*
* 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.org', 'maxResults' => 500));
print_r($list);
@kamaldanish
Copy link

Hi,
Showing bellow error

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

@xaerolab
Copy link

Work for me! thanks

@mg4u
Copy link

mg4u commented Jan 11, 2021

orgUnitPath for non-admin users returned null, how can I fix that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment