所有api浏览器搜索框接口

tech2022-08-30  132

所有api浏览器搜索框接口

In this tutorial, you’ll take a look at Amazon’s Product Advertising API. It’s an API that allows developers to access data about items for sale, seller reviews, customer reviews, and product promotions on all Amazon marketplaces worldwide.

在本教程中,您将了解Amazon的Product Advertising API 。 这是一个API,开发人员可以通过它访问全球所有亚马逊市场上有关待售商品,卖家评论,客户评论和产品促销的数据。

基本API概念 (Basic API Concepts)

When working with the API, the first thing that you need to know is which Amazon website you wish to target. Not all Amazon websites sell the same kinds of products. If you’re a seller, you’ll really have to target your own locale rather than just the US website (amazon.com). You can find information on what locales are available on this page: Anatomy of a REST Request. Once on that page, look for Product Advertising API Endpoints and you’ll see a list of locales and their corresponding endpoints. Note that you can only make a request to endpoints where you registered. For example, if you registered as an affiliate on the US website, you’ll only be able to make a request to the http://webservices.amazon.com/onca/xml endpoint.

使用API​​时,您首先需要了解的是您希望定位到哪个Amazon网站。 并非所有亚马逊网站都出售相同种类的产品。 如果您是卖家,则确实必须针对自己的语言环境,而不仅仅是美国网站(amazon.com)。 您可以在此页面上找到可用的语言环境信息: REST请求剖析 。 在该页面上,查找“ Product Advertising API端点” ,您将看到语言环境及其对应端点的列表。 请注意,您只能向您注册的端点发出请求。 例如,如果您在美国网站上注册为会员,则只能向http://webservices.amazon.com/onca/xml端点提出请求。

运作方式 (Operations)

Operations are the things you can do with the API. Here are a few examples:

操作是你可以用API做的事。 这里有一些例子:

ItemSearch – search for items based on specific parameters such as the category, title, manufacturer, and minimum price. This returns one or more items.

ItemSearch –根据类别,标题,制造商和最低价格等特定参数搜索项目。 这将返回一个或多个项目。

ItemLookup – search for an item based on an identifier such as ASIN or ISBN (for books). This returns only one item.

ItemLookup –根据标识符(例如,ASIN或ISBN)搜索项目。 这仅返回一项。

SimilarityLookup – search for items that are similar to the item that you specified in your request.

相似性查找–搜索与您在请求中指定的项目相似的项目。

CartCreate – creates a remote shopping cart on Amazon’s servers.

CartCreate –在Amazon服务器上创建一个远程购物车。

CartAdd – adds item to a remote shopping cart.

CartAdd –将商品添加到远程购物车。

回应小组 (Response Groups)

Response groups allow you to specify which information about the products you want to include in the response. Note that response groups depend on the operation that you’re using. This means that not all response groups are available to all operations. Here are a few examples of response groups that you can use:

响应组允许您指定要包含在响应中的产品信息。 请注意,响应组取决于您使用的操作。 这意味着并非所有响应组都可用于所有操作。 以下是一些您可以使用的响应组示例:

Small – returns basic information about the item. Example data returned include the ASIN, Title, ProductGroup.

小 –返回有关商品的基本信息。 返回的示例数据包括ASIN,标题,产品组。

Reviews – returns the URL of the iframe containing the item’s reviews.

评论 –返回包含该商品评论的iframe的URL。

OfferSummary – returns the lowest price for each condition type (new item, used item, collectible item, refurbished item).

OfferSummary –返回每种条件类型(新商品,二手商品,收藏品,翻新商品)的最低价格。

ItemAttributes – returns all the attributes that an item has. Item attributes depend on the type of the item. For example, a book would have a different set of attributes than computer hardware. However, attributes such as the title or the list price are common to all products.

ItemAttributes –返回项目具有的所有属性。 项目属性取决于项目的类型。 例如,一本书将具有与计算机硬件不同的属性集。 但是, 标题或标价等属性对于所有产品都是通用的。

浏览节点 (Browse Nodes)

Browse nodes is Amazon’s method for classifying items. They are called browse nodes because each node can have children and each child can also have children of its own. Examples of browse nodes include:

浏览节点是Amazon的商品分类方法。 之所以称为浏览节点,是因为每个节点可以有子节点,并且每个子节点也可以有自己的子节点。 浏览节点的示例包括:

Books

图书 Electronics

电子产品 Mobile Apps

行动应用程式 Software

软件 Office Products

办公用品 Automotive

汽车行业

The examples given above are all root nodes. In the API you can use root nodes as the value for the search index if you don’t want to be too specific with your request. However, if you want to be specific, you can always dig in deeper towards the child or grandchild of the root node. You don’t want to just search “Books”, for example. You specifically want books about African History. In that case, your browse node traversal would look something like this:

