<?php
/*************************************************************
 * This block of code is here to enable source display.
 * This is because this is demonstration code.
 * This would normally never be included in production code.
 */
if (isset($_REQUEST['show_source'])) {
    
show_source(__FILE__);
    exit ;
}
/*************************************************************
 */

class apiClass {

    
/**
     * @var string $apiCredentials
     * Will contain any required credentials for the API being called.
     * This is initialized in the constructor if a file name and path
     * are passed to it.
     * If no file name is passed then it's assumed that no credentials
     * are required for the API being called.
     *
     */
    
protected $apiCredentials;

    
/**
     * Constructor for class apiClass
     *
     * @param optional string $credentialsFileName
     * The path and filename to a text file
     * containing any required credentials
     * for the API.
     * The contents of this file are loaded into the
     * class property $apiCredentials.
     * The credentials are loaded this way for security
     * reasons.
     */
    
function __construct($credentialsFileName null) {
        if (!
is_null($credentialsFileName)) {
            if (
file_exists($credentialsFileName)) {
                
$file_handle fopen($credentialsFileName'r');
                
$this -> apiCredentials fgets($file_handle);
                
fclose($file_handle);
            } else {
                throw new 
Exception("Specified API Credentials Not Found<br>Please Contact Support");
            }
        } else {
            
$this -> apiCredentials null;
        }
    }

    
/**
     * function callAPI
     *
     * @param string $apiURL
     * The full URL for the API
     *
     * @param array $params
     * an associative array of key value pairs
     * which will be added to the URL as query
     * parameters.
     *
     * @return The data returned by API.
     * The format depends on the API and may
     * be JSON, XML, etc.
     */
    
public function callAPI($apiURL$params) {
        
$restParams http_build_query($params'''&');
        
$apiCall $apiURL '?' $restParams;
        if (!
is_null($this -> apiCredentials)) {
            
$apiCall .= '&' $this -> apiCredentials;
        }
        
$ch curl_init();
        
curl_setopt($chCURLOPT_URL$apiCall);
        
curl_setopt($chCURLOPT_RETURNTRANSFERTRUE);
        if (
strpos($apiCall'https') === 0) {
            
// required for https urls
            
curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);
        }
        
$content curl_exec($ch);
        
$response curl_getinfo($chCURLINFO_HTTP_CODE);
        
curl_close($ch);
        if (
$response != '200') {
            throw new 
Exception('API call failed. HTTP Response = ' $response '\n' $content);
        }
        return 
$content;
    }

}
?>