产品广告API PHP无效xml响应 [英] Product advertising API PHP invalid xml response

查看:27
本文介绍了产品广告API PHP无效xml响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名初级程序员,正在尝试将 API 集成到我的移动应用程序中,以便我可以从我的应用程序中查看来自亚马逊的项目.我已按照此处 但该示例对我不起作用,如此处所示.

Hi I am a beginner programmer trying to integrate the API into my mobile app so I can view items from amazon from my app. I have followed all the 6 simple steps here but the example did not work for me, as shown here.

这是我的亚马逊 PHP 代码:
aws_signed_request.php

Here are my amazon PHP codes:
aws_signed_request.php

<?php

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

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


    $params["Service"]          = "AWSECommerceService";
    $params["AWSAccessKeyId"]   = $public_key;
    $params["AssociateTag"]     = $associate_tag;
    $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 cURL doesn't work for you, then use the 'file_get_contents'
       function as given below.
    */

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

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     = "AKIAJETPMOLIUXXXXXXX";

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

        /**
         * Your Amazon Associate Tag
         * Now required, effective from 25th Oct. 2011
         * @access private
         * @var string
         */
        private $associate_tag  = "mpXXXX-20";

        /**
         * Constants for product types
         * @access public
         * @var string
         */

        /*
            Only three categories are listed here. 
            More categories can be found here:
            http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/APPNDX_SearchIndexValues.html
        */
        const MUSIC = "Music";
        const DVD   = "DVD";
        const GAMES = "VideoGames";


        /**
         * Check if the xml received from Amazon is valid
         * 
         * @param mixed $response xml response to check
         * @return bool false if the xml is invalid
         * @return mixed the xml response if it is valid
         * @return exception if we could not connect to Amazon
         */
        private function verifyXmlResponse($response)
        {
            if ($response === False)
            {
                throw new Exception("Could not connect to Amazon");
            }
            else
            {
                if (isset($response->Items->Item->ItemAttributes->Title))
                {
                    return ($response);
                }
                else
                {
                    throw new Exception("Invalid xml response.");
                }
            }
        }


        /**
         * Query Amazon with the issued parameters
         * 
         * @param array $parameters parameters to query around
         * @return simpleXmlObject xml query response
         */
        private function queryAmazon($parameters)
        {
            return aws_signed_request("com", $parameters, $this->public_key, $this->private_key, $this->associate_tag);
        }


        /**
         * Return details of products searched by various types
         * 
         * @param string $search search term
         * @param string $category search category         
         * @param string $searchType type of search
         * @return mixed simpleXML object
         */
        public function searchProducts($search, $category, $searchType = "UPC")
        {
            $allowedTypes = array("UPC", "TITLE", "ARTIST", "KEYWORD");
            $allowedCategories = array("Music", "DVD", "VideoGames");

            switch($searchType) 
            {
                case "UPC" :    $parameters = array("Operation"     => "ItemLookup",
                                                    "ItemId"        => $search,
                                                    "SearchIndex"   => $category,
                                                    "IdType"        => "UPC",
                                                    "ResponseGroup" => "Medium");
                                break;

                case "TITLE" :  $parameters = array("Operation"     => "ItemSearch",
                                                    "Title"         => $search,
                                                    "SearchIndex"   => $category,
                                                    "ResponseGroup" => "Medium");
                                break;

            }

            $xml_response = $this->queryAmazon($parameters);

            return $this->verifyXmlResponse($xml_response);

        }


        /**
         * Return details of a product searched by UPC
         * 
         * @param int $upc_code UPC code of the product to search
         * @param string $product_type type of the product
         * @return mixed simpleXML object
         */
        public function getItemByUpc($upc_code, $product_type)
        {
            $parameters = array("Operation"     => "ItemLookup",
                                "ItemId"        => $upc_code,
                                "SearchIndex"   => $product_type,
                                "IdType"        => "UPC",
                                "ResponseGroup" => "Medium");

            $xml_response = $this->queryAmazon($parameters);

            return $this->verifyXmlResponse($xml_response);

        }


        /**
         * Return details of a product searched by ASIN
         * 
         * @param int $asin_code ASIN code of the product to search
         * @return mixed simpleXML object
         */
        public function getItemByAsin($asin_code)
        {
            $parameters = array("Operation"     => "ItemLookup",
                                "ItemId"        => $asin_code,
                                "ResponseGroup" => "Medium");

            $xml_response = $this->queryAmazon($parameters);

            return $this->verifyXmlResponse($xml_response);
        }


        /**
         * Return details of a product searched by keyword
         * 
         * @param string $keyword keyword to search
         * @param string $product_type type of the product
         * @return mixed simpleXML object
         */
        public function getItemByKeyword($keyword, $product_type)
        {
            $parameters = array("Operation"   => "ItemSearch",
                                "Keywords"    => $keyword,
                                "SearchIndex" => $product_type);

            $xml_response = $this->queryAmazon($parameters);

            return $this->verifyXmlResponse($xml_response);
        }

    }

?>

示例.php

<?php

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

    $obj = new AmazonProductAPI();

    try
    {
        $result = $obj->searchProducts("X-Men Origins",
                                       AmazonProductAPI::DVD,
                                       "TITLE");
    }
    catch(Exception $e)
    {
        echo $e->getMessage();
    }

    print_r($result);


    echo "Sales Rank : {$result->Items->Item->SalesRank}<br>";
    echo "ASIN : {$result->Items->Item->ASIN}<br>";
    echo "<br><img src=\"" . $result->Items->Item->MediumImage->URL . "\" /><br>";


?>

同样,这是运行 Example.php 的结果 此处显示. 的结果print_r($result);无效的xml响应.

Again, this is the result of running Example.php shown here. The result of print_r($result); is invalid xml respnse.

推荐答案

对于我的情况,我的错误是 InvalidClientTokenId提供的 X.509 证书或 AWS 访问密钥 ID 不存在 我只是(非常小心地)用 本指南 并参考 本指南 以确认我的助理 ID.

For my case, my error was InvalidClientTokenId , The X.509 certificate or AWS access key ID provided does not exist in our records. I simply (very carefuly) created a new access and secret keys with this guide and referred to this guide to confirm my associate ID.

要查找错误,只需使用 throw new Exception("Invalid xml response."); 取消该行并添加 return ($response); 并运行php 页面.有关错误列表,请参阅此页面.

To find your error, simply nullify the line with throw new Exception("Invalid xml response."); and add return ($response); and run the php page. Refer to this page for the list of errors.

这篇关于产品广告API PHP无效xml响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