Categories
Code

Google OAuth 2.0 Service account with PHP and Google APIs

This sample code uses Google Service Accounts with PHP to get a list of users in a Google Apps Domain using the Admin Directory API.

To get started, install the Google API PHP library, create a Google Service account with domain-wide delegation and save the private JSON file in the same directory as your PHP application.

useApplicationDefaultCredentials(); 
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES); 
  $client->setAccessType("offline");
  $client->setSubject($user);

  $service = new Google_Service_Directory($client); 

  $optParams = array( 
    'domain' => 'ctrlq.org', 
    'maxResults' => 10, 
    'orderBy' => 'email'
  ); 

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

  print_r($results);

?>