PHP Classes

PHP Google Contacts API: Access Google contacts with the Google People API

Recommend this page to a friend!
  Info   View files Example   View files View files (27)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog (2)    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 107 All time: 9,671 This week: 78Up
Version License PHP version Categories
gcontacts 1.0.0GNU General Publi...7.4User Management, Web services, PHP 7
Description 

Author

This package can access Google contacts with the Google People API.

It can send HTTP requests to the Google People API Web server to perform several operations with the contact information of users with Google accounts.

Currently, it can:

- Obtain authorization to access the contacts of user with a Google account using the OAuth 2 protocol

- List the user contacts

- Search for contacts

- Filter contacts by contact group label

- Create, edit, and delete contacts

- List contact groups

- Create, edit, and delete contact groups

- Assign and remove contacts to contact groups

- Set and remove contact photo images

Innovation Award
PHP Programming Innovation award nominee
April 2023
Number 3
Many people that access the Internet have Google accounts to access Google products like, for instance, Gmail.

Gmail users have a contact list to make it easy to send emails to other people they have exchanged messages. These contacts are accessible using the Google People API.

This package can access the Google People API to perform operations with a user's contacts with a Google account.

This way, this package makes it easier to implement applications that can make good use of the access to a person's contacts with a Google account, for instance, sending invitations to social networks to people in their contact list.

Manuel Lemos
Picture of Stefan Kientzler
  Performance   Level  
Name: Stefan Kientzler is available for providing paid consulting. Contact Stefan Kientzler .
Classes: 19 packages by
Country: Germany Germany
Age: 56
All time rank: 72547 in Germany Germany
Week rank: 15 Up1 in Germany Germany Up
Innovation award
Innovation award
Nominee: 11x

Winner: 6x

Example

<?php
declare(strict_types=1);

use
SKien\Google\GClient;
use
SKien\Google\GContact;
use
SKien\Google\GContactGroups;
use
SKien\Google\GContacts;
use
SKien\Google\GSecrets;

require_once
'autoloader.php';

/**
 * This example is only intended to demonstrate the use of the package. The UI
 * is only coded 'quick and dirty', contains no validations and should only be
 * used as a starting point for your own implementation.
 *
 * @author Stefanius <s.kientzler@online.de>
 * @copyright MIT License - see the LICENSE file for details
 */

$oSecrets = new GSecrets(-1, GSecrets::TOKEN_FILE);
$oClient = new GClient();
$oClient->setAccessToken($oSecrets->getAccessToken());
if (
$oClient->isAccessTokenExpired()) {
   
// try to refresh the accesstoken
   
$strRefreshToken = $oSecrets->getRefreshToken();
    if (empty(
$strRefreshToken)) {
       
// no refresh token available - redirect to google login
       
header('Location: ./GoogleLogin.php');
        exit;
    }
   
$oClient->setOAuthClient($oSecrets->getClientSecrets());
   
$oSecrets->saveAccessToken($oClient->refreshAccessToken($strRefreshToken));
}

$strSearch = $_REQUEST['search'] ?? '';
$strGroup = $_REQUEST['group'] ?? '';

// load available user defined contact groups
$oGroups = new GContactGroups($oClient);
$aGroups = $oGroups->list(GContactGroups::GT_USER_CONTACT_GROUPS);
if (
$aGroups === false) {
   
displayApiError(
       
'list contact groups',
       
'',
       
$oClient->getLastResponseCode(),
       
$oClient->getLastError(),
       
$oClient->getLastStatus()
        );
    exit;
}
$strGroupSelect = '<select id="group" onchange="onSelectGroup(this);">' . PHP_EOL;
$strGroupSelect .= ' <option value="">&lt;all contacts&gt;</option>' . PHP_EOL;
foreach (
$aGroups as $strGroupResourceName => $strGroupName) {
   
$strSelected = ($strGroup == $strGroupResourceName ? ' selected' : '');
   
$strGroupSelect .= ' <option value="' . $strGroupResourceName . '"' . $strSelected . '>' . $strGroupName . '</option>' . PHP_EOL;
}
$strGroupSelect .= ' </select>' . PHP_EOL;

$oContacts = new GContacts($oClient);
$oContacts->addPersonFields(GContacts::DEF_LIST_PERSON_FIELDS);