上面给出的示例都是根节点。 如果您不想对请求太具体,可以在API中使用根节点作为搜索索引的值。 但是,如果要具体化,则始终可以更深入地挖掘根节点的子代或孙代。 例如,您不想只搜索“书籍”。 您特别想要有关非洲历史的书籍。 在这种情况下,您的浏览节点遍历如下所示:

Books -> History -> African

“Books” is the root node, “History” is the child, and “African” is the grand-child. What you want is the ID of the furthest node (the grand-child). Specify that as the value for the BrowseNode parameter in your request so that the API will only look for books on African History. You can find a list of browse nodes and their corresponding IDs on findbrowsenodes.com.

“书”是根节点,“历史”是子节点,“非洲”是孙子节点。 您需要的是最远节点(孙子节点)的ID。 将其指定为请求中的BrowseNode参数的值,以便API仅查找有关非洲历史的书籍。 您可以在findbrowsenodes.com上找到浏览节点及其对应ID的列表 。

区域设置 (Locale)

As previously discussed, there are a few Amazon locales or marketplaces worldwide, and each API request that you’ll be making needs to target a specific locale. But each locale has different valid values for search indices, browse node IDs, sort values and ItemSearch parameters. For example, the Brazil marketplace only has a few search indices available. But if you look at the Canada Marketplace, the search indices available closely match that of the US Marketplace. You can check out specific locale information on the locale reference page.

如前所述,全球有一些Amazon语言环境或市场,您将需要针对每个API请求定位特定的语言环境。 但是每个语言环境对于搜索索引,浏览节点ID,排序值和ItemSearch参数都有不同的有效值。 例如, 巴西市场上只有几个搜索索引可用。 但是,如果您查看加拿大市场 ,则可用的搜索索引与美国市场的搜索索引非常匹配。 您可以在区域设置参考页面上查看特定的区域设置信息。

获取访问密钥 (Getting An Access Key)

In order to make requests to the Product Advertising API, you need to have an access key, secret key, and an affiliate ID. Here are the steps to get you started:

为了向Product Advertising API发出请求,您需要具有访问密钥,秘密密钥和会员ID。 以下是使您入门的步骤:

Sign up for an Amazon Account

注册一个亚马逊账户

Sign up as a Product Advertising API developer based on your locale. Go to this page and scroll down to the bottom to find the URL for your locale. This requires you to enter the following information:

根据您的语言环境注册为产品广告API开发人员。 转到此页面并向下滚动至底部以找到您的语言环境的URL。 这要求您输入以下信息:

Once you’re done, it should show the following screen:

完成后,它将显示以下屏幕:

Click on the link for managing your account and it should return the following page:

单击用于管理帐户的链接,它将返回以下页面:

Click the link that says AWS Security Credentials Console and you’ll be redirected to the Amazon Web Service console. If this is your first time accessing it, it should show a modal box asking you to continue to security credentials.

单击显示AWS安全凭证控制台的链接,您将被重定向到Amazon Web Service控制台。 如果这是您第一次访问它,它应该显示一个模式框,要求您继续使用安全凭证。

Click the Access Keys tab to reveal a list of access keys that you already have. By default, there should be one listed but you won’t really be able to use that since you can’t see the corresponding secret key. If this is a new account you can go ahead and delete that.

单击访问密钥选项卡,以显示您已经拥有的访问密钥的列表。 默认情况下,应该列出一个,但是由于看不到相应的密钥,您将无法使用它。 如果这是一个新帐户,您可以继续删除它。

Click the Create New Access key button to generate a new access key and secret key combination. Once generated, copy the key combination or download the key file. This is because you won’t be able to see the secret key again on the website.

单击创建新访问密钥按钮以生成新的访问密钥和秘密密钥组合。 生成密钥后,复制密钥组合或下载密钥文件。 这是因为您将无法在网站上再次看到密钥。

Sign up for an Amazon Associates Account based on your locale. This is where they’ll ask the details of your website and the products that you’re selling. It will also ask you to verify your phone number. Once you’re done with all that, you’ll be given a unique associate ID.

根据您的语言环境注册一个Amazon Associates帐户。 在这里,他们会询问您的网站和所销售产品的详细信息。 它还将要求您验证您的电话号码。 完成所有操作后,您将获得一个唯一的关联ID。

便笺 (Scratchpad)

You can use the scratchpad to play around with the API without having to write code. To use the scratchpad, first select the operation you want to perform:

您可以使用暂存器来使用API​​,而无需编写代码。 要使用暂存器,请首先选择要执行的操作:

Supply the common parameters. This includes the Amazon website where you want to perform the request, your associate ID, access key, and secret key.

提供常用参数。 这包括您要在其中执行请求的亚马逊网站,您的关联ID,访问密钥和秘密密钥。

Next are the request parameters. This is where you can choose the category to search (search index), query (keywords), specific product data (response group) that you want to return, sorting, browse node, and any additional parameter that you wish to add to the request.

接下来是请求参数。 在这里,您可以选择要搜索的类别(搜索索引),查询(关键字),要返回的特定产品数据(响应组),排序,浏览节点以及希望添加到请求中的任何其他参数。 。

Click the Run request button to send the request.

单击运行请求按钮以发送请求。

Once you get a response back, it should show the following:

收到回复后,它应显示以下内容:

Note that the XML response is what you get from the API. The rendered response is the output of the code that’s in the HTML response tab, but it’s basically using the same data that’s in the XML response.

请注意,XML响应就是您从API获得的响应。 呈现的响应是HTML响应选项卡中代码的输出,但基本上使用的是与XML响应中相同的数据。

向API发出请求 (Making Requests to the API)

In this section, you’ll take a look at how you can make requests to the API. You’ll be using Guzzle to do this. Let’s install it with Composer.

在本节中,您将了解如何向API发出请求。 您将使用Guzzle执行此操作。 让我们用Composer安装它。

composer require guzzlehttp/guzzle:~6.0

Create an amazon-tester.php file and add the following code. Just hard-code the keys for now so you can test things quickly.

创建一个amazon-tester.php文件并添加以下代码。 只需暂时对密钥进行硬编码,以便您可以快速进行测试。

<?php require 'vendor/autoload.php'; $client = new GuzzleHttp\Client(); $access_key = 'YOUR-ACCESS-KEY'; $secret_key = 'YOUR-SECRET-KEY'; $associate_tag = 'YOUR-ASSOCIATE-ID'; $timestamp = date('c'); $query = [ 'Service' => 'AWSECommerceService', 'Operation' => 'ItemLookup', 'ResponseGroup' => 'Medium', 'IdType' => 'ASIN', 'ItemId' => 'B00BGO0Q9O', 'AssociateTag' => $associate_tag, 'AWSAccessKeyId' => $access_key, 'Timestamp' => $timestamp ]; ksort($query); $sign = http_build_query($query); $request_method = 'GET'; $base_url = 'webservices.amazon.com'; $endpoint = '/onca/xml'; $string_to_sign = "{$request_method}\n{$base_url}\n{$endpoint}\n{$sign}"; $signature = base64_encode( hash_hmac("sha256", $string_to_sign, $secret_key, true) ); $query['Signature'] = $signature; try { $response = $client->request( 'GET', 'http://webservices.amazon.com/onca/xml', ['query' => $query] ); $contents = new SimpleXMLElement($response->getBody()->getContents()); echo "<pre>"; print_r($contents); echo "</pre>"; } catch(Exception $e) { echo "something went wrong: <br>"; echo $e->getMessage(); }

Breaking down the code above, first include the autoload file so you can use Guzzle, then create a new Guzzle client:

分解上面的代码,首先包括自动加载文件,以便可以使用Guzzle,然后创建一个新的Guzzle客户端:

require 'vendor/autoload.php'; $client = new GuzzleHttp\Client();

Declare your access key, secret key, associate ID, as well as the current timestamp. Note that the API requires the timestamp to be in ISO 8601 date format.

声明您的访问密钥,秘密密钥,关联ID以及当前时间戳。 请注意,API要求时间戳记必须为ISO 8601日期格式 。

$access_key = 'YOUR-ACCESS-KEY'; $secret_key = 'YOUR-SECRET-KEY'; $associate_tag = 'YOUR-ASSOCIATE-ID'; $timestamp = date('c');

Declare the query parameters to be supplied to the API. The only thing that’s constant here is the Service, AssociateTag, AWSAccessKeyId, and Timestamp. All the other parameters may change based on what operation you wish to perform. In this case, you’re performing an ItemLookup operation. As mentioned earlier, this operation allows you to get information on a single product based on a unique identifier. The most common product identifier used in Amazon products is the ASIN (Amazon Standard Identification Number). This number is unique to each Amazon Marketplace, which means that the same kind of item can have different ASIN throughout marketplaces. Supply the IdType parameter and give it a value of ASIN to specify that you want to use the ASIN as the product identifier. Then add the IdType to specify the value for the product identifier itself.

声明要提供给API的查询参数。 这里唯一不变的是Service , AssociateTag , AWSAccessKeyId和Timestamp 。 所有其他参数可能会根据您希望执行的操作而改变。 在这种情况下,您要执行ItemLookup操作。 如前所述,此操作使您可以基于唯一标识符获取有关单个产品的信息。 亚马逊产品中最常用的产品标识符是ASIN(亚马逊标准标识号)。 该编号对于每个亚马逊市场都是唯一的,这意味着同一种类的商品在整个市场中可以具有不同的ASIN。 提供IdType参数,并为其指定ASIN值,以指定您要将ASIN用作产品标识符。 然后添加IdType以指定产品标识符本身的值。

$query = [ 'Service' => 'AWSECommerceService', 'Operation' => 'ItemLookup', 'ResponseGroup' => 'Small', 'IdType' => 'ASIN', 'ItemId' => 'B00BGO0Q9O', 'AssociateTag' => $associate_tag, 'AWSAccessKeyId' => $access_key, 'Timestamp' => $timestamp ];

You can get the ASIN of an item by simply looking at the URL or the page itself. For example, this item has the following URL:

您只需查看URL或页面本身即可获得项目的ASIN。 例如, 该项目具有以下URL:

http://www.amazon.com/Pokemon-Sun-Nintendo-3DS/dp/B01C93CWU6?ie=UTF8&keywords=pokemon&qid=1461061906&ref_=sr_1_9&sr=8-9

The ASIN is the string of characters that comes after dp/: B01C93CWU6. If you scroll down to the product’s details, you can see the ASIN as well.

ASIN是dp/ : B01C93CWU6之后的字符串。 如果向下滚动到产品的详细信息,则也可以看到ASIN。

Moving on, use ksort to sort the array keys alphabetically. This is also part of the API’s requirement.

继续,使用ksort按字母顺序对数组键进行排序。 这也是API要求的一部分。

ksort($query);

Generate a URL-encoded query string based on the array of query parameters:

根据查询参数数组生成URL编码的查询字符串:

$sign = http_build_query($query);

Next, you need to construct the signature for the request that you’ll be making. The signature consists of the request method, the base URL where the request will be made, the endpoint and the query parameters. Each of these should be separated by a new line.

接下来,您需要为将要发出的请求构造签名。 签名包括请求方法,发出请求的基本URL,端点和查询参数。 这些中的每一个都应用换行符分隔。

$request_method = 'GET'; $base_url = 'webservices.amazon.com'; $endpoint = '/onca/xml'; $string_to_sign = "{$request_method}\n{$base_url}\n{$endpoint}\n{$sign}";

Generate a keyed hash value based on the string that you’ve just constructed by calling the hash_hmac method. This accepts the hashing algorithm as its first argument, the string to sign as its second, and a key for its third. The fourth argument is a boolean value for setting whether to output raw binary data (true) or lowercase hexits (false). You then use base64_encode so you can make the signature transportable.

通过调用hash_hmac方法,基于刚刚构造的字符串生成键控哈希值。 这接受哈希算法作为第一个参数,将要签名的字符串作为第二个参数,并将密钥作为第三个参数。 第四个参数是一个布尔值,用于设置是输出原始二进制数据( true )还是小写十六进制( false )。 然后,您可以使用base64_encode以便使签名可以传输。

$signature = base64_encode( hash_hmac("sha256", $string_to_sign, $secret_key, true) );

Add the signature into the original query parameters:

将签名添加到原始查询参数中:

$query['Signature'] = $signature;

Make the request:

提出要求:

try { $response = $client->request( 'GET', 'http://webservices.amazon.com/onca/xml', ['query' => $query] ); $contents = new SimpleXMLElement($response->getBody()->getContents()); echo "<pre>"; print_r($contents); echo "</pre>"; } catch (Exception $e) { echo "something went wrong: <br>"; echo $e->getMessage(); }

Note that Guzzle handles converting the array of query parameters into query strings. It will also urlencode the values so you can just supply the array like you did above. Also note that the API returns an XML document, so in order to work with it you need to use the SimpleXMLElement class. This converts the XML document to a simpleXML object which you can work on.

请注意,Guzzle负责将查询参数数组转换为查询字符串。 它还将对值进行urlencode ,因此您可以像上面一样提供数组。 还要注意,API返回一个XML文档,因此要使用它,您需要使用SimpleXMLElement类。 这会将XML文档转换为可以使用的simpleXML对象。

$contents = new SimpleXMLElement($response->getBody()->getContents());

Here’s an example response that you get from the API.

这是您从API获得的示例响应 。

构建一个亚马逊产品搜索器 (Building an Amazon Product Searcher)

Now it’s time to put your newfound skills to the test. You can do that by building a simple app that lets users search for Amazon products. Here’s what it’s going to look like:

现在是时候测试您的新技能了。 您可以通过构建一个简单的应用程序来做到这一点,该应用程序使用户可以搜索Amazon产品。 它将是这样的:

You can access the source code for this project in this Github repo.

您可以在此Github存储库中访问该项目的源代码。

Start by installing the dependencies. Create a composer.json file at the root of your working directory and add the following:

首先安装依赖项。 在工作目录的根目录下创建一个composer.json文件,并添加以下内容:

{ "require": { "guzzlehttp/guzzle": "~6.0", "twig/twig": "^1.24", "vlucas/phpdotenv": "^2.2", "respect/validation": "^1.0" }, "autoload": { "psr-4": { "Lib\\": "lib" } } }

This will install Guzzle for making requests to the API, Twig for templating, phpdotenv for loading environment variables, and Respect for validating user input.

这将安装Guzzle来向API发出请求, Twig来进行模板化, phpdotenv来加载环境变量,以及尊重来验证用户输入。

You’ll also be using a custom class for easily making requests to the Amazon API so you need to add the path to that class in the autoload object:

您还将使用自定义类轻松地向Amazon API发出请求,因此您需要在autoload对象中添加该类的路径:

"autoload": { "psr-4": { "Lib\\": "lib" } }

Create a lib/Amazon.php file and add the following:

创建一个lib/Amazon.php文件并添加以下内容:

<?php namespace Lib; use GuzzleHttp; class Amazon { public $common_params; private $access_key; private $secret_key; private $associate_tag; private $client; public function __construct($access_key, $secret_key, $associate_tag) { $this->access_key = $access_key; $this->secret_key = $secret_key; $this->associate_tag = $associate_tag; $this->common_params = [ 'Service' => 'AWSECommerceService', 'Operation' => 'ItemSearch', 'ResponseGroup' => 'Medium', 'AssociateTag' => $associate_tag, 'AWSAccessKeyId' => $access_key, ]; $this->client = new GuzzleHttp\Client(); } private function generateSignature($query) { ksort($query); $sign = http_build_query($query); $request_method = 'GET'; $base_url = 'webservices.amazon.com'; $endpoint = '/onca/xml'; $string_to_sign = "{$request_method}\n{$base_url}\n{$endpoint}\n{$sign}"; $signature = base64_encode( hash_hmac("sha256", $string_to_sign, $this->secret_key, true) ); return $signature; } private function doRequest($query) { $timestamp = date('c'); $query['Timestamp'] = $timestamp; $query = array_merge($this->common_params, $query); $query['Signature'] = $this->generateSignature($query); try { $response = $this->client->request( 'GET', 'http://webservices.amazon.com/onca/xml', ['query' => $query] ); $contents = new \SimpleXMLElement($response->getBody()->getContents()); return $contents; } catch (Exception $e) { return [ 'error' => $e->getMessage() ]; } } public function getSearchIndices() { return [ 'All', 'UnboxVideo', 'Appliances', 'MobileApps', 'ArtsAndCrafts', 'Automotive', 'Books', 'Music', 'Wireless', 'Collectibles', 'PCHardware', 'Electronics', 'KindleStore', 'Movies', 'OfficeProducts', 'Software', 'Tools', 'VideoGames' ]; } public function itemSearch($keywords, $search_index) { $query = [ 'Keywords' => $keywords, 'SearchIndex' => $search_index ]; $response = $this->doRequest($query); return $response; } }

Breaking down the code above: create a new Guzzle client in the constructor by using the access key, secret key, and associate tag that was passed to it.

分解上面的代码:使用访问密钥,秘密密钥和传递给它的关联标签在构造函数中创建一个新的Guzzle客户端。

public function __construct($access_key, $secret_key, $associate_tag) { $this->access_key = $access_key; $this->secret_key = $secret_key; $this->associate_tag = $associate_tag; $this->common_params = [ 'Service' => 'AWSECommerceService', 'Operation' => 'ItemSearch', 'ResponseGroup' => 'Medium', 'AssociateTag' => $associate_tag, 'AWSAccessKeyId' => $access_key, ]; $this->client = new GuzzleHttp\Client(); }

When someone makes a request, the itemSearch method is called. The parameters required by the API are passed in as an argument.

当有人提出请求时,将itemSearch方法。 API所需的参数作为参数传递。

public function itemSearch($keywords, $search_index) { $query = [ 'Keywords' => $keywords, 'SearchIndex' => $search_index ]; $response = $this->doRequest($query); return $response; }

The arguments are then passed to the doRequest method which is responsible for making the actual request to the API. This merges the array of common parameters with the argument that was passed to it. Then it calls the generateSignature method to generate the signature for the request. Finally, the result is added as one of the query parameters.

然后将参数传递给doRequest方法,该方法负责向API发出实际请求。 这会将公用参数数组与传递给它的参数合并。 然后,它调用generateSignature方法为请求生成签名。 最后,将结果添加为查询参数之一。

