This post explains an example of use of the Google API client library for PHP, based on some code I have written recently.
Introduction to Google API
Google APIs Client Library for PHP provides access to many Google APIs. In this post I will show an example of use of the Google Directory API which will allow me to create new users on my domain, and to add them to my groups. While working on the code, I have found complicated the authentication part, where you create a user and a token and assign them to an API, so I thought a clear post showing this will help someone.
First steps using the Google API for PHP
The first thing you will need is a Google account, but if you are reading this post you have probably one already; if not go to Google and look for the link ‘Create an account’.
Next thing you will need is a Google API project. A project in Google is some kind of container; inside the project we will later define APIs, access rights, access methods, etc. Head to the Google Developers Console, create one and give it a name. If you have no ideas, something like “My first project” should do the job.
Now you must install the Google’s API client library on your development host. The Google page with the instructions is easy to follow, but I have found that you will rather need “PHP 5.3 or greater” instead of “PHP 5.2.1 or greater” as it is explained on the page, so check your PHP version. I have cloned the repository from Github on my /usr/share/php5 folder and added the path to the library’s src folder to the include_path variable on the php.ini file.
$ cd /user/share/php5 $ sudo git clone https://github.com/google/google-api-php-client.git .
Add the path to the php.ini file. It will look something like this:
include_path = ".:/usr/local/lib/php:/path/to/google-api-php-client/src"
Getting rights to execute the Google API
Google has two types of access to the APIs, depending on the type of data the API manage:
- Simple API access when the API does not manage private user data.
- Authorized API access, you guess it, when the API manage private user data. Because my application will create user accounts I will need this one.
Go to the Google Developer Console and click on your project. You are now on the project’s console:
- Go to the APIs & auth – APIs menu option. We will give execution rights to the API. The Google Directory API belongs to the Admin Software Development Kit (SDK), so I will look for the Admin SDK and will change the status from Off to On.
- Go to the APIs & auth – Credentials menu option. We will create a user to access the API. Click on the Create new Client ID on the OAuth section and create a Service account.
You will need these values later on your code.
It is also needed an account with ‘admin’ privileges. If you have none just create one, or reuse an account and give it these privileges on the Google Apps Admin interface.
How this code looks like?
One more thing. Google’s library use an autoload to include automatically the classes when they are invoked; the autoload.php file is required at the beginning of the code.
Armed with the project, the library, the API and the credentials you can start your favourite editor and start typing some code.
The credentials are declared at the beginning of the code:
<?php /** * This file is on Google's library */ require_once realpath('/path/to/autoload.php'); /** * Client id and service account name as reported * on https://console.developers.google.com/ - Projects - Credentials */ $client_id = 'long-string.apps.googleusercontent.com'; // 'CLIENT ID' on Google $service_account_name = 'long-string@developer.gserviceaccount.com'; // 'EMAIL ADDRESS' on Google /** * This is the .p12 file generated on https://console.developers.google.com/ - Projects - Credentials */ $key_file_location = '/path/to/file_name.p12'; /** * 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 = 'admin@yourdomain.com'; /** * Array of scopes you need for whatever actions you want to perform * See https://developers.google.com/admin-sdk/directory/v1/guides/authorizing * The admin.directory.user is needed to create the user, the admin.directory.group is needed to add the * user to a group (see later on this file) */ $scopes = array( 'https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.group' ); /** * Create AssertionCredentails object for use with Google_Client */ $cred = new Google_Auth_AssertionCredentials( $service_account_name, $scopes, file_get_contents($key_file_location) ); /** * API requests shall be used using the delegated admin */ $cred->sub = $delegatedAdmin;
With valid credentials is relatively easy to create a user:
/** * Create Google_Client for making API calls */ $client = new Google_Client(); $client->setApplicationName("This is the name"); $client->setAssertionCredentials($cred); if ($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion($cred); } /** * Create Google_Service_Directory */ $service = new Google_Service_Directory($client); /** * Create the user */ $nameInstance = new Google_Service_Directory_UserName(); $nameInstance -> setGivenName('John'); $nameInstance -> setFamilyName('Doe'); $email = 'john.doe@domain.com'; $password = 'password'; $userInstance = new Google_Service_Directory_User(); $userInstance -> setName($nameInstance); $userInstance -> setHashFunction("MD5"); $userInstance -> setPrimaryEmail($email); $userInstance -> setPassword(hash("md5", $password)); try { $createUserResult = $service->users->insert($userInstance); var_dump($createUserResult); } catch (Google_IO_Exception $gioe) { echo "Error in connection: ".$gioe->getMessage(); } catch (Google_Service_Exception $gse) { echo "User already exists: ".$gse->getMessage(); }
The last part, adding the user to a group, is shown here:
$memberInstance = new Google_Service_Directory_Member(); $memberInstance->setEmail($email); $memberInstance->setRole('MEMBER'); $memberInstance->setType('USER'); try { $insertMembersResult = $service->members->insert('groupname@domain.com', $memberInstance); } catch (Google_IO_Exception $gioe) { echo "Error in connection: ".$gioe->getMessage(); }
For those of you not willing to type it is also the option to clone this easy example from its Github repository. I hope it helps someone.