This package provides a user friendly way of interacting with Google Contacts via the Google People API.
PHP Google People API can be easily installed using Composer. Just run the following command from the root of your project.
composer require titeya/google-people-api
If you have never used the Composer dependency manager before, head to the Composer website for more information on how to get started.
To use this package, you need to authenticate with Google via OAuth 2. Thankfully, this is made easy by the PHP Google OAuth 2 Handler package.
You can run its guided setup script with the following command.
php vendor/titeya/google-oauth-2-handler/src/setup.php
This will guide you through the process of setting up a project, and logging into to the Google account that you wish to manage contacts for. When asked which scopes you require access to, enter the following.
https://www.googleapis.com/auth/userinfo.profile
https://www.googleapis.com/auth/contacts
https://www.googleapis.com/auth/contacts.readonly
When complete, you will have to code you need to create a GoogleOAuth2Handler
object for this Google account.
You can then create a GooglePeople
object, as follows.
$people = new GooglePeople($googleOAuth2Handler);
// Retrieval all contacts
foreach($people->groupAll() as $group) {
echo $group->resourceName.' - ';
echo $group->name;
echo PHP_EOL;
}
// Retrieve single contact (by resource name)
$group = $people->groupGet('contactGroups/c805502054287');
// Create new group
$group = new \stdClass();
$group->name="new group";
$people->groupSave($group);
// Delete group
$people->groupDelete("contactGroups/c805502054287");
// Retrieval all contacts
foreach($people->contactall() as $contact) {
echo $contact->resourceName.' - ';
if ($contact->names) {
echo $contact->names[0]->displayName;
}
echo PHP_EOL;
}
// Retrieve single contact (by resource name)
$contact = $people->contactGet('people/c8055020007701654287');
// Create new contact
$contact = new Contact($people);
$contact->names[0] = new stdClass;
$contact->names[0]->givenName = 'Testy';
$contact->names[0]->familyName = 'McTest Test';
$contact->save();
// Update contact
$contact->names[0]->familyName = 'McTest';
$contact->save();
// Delete contact
$contact->delete();