$aContactList = [];
$strTitle = '';
if (!empty(
$strSearch)) {
   
$oContacts->setPageSize(50);
   
$aContactList = $oContacts->search($strSearch);
   
$strTitle = ' - Search for <b><i>[' . $strSearch . ']</i></b>';
    if (
$aContactList === false) {
       
displayApiError(
           
'search contacts',
           
'search: ' . $strSearch,
           
$oClient->getLastResponseCode(),
           
$oClient->getLastError(),
           
$oClient->getLastStatus()
            );
        exit;
    }
} else {
   
$aContactList = $oContacts->list(GContacts::SO_LAST_NAME_ASCENDING, $strGroup);
    if (
$aContactList === false) {
       
displayApiError(
           
'list contacts',
           
'group: ' . $strGroup,
           
$oClient->getLastResponseCode(),
           
$oClient->getLastError(),
           
$oClient->getLastStatus()
            );
        exit;
    }
}
$strTitle = count($aContactList) . ' Contacts' . $strTitle;
?>
<html>
<head>
<style>
body, table {
    font-family: Sans-Serif;
    font-size: 12px;
}
a, a:visited {
    color: blue;
}
label {
    display: inline-block;
    width: 100px;
}
table {
    border-spacing: 0;
    border-collapse: collapse;
}
th {
    color: white;
    background-color: #777;
    border: 1px solid #333;
    padding: 2px 4px;
}
td {
    border: 1px solid #ccc;
    padding: 2px 4px;
}
tr:nth-child(2n+1) {
    background-color: #eee;
}
td:nth-child(9) {
    text-align: center;
}
a.trash {
    color: #999;
    font-size: 16px;
    font-weight: bold;
    text-decoration: none;
}
a.trash:hover {
    color: #009;
}
a.starred,
a.unstarred {
    font-size: 16px;
    font-weight: bold;
    text-decoration: none;
}
a.starred,
a.unstarred:hover {
    color: goldenrod;
}
a.starred:hover,
a.unstarred {
    color: #ccc;
}
</style>
<script>
function onSelectGroup(oSelect)
{
    window.location = './ContactList.php?group=' + encodeURI(oSelect.value);
}
function deleteContact(strResourceName)
{
    if (confirm("Delete the contact?")) {
        window.location = './DoAction.php?action=deleteContact&res=' + encodeURI(strResourceName);
    }
}
function createGroup()
{
    var strGroupName = prompt('Enter new group name', '');
    if (strGroupName !== null) {
        window.location = './DoAction.php?action=saveGroup&name=' + encodeURI(strGroupName);
    }
}
function deleteGroup()
{
    var strGroupName = prompt('Enter name of group to delete', '');
    if (strGroupName !== null) {
        window.location = './DoAction.php?action=deleteGroup&name=' + encodeURI(strGroupName);
    }
}
</script>
</head>
<body>
    <form action="./ContactList.php" method="post">
        <div>
            <label for="search">Query:</label>
            <input id="search" type="text" name="search" />
            <input type="submit" value="Search" />
            <br/><br/>
            <label for="group">or select group:</label>
            <?=$strGroupSelect?>
</div>
    </form>
    <h2><?=$strTitle?></h2>
    <a href="./ContactDetails.php">Add new contact</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="javascript: createGroup()">Create new contactgroup</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="javascript: deleteGroup()">Delete existing contactgroup</a>
    <br/><br/>
    <table style="width: 100%">
        <tbody>
            <tr>
                <th style="width: 4%">#</th>
                <th style="width: 3%">&nbsp;</th>
                <th style="width: 25%">Name</th>
                <th style="width: 20%" colspan="2">Phone 1</th>
                <th style="width: 20%" colspan="2">Phone 2</th>
                <th style="width: 25%">e-Mail</th>
                <th style="width: 3%">&nbsp;</th>
            </tr>
<?php
$i
= 0;
foreach (
$aContactList as $aContact) {
   
$i++;
   
$oContact = GContact::fromArray($aContact);
   
$strResourceName = rawurlencode($aContact['resourceName']);
   
$strStarrURL = './DoAction.php?action=starreContact&res=' . $strResourceName . '&setstarred=';
   
$strDeleteFunc = "javascript: deleteContact('" . $strResourceName . "')";
   
$strName = '[not set]';
    if (isset(
$aContact['names'][0])) {
       
$strName = $aContact['names'][0]['displayNameLastFirst'];
    } else if (isset(
$aContact['organizations'][0])) {
       
$strName = $aContact['organizations'][0]['name'];
    }
    echo
' <tr id="' . $aContact['resourceName'] . '">' . PHP_EOL;
    echo
' <td>' . $i . '</td>' . PHP_EOL;
    if (
$oContact->isStarred()) {
       
$strStarrURL;
        echo
' <td><a class="starred" href="' . $strStarrURL . 'false" title="unmark">&#x2605;</a></td>' . PHP_EOL;
    } else {
        echo
' <td><a class="unstarred" href="' . $strStarrURL . 'true" title="mark starred">&#x2606;</a></td>' . PHP_EOL;
    }
    echo
' <td><a href="./ContactDetails.php?res=' . $strResourceName . '">' . $strName . '</a></td>' . PHP_EOL;
    echo
' <td>' . (isset($aContact['phoneNumbers'][0]) ? $aContact['phoneNumbers'][0]['type'] : '') . '</td>' . PHP_EOL;
    echo
' <td>' . (isset($aContact['phoneNumbers'][0]) ? $aContact['phoneNumbers'][0]['value'] : '') . '</td>' . PHP_EOL;
    echo
' <td>' . (isset($aContact['phoneNumbers'][1]) ? $aContact['phoneNumbers'][1]['type'] : '') . '</td>' . PHP_EOL;
    echo
' <td>' . (isset($aContact['phoneNumbers'][1]) ? $aContact['phoneNumbers'][1]['value'] : '') . '</td>' . PHP_EOL;
    echo
' <td>' . (isset($aContact['emailAddresses'][0]) ? $aContact['emailAddresses'][0]['value'] : '') . '</td>' . PHP_EOL;
    echo
' <td><a class="trash" href="' . $strDeleteFunc . '" title="delete contact">&#128465;</a></td>' . PHP_EOL;
    echo
' </tr>' . PHP_EOL;
}
?>
</tbody>
    </table>
