Previous Next

Using Google Health

The Google Health Data API is designed to enable developers to do two things:

  • Read a user's Google Health profile or query for medical records that match particular criteria and then use the results to provide personalized functionality based on the data.

  • Add new medical records to a user's profile by including CCR data when sending a notice to a user's profile. Note: The CCR data is stored as an XML blob within the <atom> entry. The library does not provide direct accessors to the object model but it does have helpers for extracting specific fields.

There are three main feeds, each of which requires authentication. Unlike other Google Data APIs, each Google Health feed has a limited set of HTTP operations you can perform on it, depending on which authentication method you are using (ClientLogin or AuthSub/OAuth). For a list of permitted operations, see » http://code.google.com/apis/health/reference.html#Authentication.

  • Profile Feed use the profile feed to query a user's health profile for specific information.

  • Register Feed use the register feed to reconcile new CCR data into a profile.

  • Profile List Feed the profile list feed should be used to determine which of the user's Health profiles to interact with. This feed is only available when using ClientLogin.

See » http://code.google.com/apis/health for more information about the Google Health API.

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:

// 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.

/*
 * 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 'Your Google Health Account';
    } 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.

Profile Feed

To query the user's profile feed, make sure your initial AuthSub token was requested with the permission parameter set to 1. The process of extracting data from the profile requires two steps, sending a query and iterating through the resulting feed.

Send a Structured Query

You can send structured queries to retrieve specific records from a user's profile.

When retrieving the profile using the Health API, specifically constructed query URLs are used to describe what (CCR) data should be returned. The Zend_Gdata_Health_Query class helps simplify this task by automatically constructing a query URL based on the parameters you set.

Query The Feed

To execute a query against the profile feed, invoke a new instance of an Zend_Gdata_Health_Query and call the service's getHealthProfileFeed() method:

$healthService = new Zend_Gdata_Health($client);

// example query for the top 10 medications with 2 items each
$query = new Zend_Gdata_Health_Query();
$query->setDigest("true");
$query->setGrouped("true");
$query->setMaxResultsGroup(10);
$query->setMaxResultsInGroup(2);
$query->setCategory("medication");

$profileFeed = $healthService->getHealthProfileFeed($query);

Using setDigest("true") returns all of user's CCR data in a single Atom <entry>.

The setCategory() helper can be passed an additional parameter to return more specific CCR information. For example, to return just the medication Lipitor, use setCategory("medication", "Lipitor"). The same methodology can be applied to other categories such as conditions, allergies, lab results, etc.

A full list of supported query parameters is available in the » query parameters section of the Health API Reference Guide.

Iterate Through The Profile Entries

Each Google Health entry contains CCR data, however, using the digest query parameter and setting is to TRUE will consolidate all of the CCR elements (that match your query) into a single Atom <entry>.

To retrieve the full CCR information from an entry, make a call to the Zend_Gdata_Health_ProfileEntry class's getCcr() method. That returns a Zend_Gdata_Health_Extension_CCR:

$entries = $profileFeed->getEntries();
foreach ($entries as $entry) {
    $medications = $entry->getCcr()->getMedications();
    //$conditions = $entry->getCcr()->getConditions();
    //$immunizations = $entry->getCcr()->getImmunizations();

    // print the CCR xml (this will just be the entry's medications)
    foreach ($medications as $med) {
        $xmlStr = $med->ownerDocument->saveXML($med);
        echo "
" . $xmlStr . "
"; } }

Here, the getCcr() method is used in conjunction with a magic helper to drill down and extract just the medication data from the entry's CCR. The formentioned magic helper takes the form getCATEGORYNAME(), where CATEGORYNAME is a supported Google Health category. See the » Google Health reference Guide for the possible categories.

To be more efficient, you can also use category queries to only return the necessary CCR from the Google Health servers. Then, iterate through those results:

$query = new Zend_Gdata_Health_Query();
$query->setDigest("true");
$query->setCategory("condition");
$profileFeed = $healthService->getHealthProfileFeed($query);

// Since the query contained digest=true, only one Atom entry is returned
$entry = $profileFeed->entry[0];
$conditions = $entry->getCcr()->getConditions();

// print the CCR xml (this will just be the profile's conditions)
foreach ($conditions as $cond) {
    $xmlStr = $cond->ownerDocument->saveXML($cond);
    echo "
" . $xmlStr . "
"; }

Profile List Feed

NOTE: This feed is only available when using ClientLogin

Since ClientLogin requires a profile ID with each of its feeds, applications will likely want to query this feed first in order to select the appropriate profile. The profile list feed returns Atom entries corresponding each profile in the user's Google Health account. The profile ID is returned in the Atom <content> and the profile name in the <title> element.

Query The Feed

To execute a query against the profile list feed, call the service's getHealthProfileListFeed() method:

$client = Zend_Gdata_ClientLogin::getHttpClient('user@gmail.com',
                                                'pa$$word',
                                                'health');
$healthService = new Zend_Gdata_Health($client);
$feed = $healthService->getHealthProfileListFeed();

// print each profile's name and id
$entries = $feed->getEntries();
foreach ($entries as $entry) {
    echo '

Profile name: ' . $entry->getProfileName() . '
'; echo 'profile ID: ' . $entry->getProfileID() . '

'; }

Once you've determined which profile to use, call setProfileID() with the profileID as an argument. This will restrict subsequent API requests to be against that particular profile:

// use the first profile
$profileID = $feed->entry[0]->getProfileID();
$healthService->setProfileID($profileID);

$profileFeed = $healthService->getHealthProfileFeed();

$profileID = $healthService->getProfileID();
echo '

Queried profileID: ' . $profileID . '

';

Sending Notices to the Register Feed

Individual posts to the register feed are known as notices. Notice are sent from third-party applications to inform the user of a new event. With AuthSub/OAuth, notices are the single means by which your application can add new CCR information into a user's profile. Notices can contain plain text (including certain XHTML elements), a CCR document, or both. As an example, notices might be sent to remind users to pick up a prescription, or they might contain lab results in the CCR format.

Sending a notice

Notices can be sent by using the sendHealthNotice() method for the Health service:

$healthService = new Zend_Gdata_Health($client);

$subject = "Title of your notice goes here";
$body = "Notice body can contain html entities";
$ccr = '
  
   
    
      
        Start date
        2007-04-04T07:00:00Z
      
      
        Aortic valve disorders
        
          410.10
          ICD9
          2004
        
      
      Active
    
  
  
';

$responseEntry = $healthService->sendHealthNotice($subject,
                                                  $body,
                                                  "html",
                                                  $ccr);
Previous Next
Introdução ao Zend Framework
Resumo
Instalação
Conhecendo o Zend Framework
Guia Rápido do Zend Framework
Zend Framework & MVC Introduction
Create Your Project
Create A Layout
Create a Model and Database Table
Create A Form
Congratulations!
Auto-carregamento no Zend Framework
Introduction
Goals and Design
Basic Autoloader Usage
Resource Autoloading
Conclusion
Plugins no Zend Framework
Introduction
Using Plugins
Conclusion
Iniciando com o Zend_Layout
Introduction
Using Zend_Layout
Zend_Layout: Conclusions
Iniciando com os Marcadores do Zend_View
Introduction
Basic Placeholder Usage
Standard Placeholders
View Placeholders: Conclusion
Entendendo e Usando os Decoradores do Zend Form
Introduction
Decorator Basics
Layering Decorators
Rendering Individual Decorators
Creating and Rendering Composite Elements
Conclusion
Iniciando com o Zend_Session, Zend_Auth, e Zend_Acl
Building Multi-User Applications With Zend Framework
Managing User Sessions In ZF
Authenticating Users in Zend Framework
Building an Authorization System in Zend Framework
Iniciando com o Zend_Search_Lucene
Zend_Search_Lucene Introduction
Lucene Index Structure
Index Opening and Creation
Indexing
Searching
Supported queries
Search result pagination
Iniciando com o Zend_Paginator
Introduction
Simple Examples
Pagination Control and ScrollingStyles
Putting it all Together
Referência do Zend Framework
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introdução
Zend_Amf_Server
Zend_Application
Introdução
Zend_Application Quick Start
Theory of Operation
Examples
Core Functionality
Available Resource Plugins
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Barcode
Introdução
Criação de código de barras usando a classe Zend_Barcode
Objetos Zend_Barcode
Renderizadores do Zend_Barcode
Zend_Cache
Introduction
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
The Cache Manager
Zend_Captcha
Introdução
Captcha Operation
CAPTCHA Adapters
Zend_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introdução
Teoria de Operação
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Guia de Início Rápido do Zend_Controller
O Básico de Zend_Controller
O Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Zend_Currency
Introduction to Zend_Currency
Using Zend_Currency
Options for currencies
What makes a currency?
Where is the currency?
How does the currency look like?
How much is my currency?
Calculating with currencies
Exchanging currencies
Additional informations on Zend_Currency
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of Dates
Constants for General Date Functions
Working Examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Db_Table_Definition
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dojo build layer support
Zend_Dom
Introdução
Zend_Dom_Query
Zend_Exception
Usando as Exceções
Uso básico
Exceções Anteriores
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_Feed_Reader
Zend_Feed_Writer
Zend_Feed_Pubsubhubbub
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introdução
Uso Básico
Uso Avançado do Zend_Json
Conversão de XML para JSON
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introdução
Guia Rápido Zend_Layout
Opções de Configuração Zend_Layout
Uso Avançado de Zend_Layout
Zend_Ldap
Introduction
API overview
Usage Scenarios
Tools
Object oriented access to the LDAP tree using Zend_Ldap_Node
Getting information from the LDAP server
Serializing LDAP data to and from LDIF
Zend_Loader
Loading Files and Classes Dynamically
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Zend_Log
Overview
Writers
Formatters
Filters
Using the Factory to Create a Log
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Markup
Introduction
Getting Started With Zend_Markup
Zend_Markup Parsers
Zend_Markup Renderers
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Zend_Oauth
Introduction to OAuth
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introdução
Usage
Configuração
Advanced usage
Zend_Pdf
Introdução.
Criando e Carregando documentos PDF.
Salvar mudanças no documento PDF.
Document pages.
Drawing.
Interactive Features
Informação do Documento e Metadados.
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Queue
Introduction
Example usage
Framework
Adapters
Customizing Zend_Queue
Stomp
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Resumo
Construindo Índices
Pesquisando em um Índice
Query Language
Tipos de Consulta
Conjuntos de Caracteres
Extensibilidade
Interoperando com Java Lucene
Advanced
Best Practices
Zend_Serializer
Introduction
Zend_Serializer_Adapter
Zend_Server
Introdução
Zend_Server_Reflection
Zend_Service
Introdução
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Storage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Amazon_Sqs
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_DeveloperGarden
Zend_Service_Flickr
Zend_Service_LiveDocx
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Zend_Service_SlideShare
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_WindowsAzure
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introdução
Zend_Test_PHPUnit
Zend_Test_PHPUnit_Db
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool
Using Zend_Tool On The Command Line
Extending Zend_Tool
Zend_Tool_Framework
Introduction
Using the CLI Tool
Architecture
Creating Providers to use with Zend_Tool_Framework
Shipped System Providers
Extending and Configuring Zend_Tool_Framework
Zend_Tool_Project
Introduction
Create A Project
Zend_Tool Project Providers
Zend_Tool_Project Internals
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Creating source files
Additional features for translation
Plural notations for Translation
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Validation Messages
Zend_Version
Obtendo a Versão do Zend Framework
Zend_View
Introdução
Scripts Controladores
Scripts de Visualização
Assistentes de Visualização (Modificadores)
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
ZendX_Console_Process_Unix
ZendX_Console_Process_Unix
ZendX_JQuery
Introduction
ZendX_JQuery View Helpers
ZendX_JQuery Form Elements and Decorators
Pré-requisitos do Zend Framework
Introdução
Notas de Migração do Zend Framework
Zend Framework 1.10
Zend Framework 1.9
Zend Framework 1.8
Zend Framework 1.7
Zend Framework 1.6
Zend Framework 1.5
Zend Framework 1.0
Zend Framework 0.9
Zend Framework 0.8
Zend Framework 0.6
Padrões de Codificação do Framework Zend para PHP
Visão Geral
Formato do Arquivo PHP
Convenções de Nomes
Estilo de Código
Zend Framework Documentation Standard
Overview
Documentation File Formatting
Recommendations
Recommended Project Structure for Zend Framework MVC Applications
Overview
Recommended Project Directory Structure
Module Structure
Rewrite Configuration Guide
Guia de Desempenho do Zend Framework
Introdução
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Informações Sobre Direitos Autorais