0 Replies - 1553 Views - Last Post: 29 September 2011 - 02:21 PM

#1 codeprada   User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 963
  • View blog
  • Posts: 2,382
  • Joined: 15-February 11

GoogleBooks API Class

Posted 29 September 2011 - 02:21 PM

Description:
<?php
#autoload or include path
#require_once 'GoogleBooks.class.php';
$gb = new GoogleBooks;
/*
*Authorizing requests and identifying your application
*http://code.google.com/apis/books/docs/v1/using.html#auth
*/
$gb->setOAuthToken('view link above to get this');
$gb->setKey('view link above to get this also');
$gb->setCertificateFilePath('certificate path on server');
/*********************************************************/

#fetching a book using OAuth
$results = $gb->fetch('IbiEAAAAIAAJ', GoogleBooks::GOOGLE_AUTH_ACCESS_TYPE_OAUTH);
echo nl2br(print_r($results, true));

#fetching a book using API Key
$results = $gb->fetch('IbiEAAAAIAAJ', GoogleBooks::GOOGLE_AUTH_ACCESS_TYPE_KEY);
echo nl2br(print_r($results, true));

#Searching for a book using OAuth
$results = $gb->search('php power programming', NULL, GoogleBooks::FILTER_PARAM_FREE_EBOOKS, GoogleBooks::GOOGLE_AUTH_ACCESS_TYPE_OAUTH, true);
echo nl2br(print_r($results, true));
?>



Access the GoogleBooks API using this class. It allows for the fetching and searching of books. It also supports authentication via OAuth or your API Key.
<?php
/*
 * @class GoogleBooks
 * @abstract Access the GoogleBooks API with just a few function calls
 * @author Chavez Watkins
 * @datecreated Tuesday, 9th August, 2011
 */
class GoogleBooks
{
	/*
	* @var (string) $certificateFilePath	Path of certificate file
	* @var (string) $googleApiKey			Key used in query
	* @var (Object) $curl					cURL Object
	* @var (string) $googleApiBaseUrl		Base url used to perform all operations
	* @var (string) $error					Error messages
	* @const (string) SEARCH_PARAM_KEYWORD 		Keyword used in search
	* @const (string) SEARCH_PARAM_AUTHOR 		Perofrm search by Author
	* @const (string) SEARCH_PARAM_TITLE 		Perform search by Title
	* @const (string) SEARCH_PARAM_SUBJECT 		Perform search by Subject
	* @const (string) SEARCH_PARAM_PUBLISHER 	Perform search by publisher
	* @const (string) SEARCH_PARAM_ISBN 		Perform a search by ISBN
	* @const (string) FILTER_PARAM_PARTIAL 		Apply a filter 'partial' to search
	* @const (string) FILTER_PARAM_FULL 		Apply filter 'full' to search
	* @const (string) FILTER_PARAM_FREE_EBOOKS 	Apply filter 'free-ebooks' to search
	* @const (string) FILTER_PARAM_PAID_EBOOKS 	Apply filter 'paid-ebooks' to search
	* @const (string) FILTER_PARAM_EBOOKS 		Apply filer 'ebooks' to search
	*/
    private
        $certificateFilePath    = NULL,
        $googleApiKey           = NULL,
		$googleOAuthToken		= NULL,
        $curl                   = NULL,
        $googleApiBaseUrl       = 'https://www.googleapis.com/books/v1/volumes'
    ;
	
	public
		$error					= NULL
	;
    
    const
        SEARCH_PARAM_KEYWORD        	= 'q',
        SEARCH_PARAM_AUTHOR         	= 'inauthor',
        SEARCH_PARAM_TITLE          	= 'intitle',
        SEARCH_PARAM_SUBJECT        	= 'subject',
        SEARCH_PARAM_PUBLISHER      	= 'inpublisher',
        SEARCH_PARAM_ISBN           	= 'isbn',
        FILTER_PARAM_PARTIAL        	= 'partial',
        FILTER_PARAM_FULL           	= 'full',
        FILTER_PARAM_FREE_EBOOKS    	= 'free-ebooks',
        FILTER_PARAM_PAID_EBOOKS    	= 'paid-ebooks',
        FILTER_PARAM_EBOOKS         	= 'ebooks',
		GOOGLE_AUTH_ACCESS_TYPE_OAUTH	= 1000,
		GOOGLE_AUTH_ACCESS_TYPE_KEY		= 1001
    ;
    
	/*
	* Set googleapi key, initialize curl and set the certificate file path
	*
	* @param (string) $key  					Googleapi key
	* @param (string) $certificate_file_path	Certificate file path
	* @return (void)
	*/	
    public function __construct($key = NULL, $oauth_token = NULL, $certificate_file_path = NULL)
    {
		$this->curl = curl_init();
        $this->setKey($key);
        $this->setOAuthToken($oauth_token);
        $this->setCertificateFilePath($certificate_file_path);
    }
    
	/*
	* Set the googleapi key
	*
	* @param (string) $key 		Googleapi key
	* @return (void)
	*/
    public function setKey($key)
    {
        if(is_string($key))
		{
            $this->googleApiKey = $key;
		}
		else
		{
			$this->error = 'Type mismatch on key. Key should be of type string';
		}
    }
    
