source: spip-zone/_plugins_/booksearch/lib/AmazonECS.class.php @ 43183

Last change on this file since 43183 was 43183, checked in by fil@…, 10 years ago

plugin booksearch pour la boucle (DATA){datasource SPIP, booksearch}

cf. la page de spip.php?page=demo/iterateurs

https://affiliate-program.amazon.com/gp/advertising/api/detail/main.html

File size: 9.1 KB
Line 
1<?php
2/**
3 * Amazon ECS Class
4 * http://www.amazon.com
5 * =====================
6 *
7 * This class fetchs productinformation via the Product Advertising API by Amazon (formerly ECS).
8 * It supports two basic operations: ItemSearch and ItemLookup.
9 * These operations could be expanded with extra prarmeters to specialize the query.
10 *
11 * Requirement is the PHP extension SOAP.
12 *
13 * @package AmazonECS
14 * @license http://www.gnu.org/licenses/gpl.txt GPL
15 * @version 1.0
16 * @author  Exeu <exeu65@googlemail.com>
17 * @link http://github.com/Exeu/Amazon-ECS-PHP-Library/wiki Wiki
18 * @link http://github.com/Exeu/Amazon-ECS-PHP-Library Source
19 */
20class AmazonECS
21{
22  /**
23   * Basic Responsetypes
24   *
25   * @var integer
26   */
27  const RETURN_TYPE_ARRAY  = 1;
28  const RETURN_TYPE_OBJECT = 2;
29
30  /**
31   * Baseconfigurationstorage
32   *
33   * @var array
34   */
35  private $requestConfig = array();
36
37
38  /**
39   * Responseconfig
40   *
41   * @var array
42   */
43  private $responseConfig = array(
44    'returnType'    => self::RETURN_TYPE_OBJECT,
45    'responseGroup' => 'Small',
46    'optionalParameters' => array()
47  );
48
49  /**
50   * @param string $accessKey
51   * @param string $secretKey
52   * @param string $country
53   * @param string $associateTag
54   */
55  public function __construct($accessKey, $secretKey, $country = 'US', $associateTag = '')
56  {
57    if (empty($accessKey) || empty($secretKey))
58    {
59      throw new Exception('No Access Key or Secret Key has been set');
60    }
61
62    $this->requestConfig['accessKey']     = $accessKey;
63    $this->requestConfig['secretKey']     = $secretKey;
64    $this->requestConfig['associateTag']  = $associateTag;
65    $this->responseConfig['country']      = $country;
66  }
67
68  /**
69   * execute search
70   *
71   * @param string $pattern
72   *
73   * @return array|object return type depends on setting
74   *
75   * @see returnType()
76   */
77  public function search($pattern)
78  {
79    if (false === isset($this->requestConfig['category']))
80    {
81      throw new Exception('No Category given: Please set it up before');
82    }
83
84    $params = $this->buildRequestParams('ItemSearch', array(
85      'Keywords' => $pattern,
86      'SearchIndex' => $this->requestConfig['category']
87    ));
88
89    return $this->returnData(
90      $this->performSoapRequest("ItemSearch", $params)
91    );
92  }
93
94
95  public function lookup($asin)
96  {
97    $params = $this->buildRequestParams('ItemLookup', array(
98      'ItemId' => $asin,
99    ));
100
101    return $this->returnData(
102      $this->performSoapRequest("ItemLookup", $params)
103    );
104  }
105
106  /**
107   * Builds the request parameters
108   *
109   * @param string $function
110   * @param array  $params
111   *
112   * @return array
113   */
114  protected function buildRequestParams($function, array $params)
115  {
116    $associateTag = array();
117
118    if(false === empty($this->requestConfig['associateTag']))
119    {
120      $associateTag = array('AssociateTag' => $this->requestConfig['associateTag']);
121    }
122
123    return array_merge(
124      $associateTag,
125      array(
126        'AWSAccessKeyId' => $this->requestConfig['accessKey'],
127        'Request' => array_merge(
128          array('Operation' => $function),
129          $params,
130          $this->responseConfig['optionalParameters'],
131          array('ResponseGroup' => $this->prepareResponseGroup())
132    )));
133  }
134
135  /**
136   * Prepares the responsegroups and returns them as array
137   *
138   * @return array|prepared responsegroups
139   */
140  protected function prepareResponseGroup()
141  {
142    if (false === strstr($this->responseConfig['responseGroup'], ','))
143      return $this->responseConfig['responseGroup'];
144
145    return explode(',', $this->responseConfig['responseGroup']);
146  }
147
148  /**
149   * @param string $function Name of the function which should be called
150   * @param array $params Requestparameters 'ParameterName' => 'ParameterValue'
151   *
152   * @return array The response as an array with stdClass objects
153   */
154  protected function performSoapRequest($function, $params)
155  {
156    $soapClient = new SoapClient(
157      'http://ecs.amazonaws.com/AWSECommerceService/2010-09-01/'.strtoupper($this->responseConfig['country']).'/AWSECommerceService.wsdl',
158      array('exceptions' => 1)
159    );
160
161    $soapClient->__setSoapHeaders($this->buildSoapHeader($function));
162
163    return $soapClient->__soapCall($function, array($params));
164  }
165
166  /**
167   * Provides some necessary soap headers
168   *
169   * @param string $function
170   *
171   * @return array Each element is a concrete SoapHeader object
172   */
173  protected function buildSoapHeader($function)
174  {
175    $timeStamp = $this->getTimestamp();
176    $signature = $this->buildSignature($function . $timeStamp);
177
178    return array(
179      new SoapHeader(
180        'http://security.amazonaws.com/doc/2007-01-01/',
181        'AWSAccessKeyId',
182        $this->requestConfig['accessKey']
183      ),
184      new SoapHeader(
185        'http://security.amazonaws.com/doc/2007-01-01/',
186        'Timestamp',
187        $timeStamp
188      ),
189      new SoapHeader(
190        'http://security.amazonaws.com/doc/2007-01-01/',
191        'Signature',
192        $signature
193      )
194    );
195  }
196
197  /**
198   * provides current gm date
199   *
200   * primary needed for the signature
201   *
202   * @return string
203   */
204  final protected function getTimestamp()
205  {
206    return gmdate("Y-m-d\TH:i:s\Z");
207  }
208
209  /**
210   * provides the signature
211   *
212   * @return string
213   */
214  final protected function buildSignature($request)
215  {
216    return base64_encode(hash_hmac("sha256", $request, $this->requestConfig['secretKey'], true));
217  }
218
219  /**
220   * Returns the Response either as Array or Array/Object
221   *
222   * @param object $object
223   *
224   * @return mixed
225   */
226  protected function returnData($object)
227  {
228    switch ($this->responseConfig['returnType'])
229    {
230      case self::RETURN_TYPE_OBJECT:
231        return $object;
232      break;
233
234      case self::RETURN_TYPE_ARRAY:
235        return $this->objectToArray($object);
236      break;
237
238      default:
239        throw new InvalidArgumentException(sprintf(
240          "Unknwon return type %s", $this->responseConfig['returnType']
241        ));
242      break;
243    }
244  }
245
246  /**
247   * Transforms the responseobject to an array
248   *
249   * @param object $object
250   *
251   * @return array An arrayrepresentation of the given object
252   */
253  protected function objectToArray($object)
254  {
255    $out = array();
256    foreach ($object as $key => $value)
257    {
258      switch (true)
259      {
260        case is_object($value):
261          $out[$key] = $this->objectToArray($value);
262        break;
263
264        case is_array($value):
265          $out[$key] = $this->objectToArray($value);
266
267        break;
268
269        default:
270          $out[$key] = $value;
271        break;
272      }
273    }
274
275    return $out;
276  }
277
278  /**
279   * set or get optional parameters
280   *
281   * if the argument params is null it will reutrn the current parameters,
282   * otherwise it will set the params and return itself.
283   *
284   * @param array $params the optional parameters
285   *
286   * @return array|AmazonECS depends on params argument
287   */
288  public function optionalParameters($params = null)
289  {
290    if (null === $params)
291    {
292      return $this->responseConfig['optionalParameters'];
293    }
294
295    $this->responseConfig['optionalParameters'] = $params;
296
297    return $this;
298  }
299
300  /**
301   * Set or get the country
302   *
303   * if the country argument is null it will return the current
304   * country, otherwise it will set the country and reutrn itself.
305   *
306   * @param string|null $country
307   *
308   * @return string|AmazonECS depends on country argument
309   */
310  public function country($country = null)
311  {
312    if (null === $country)
313    {
314      return $this->responseConfig['country'];
315    }
316
317    $this->responseConfig['country'] = $country;
318
319    return $this;
320  }
321
322  public function category($category = null)
323  {
324    if (null === $category)
325    {
326      return isset($this->requestConfig['category']) ? $this->requestConfig['category'] : null;
327    }
328
329    $this->requestConfig['category'] = $category;
330
331    return $this;
332  }
333
334  public function responseGroup($responseGroup = null)
335  {
336    if (null === $responseGroup)
337    {
338      return $this->responseConfig['responseGroup'];
339    }
340
341    $this->responseConfig['responseGroup'] = $responseGroup;
342
343    return $this;
344  }
345
346  public function returnType($type = null)
347  {
348    if (null === $type)
349    {
350      return $this->responseConfig['returnType'];
351    }
352
353    $this->responseConfig['returnType'] = $type;
354
355    return $this;
356  }
357
358  /**
359   * Setter/Getter of the AssociateTag.
360   * This could be used for late bindings of this attribute
361   *
362   * @param string $associateTag
363   *
364   * @return string|AmazonECS depends on associateTag argument
365   */
366  public function associateTag($associateTag = null)
367  {
368    if (null === $associateTag)
369    {
370      return $this->requestConfig['associateTag'];
371    }
372
373    $this->requestConfig['associateTag'] = $associateTag;
374
375    return $this;
376  }
377
378  /**
379   * @deprected use returnType() instead
380   */
381  public function setReturnType($type)
382  {
383    return $this->returnType($type);
384  }
385}
Note: See TracBrowser for help on using the repository browser.