2014-09-09 4 views
0

Я создаю модуль, который поможет продавцу разместить каталог своих продуктов в службе рекламных объявлений Amazon. Для этого мне нужно сделать сопоставление между категорией клиента и категориями товарных объявлений Amazon.Amazon Product Ads, есть ли API для поиска категорий?

Проблема в том, что я не могу найти API, который поможет мне найти категории или файл, содержащий все существующие категории для рекламных объявлений Amazon.

Я нашел ссылку http://docs.aws.amazon.com/AWSECommerceService/latest/DG/BrowseNodeIDs.html, которая может быть запущена, но на основе их API невозможно выполнить поиск по тексту (например, «Apparel»), но NodeId, что не то, что я ищу:/

Может ли кто-нибудь из вас мне помочь?

Спасибо за вашу помощь :)

ответ

1

Вы должны использовать Обзор идентификатор узла родительских категорий и баз на которые можно найти подкатегории.

Создайте файл с именем amazon_api_class.php

<?php 

require_once 'aws_signed_request.php'; 

class AmazonProductAPI 
{ 
/** 
* Your Amazon Access Key Id 
* @access private 
* @var string 
*/ 
private $public_key  = ""; 

/** 
* Your Amazon Secret Access Key 
* @access private 
* @var string 
*/ 
private $private_key = ""; 

private $media_type  = ""; 

private $region   = ""; 

private $out_file_fp = ""; 


public function __construct($public, $private, $region) { 
    $this->public_key = $public; 
    $this->private_key = $private; 
    $this->region  = $region; 
}   

public function getNode($node) 
{ 
    $parameters = array("Operation" => "BrowseNodeLookup", 
             "BrowseNodeId" => $node, 
             "ResponseGroup" => "BrowseNodeInfo"); 

    $xml_response = aws_signed_request($parameters, 
             $this->public_key, 
             $this->private_key, 
             $this->region); 

    return ($xml_response); 
} 


public function setMedia($media, $file = "") { 
    $media_type = array("display", "csv"); 

    if(!in_array($media,$media_type)) { 
     throw new Exception("Invalid Media Type"); 
     exit(); 
    } 

    $this->media_type = $media; 

    if($media == "csv") { 
     $this->out_file_fp = fopen($file,'a+'); 
    } 
} 


private function writeOut($level, $name, $id, $parent) { 
    if($this->media_type == "display") { 
     $spaces = str_repeat(' ', ($level * 6)); 
     echo $spaces . $parent . ' : ' . $name . ' : ' . $id . "\n"; 
    } elseif ($this->media_type == "csv") { 
     $csv_line = '"' . $parent . '","' . $name . '","' . $id . '"' . "\n"; 
     fputs($this->out_file_fp, $csv_line); 
    } else { 
     throw new Exception("Invalid Media Type"); 
     exit(); 
    } 
} 


public function getBrowseNodes($nodeValue, $level = 0) 
{ 
    try { 
     $result = $this->getNode($nodeValue); 
    } 
    catch(Exception $e) { 
     echo $e->getMessage(); 
    } 

    if(!isset($result->BrowseNodes->BrowseNode->Children->BrowseNode)) return; 

    if(count($result->BrowseNodes->BrowseNode->Children->BrowseNode) > 0) { 
     foreach($result->BrowseNodes->BrowseNode->Children->BrowseNode as $node) { 
      $this->writeOut($level, $node->Name, 
          $node->BrowseNodeId, 
          $result->BrowseNodes->BrowseNode->Name); 

      $this->getBrowseNodes($node->BrowseNodeId, $level+1); 
     } 
    } else { 
     return;   
    } 
} 


public function getNodeName($nodeValue) 
{ 
    try { 
     $result = $this->getNode($nodeValue); 
    } 
    catch(Exception $e) { 
     echo $e->getMessage(); 
    } 

    if(!isset($result->BrowseNodes->BrowseNode->Name)) return; 

    return (string)$result->BrowseNodes->BrowseNode->Name; 
} 


public function getParentNode($nodeValue) 
{ 
    try { 
     $result = $this->getNode($nodeValue); 
    } 
    catch(Exception $e) { 
     echo $e->getMessage(); 
    } 

    if(!isset($result->BrowseNodes->BrowseNode->Ancestors->BrowseNode->BrowseNodeId)) return; 

    $parent_node = array("id" => (string)$result->BrowseNodes->BrowseNode->Ancestors->BrowseNode->BrowseNodeId, 
         "name" => (string)$result->BrowseNodes->BrowseNode->Ancestors->BrowseNode->Name); 
    return $parent_node; 
}}?> 

Создать файл с именем, как aws_signed_request.php

<?php 


function aws_signed_request($params,$public_key,$private_key,$region) 
{ 

$method = "GET"; 
$host = "ecs.amazonaws.".$region; // must be in small case 
$uri = "/onca/xml"; 


$params["Service"]   = "AWSECommerceService"; 
$params["AWSAccessKeyId"] = $public_key; 
$params["AssociateTag"]  = 'YOUR-ASSOCIATES-ID-HERE'; 
$params["Timestamp"]  = gmdate("Y-m-d\TH:i:s\Z"); 
$params["Version"]   = "2009-03-31"; 

/* The params need to be sorted by the key, as Amazon does this at 
    their end and then generates the hash of the same. If the params 
    are not in order then the generated hash will be different thus 
    failing the authetication process. 
*/ 
ksort($params); 

$canonicalized_query = array(); 

foreach ($params as $param=>$value) 
{ 
    $param = str_replace("%7E", "~", rawurlencode($param)); 
    $value = str_replace("%7E", "~", rawurlencode($value)); 
    $canonicalized_query[] = $param."=".$value; 
} 

$canonicalized_query = implode("&", $canonicalized_query); 

$string_to_sign = $method."\n".$host."\n".$uri."\n".$canonicalized_query; 

/* calculate the signature using HMAC with SHA256 and base64-encoding. 
    The 'hash_hmac' function is only available from PHP 5 >= 5.1.2. 
*/ 
$signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True)); 

/* encode the signature for the request */ 
$signature = str_replace("%7E", "~", rawurlencode($signature)); 

/* create request */ 
$request = "http://".$host.$uri."?".$canonicalized_query."&Signature=".$signature; 

/* I prefer using CURL */ 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$request); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_TIMEOUT, 15); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 

$xml_response = curl_exec($ch); 

if ($xml_response === False) 
{ 
    return False; 
} 
else 
{ 
    /* parse XML */ 
    $parsed_xml = @simplexml_load_string($xml_response); 
    return ($parsed_xml === False) ? False : $parsed_xml; 
} 
} 
?> 

Создать файл с именем, как index.php

<?php 

/* Example usage of the Amazon Product Advertising API */ 
include("amazon_api_class.php"); 

$public_key  = "YOUR-AMAZON-PUBLIC-KEY"; 
$private_key = "YOUR-AMAZON-SECRET-KEY"; 
$region   = "com"; // or "CA" or "DE" etc. 

$obj = new AmazonProductAPI($public_key, $private_key, $region); 
$obj->setMedia("display"); 
$obj->getBrowseNodes("1036592"); //Apparel US store 

?> 

Не забудьте обновить ваш открытый и закрытый ключ в index.php

+0

О, такой полный ответ! Спасибо! :) –

+0

мое удовольствие ..;) – Upinder

+0

С вашей реализацией я всегда получаю все узлы в одном заданном родительском узле правильно? Я не смогу выполнить поиск через, например, «ткань», чтобы найти все идентификаторы узлов с их текстом «ткань»? –