【PHP】Amazon APIで商品情報を取得する方法【個人メモ】

参考リンク

https://webservices.amazon.com/paapi5/documentation/

https://webservices.amazon.com/paapi5/documentation/quick-start/using-sdk.html#php

インストール

公式がcomposer でインストールできないので有志の方が提供してくれているパッケージを利用します。
https://github.com/thewirecutter/paapi5-php-sdk

   composer require thewirecutter/paapi5-php-sdk

とりあえずREADMEの通りに記載

<?php

/**
 * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

/*
 * ProductAdvertisingAPI
 *
 * https://webservices.amazon.com/paapi5/documentation/index.html
 */

/*
 * This sample code snippet is for ProductAdvertisingAPI 5.0's SearchItems API
 *
 * For more details, refer: https://webservices.amazon.com/paapi5/documentation/search-items.html
 */

use Amazon\ProductAdvertisingAPI\v1\com\amazon\paapi5\v1\api\DefaultApi;
use Amazon\ProductAdvertisingAPI\v1\ApiException;
use Amazon\ProductAdvertisingAPI\v1\Configuration;
use Amazon\ProductAdvertisingAPI\v1\com\amazon\paapi5\v1\SearchItemsRequest;
use Amazon\ProductAdvertisingAPI\v1\com\amazon\paapi5\v1\SearchItemsResource;
use Amazon\ProductAdvertisingAPI\v1\com\amazon\paapi5\v1\PartnerType;
use Amazon\ProductAdvertisingAPI\v1\com\amazon\paapi5\v1\ProductAdvertisingAPIClientException;

require_once(__DIR__ . '/vendor/autoload.php'); // change path as needed


$config = new Configuration();

/*
 * Add your credentials
 * Please add your access key here
 */
$config->setAccessKey('<YOUR ACCESS KEY>');
# Please add your secret key here
$config->setSecretKey('<YOUR SECRET KEY>');

# Please add your partner tag (store/tracking id) here
$partnerTag = '<YOUR PARTNER TAG>';

/*
 * PAAPI host and region to which you want to send request
 * For more details refer: https://webservices.amazon.com/paapi5/documentation/common-request-parameters.html#host-and-region
 */
$config->setHost('webservices.amazon.com');
$config->setRegion('us-east-1');

$apiInstance = new DefaultApi(
/*
 * If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
 * This is optional, `GuzzleHttp\Client` will be used as default.
 */
    new GuzzleHttp\Client(), $config);

# Request initialization

# Specify keywords
$keyword = 'Harry Potter';

/*
 * Specify the category in which search request is to be made
 * For more details, refer: https://webservices.amazon.com/paapi5/documentation/use-cases/organization-of-items-on-amazon/search-index.html
 */
$searchIndex = "All";

# Specify item count to be returned in search result
$itemCount = 1;

/*
 * Choose resources you want from SearchItemsResource enum
 * For more details, refer: https://webservices.amazon.com/paapi5/documentation/search-items.html#resources-parameter
 */
$resources = array(
    SearchItemsResource::ITEM_INFOTITLE,
    SearchItemsResource::OFFERSLISTINGSPRICE);

# Forming the request
$searchItemsRequest = new SearchItemsRequest();
$searchItemsRequest->setSearchIndex($searchIndex);
$searchItemsRequest->setKeywords($keyword);
$searchItemsRequest->setItemCount($itemCount);
$searchItemsRequest->setPartnerTag($partnerTag);
$searchItemsRequest->setPartnerType(PartnerType::ASSOCIATES);
$searchItemsRequest->setResources($resources);

# Validating request
$invalidPropertyList = $searchItemsRequest->listInvalidProperties();
$length = count($invalidPropertyList);
if ($length > 0) {
    echo "Error forming the request", PHP_EOL;
    foreach ($invalidPropertyList as $invalidProperty) {
        echo $invalidProperty, PHP_EOL;
    }
    return;
}

# Sending the request
try {
    $searchItemsResponse = $apiInstance->searchItems($searchItemsRequest);

    echo 'API called successfully', PHP_EOL;
    echo 'Complete Response: ', $searchItemsResponse, PHP_EOL;

    # Parsing the response
    if ($searchItemsResponse->getSearchResult() != null) {
        echo 'Printing first item information in SearchResult:', PHP_EOL;
        $item = $searchItemsResponse->getSearchResult()->getItems()[0];
        if ($item != null) {
            if ($item->getASIN() != null) {
                echo "ASIN: ", $item->getASIN(), PHP_EOL;
            }
            if ($item->getDetailPageURL() != null) {
                echo "DetailPageURL: ", $item->getDetailPageURL(), PHP_EOL;
            }
            if ($item->getItemInfo() != null
                and $item->getItemInfo()->getTitle() != null
                and $item->getItemInfo()->getTitle()->getDisplayValue() != null) {
                echo "Title: ", $item->getItemInfo()->getTitle()->getDisplayValue(), PHP_EOL;
            }
            if ($item->getOffers() != null
                and $item->getOffers() != null
                and $item->getOffers()->getListings() != null
                and $item->getOffers()->getListings()[0]->getPrice() != null
                and $item->getOffers()->getListings()[0]->getPrice()->getDisplayAmount() != null) {
                echo "Buying price: ", $item->getOffers()->getListings()[0]->getPrice()
                    ->getDisplayAmount(), PHP_EOL;
            }
        }
    }
    if ($searchItemsResponse->getErrors() != null) {
        echo PHP_EOL, 'Printing Errors:', PHP_EOL, 'Printing first error object from list of errors', PHP_EOL;
        echo 'Error code: ', $searchItemsResponse->getErrors()[0]->getCode(), PHP_EOL;
        echo 'Error message: ', $searchItemsResponse->getErrors()[0]->getMessage(), PHP_EOL;
    }
} catch (ApiException $exception) {
    echo "Error calling PA-API 5.0!", PHP_EOL;
    echo "HTTP Status Code: ", $exception->getCode(), PHP_EOL;
    echo "Error Message: ", $exception->getMessage(), PHP_EOL;
    if ($exception->getResponseObject() instanceof ProductAdvertisingAPIClientException) {
        $errors = $exception->getResponseObject()->getErrors();
        foreach ($errors as $error) {
            echo "Error Type: ", $error->getCode(), PHP_EOL;
            echo "Error Message: ", $error->getMessage(), PHP_EOL;
        }
    } else {
        echo "Error response body: ", $exception->getResponseBody(), PHP_EOL;
    }
} catch (Exception $exception) {
    echo "Error Message: ", $exception->getMessage(), PHP_EOL;
}

エラーが発生した場合

以下のエラーが発生した場合は認証キーを作り直したら直りました。

Error Type: IncompleteSignature
Error Message: The request signature did not include all of the required components. If you are using an AWS SDK, requests are signed for you automatically; otherwise, go to https://webservices.amazon.co.jp/paapi5/documentation/sending-request.html#signing.

取得したい情報を指定

欲しい情報を指定します。

        $resources = array(
            SearchItemsResource::ITEM_INFOTITLE,
            SearchItemsResource::OFFERSLISTINGSPRICE,
            SearchItemsResource::IMAGESPRIMARYMEDIUM,
        );

参考: https://webservices.amazon.com/paapi5/documentation/get-items.html#resources-parameter

リクエストパラメータ

公式参考

