There is a new function in the php library that comes close to it, but does not allow installing sub, therefore it always gives an authorization failure. So, first update the php library function loadServiceAccountJson in src / Google / Client.php:
public function loadServiceAccountJson($jsonLocation, $scopes) { $data = json_decode(file_get_contents($jsonLocation)); if (isset($data->type) && $data->type == 'service_account') { // Service Account format. $cred = new Google_Auth_AssertionCredentials( $data->client_email, $scopes, $data->private_key, 'notasecret', 'http://oauth.net/grant_type/jwt/1.0/bearer', $data->sub ); return $cred; } else { throw new Google_Exception("Invalid service account JSON file."); } }
Then add the sub value to the data in the server json auth file:
{ "private_key_id": "removed", "private_key": "-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----\n", "client_email": "removed", "client_id": "removed", "redirect_uris":[your urls here], "type": "service_account", "sub": " valid.user@google.domain.com " }
Now get authorization:
$credentials = $client->loadServiceAccountJson('serverauth.json',"https://www.googleapis.com/auth/admin.directory.user.readonly"); $client->setAssertionCredentials($credentials); if ($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion(); }
Where serverauth.json is the JSON key file downloaded from the service account you want to use and added a substring to.
Finally, create an instance of the directory and request it:
$service = new Google_Service_Directory($client); $optParams = array( 'domain' => 'google.domain.com', 'orderBy' => 'email', 'viewType' => 'domain_public', 'query' => "givenName:'Joe' familyName:'Schmoe Jr'" ); $results = $service->users->listUsers($optParams); $users = $results->getUsers(); print_r($users);