ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Updated: Amazon Services API Library

February 07, 2010 11:56pm

Subscribe [5]
  • #1 / Feb 07, 2010 11:56pm

    johnnytoobad

    8 posts

    I found a basic Amazon Product Advertising API (APAA) library here: http://codeigniter.com/wiki/Amazon_Services_API_Integration/

    However since last year APAA has required a signature, which has broken this code. I used it as a based, fixed the signature issue, cleaned up the code and introduced the CI pagination class. Since I used this code to get started I thought it was only fair to post my working updated library here in case someone else finds it useful.

    My questions here are;
    1) I’m only a beginner so if someone more experienced has a second to cast their eye over the code, i would be grateful. Just to make sure i haven’t made any outrageous errors
    2) Whats the etiquette regarding posting this to the wiki, should I update the old non-working page or create something new?


    Here is my code (also attached):

    Amazon_api.php (library)

    <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
    
    // -------------------------------------------------------------------------------------------------
    /**
     * Amazon Product Advertising API library
     * 
     * This is a very basic libary allowing you to search the Amazon Product Advertising API
     *
     * Based on and inspired by original CI Amazon library by Zac G. (<a href="http://zgordon.org">http://zgordon.org</a>) and on code by Richard Cummings (<a href="http://richardcummings.info/the-request-must-contain-the-parameter-signature-quick-fix-for-your-php-rest-requests/">http://richardcummings.info/the-request-must-contain-the-parameter-signature-quick-fix-for-your-php-rest-requests/</a>)
     *
     * @package        CodeIgniter
     * @subpackage    Libraries
     * @author        johnnytoobad <http://ellislab.com/forums/member/88806>    
     * @version        2.0
     * @license        <a href="http://www.opensource.org/licenses/bsd-license.php">http://www.opensource.org/licenses/bsd-license.php</a> BSD licensed.
     *
     */
    // -------------------------------------------------------------------------------------------------
    
    
    class Amazon_api
    {
    
        function Amazon_api()
        {
            $this->ci =& get_instance();
        }
    
        
        function search_amazon($keywords, $item_page)
        {   
    
            //You Amazon API keys
            $aws_access_key_id = 'XXXXXXXXXXXXXXXXXXX';
            $aws_secret_access_key = 'XXXXXXXXXXXXXXXXXXXXX';
             
            $base_url = 'http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId;=' . $aws_access_key_id . '&';
            
            //Set parameters for API search, see AWS documentation for a detailed list of parameters
            $url_params = array(
                'Operation'=>'ItemSearch',
                'ItemPage'=>$item_page,
                'AssociateTag'=>'YOUR-ASSOCIATE-TAG',
                'Version'=>'2006-09-11',
                'ResponseGroup'=>'Images,ItemAttributes,EditorialReview',
                 'SearchIndex'=>'Books',
                 'Keywords'=>rawurlencode($keywords)
             );
             
            //Sort the URL parameters
            $url_parts = array();
            foreach(array_keys($url_params) as $key)
                $url_parts[] = $key."=".$url_params[$key];
            sort($url_parts);
            
            //Build and encode the request URL
            $url = $base_url . implode('&',$url_parts);
            $host = parse_url($base_url . implode('&',$url_parts),PHP_URL_HOST);
            $timestamp = gmstrftime('%Y-%m-%dT%H:%M:%S.000Z');
            $url = $url. '&Timestamp;=' . $timestamp;
            $paramstart = strpos($url,'?');
            $workurl = substr($url,$paramstart+1);
            $workurl = str_replace(",",",",$workurl);
            $workurl = str_replace(":",":",$workurl);
            $params = explode("&",$workurl);
            sort($params);
            $signstr = "GET\n" . $host . "\n/onca/xml\n" . implode("&",$params);
            $signstr = base64_encode(hash_hmac('sha256', $signstr, $aws_secret_access_key, true));
            $signstr = urlencode($signstr);
            $signedurl = $url . "&Signature;=" . $signstr;
            $request = $signedurl;    
            
            //Send request to AWS
            $session = curl_init($request);
            curl_setopt($session, CURLOPT_HEADER, false);
            curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($session);
            curl_close($session); 
            $parsed_xml = simplexml_load_string($response);
            
            //Return parsed Amazon data
            return $parsed_xml;                
        }
    
    }
    ?>
  • #2 / Feb 07, 2010 11:58pm

    johnnytoobad

    8 posts

    books.php Controller

    <?php
    
    class Books extends Controller {
    
        function Books()
        {
            parent::Controller();    
            $this->load->library('amazon_api');
            $this->load->helper('form');
            $this->load->library('pagination');
    
        }
        
        function index()
        {
            $this->search_amazon();
        }
    
        function search_amazon($keywords = NULL, $offset = 0)
        {
            //Check if keywords have been submitted via the input
            if($this->input->post('keywords')) {
                $keywords = $this->input->post('keywords');
            }
            
            //If keywords have been entered        
            if ($keywords) {
            
                //Convert CI pagination values to Amazon API ItemPage values
                $page_number = ($offset/10)+1;
    
                //Calls search_amazon method
                $search_results = $this->amazon_api->search_amazon($keywords, $page_number);        
                
                //Configure and initialize pagination        
                $config = array (
                    'base_url' => base_url() . 'books/search_amazon/' . $keywords,
                    'total_rows' => $search_results->Items->TotalResults,
                    'uri_segment' => 4,
                    'per_page' => '10'
                ); 
                $this->pagination->initialize($config); 
                
                $data = array(
                    'search_results' => $search_results,
                    'title' => 'Results From Amazon Search',
                    'keywords' => $keywords,
                    'total_pages' => round($search_results->Items->TotalResults/10),
                    'page_number' => $page_number,
                    'pagination' => $this->pagination->create_links()
                );
            
            //No keywords have been enetred
            } else {
            
                $data = array(
                    'title' => 'Results From Amazon Search', 
                    'error_message' => 'Please enter in a search term'
                );
            }
            
            //Load the views and pass the data
            $this->load->view('find-books', $data);        
        }
    
    }

    find-books.php (view)

    <?php
    //If page is displaying a search result, include that information
    //at the top of the page.  If not, then just display instructions
    //for searching Amazon Database.    
    if (isset($keywords)) {
        echo "<h2>Search Results For \"". $keywords ."\"</h2><p>";<br />
        echo "Go back to the \"". anchor('books', 'Find Books')."\" page. Search again below.";<br />
    }else if (isset($error_message)) {<br />
        echo "</p><h2>".$title."</h2><p>";<br />
        echo "".$error_message.".";<br />
    } else {<br />
        echo "</p><h2>".$title."</h2><p>";<br />
        echo "In the search field below type the name of a <em>teacher</em>, <em>author</em>, or <em>book title</em>.";<br />
    }    </p>
    
    <p>//Check if search keywords are present<br />
    if (!isset($keywords)) { $keywords = ''; }<br />
    $keyword_input = array(<br />
        'name'    => 'keywords',<br />
        'id'    => 'keywords',<br />
        'size'    => 20,<br />
        'value' =>  set_value('keywords', $keywords )<br />
    );<br />
    $form_attributes = array(<br />
        'class' => 'search-form', <br />
        'id' => 'search-form', <br />
        'name' => 'search_terms'<br />
    );</p>
    
    <p>// Set attributes for the form<br />
    echo form_open('books/search_amazon', $form_attributes); <br />
    // Set attributes for the input field<br />
    echo form_input($keyword_input);<br />
    // Set attributes for the submit field<br />
    echo form_submit('submit_button', 'Search Amazon!');<br />
    echo '</form>';<br />
    ?></p>
    
    <p><?php if (isset($search_results)): // Check to see if $search_results has been passed ?><br />
    Page: <?= $page_number ?> of <?= $total_pages ?><br />
    <?= (isset($pagination)) ? $pagination: ''; ?><br />
        <ul class="books"><br />
            <?php foreach($search_results->Items->Item as $book): //Loop through results ?><br />
                <li><br />
                    Title: <a >DetailPageURL ?>" title=""><?=$book->ItemAttributes->Title //Echo title of book ?></a><br><br />
                    Author: <i><?=$book->ItemAttributes->Author // Echo author of book ?></i><br><br />
                    <img >MediumImage->URL //Link to Thumbnail ?>" alt="Cover of <?=$book->ItemAttributes->Title //Add title of book to alt attribute ?>" class="image-thumbnail" border="1" ><br />
                </li><br />
            <?php endforeach; ?><br />
        </ul><br />
    <?= (isset($pagination)) ? $pagination: ''; ?><br />
    <?php endif; ?>

  • #3 / Mar 25, 2010 12:23am

    nandish

    20 posts

    Hi

    How can i get more than 10 rows or all result in one page

    Thanks In Advance

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases