dongtan5555 2013-08-04 21:34
浏览 96

亚马逊API和Woocommerce桥

I'm trying to get WooCommerce to grap the price from the Amazon API but I'm failing badly. I'm terrible at PHP but here's what I've got so far. I can't get it to work.

I'm using a template I found online to call from the Amazon API. These are the files:

<?php

/**
 * Class to access Amazons Product Advertising API
 * @author Sameer Borate
 * @link http://www.codediesel.com
 * @version 1.0
 * All requests are not implemented here. You can easily
 * implement the others from the ones given below.
 */


/*
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

require_once 'amazon_product_api_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;

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

    private $local_site;

    /**
     * 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";


    public function __construct($public, $private, $local_site, $associate_tag){

        $this->public_key = $public;
        $this->private_key = $private;
        $this->local_site = $local_site;
        $this->associate_tag = $associate_tag;

    }

    public function get_local(){
        return $this->local_site;
    }

    /**
     * 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
     */
    public function queryAmazon($parameters)
    {
        return amazon_product_api_signed_request($this->local_site, $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);

    }




    public function getBrowseNodeProducts($category, $browseNode = 1000, $searchType = "UPC")
    {
        $allowedTypes = array("UPC", "TITLE", "ARTIST", "KEYWORD");
        $allowedCategories = array("Music", "DVD", "VideoGames");

         $parameters = array(
                            "Operation"     => "ItemSearch",
                            "BrowseNode"    => $browseNode,
                            "SearchIndex"   => $category,
                            "ResponseGroup" => "Medium,Reviews"
                            );

        $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);
    }

}

?>

Here's the file to access the API I believe:

<?php

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

if($region == 'jp'){
    $host = "ecs.amazonaws.".$region;
}else{
    $host = "webservices.amazon.".$region;
}

$method = "GET";
$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"]          = "2011-08-01";

/* 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."
".$host."
".$uri."
".$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;
}
}
?>

This is a WooCommerce function that I believe does the price:

function woocommerce_get_formatted_product_name( $product ) {
if ( ! $product || ! is_object( $product ) )
    return;

if ( $product->get_sku() )
    $identifier = $product->get_sku();
elseif ( $product->is_type( 'variation' ) )
    $identifier = '#' . $product->variation_id;
else
    $identifier = '#' . $product->id;

if ( $product->is_type( 'variation' ) ) {
    $attributes = $product->get_variation_attributes();
    $extra_data = ' &ndash; ' . implode( ', ', $attributes ) . ' &ndash; ' .    woocommerce_price( $product->get_price() );
} else {
    $extra_data = '';
}

return sprintf( __( '%s &ndash; %s%s', 'woocommerce' ), $identifier, $product- >get_title(), $extra_data );
}

And this is what I have added to the functions.php file in the hope to make it all come together, sadly, it's not working :(

require_once('amazon_product_api_class.php');

$public = 'my code goes here'; //amazon public key here
$private = 'my code goes here'; //amazon private/secret key here
$site = 'com'; //amazon region
$affiliate_id = 'my affiliate goes here(removed for security reasons)'; //amazon affiliate id



$amazon = $amazon = new AmazonProductAPI($public, $private, $site, $affiliate_id);

$single = array(
'Operation' => 'ItemLookup',
'ItemId' => 'B0006N149M',
'ResponseGroup' => 'Reviews,Medium'
);


function return_custom_price($price, $product) { 

amazon_item_info(); 

$result =   $amazon->queryAmazon($single);
$single_products = $result->Items->Item;

foreach($single_products as $si){

$item_url = $si->DetailPageURL; //get its amazon url
$img = $si->MediumImage->URL; //get the image url

echo "<li>";
echo "<img src='$img'/>";
echo "<a href='$item_url'>". $si->ASIN . "</a>";
echo $si->ItemAttributes->ListPrice->FormattedPrice; //item price
echo "</li>";       
}

}      
add_filter('woocommerce_get_price', 'return_custom_price', $product, 2);   
  • 写回答

1条回答 默认 最新

  • dongyu5482 2013-12-07 14:27
    关注

    Why not try something like Zapier?

    评论

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'