NameDescriptionRequired
ActorActor name associated with the item. You can enter all or part of the name.Type: String (Non-Empty)Default Value: NoneUsage: {"Actor": "Tom Cruise"}No
ArtistArtist name associated with the item. You can enter all or part of the name.Type: String (Non-Empty)Default Value: NoneUsage: {"Artist":"Coldplay"}No
AuthorAuthor name associated with the item. You can enter all or part of the name.Type: String (Non-Empty)Default Value: NoneUsage: {"Author":"Enid Blyton"}No
AvailabilityFilters available items on Amazon. By default, all requests returns available items only. For more information and valid values, refer Availability Parameter.Type: StringDefault Value: AvailableUsage: {"Availability":"IncludeOutOfStock"}No
BrandBrand name associated with the item. You can enter all or part of the name.Type: String (Non-Empty)Default Value: NoneUsage: {"Brand":"Apple"}No
BrowseNodeIdA unique ID assigned by Amazon that identifies a product category/sub-category. The BrowseNodeId is a positive Long having max value upto Long.MAX_VALUE i.e. 9223372036854775807 (inclusive).Type: String (Positive integers only)Default Value: NoneUsage: {"BrowseNodeId": "290060"}No
ConditionThe condition parameter filters offers by condition type. For example, Condition:Used will return items having atleast one offer of Used condition type. By default, condition equals Any. For more information and valid values, refer Condition Parameter.Type: StringDefault Value: AnyUsage: {"Condition":"Used"}No
CurrencyOfPreferenceCurrency of preference in which the prices information should be returned in response. By default the prices are returned in the default currency of the marketplace. Expected currency code format is the ISO 4217 currency code (i.e. USD, EUR etc.). For information on default currency and valid currencies for a marketplace, refer Locale Reference.Type: String (Non-Empty)Default Value: NoneUsage: {"CurrencyOfPreference":"USD"}No
DeliveryFlagsThe delivery flag filters items which satisfy a certain delivery program promoted by the specific Amazon Marketplace. For example, Prime DeliveryFlag will return items having at least one offer which is Prime Eligible. For more information and valid values, refer DeliveryFlags Parameter.Type: List of StringsDefault Value: NoneUsage: {"DeliveryFlags":["Prime"]}No
ItemCountThe number of items desired in SearchItems response.Type: Integer (Between 1 to 10)Default Value: 10Usage: {"ItemCount":5}No
ItemPageThe ItemPage parameter can be used to fetch the specific set/page of items to be returned from the available Search Results. The number of items returned in a page is determined by the ItemCount parameter. For e.g. if the third set of 5 items (i.e. items numbered 11 to 15) are desired for a search request, you may specify ItemPage as 3 and ItemCount as 5.Type: Integer (Between 1 to 10)Default Value: 1Usage: {"ItemPage":3}No
KeywordsA word or phrase that describes an item i.e. the search query.Type: String (Non-Empty)Default Value: NoneUsage: {"Keywords":"Harry Potter"}No
LanguagesOfPreferenceLanguages in order of preference in which the item information should be returned in response. By default the item information is returned in the default language of the marketplace. Expected locale format is the ISO 639 language code followed by underscore followed by the ISO 3166 country code (i.e. en_US, fr_CA etc.). For information on default language and valid languages for a marketplace, refer Locale Reference. Currently only single language of preference is supported.Type: List of Strings (Non-Empty)Default Value: NoneUsage: {"LanguagesOfPreference":["en_GB"]}No
MarketplaceTarget Amazon Locale. For more information, refer Common Request Parameters.Type: StringDefault Value: NoneUsage: {"Marketplace":"www.amazon.com"}No
MaxPriceFilters search results to items with at least one offer price below the specified value. Prices appear in lowest currency denomination. For example, in US marketplace, 3241 is $31.41.Type: Positive IntegerDefault Value: NoneUsage: {"MaxPrice":3241}No
MerchantFilters search results to return items having at least one offer sold by target merchant. By default the value “All” is passed. For more information, refer Merchant Parameter.Type: StringDefault Value: AllUsage: {"Merchant":"Amazon"}No
MinPriceFilters search results to items with at least one offer price above the specified value. Prices appear in lowest currency denomination. For example, in US marketplace, 3241 is $32.41.Type: Positive IntegerDefault Value: NoneUsage: {"MinPrice":3241}No
MinReviewsRatingFilters search results to items with customer review ratings above specified value.Type: Positive Integer less than 5Default Value: NoneUsage: {"MinReviewsRating":2}No
MinSavingPercentFilters search results to items with at least one offer having saving percentage above the specified value.Type: Positive Integer less than 100Default Value: NoneUsage: {"MinSavingPercent":50}No
OfferCountThe number of offers desired for each item in the search results. Offers are returned if any of Offers Resources are requested. Currently only value of 1 is supported.Type: Positive IntegerDefault Value: 1Usage: {"OfferCount":1}No
PartnerTagUnique ID for a partner. For more information, refer Common Request Parameters.Type: String (Non-Empty)Default Value: NoneUsage: {"PartnerTag":"xyz-20"}Yes
PartnerTypeThe type of Amazon program. For more information and valid values, refer Common Request Parameters.Type: StringDefault Value: NoneUsage: {"PartnerType":"Associates"}Yes
PropertiesReserved Parameter.Type: Map (String, String)Default Value: NoneUsage: {"Properties": {"Key": "Value"} }No
ResourcesSpecifies the types of values to return. You can specify multiple resources in one request. For list of valid Resources for SearchItems operation, refer Resources Parameter.Type: List of StringDefault Value: ItemInfo.TitleUsage: {"Resources":["Images.Primary.Medium", "ItemInfo.Title"]}No
SearchIndexIndicates the product category to search. SearchIndex values differ by marketplace. For list of search index values, refer Locale Reference.Type: String (Non-Empty)Default Value: AllUsage: {"SearchIndex":"Electronics"}No
SortByThe way in which items in the response are sorted. For more information on valid values, refer SortBy Parameter.Type: StringDefault Value: NoneUsage: {"SortBy":"Relevance"}No
TitleTitle associated with the item. Title searches are subset of Keywords searches. Use a Keywords search if a Title search does not return desired items.Type: String (Non-Empty)Default Value: NoneUsage: {"Title":"And Then There Were None"}No

