PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Connect To The Health Service

The Google Health API, like all Google Data APIs, is based off of the Atom Publishing Protocol (APP), an XML based format for managing web-based resources. Traffic between a client and the Google Health servers occurs over HTTP and allows for authenticated connections.

Before any transactions can occur, a connection needs to be made. Creating a connection to the Health servers involves two steps: creating an HTTP client and binding a Zend_Gdata_Health service instance to that client.

Authentication

The Google Health API allows programmatic access to a user's Health profile. There are three authentication schemes that are supported by Google Health:

  • ClientLogin provides direct username/password authentication to the Health servers. Since this method requires that users provide your application with their password, this authentication scheme is only recommended for installed/desktop applications.

  • AuthSub allows a user to authorize the sharing of their private data. This provides the same level of convenience as ClientLogin but without the security risk, making it an ideal choice for web-based applications. For Google Health, AuthSub must be used in registered and secure mode--meaning that all requests to the API must be digitally signed.

  • OAuth is an alternative to AuthSub. Although this authentication scheme is not discussed in this document, more information can be found in the Health Data API Developer's Guide.

See Authentication Overview in the Google Data API documentation for more information on each authentication method.

Create A Health Service Instance

In order to interact with Google Health, the client library provides the Zend_Gdata_Health service class. This class provides a common interface to the Google Data and Atom Publishing Protocol models and assists in marshaling requests to and from the Health API.

Once you've decided on an authentication scheme, the next step is to create an instance of Zend_Gdata_Health. This class should be passed an instance of Zend_Gdata_HttpClient. This provides an interface for AuthSub/OAuth and ClientLogin to create a special authenticated HTTP client.

To test against the H9 Developer's (/h9) instead of Google Health (/health), the Zend_Gdata_Health constructor takes an optional third argument for you to specify the H9 service name 'weaver'.

The example below shows how to create a Health service class using ClientLogin authentication:

<?php
// Parameters for ClientLogin authentication
$healthServiceName Zend_Gdata_Health::HEALTH_SERVICE_NAME;
//$h9ServiceName = Zend_Gdata_Health::H9_SANDBOX_SERVICE_NAME;
$user "user@gmail.com";
$pass "pa$$w0rd";

// Create an authenticated HTTP client
$client Zend_Gdata_ClientLogin::getHttpClient($user,
                                                
$pass,
                                                
$healthServiceName);

// Create an instance of the Health service
$service = new Zend_Gdata_Health($client);

A Health service using AuthSub can be created in a similar, though slightly more lengthy fashion. AuthSub is the recommend interface to communicate with Google Health because each token is directly linked to a specific profile in the user's account. Unlike other Google Data APIs, it is required that all requests from your application be digitally signed.

<?php
/*
 * Retrieve the current URL so that the AuthSub server knows where to
 * redirect the user after authentication is complete.
 */
function getCurrentUrl() {
    
$phpRequestUri htmlentities(substr($_SERVER['REQUEST_URI'],
                                         
0,
                                         
strcspn($_SERVER['REQUEST_URI'],
                                                 
"\n\r")),
                                  
ENT_QUOTES);

    if (isset(
$_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
        
$protocol 'https://';
    } else {
        
$protocol 'http://';
    }
    
$host $_SERVER['HTTP_HOST'];
    if (
$_SERVER['SERVER_PORT'] != '' &&
       ((
$protocol == 'http://' && $_SERVER['SERVER_PORT'] != '80') ||
       (
$protocol == 'https://' && $_SERVER['SERVER_PORT'] != '443'))) {
        
$port ':' $_SERVER['SERVER_PORT'];
    } else {
        
$port '';
    }
    return 
$protocol $host $port $phpRequestUri;
}

/*
 * Redirect a user to AuthSub if they do not have a valid session token.
 * If they're coming back from AuthSub with a single-use token, instantiate
 * a new HTTP client and exchange the token for a long-lived session token
 * instead.
 */
function setupClient($singleUseToken null) {
    
$client null;

    
// Fetch a new AuthSub token?
    
if (!$singleUseToken) {
        
$next getCurrentUrl();
        
$scope 'https://www.google.com/health/feeds';
        
$authSubHandler 'https://www.google.com/health/authsub';
        
$secure 1;
        
$session 1;
        
$authSubURL =  Zend_Gdata_AuthSub::getAuthSubTokenUri($next,
                                                              
$scope,
                                                              
$secure,
                                                              
$session,
                                                              
$authSubHandler);

         
// 1 - allows posting notices && allows reading profile data
        
$permission 1;
        
$authSubURL .= '&permission=' $permission;

        echo 
'<a href="' $authSubURL '">Your Google Health Account</a>';
    } else {
        
$client = new Zend_Gdata_HttpClient();

        
// This sets your private key to be used to sign subsequent requests
        
$client->setAuthSubPrivateKeyFile('/path/to/your/rsa_private_key.pem',
                                          
null,
                                          
true);

        
$sessionToken =
            
Zend_Gdata_AuthSub::getAuthSubSessionToken(trim($singleUseToken),
                                                       
$client);

        
// Set the long-lived session token for subsequent requests
        
$client->setAuthSubToken($sessionToken);
    }
    return 
$client;
}

// -> Script execution begins here <-

session_start();

$client setupClient(@$_GET['token']);

// Create an instance of the Health service
$userH9Sandbox false;
$healthService = new Zend_Gdata_Health($client,
                                       
'googleInc-MyTestAppName-v1.0',
                                       
$userH9Sandbox);

NOTE: the remainder of this document will assume you are using AuthSub for authentication.

Zend Framework