	/*
    * Set certificate file path
    * 
    * @param (string) $certificate_path     Certificate file path
    * @return (bool)                        If path was set or not
    */
    public function setCertificateFilePath($certificate_path)
    {
		$successful = false;
		
        if(file_exists($certificate_path))
        {
            $this->certificateFilePath = $certificate_path;
            $successful = true;
        }
		else
		{
			$this->error = 'Certificate not found';
		}
        return $successful;
    }
	
	/*
	* Set OAuth access token
	*
	* @param (string) $oauth_token
	* @return (void)
	*/
	public function setOAuthToken($oauth_token)
	{
		if(is_string($oauth_token))
		{
			$this->googleOAuthToken = $oauth_token;
		}
		else
		{
			$this->error = 'Type mismatch on OAuth Token. OAuth Token should be of type string';
		}
	}
    
    /*
    * Perform a search
    * 
    * @param (string) $keyword              Keyword used in search
    * @param (Array)  $search_parameters    Search Parameters used in search
    * @param (string) $filter               Filter used in search
    * @param (boolean) $secure              Use certificate in search
    * @return (string)                      JSON string of results
    */
    public function search($keyword, $search_parameters, $filter = NULL, $google_auth_access_type = GoogleBooks::GOOGLE_AUTH_ACCESS_TYPE_KEY, $verify_peer = false)
    {
        return $this->executeCurl($this->prepareSearchUrl($keyword, $search_parameters, $filter, $google_auth_access_type), $verify_peer);
    }
	
    /*
    * Fetch book from GoogleBooks based on book id
    * 
    * @param (string) $google_book_id   Google Book ID
    * @param (boolean) $secure          Use certificate in search
    * @return (string)                  JSON string of results
    */
	public function fetch($google_book_id, $google_auth_access_type = GoogleBooks::GOOGLE_AUTH_ACCESS_TYPE_KEY, $verify_peer = false)
    {
        return $this->executeCurl($this->prepareFetchUrl($google_book_id, $google_auth_access_type), $verify_peer);
    }
	
    /*
    * Perform use cURL to make request
    * 
    * @param (string) $url        URL to send request to
    * @param (boolean) $secure    Use certificate in search
    * @return (string)            JSON string of results
    */
    private function executeCurl($url, $verify_peer)
    {
        $curl_options = array(CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true);
		
        if($verify_peer == true)
        {
            if(!empty($this->certificateFilePath))
            {
                $curl_options[CURLOPT_SSL_VERIFYPEER] = true;
                $curl_options[CURLOPT_SSL_VERIFYHOST] = 2;
                $curl_options[CURLOPT_CAINFO] = $this->certificateFilePath;
            }
        } 
        else
        {
            $curl_options[CURLOPT_SSL_VERIFYPEER] = false;
        }
        
        curl_setopt_array($this->curl, $curl_options);
		
		$results = curl_exec($this->curl);
		$this->error = curl_error($this->curl);
		
		return $results;
    }
    
    /*
    * Prepare search URL
    * 
    * @param (string) $keyword              Keyword used in search
    * @param (Array)  $search_parameters    Search Parameters used in search
    * @param (string) $filter               Filter used in search
    * @return (string)                      Prepared URL
    */        
    private function prepareSearchUrl($keyword, $search_parameters, $filter, $google_auth_access_type)
    {
        $google_api_url = $this->googleApiBaseUrl . '?q=' . urlencode($keyword);    
        
		if(is_array($search_parameters))
		{
			foreach($search_parameters as $param => $value)
			{
				$google_api_url .= '+' . $param . ':' . urlencode($value);
			}
		}
        
        if(!empty($filter))
        {
            $google_api_url .= '&filter=' . $filter; 
        }
        
        if($auth_url_query = $this->prepareAuthUrlQuery($google_auth_access_type))
		{
			$google_fetch_url .= '?' . $auth_url_query;
		}
        
        return $google_api_url;
    }
    
    /*
    * Prepare fetch URL
    * 
    * @param (string) $google_book_id   Google Book ID
    * @return (string)                  URL used to fetch book
    */
    private function prepareFetchUrl($google_book_id, $google_auth_access_type)
    {
        $google_fetch_url = $this->googleApiBaseUrl . '/' . $google_book_id;
		
		if($auth_url_query = $this->prepareAuthUrlQuery($google_auth_access_type))
		{
			$google_fetch_url .= '?' . $auth_url_query;
		}
		
        return $google_fetch_url;
    }
	
	/*
	* Prepare OAuth2.0 url query
	*
	* @return (mixed) Returns query string null if required variabes are not set
	*/
	private function prepareAuthUrlQuery($google_auth_access_type)
	{
		$auth_url_query = NULL;
		
		switch($google_auth_access_type)
		{
			case GoogleBooks::GOOGLE_AUTH_ACCESS_TYPE_KEY:
			{
				if(!empty($this->googleApiKey))
				{
					$auth_url_query = 'key=' . urlencode($this->googleApiKey);
				}	
			}
			break;
			
			case GoogleBooks::GOOGLE_AUTH_ACCESS_TYPE_OAUTH:
			{
				if(!empty($this->googleOAuthToken))
				{
					$auth_url_query = 'oauth_token=' . urlencode($this->googleOAuthToken);
				}	
			}
			break;
			
			default:
				throw new Exception('Invalid access method'); 
		}
		
		return $auth_url_query;
	}
}
?>


Is This A Good Question/Topic? 0
  • +

Page 1 of 1