レスポンス例

{
    "SearchResult": {
        "TotalResultCount": 146,
        "SearchURL": "https:\/\/www.amazon.co.jp\/s?k=%E3%81%86%E3%81%A9%E3%82%93&rh=p_n_availability%3A-1&tag=selegee06-22&linkCode=osi",
        "Items": [
            {
                "ASIN": "B019I0592Q",
                "BrowseNodeInfo": {
                    "BrowseNodes": [
                        {
                            "ContextFreeName": "\u3046\u3069\u3093",
                            "DisplayName": "\u3046\u3069\u3093",
                            "Id": "2140644051",
                            "IsRoot": false
                        }
                    ]
                },
                "DetailPageURL": "https:\/\/www.amazon.co.jp\/dp\/B019I0592Q?tag=selegee06-22&linkCode=osi&th=1&psc=1",
                "Images": {
                    "Primary": {
                        "Medium": {
                            "URL": "https:\/\/m.media-amazon.com\/images\/I\/419TR-qs9KL._SL160_.jpg",
                            "Height": 160,
                            "Width": 68
                        }
                    }
                },
                "ItemInfo": {
                    "Title": {
                        "DisplayValue": "\u8b83\u5c90\u7269\u7523 \u3046\u3069\u3093\u770c\u306e\u3046\u3069\u3093 300g\u00d75\u888b",
                        "Label": "Title",
                        "Locale": "ja_JP"
                    }
                },
                "Offers": {
                    "Listings": [
                        {
                            "Id": "kwDwFZ4iGv8TRDaapKqnpmYxFHzVazP%2FRCSpipt%2FHZ%2FcnkgWV7%2BMB2OllGl0VRuzdbTyjqIEJMdpSR4gWbS3iHLghso4JTXFuOC1tyF62ew%3D",
                            "Price": {
                                "Amount": 1071,
                                "Currency": "JPY",
                                "DisplayAmount": "\uffe51,071 (\uffe5214 \/ \u888b)",
                                "PricePerUnit": 214.2,
                                "Savings": {
                                    "Amount": 603,
                                    "Currency": "JPY",
                                    "DisplayAmount": "\uffe5603 (36%)",
                                    "Percentage": 36,
                                    "PricePerUnit": 120.6
                                }
                            },
                            "ViolatesMAP": false
                        }
                    ]
                }
            }
        ]
    }
}

カテゴリーはBrowseNodeId

URLで判別する場合はbbn=[id]で、rh=があればrh=[]の最後の数字で判別できます。

以下の場合は3001573051になります。

https://www.amazon.co.jp/s?i=pets&bbn=2155497051&rh=n:2127212051,n:2127213051,n:2153210051,n:2155497051,p_n_feature_three_browse-bin:3001573051&s=price-desc-rank&dc&fst=as:off&qid=1605279561&rnid=3001534051&ref=sr_st_price-desc-rank

コメントを残す

メールアドレスが公開されることはありません。