Skip to content

Instantly share code, notes, and snippets.

@deanet
Forked from fillup/google-example.php
Last active August 29, 2015 14:23
Show Gist options
  • Save deanet/a3051682bfa75a94c621 to your computer and use it in GitHub Desktop.
Save deanet/a3051682bfa75a94c621 to your computer and use it in GitHub Desktop.
<?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);