Google API PHP Client - Contacts Service

12,306

Solution 1

From here:

Unfortunately the contacts API is one of the older GData ones, while this library is for the newer APIs. You can use the OAuth part of the library to request the scope (https://www.googleapis.com/auth/contacts.readonly), and use the token to make the request, but you'll have to parse the data manually. Zend Framework does have the Zend_Gdata classes that might make reading the results a bit easier!

I found an example using the old library.

Solution 2

Update, 28th March 2018:

I've created a new package to manage Google Contacts based on the newer Google People API. If you're started a new project, I'd recommend you use this package instead of the one mentioned in my original post below.

You can find more details here: https://github.com/rapidwebltd/php-google-people-api


Original Post:

I had to work with this recently and after finding the lack of a Contacts service in the official PHP Google Client, I created a (MIT licensed) PHP library for the Google Contacts API.

One of the aims is to really simplify some of the process involved. So to answer your question, after setting up the library, the following code is all that is needed to retrieve contacts.

require_once '../../../vendor/autoload.php';
use rapidweb\googlecontacts\factories\ContactFactory;
$contacts = ContactFactory::getAll();
if (count($contacts)) {
    echo 'Test retrieved '.count($contacts).' contacts.';
} else {
    echo 'No contacts retrieved!';
}

The library needs a little work, but works well for basic contact retrieval, creation and updating. It can also be installed via composer if needed. Just add the following to your composer.json and run composer update.

{
  "require": {
       "rapidwebltd/php-google-contacts-v3-api": "dev-master"
   }
}

Further setup instructions and examples are available on GitHub.

GitHub Link: https://github.com/rapidwebltd/php-google-contacts-v3-api

Solution 3

I was able to get this working via the new library... mostly. Its not as slick as a full Service implementation, obviously, but it gets things moving.

Git the library as mentioned in posts above. I started with the examples here: https://developers.google.com/api-client-library/php/auth/web-app

oauth2callback.php (note that the full path to this has to be listed on the APIs & Auth/Credentials section of your Developer Console or your calls will fail):

<?php

set_include_path(get_include_path() . PATH_SEPARATOR . '/data/www/unity/html/lib');  # The path where I git got google-api-php-client
require_once 'google-api-php-client/src/Google/autoload.php';

$APPPATH = "/Applications/GFContacts";

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('accountinfo.json'); # JSON config file downloaded from the credentials page of my project https://console.developers.google.com/project
$client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . $APPPATH . '/oauth2callback.php');
$client->addScope("https://www.googleapis.com/auth/contacts.readonly");

if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . $APPPATH;
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

?>

And then index.php:

<?php

set_include_path(get_include_path() . PATH_SEPARATOR . '/data/www/unity/html/lib');  # The path where I git got google-api-php-client

require_once 'google-api-php-client/src/Google/autoload.php';
$APPPATH = "/Applications/GFContacts"; # relative path from server root

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('accountinfo.json'); # JSON config file downloaded from the credentials page of my project https://console.developers.google.com/project
$client->addScope("https://www.googleapis.com/auth/contacts.readonly");

# Allow a param 'logout' to remove the access token - sometimes doing this helps debug issues
if (isset($_REQUEST['logout'])) {
    unset($_SESSION['access_token']);
    $client->revokeToken();

    print "You're logged out of Google";

    exit;
}

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

    $access_token = json_decode($_SESSION['access_token'])->access_token;

    $client->setAccessToken($_SESSION['access_token']);

    $req = new Google_Http_Request("https://www.google.com/m8/feeds/contacts/default/full");
    $val = $client->getAuth()->authenticatedRequest($req);

    // The contacts api only returns XML responses.
    $response = json_encode(simplexml_load_string($val->getResponseBody()));
    print "<pre>" . print_r(json_decode($response, true), true) . "</pre>"; 

} else {
    $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . $APPPATH . '/oauth2callback.php';
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

?>

Good luck! Its been a while since this post was updated, so if anyone's written a Service I'd love to know about it. In the meantime, this should get you started!

Share:
12,306
FooBar
Author by

FooBar

Updated on June 06, 2022

Comments

  • FooBar
    FooBar almost 2 years

    I have, after hours of deep, deep pain, finally got a bit closer to the configuration and usage of Google's API PHP Client, using this tutorial (based on Analytics though).

    So, now I finally auth my self, in a way that seems legit and official. My natural thought was that there would exist an contrib/Google_ContactsService.php, but to my surprise, it is nowhere to find amogst the 32 other service classes.

    I feel like back to scratch. Is there any way I can - legit and officially - fetch a specific users' contacts? (tons of tutorials out there, but all outdated and hacky).

    EDIT: I notice there is a newer version of the library available here, but there is still not any "Contacts" service to be found in the .../Service/ folder

    EDIT: My progress so far. The last lines fails with response from Google: 401. There was an error in your request. - I guess that is because of lack of permission (I didn't ask for Contacts permission). But how do I do this, without the "Google_ContactsService.php"? I am lost. See code:

    <?php
    session_start();
    
    /**
     * Require the libaries
     */
    
        require_once 'assets/php/Google/Google_Client.php';
        require_once 'assets/php/Google/contrib/Google_AnalyticsService.php'; // from tutorial - I am supposed to get the Contacts Service, which is nowhere to find.
    
    /**
     * Set up the Google_Client
     */
    
        $client = new Google_Client();
        $client->setAccessType('online'); // default: offline
        $client->setApplicationName($apiConfig['application_name']);
        $client->setClientId($apiConfig['oauth2_client_id']);
        $client->setClientSecret($apiConfig['oauth2_client_secret']);
        $client->setRedirectUri($apiConfig['oauth2_redirect_uri']);
        $client->setDeveloperKey($apiConfig['developer_key']); // API key
    
    /**
     * $service implements the client interface, has to be set before auth call
     */
    
        $service = new Google_AnalyticsService($client);
    
    /**
     * Log out
     */
    
        if (isset($_GET['logout'])) { // logout: destroy token
            unset($_SESSION['google_token']);
            exit('Logged out.');
        }
    
    /**
     * Google auth code received
     *
     * Store access token
     */
    
        if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
            $client->authenticate();
            $_SESSION['google_token'] = $client->getAccessToken();
        }
    
    /**
     * Set auth token
     */
    
        if (isset($_SESSION['token'])) { // extract token from session and configure client
            $token = $_SESSION['token'];
            $client->setAccessToken($token);
        }
    
    /**
     * If no token, redirect and auth
     */
    
        if (!$client->getAccessToken()) { // auth call to google
            $authUrl = $client->createAuthUrl();
            header("Location: ".$authUrl);
            exit;
        }
    
    /**
     * Get contacts
     */
    
        $access_token = json_decode($client->getAccessToken())->access_token;
    
        $url = 'https://www.google.com/m8/feeds/contacts/default/full?alt=json&v=3.0&oauth_token='.$access_token;
    
        $response =  file_get_contents($url);
    
        exit($response);
    
        echo 'Hello, world.';