</body>
</html>


Details

Access to google contacts through the google people API

Latest Stable Version License Donate Minimum PHP Version Scrutinizer Code Quality

Overview

This package provides all classes and functions to manage the contacts of a Google account. Access is via the Google Perons API with OAuth2 authentication. The following functionalities are supported: - Login and authentication to the google account - List contacts - Search in contacts - Filter contacts per conatct group (-> Label) - create / edit / delete contacts - list contact groups - create / edit / delete contact groups - assign /remove contacts to contact groups - set / remove contact photos

The package only uses the standard PHP cURL library and have no further dependencies to any other 3rd party libraries or packages.

The fact that on almost every mobile phone that runs under Android, the contacts are managed either with the Google Contacts or with a compatible app and are also automatically be synchronised with the Google account contacts (with the appropriate setting), makes this package interesting for management- and/or synchronization purposes.

Usage

A smart example of using the package is provided. This example is only intended to demonstrate the use of the package. The UI is only coded 'quick and dirty', contains no validations and should therefore only be used as a starting point for your own implementation.

Take a lock at the files - ContactList.php - ContactDetails.php - DoAction.php - GoogleLogin.php - GoogleOauth2Callback.php

The starting point is the file ´ContactList.php´

A complete documentation of the classes and a detailed description, how to create your own credential to access the google API can be found at https://github.com/Stefanius67/GContacts/wiki

Logging

This package can use any PSR-3 compliant logger. The logger is initialized with a NullLogger-object by default. The logger of your choice have to be passed to the constructor of the ´GClient´ class.

If you are not working with a PSR-3 compatible logger so far, this is a good opportunity to deal with this recommendation and may work with it in the future.

There are several more or less extensive PSR-3 packages available on the Internet.

You can also take a look at the 'XLogger' package and the associated blog 'PSR-3 logging in a PHP application' as an introduction to this topic.


  Files folder image Files  
File Role Description
Files folder imagesecrets (1 file)
Files folder imageSKien (1 directory)
Files folder imageVendor (1 directory)
Accessible without login Plain text file autoloader.php Aux. Auxiliary script
Accessible without login Plain text file ContactDetails.php Example Example script
Accessible without login Plain text file ContactList.php Example Example script
Accessible without login Plain text file displayApiError.php Aux. Auxiliary script
Accessible without login Plain text file DoAction.php Example Example script
Accessible without login Plain text file githubwiki.xml Data Auxiliary data
Accessible without login Plain text file GoogleLogin.php Example Example script
Accessible without login Plain text file GoogleOauth2Callback.php Example Example script
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpstan.neon Data Auxiliary data
Accessible without login Plain text file readme.md Doc. Documentation

  Files folder image Files  /  secrets  
File Role Description
  Accessible without login Plain text file .htaccess Data Auxiliary data

  Files folder image Files  /  SKien  
File Role Description
Files folder imageGoogle (7 files)

  Files folder image Files  /  SKien  /  Google  
File Role Description
  Plain text file GClient.php Class Class source
  Plain text file GContact.php Class Class source
  Plain text file GContactGroups.php Class Class source
  Plain text file GContacts.php Class Class source
  Plain text file GSecrets.php Class Class source
  Plain text file MissingClientInformationException.php Class Class source
  Plain text file MissingPropertyException.php Class Class source

  Files folder image Files  /  Vendor  
File Role Description
Files folder imagePsr (1 directory)

  Files folder image Files  /  Vendor  /  Psr  
File Role Description
Files folder imageLog (8 files)

  Files folder image Files  /  Vendor  /  Psr  /  Log  
File Role Description
  Plain text file AbstractLogger.php Class Class source
  Plain text file InvalidArgumentException.php Class Class source
  Plain text file LoggerAwareInterface.php Class Class source
  Plain text file LoggerAwareTrait.php Class Class source
  Plain text file LoggerInterface.php Class Class source
  Plain text file LoggerTrait.php Class Class source
  Plain text file LogLevel.php Class Class source
  Plain text file NullLogger.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:107
This week:0
All time:9,671
This week:78Up