private function doRequest($query) { $timestamp = date('c'); $query['Timestamp'] = $timestamp; $query = array_merge($this->common_params, $query); $query['Signature'] = $this->generateSignature($query); try { $response = $this->client->request( 'GET', 'http://webservices.amazon.com/onca/xml', ['query' => $query] ); $contents = new \SimpleXMLElement($response->getBody()->getContents()); return $contents; } catch (Exception $e) { return [ 'error' => $e->getMessage() ]; } }

The generateSignature method is responsible for generating the signature required by the API.

generateSignature方法负责生成API所需的签名。

private function generateSignature($query) { ksort($query); $sign = http_build_query($query); $request_method = 'GET'; $base_url = 'webservices.amazon.com'; $endpoint = '/onca/xml'; $string_to_sign = "{$request_method}\n{$base_url}\n{$endpoint}\n{$sign}"; $signature = base64_encode( hash_hmac("sha256", $string_to_sign, $this->secret_key, true) ); return $signature; }

You also have the getSearchIndices method which just returns hard-coded search index values.

您还具有getSearchIndices方法,该方法仅返回硬编码的搜索索引值。

public function getSearchIndices() { return [ 'All', 'UnboxVideo', 'Appliances', 'MobileApps', 'ArtsAndCrafts', 'Automotive', 'Books', 'Music', 'Wireless', 'Collectibles', 'PCHardware', 'Electronics', 'KindleStore', 'Movies', 'OfficeProducts', 'Software', 'Tools', 'VideoGames' ]; }

Create a .env file at the root of your working directory and add your Amazon associate ID, access key and secret key.

在工作目录的根目录中创建一个.env文件,并添加您的Amazon关联ID,访问密钥和秘密密钥。

APP_TITLE="Amazon Searcher" ASSOCIATE_TAG=YOUR-ASSOCIATE-ID ACCESS_KEY=YOUR-AMAZON-ACCESS-KEY SECRET_KEY=YOUR-AMAZON-SECRET-KEY

Create an index.php file at the root of your working directory and add the following:

在工作目录的根目录下创建一个index.php文件,并添加以下内容:

<?php require 'vendor/autoload.php'; use Respect\Validation\Validator as v; $dotenv = new Dotenv\Dotenv(__DIR__); $dotenv->load(); $access_key = getenv('ACCESS_KEY'); $secret_key = getenv('SECRET_KEY'); $associate_tag = getenv('ASSOCIATE_TAG'); $amazon = new Lib\Amazon($access_key, $secret_key, $associate_tag); $search_indices = $amazon->getSearchIndices(); $items = []; $keyword = ''; $search_index = ''; $has_searched = false; if (!empty($_GET['keyword'])) { $keyword = $_GET['keyword']; $search_index = $_GET['search_index']; $has_searched = true; $keyword_validator = v::alnum() ->noWhitespace() ->length(3, 80); if ($keyword_validator->validate($_GET['keyword']) && in_array($search_index, $search_indices)) { $response = $amazon->itemSearch($keyword, $search_index); $items = $response->Items->Item; } } $loader = new Twig_Loader_Filesystem('templates'); $twig = new Twig_Environment($loader, [ 'cache' => 'cache', 'auto_reload' => true ]); $selected_filter = new Twig_SimpleFilter('selected', function ($string) { $exploded_string = explode(',', $string); $selected_value = $exploded_string[0]; $current_value = $exploded_string[1]; return ($selected_value == $current_value) ? 'selected' : ''; }); $twig->addFilter($selected_filter); $template = $twig->loadTemplate('index.html'); echo $template->render([ 'app_title' => getenv('APP_TITLE'), 'search_indices' => $search_indices, 'keyword' => $keyword, 'search_index' => $search_index, 'items' => $items, 'has_searched' => $has_searched ]); ?>

Breaking it down.

分解。

First, get the access key, secret key, and associate tag from the .env file:

首先,从.env文件中获取访问密钥,秘密密钥和关联标签:

$dotenv = new Dotenv\Dotenv(__DIR__); $dotenv->load(); $access_key = getenv('ACCESS_KEY'); $secret_key = getenv('SECRET_KEY'); $associate_tag = getenv('ASSOCIATE_TAG');

Create a new instance of the Amazon class and retrieve the search indices from it.

创建一个新的Amazon类实例,并从中检索搜索索引。

$amazon = new Lib\Amazon($access_key, $secret_key, $associate_tag); $search_indices = $amazon->getSearchIndices();

Assign default values for the variables that you’ll be using on the template. $items represent the array of items in the search results, $keyword represents the value entered by the user, $search_index is the search index selected by the user, and $has_searched is a boolean value representing whether the user has searched for anything or not.

