Skip to content

Commit

Permalink
Merge pull request #5 from MarcL/fix/tidy-up
Browse files Browse the repository at this point in the history
Add sort into ItemSearch and tidy up
  • Loading branch information
MarcL authored Jul 11, 2017
2 parents ad9c87d + 33b79cf commit 71bcc64
Show file tree
Hide file tree
Showing 5 changed files with 228 additions and 88 deletions.
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
test.php
# Composer specific
composer.phar
/vendor/

# Avoid commiting secret keys
secretKeys.php
52 changes: 45 additions & 7 deletions AmazonAPI.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class AmazonAPI
private $m_amazonUrl = '';
private $m_locale = 'uk';
private $m_retrieveArray = false;
private $m_useSSL = false;
private $m_useSSL = true;

// AWS endpoint for each locale
private $m_localeTable = array(
Expand All @@ -38,7 +38,45 @@ class AmazonAPI

// Valid names that can be used for search
private $mValidSearchNames = array(
'All','Apparel','Appliances','Automotive','Baby','Beauty','Blended','Books','Classical','DVD','Electronics','Grocery','HealthPersonalCare','HomeGarden','HomeImprovement','Jewelry','KindleStore','Kitchen','Lighting','Marketplace','MP3Downloads','Music','MusicTracks','MusicalInstruments','OfficeProducts','OutdoorLiving','Outlet','PetSupplies','PCHardware','Shoes','Software','SoftwareVideoGames','SportingGoods','Tools','Toys','VHS','Video','VideoGames','Watches',
'All',
'Apparel',
'Appliances',
'Automotive',
'Baby',
'Beauty',
'Blended',
'Books',
'Classical',
'DVD',
'Electronics',
'Grocery',
'HealthPersonalCare',
'HomeGarden',
'HomeImprovement',
'Jewelry',
'KindleStore',
'Kitchen',
'Lighting',
'Marketplace',
'MP3Downloads',
'Music',
'MusicTracks',
'MusicalInstruments',
'OfficeProducts',
'OutdoorLiving',
'Outlet',
'PetSupplies',
'PCHardware',
'Shoes',
'Software',
'SoftwareVideoGames',
'SportingGoods',
'Tools',
'Toys',
'VHS',
'Video',
'VideoGames',
'Watches'
);

private $mErrors = array();
Expand Down Expand Up @@ -163,12 +201,12 @@ private function MakeRequest( $url )
*
* @param keywords Keywords which we're requesting
* @param searchIndex Name of search index (category) requested. NULL if searching all.
* @param sortBySalesRank True if sorting by sales rank, false otherwise.
* @param sortBy Category to sort by, only used if searchIndex is not 'All'
* @param condition Condition of item. Valid conditions : Used, Collectible, Refurbished, All
*
* @return mixed SimpleXML object, array of data or false if failure.
*/
public function ItemSearch( $keywords, $searchIndex = NULL, $sortBySalesRank = true, $condition = 'New' )
public function ItemSearch( $keywords, $searchIndex = NULL, $sortBy = NULL, $condition = 'New' )
{
// Set the values for some of the parameters.
$operation = "ItemSearch";
Expand All @@ -192,9 +230,9 @@ public function ItemSearch( $keywords, $searchIndex = NULL, $sortBySalesRank = t
// Searching for specific index
$request .= "&SearchIndex=" . $searchIndex;

// If we're sorting by sales rank
if ( $sortBySalesRank && ( $searchIndex != 'All' ) )
$request .= "&Sort=salesrank";
// Set sort category
if ( $sortBy && ( $searchIndex != 'All' ) )
$request .= "&Sort=" . $sortBy;
}

// Need to sign the request now
Expand Down
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2016 Marc Littlemore
Copyright (c) 2017 Marc Littlemore

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
225 changes: 146 additions & 79 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,50 @@ It also assumes that you have some knowledge of Amazon's Product API and have se
## Installation
Clone the git repository:

git clone https://github.com/MarcL/AmazonProductAPI.git
```shell
git clone https://github.com/MarcL/AmazonProductAPI.git
```

## Examples

I've added some simple examples in `examples.php`. To run them create a file called `secretKeys.php` containing your secret keys:

```php
<?php
$keyId = 'YOUR-AWS-KEY';
$secretKey = 'YOUR-AWS-SECRET-KEY';
$associateId = 'YOUR-AMAZON-ASSOCIATE-ID';
?>
```

and then run the examples with:

```shell
php examples.php
```

## Usage
Include the library in your code
Include the library in your code:

require_once( 'AmazonAPI' )
```php
include_once('./AmazonAPI.php');
```

Instantiate the class using your secret keys
Instantiate the class using your secret keys:

$keyId = 'YOUR-AWS-KEY';
$secretKey = 'YOUR-AWS-SECRET-KEY';
$associateId = 'YOUR-AMAZON-ASSOCIATE-ID';
```php
// Keep these safe
$keyId = 'YOUR-AWS-KEY';
$secretKey = 'YOUR-AWS-SECRET-KEY';
$associateId = 'YOUR-AMAZON-ASSOCIATE-ID';

$amazonAPI = new AmazonAPI( $keyId, $secretKey, $associateId );
$amazonAPI = new AmazonAPI($keyId, $secretKey, $associateId);
```

**Note:** Keep your Amazon keys safe. Either use environment variables or include from a file that you don't check into GitHub.

It supports all Amazon regions:

* Canada ('ca')
* China ('cn')
* Germany ('de')
Expand All @@ -35,101 +62,141 @@ It supports all Amazon regions:
* United Kingdom ('uk')
* United States ('us').

The default is UK but to set the locale call SetLocale __before__ calling the product methods. E.g.
The default is UK but to set the locale call `SetLocale()` __before__ calling the product methods. E.g.

$amazonAPI->SetLocale( 'us' );
```php
$amazonAPI->SetLocale('us');
```

By default it will use HTTP but if you need to use SSL then call the following before using the product methods and it will connect to the HTTPS endpoints:
By default it will use HTTPS, but if you don't want to use SSL then call the following before using the product methods and it will connect to the HTTP endpoints:

$amazonAPI->SetSSL( true );
```
$amazonAPI->SetSSL(false);
```

**Note:** I have no idea why I originally had this method. Perhaps the Amazon Product API didn't use SSL at one point. I've enabled HTTPS as default now but you can turn it off if you need to. I assume you won't.

### Item Search
To search for an item use the ItemSearch method:

// Search for Harry Potter items in all categories
$items = $amazonAPI->ItemSearch( 'harry potter' );
```php
// Search for harry potter items in all categories
$items = $amazonAPI->ItemSearch('harry potter');

// Search for harry potter items in Books category only
$items = $amazonAPI->ItemSearch('harry potter', 'Books');
```

// Search for Harry Potter items in Books category only
$items = $amazonAPI->ItemSearch( 'harry potter', 'Books' );
#### Default sort

To determine valid categories for search call GetValidSearchNames() :
By default, the `ItemSearch` method will search by featured. If you want to sort by another category then pass a 3rd parameter with the name of the category you wish to sort by. These differ by category type but the two you'll probably need are `price` (sort by price low to high) or `-price` (sort by price high to low). See [ItemSearch Sort Values](http://docs.aws.amazon.com/AWSECommerceService/latest/DG/APPNDX_SortValuesArticle.html) for more details.

// Get an array of valid search categories we can use
$searchCategories = $amazonAPI->GetValidSearchNames();
```php
// Search for harry potter items in Books category, sort by low to high
$items = $amazonAPI->ItemSearch('harry potter', 'Books', 'price');

// Search for harry potter items in Books category, sort by high to low
$items = $amazonAPI->ItemSearch('harry potter', 'Books', '-price');
```

To determine valid categories for search call `GetValidSearchNames()`:

```php
// Get an array of valid search categories we can use
$searchCategories = $amazonAPI->GetValidSearchNames();
```

### Item Lookup
To look up product using the product ASIN number use ItemLookup:

// Retrieve specific item by id
$items = $amazonAPI->ItemLookUp( 'B003U6I396' );
```php
// Retrieve specific item by id
$items = $amazonAPI->ItemLookUp('B003U6I396');

// Retrieve a list of items by ids
$asinIds = array( 'B003U6I396', 'B003U6I397', 'B003U6I398' );
$items = $amazonAPI->ItemLookUp( $asinIds );
// Retrieve a list of items by ids
$asinIds = array('B003U6I396', 'B003U6I397', 'B003U6I398');
$items = $amazonAPI->ItemLookUp($asinIds);
```

## Returned data
By default the data will be returned as SimpleXML nodes. However if you call SetRetrieveAsArray() then a simplified array of items will be returned. For example:
By default the data will be returned as SimpleXML nodes. However if you call `SetRetrieveAsArray()` then a simplified array of items will be returned. For example:

// Return XML data
$amazonAPI = new AmazonAPI( $keyId, $secretKey, $associateId );
$items = $amazonAPI->ItemSearch( 'harry potter' );
var_dump( $items );
```php
// Return XML data
$amazonAPI = new AmazonAPI($keyId, $secretKey, $associateId);
$items = $amazonAPI->ItemSearch('harry potter');
var_dump($items);
```

This will output:

class SimpleXMLElement#2 (2) {
public $OperationRequest =>
class SimpleXMLElement#3 (3) {
public $RequestId =>
string(36) "de58449e-0c1a-47ac-9823-00fd049c52df"
public $Arguments =>
class SimpleXMLElement#5 (1) {
public $Argument =>
array(11) {
...

// Return simplified data
$amazonAPI = new AmazonAPI( $keyId, $secretKey, $associateId );
$amazonAPI->SetRetrieveAsArray();
$items = $amazonAPI->ItemSearch( 'harry potter' );
var_dump( $items );

Returning simplified data gives:

array(10) {
[0] =>
array(8) {
'asin' =>
string(10) "B00543R3WG"
'url' =>
string(212) "http://www.amazon.co.uk/Harry-Potter-Complete-8-Film-Collection/dp/B00543R3WG%3FSubscriptionId%3D1BM0B8TXM1YSZ1M0XDR2%26tag%3Ddjcr-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB00543R3WG"
'rrp' =>
double(44.99)
'title' =>
string(58) "Harry Potter - The Complete 8-Film Collection [DVD] [2011]"
'lowestPrice' =>
double(23.4)
'largeImage' =>
string(53) "http://ecx.images-amazon.com/images/I/51qa9nTUsEL.jpg"
'mediumImage' =>
string(61) "http://ecx.images-amazon.com/images/I/51qa9nTUsEL._SL160_.jpg"
'smallImage' =>
string(60) "http://ecx.images-amazon.com/images/I/51qa9nTUsEL._SL75_.jpg"
}
[1] =>
array(8) {
'asin' =>
string(10) "0747558191"
'url' =>
string(212) "http://www.amazon.co.uk/Harry-Potter-Philosophers-Stone-Rowling/dp/0747558191%3FSubscriptionId%3D1BM0B8TXM1YSZ1M0XDR2%26tag%3Ddjcr-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0747558191"
'rrp' =>
double(6.99)
'title' =>
string(40) "Harry Potter and the Philosopher\'s Stone"
```shell
class SimpleXMLElement#2 (2) {
public $OperationRequest =>
class SimpleXMLElement#3 (3) {
public $RequestId =>
string(36) "de58449e-0c1a-47ac-9823-00fd049c52df"
public $Arguments =>
class SimpleXMLElement#5 (1) {
public $Argument =>
array(11) {
...
```
```php
// Return simplified data
$amazonAPI = new AmazonAPI($keyId, $secretKey, $associateId);
$amazonAPI->SetRetrieveAsArray();
$items = $amazonAPI->ItemSearch('harry potter');
var_dump($items);
```
Returning simplified data gives a PHP array
```
array(10) {
[0] =>
array(8) {
'asin' =>
string(10) "B00543R3WG"
'url' =>
string(212) "http://www.amazon.co.uk/Harry-Potter-Complete-8-Film-Collection/dp/B00543R3WG%3FSubscriptionId%3D1BM0B8TXM1YSZ1M0XDR2%26tag%3Ddjcr-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB00543R3WG"
'rrp' =>
double(44.99)
'title' =>
string(58) "Harry Potter - The Complete 8-Film Collection [DVD] [2011]"
'lowestPrice' =>
double(23.4)
'largeImage' =>
string(53) "http://ecx.images-amazon.com/images/I/51qa9nTUsEL.jpg"
'mediumImage' =>
string(61) "http://ecx.images-amazon.com/images/I/51qa9nTUsEL._SL160_.jpg"
'smallImage' =>
string(60) "http://ecx.images-amazon.com/images/I/51qa9nTUsEL._SL75_.jpg"
}
[1] =>
array(8) {
'asin' =>
string(10) "0747558191"
'url' =>
string(212) "http://www.amazon.co.uk/Harry-Potter-Philosophers-Stone-Rowling/dp/0747558191%3FSubscriptionId%3D1BM0B8TXM1YSZ1M0XDR2%26tag%3Ddjcr-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0747558191"
'rrp' =>
double(6.99)
'title' =>
string(40) "Harry Potter and the Philosopher\'s Stone"
```
## TODO
* Need to make the simplified data less hardcoded!
* Make this a Composer package
* Add unit tests
## Thanks
This library uses code based on [AWS API authentication For PHP](http://randomdrake.com/2009/07/27/amazon-aws-api-rest-authentication-for-php-5/) by [David Drake](https://github.com/randomdrake).
## LICENSE
See [LICENSE](LICENSE)
Loading

0 comments on commit 71bcc64

Please sign in to comment.