Skip to content

CHICPRO

  • Life Log
  • Cycling Log
  • Photo Log
    • Portrait
    • Landscape
    • Flower
    • Etc
  • Coding Log
  • Information

[PHP] 아마존 Product Advertising API 간단 예제

2017-06-15 by 편리

아마존의 Product Advertising API 를 사용하기 위한 멋진 오픈소스가 존재하지만 서비스 구현 중에 그 오픈소스를 사용하면 네트웍 문제인지 간혹 제대로된 작업이 되지 않는 듯 하여 간단하게 코드를 작성해서 테스트를 해보기로 했다. 아래 코드는 테스트를 위해 작성한 것으로 최소한의 기능만 포함되어 있다.

<?php
class AMAZON
{
    protected $country;
    protected $accessKey;
    protected $secretKey;
    protected $associateTag;

    protected $operation;
    protected $searchIndex;
    protected $keyWord;
    protected $itemPage = 1;
    protected $itemId;
    protected $idType;
    protected $responseGroup = 'Large';

    public function __construct($accessKey, $secretKey, $associateTag)
    {
        $this->accessKey      = $accessKey;
        $this->secretKey      = $secretKey;
        $this->associateTag = $associateTag;
    }

    public function setCountry($country)
    {
        $this->country = strtolower($country);
    }

    public function setResponseGroup($group)
    {
        $this->responseGroup = $group;
    }

    public function setPage($page)
    {
        $this->itemPage = $page;
    }

    protected function getTimeStamp()
    {
        return gmdate("Y-m-d\TH:i:s\Z");
    }

    protected function buildSignature(array $params)
    {
        $stringToSign = sprintf(
                "GET\nwebservices.amazon.%s\n/onca/xml\n%s",
                $this->country,
                implode('&', $params)
            );

        return base64_encode(hash_hmac("sha256", $stringToSign, $this->secretKey, true));
    }

    public function ItemSearch($searchIndex, $keyWord)
    {
        $this->operation = 'ItemSearch';
        $this->searchIndex = $searchIndex;
        $this->keyWord = $keyWord;
    }

    public function ItemLookup($itemId)
    {
        $this->operation = 'ItemLookup';
        $this->itemId = $itemId;
        $this->idType = 'ASIN';
    }

    protected function prepareParams()
    {
        $requestParams = [
            'Service'        => 'AWSECommerceService',
            'AWSAccessKeyId' => $this->accessKey,
            'AssociateTag'   => $this->associateTag,
            'Operation'      => $this->operation,
            'Version'        => '2013-08-01',
            'Timestamp'      => $this->getTimeStamp()
        ];

        switch($this->operation) {
            case 'ItemSearch':
                $requestParams['SearchIndex'] = $this->searchIndex;
                $requestParams['Keywords'] = $this->keyWord;
                $requestParams['ItemPage'] = $this->itemPage;
                break;
            case 'ItemLookup':
                $requestParams['ItemId'] = $this->itemId;
                $requestParams['idType'] = $this->idType;
                break;
            default:
                break;
        }

        if($this->responseGroup)
            $requestParams['ResponseGroup'] = $this->responseGroup;

        ksort($requestParams);

        return $requestParams;
    }

    protected function buildQuery()
    {
        $parameterList = [];

        $params = $this->prepareParams();

        foreach ($params as $key => $value) {
            $parameterList[] = sprintf('%s=%s', $key, rawurlencode($value));
        }

        $parameterList[] = 'Signature=' . rawurlencode(
            $this->buildSignature($parameterList)
        );

        return implode("&", $parameterList);
    }

    public function runOperation()
    {
        $url = 'http://'.sprintf('webservices.amazon.%s/onca/xml?', $this->country).$this->buildQuery();
        
        $headers = [
            'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0'
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        
        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }
}

위 class를 호출하여 사용하는 것은 아래 코드와 같다.

<?php
include_once('./lib/amazon.class.php');

define('AWS_API_KEY', 'AKIAJZ6TRCZIBEYJ3GAA');
define('AWS_API_SECRET_KEY', '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');
define('AWS_ASSOCIATE_TAG', 'chicpro-22');

$amazon = new AMAZON(AWS_API_KEY, AWS_API_SECRET_KEY, AWS_ASSOCIATE_TAG);

$amazon->setCountry('com');
$amazon->ItemSearch('All', 's8');
$amazon->setPage(2);

$amazon->setResponseGroup('Small');
//$amazon->ItemLookup('B06Y137TLR');

$xml = simplexml_load_string($amazon->runOperation());

print_r($xml);

API 관련 키 등은 직접 발급받아 적용해야 한다.

Post navigation

Previous Post:

[jQuery] AJAX 요청을 Queue를 이용해 순차적으로 처리하기

Next Post:

[PHP] 랜덤 시간으로 프로그램 실행 중지하기

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

  • SK 세븐모바일 유심 셀프교체
  • php 배열 연산에서 + 와 array_merge 의 차이
  • pcntl_fork 를 이용한 다중 프로세스 실행
  • 아이폰 단축어를 이용하여 주중 공휴일엔 알람 울리지 않게 하기
  • 구글 캘린더 전체일정 재동기화
  • OpenLiteSpeed 웹서버에 HTTP 인증 적용
  • OpenLiteSpeed 웹어드민 도메인 연결
  • WireGuard를 이용한 VPN 환경 구축
  • Ubuntu 22.04 서버에 OpenLiteSpeed 웹서버 세팅
  • 맥 vim 세팅

Recent Comments

  • 편리 on 업무관리용 그누보드 게시판 스킨
  • 임종섭 on 업무관리용 그누보드 게시판 스킨
  • 캐논 5D 펌웨어 | Dslr 펌웨어 업그레이드 방법 82 개의 베스트 답변 on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • Top 5 캐논 5D 펌웨어 Top 89 Best Answers on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • 편리 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 임팀장 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 편리 on Notepad++ NppFTP 플러그인 수동 설치
  • paul-j on Notepad++ NppFTP 플러그인 수동 설치
  • YS on Windows 10 iCloud 사진 저장 폴더 변경
  • 편리 on Docker를 이용한 Centos7 + httpd + php 5.4 개발환경 구축

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
© 2025 CHICPRO | Built using WordPress and SuperbThemes