为将在模板上使用的变量分配默认值。 $items表示搜索结果中的项目数组, $keyword表示用户输入的值, $search_index是用户选择的搜索索引, $has_searched是一个布尔值,表示用户是否搜索了任何内容。

$items = []; $keyword = ''; $search_index = ''; $has_searched = false;

Check if the user has searched. If true, update the default values that you’ve assigned earlier, validate the user input, and search for the products that match the user’s query.

检查用户是否已搜索。 如果为true ,则更新您先前分配的默认值,验证用户输入,并搜索与用户查询匹配的产品。

if (!empty($_GET['keyword'])) { $keyword = $_GET['keyword']; $search_index = $_GET['search_index']; $has_searched = true; $keyword_validator = v::alnum() ->noWhitespace() ->length(3, 80); if ($keyword_validator->validate($_GET['keyword']) && in_array($search_index, $search_indices)) { $response = $amazon->itemSearch($keyword, $search_index); $items = $response->Items->Item; } }

Initialize Twig. Here, you specify the directory in which the templates are stored. In this case, it’s the templates directory.

初始化Twig。 在这里,您指定存储模板的目录。 在这种情况下,它是templates目录。

$loader = new Twig_Loader_Filesystem('templates');

Configure the Twig environment by specifying the directory in which to store the cache, and auto_reload to automatically clear the cache when you make changes to either the file supplying the data for your template or the template itself.

通过指定用于存储缓存的目录来配置Twig环境,并在对提供模板数据的文​​件或模板本身进行更改时使用auto_reload自动清除缓存。

$twig = new Twig_Environment($loader, [ 'cache' => 'cache', 'auto_reload' => true ]);

Add a custom filter for setting the selected value for the search indices select box:

添加自定义过滤器以设置搜索索引选择框的选定值:

$selected_filter = new Twig_SimpleFilter('selected', function ($string) { $exploded_string = explode(',', $string); $selected_value = $exploded_string[0]; $current_value = $exploded_string[1]; return ($selected_value == $current_value) ? 'selected' : ''; }); $twig->addFilter($selected_filter);

Supply the data and render the page:

提供数据并呈现页面:

$template = $twig->loadTemplate('index.html'); echo $template->render([ 'app_title' => getenv('APP_TITLE'), 'search_indices' => $search_indices, 'keyword' => $keyword, 'search_index' => $search_index, 'items' => $items, 'has_searched' => $has_searched ]);

Here’s the code for the template (templates/index.html):

这是模板的代码( templates/index.html ):

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ app_title }}</title> <link rel="stylesheet" href="assets/skeleton/css/skeleton.css"> <link rel="stylesheet" href="assets/css/style.css"> </head> <body> <div id="wrapper" class="container"> <header> <h1>{{ app_title }}</h1> </header> <main> <div id="filter-container"> <form> <div class="row"> <div class="eight columns"> <label for="keyword">Keyword</label> <input type="text" name="keyword" id="keyword" class="u-full-width" value="{{ keyword }}" placeholder="Keyword"> </div> <div class="two columns"> <label for="search_index">Category</label> <select name="search_index" id="search_index" class="u-full-width"> {% for index in search_indices %} {% set data = search_index ~ "," ~ index %} <option value="{{ index }}" {{ data | selected }}>{{ index }}</option> {% endfor %} </select> </div> <div class="two columns"> <button class="button-primary" id="search-button">search</button> </div> </div> </form> </div> {% if items %} <div id="results-container"> {% for item in items %} <div class="item"> <div class="item-image-container"> <img src="{{ item.MediumImage.URL }}" alt="{{ item.ItemAttributes.Title }}" class="item-image"> </div> <div class="item-details-container"> <a href="{{ item.DetailPageURL }}" class="item-title"> <strong>{{ item.ItemAttributes.Title }}</strong> </a> <div class="item-brand">{{ item.ItemAttributes.Brand }}</div> <div class="item-price">{{ item.ItemAttributes.ListPrice.FormattedPrice }}</div> </div> </div> {% endfor %} </div> {% elseif has_searched %} No results found {% endif %} </main> </div> </body> </html>

Breaking it down, link to the stylesheets stored in the assets directory:

对其进行分解,请链接到assets目录中存储的样式表:

<link rel="stylesheet" href="assets/skeleton-css/css/skeleton.css"> <link rel="stylesheet" href="assets/css/style.css">

You’re going to create style.css later but for the skeleton.css you can create a .bowerrc file at the root of your working directory and add the following:

稍后您将创建style.css但是对于skeleton.css您可以在工作目录的根目录下创建一个.bowerrc文件,并添加以下内容:

{ "directory": "assets" }

Then, install Skeleton by executing the following command in the terminal:

然后,通过在终端中执行以下命令来安装Skeleton:

bower install skeleton-css --save

Note that this requires bower to be installed. If you don’t want to bother with it, you can just link to what they have on cdnjs, or completely avoid all NodeJS stuff by using BowerPHP.

请注意,这需要安装凉亭。 如果您不想麻烦它,可以链接到他们在cdnjs上拥有的内容 ,或者通过使用BowerPHP完全避免所有NodeJS的使用。

For the main content, there are two sections: one for the form for searching products, and one for the search results:

对于主要内容,有两个部分:一个用于搜索产品的表单,另一个用于搜索结果:

<div id="filter-container"> ... </div> <div id="results-container"> ... </div>

The form has only two fields: one for entering a query and one for selecting the search index.

该表格只有两个字段:一个用于输入查询,一个用于选择搜索索引。

<div class="eight columns"> <label for="keyword">Keyword</label> <input type="text" name="keyword" id="keyword" class="u-full-width" value="{{ keyword }}" placeholder="Keyword"> </div> <div class="two columns"> <label for="search_index">Category</label> <select name="search_index" id="search_index" class="u-full-width"> {% for index in search_indices %} {% set data = search_index ~ "," ~ index %} <option value="{{ index }}" {{ data | selected }}>{{ index }}</option> {% endfor %} </select> </div>

Inside the loop for going through all the search indices, use the selected filter that you’ve defined earlier. Here, you’re joining the currently selected search index with the search index value of the current option. The comma is used as the divider so that the filter can separate it.

在遍历所有搜索索引的循环内,使用您先前定义的selected过滤器。 在这里,您将当前选择的搜索索引与当前选项的搜索索引值结合在一起。 逗号用作分隔符,以便过滤器可以将其分隔。

{% for index in search_indices %} {% set data = search_index ~ "," ~ index %} <option value="{{ index }}" {{ data | selected }}>{{ index }}</option> {% endfor %}

Clicking the search button will trigger the form submission.

单击搜索按钮将触发表单提交。

<div class="two columns"> <button class="button-primary" id="search-button">search</button> </div>

Once you get a response from the API, it should fill the items variable with an array of items, which you then loop through:

从API获得响应后,它应使用一系列项目填充items变量,然后循环遍历:

{% if items %} <div id="results-container"> {% for item in items %} <div class="item"> <div class="item-image-container"> <img src="{{ item.MediumImage.URL }}" alt="{{ item.ItemAttributes.Title }}" class="item-image"> </div> <div class="item-details-container"> <a href="{{ item.DetailPageURL }}" class="item-title"> <strong>{{ item.ItemAttributes.Title }}</strong> </a> <div class="item-brand">{{ item.ItemAttributes.Brand }}</div> <div class="item-price">{{ item.ItemAttributes.ListPrice.FormattedPrice }}</div> </div> </div> {% endfor %} </div> {% elseif has_searched %} No results found {% endif %}

Finally, here’s the stylesheet (css/style.css) for the page:

最后,这是页面的样式表( css/style.css ):

#search-button { margin-top: 30px; } .item { overflow: hidden; padding: 10px; margin-bottom: 30px; } .item-image-container { width: 200px; margin-right: 20px; text-align: center; float: left; } .item-details-container { width: 700px; float: left; } .item-title { font-size: 18px; text-decoration: none; } .item-brand { color: #626262; } .item-price { font-size: 20px; font-weight: bold; margin-top: 10px; color: #2F2F2F; }

结论 (Conclusion)

In this tutorial, you’ve taken a look at Amazon’s Product Advertising API and how you can use it to get information about products sold on Amazon. We’ve gone through the API’s basics, and ended up building a simple, well constructed application for searching Amazon items.

在本教程中,您已经了解了Amazon的Product Advertising API以及如何使用它来获取有关在Amazon上出售的产品的信息。 我们介绍了API的基础知识,最后构建了一个简单,结构良好的应用程序来搜索Amazon项目。

If you want to learn more, check out the programming guide in the official docs where the above covered topics are explored more deeply. I recommend you check out the Best Programming Practices page as well, so that you can maximize the use of the API.

如果您想了解更多信息,请查阅官方文档中的编程指南,其中更深入地探讨了上述主题。 我建议您也查看“ 最佳编程实践”页面,以便最大程度地使用API​​。

Now that we’ve explored the API, here’s some homework for you: try to get the average rating of an individual product in the least possible amount of time. The best solution gets turned into a paid tutorial!

现在我们已经研究了API,这是为您准备的一些作业:尝试在最短的时间内获得单个产品的平均评分。 最好的解决方案将变成付费教程!

翻译自: https://www.sitepoint.com/amazon-product-api-exploration-lets-build-a-product-search/

所有api浏览器搜索框接口

相关资源:Amazon 关键词下拉框联想采集
最新回复(0)