jlevers / selling-partner-api Goto Github PK
View Code? Open in Web Editor NEWA PHP client library for Amazon's Selling Partner API
License: BSD 3-Clause "New" or "Revised" License
A PHP client library for Amazon's Selling Partner API
License: BSD 3-Clause "New" or "Revised" License
SellingPartnerApi\Configuration constructor always requires a refresh token, but this won't work for one case - a hybrid Selling Partner API application.
In a hybrid application, it uses Authorization API to get authorization to call Selling Partner API operations on behalf of a seller who previously authorized you as an Amazon MWS developer. The refresh token is not available in this case.
--- some background info ---
What is the Authorization API?
The Authorization API lets you migrate an Amazon Marketplace Web Service (Amazon MWS) authorization that a seller has granted you to a hybrid Selling Partner API application. This eliminates the need to request authorization from the seller again.
When would you need to use the Authorization API? Suppose you have published an Amazon MWS application on the Marketplace Appstore. A number of sellers have authorized you as an Amazon MWS developer so they can use your application. You later convert your Amazon MWS application into a hybrid Selling Partner API application that makes calls to both Amazon MWS and Selling Partner API. Now you want your application to make calls to Selling Partner API on behalf of these sellers without requesting authorization again. The Authorization API lets you do this.
In SellersApi.php, at line 472 you have this function call:
$headers = $this->headerSelector->selectHeaders(
['application/json', 'payload'],
[],
);
The comma after the empty array is producing a syntax error.
While it works with PHP 7.3, the Readme file says the library works with PHP 7.2
Thank you very much for developing this powerful package.
I hope to explain how to use this parameter.
My understanding is: when the access_token is about to expire, this method will be called to get a new access_token, is that right?
thx.
I'm trying to upload a POST_FLAT_FILE_PRICEANDQUANTITYONLY_UPDATE_DATA file with "createFeed", but the Response is HTTP 400 InvalidInput everytime.
Here's my code that creates the document and uploads the file.
// Options are set via a Factory
$feedsApi = new FeedsApi(SellingPartnerApiConfigurationFactory::createSellingPartnerApiConfiguration($seller));
// Creating Feed Document - See my pull request for the charset addition.
$createFeedDocSpec = new CreateFeedDocumentSpecification(["content_type" => "text/tab-separated-values; charset=UTF-8"]);
$feedDocumentInfo = $feedsApi->createFeedDocument($createFeedDocSpec);
// Getting file data
$documentContents = file_get_contents($this->projectDir . '/var/files/test_add_delete.txt');
// Sending file data to SP-API
$docToUpload = new Document($feedDocumentInfo->getPayload(), "text/tab-separated-values; charset=UTF-8");
$docToUpload->upload($documentContents);
$body = new CreateFeedSpecification([
'feed_type' => "POST_FLAT_FILE_PRICEANDQUANTITYONLY_UPDATE_DATA",
'marketplace_ids' => ["A1PA6795UKMFR9"],
'input_feed_document_id' => $feedDocumentInfo->getPayload()->getFeedDocumentId(),
'feed_options' => null
]);
$result = $feedsApi->createFeed($body);
dump($result);
The JSON, that is send to the endpoint is this:
{"feedType":"POST_FLAT_FILE_PRICEANDQUANTITYONLY_UPDATE_DATA","marketplaceIds":["A1PA6795UKMFR9"],"inputFeedDocumentId":"*VALUE FROM RESPONSE HERE*"}
The response is following:
{
"errors": [
{
"code": "InvalidInput",
"message": "Invalid request parameters",
"details": ""
}
]
}
The options are correctly set in the FeedApi, I was able to generate reports with the same Factory and the ReportsApi. Other feedTypes create the same issue.
Checking the request with the API documentation doesn't reveal any errors or missing information. Any clues what the issue could be?
The library only supports SP API apps that are set up with the non-standard (but simpler) IAM user-based authentication method. Lots of people set up their SP API applications with an IAM role, per Amazon's developer guide. This library should support the official authentication strategy, using STS to make an AssumeRole
call.
When can I officially use V3?
Hi many thanks for this repo, as the aws team's java sdk is so tedious to set up. Also I am not a java guy. I have a question, I am new to aws api, I got 403 when I tried the example
$api->getMarketplaceParticipations();
I thiink my aws and lwa cred are correct. What I am missing ?
Thanks
Hello,
Love this library!
I am working on switching from MWS over to the SP-API and this tool is great. I was wondering if you have had any luck with the ReportsAPI
working?
Whenever I try to create a report, I get back a 500 "Internal Failure" message from the API. Code and Response are below.
Code
$api_tr = new ReportsApi();
$api_tr->createReport(new CreateReportSpecification([
'report_type' => ['GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE'],
'date_start_time' => Carbon::now()->subDay()->startOfDay()->toISOString(),
'date_end_time' => Carbon::now()->subDay()->endOfDay()->toISOString(),
'marketplace_ids' => ['ATVPDKIKX0DER']
]));
Response
"errors": [
{
"code": "InternalFailure",
"message": "We encountered an internal error. Please try again.",
"details": ""
}
I am trying to connect via Selling Partner API application using an IAM role ARN instead of a user ARN but it returns error.
When logging in as root:
AccessDenied (client): Roles may not be assumed by root accounts. - Sender Access Denied Roles may not be assumed by root accounts.
Or when accessing with user with permissions:
AccessDenied (client): User: arn: aws: iam :: 1234567890123: user / EXAMPLE is not authorized to perform: sts: AssumeRole on resource: arn: aws: iam :: 1234567890123: user / EXAMPLE - Sender AccessDenied User: arn: aws: iam :: 1234567890123: user / EXAMPLE is not authorized to perform: sts: AssumeRole on resource: arn: aws: iam :: 1234567890123: user / EXAMPLE c1c9f242-13c5-4025-8ff0-
There is no way for Amazon to assist me. Can you think of where the error is?
1st Issue: Sales rank is not passed to the item result for either of these calls in the catalog API.
Cause: Amazon passes the data back in the json as 'ranks' not 'sales_ranks' even though sales_ranks is how they want it to be set with the included_data.
Fix:
Line 124 on the Model/CatalogItem.php - change to.
'sales_ranks' => 'ranks',
That fixes it so rank data can be properly deserialized.
This uncovered a 2nd issue.
2nd Issue: The 'ranks' attribute in the Model/Catalog/ItemSalesRank.php should be 'value'.
Fix:
To fix this, I just replaced all 'ranks' with 'value' in the Model/Catalog/ItemSalesRank.php.
Amazon is fun with their buggy API and api docs.
But you have trailing commas - 7.2 throws a parse error for these in Configuration.php. Should update to reflect that 7.3 is needed.
PHP Parse error: syntax error, unexpected ')' in /var/www/html/integration/amazon_sp/lib/Configuration.php on line 124
Host is PHP Version 7.2.34-21+ubuntu16.04.1+deb.sury.org+1
Amazon enabled this api also for vendors. I do have the json files for this api.
Can these be added to your repository?
When I'm trying to get the orders from the UK marketplace (A1F83G8C2ARO7P) I'm getting this error Invalid value 'GB_VOEC' for 'deemed_reseller_category', must be one of 'IOSS', 'UOSS'
From what I understand this is caused by Amazon changing the API without updating the documentation.
This can be fixed by adding this 2 lines in Model/Orders/OrderItem.php
const DEEMED_RESELLER_CATEGORY_GB_VOEC = 'GB_VOEC'
( line 324, right after const DEEMED_RESELLER_CATEGORY_UOSS = 'UOSS'
self::DEEMED_RESELLER_CATEGORY_GB_VOEC
in getDeemedResellerCategoryAllowableValues()
methodThe docs currently say:
All [
Configuration.php
constructor options] array items are optional, butlwaClientId
andlwaClientSecret
must always be given together. If only one of those two options is provided, theConfiguration
constructor will throw an exception.
However, the relevant exception is actually thrown in the Authentication.php
constructor. Since the user won't usually interact with Authentication.php
directly, I think it makes more sense to move the exception to Configuration.php
instead of updating the docs.
I am getting "Not authorized for requested operation","error":"unauthorized_client"
Hi Jesse, I learned from your java version, which has benefited me a lot.. May I ask if there is a java version tutorial released recently.. I am not good at php
goodluck!
Getting One or more environment variables failed assertions: SPAPI_ENDPOINT is missing. error if it is not mentioned in env, but it is set using dynamic config.
Amazon have now released updated versions of the Reports and Feed APIs that no longer require encrypting and decrypting of the files on the client side. The old versions are being deprecated in August 2022.
Awesome work on this! I've begun poking around and testing the different API calls, and they work great. Kudos to you for providing precise/easy-to-understand directions to get to the point of running it (ie AWS Seller API setup, etc).
Hello !
We're struggling with Amazon to get our Invoices uploaded with the SP-API.
After digging around, we did the following :
$pdfFile = __DIR__ . "/my_pdf_invoice.pdf";
$pdfContent = file_get_contents($pdfFile);
// $config is an instance of SellingPartnerApi\ConfigurationOptions
$apiInstance = new Api\FeedsApi($config);
$docSpecs = new Feeds\CreateFeedDocumentSpecification([
'content_type' => 'application/pdf'
]);
$feedInfos = null;
try {
$createFeedDocumentResponse = $apiInstance->createFeedDocument($docSpecs);
$feedInfos = $createFeedDocumentResponse->getPayload();
} catch (Exception $e) {
die('Exception when calling FeedsApi->createFeedDocument : ' . $e->getMessage() . PHP_EOL);
}
try {
$doc = new Document($feedInfos);
$doc->upload($pdfContent);
} catch (Exception $e) {
echo ("Exception when calling Document->upload :\n" . $e->getMessage() . PHP_EOL);
}
But then we get the error The request signature we calculated does not match the signature you provided. Check your key and signing method.
.
What are we doing wrong ?
Thanks in advance for your answer :)
Fatal error: Uncaught Error: Class 'Aws\Sts\StsClient' not found in jlevers/vendor/jlevers/selling-partner-api/lib/Authentication.php(167):
Amazon MWS Products section and Selling Partner Catalog Items v0 operations to be deprecated on March 31, 2022
amzn/selling-partner-api-models#1498
Do we have this in our roadmap?
When uploading the document feed the createFeedDocument method works fine but when I try to upload the document I always get the message "The request signature we calculated does not match the signature you provided. Check your key and signature method."
Snippet
use SellingPartnerApi;
const CONTENT_TYPE = "text/xml";
$feedsApi = new Api\FeedsApi();
$createFeedDocSpec = new Model\Feeds\CreateFeedDocumentSpecification(["content_type" => CONTENT_TYPE]);
$feedDocumentInfo = $feedsApi->createFeedDocument($createFeedDocSpec);
$docToUpload = new Document($feedDocumentInfo->getPayload(), CONTENT_TYPE)
$docToUpload->upload($xml_document);
are there other permissions to be enabled in AWS?
.
Hi, jlevers. Sorry, my English is very bad.
In the SP-API sandbox environment, I can get the order list and order details, but I cannot get the buyer information and delivery address information. Below I list some relevant information, please help me. Thank you.
These are the permissions of my app:
This is the code that I ran while testing (using the parameters provided by the official documentation):
$config = [];
$app = new OrdersApi($config);
$result = $app->getOrderAddress('TEST_CASE_200');
dd($result);
This is the information returned by SP-API:
"""
[403] {
"errors": [
{
"message": "Access to requested resource is denied.",
"code": "Unauthorized",
"details": "The access token you provided is revoked, malformed or invalid."
}
]
}
"""
At the same time, I checked this issue, but the amazon support team hasn't responded yet.
In addition, my seller account did not get access to PII when applying for MWS.
Now I want to ask three questions:
1, Is this situation related to my account not having access to PII?
2, Is the code running during my test correct?
3. Can you share the code you used when accessing buyer information in the sandbox environment?
Thank you very much.
I am getting an error for all endpoints where it saying that access to requested resource is denied and a code of unauthorized. I believe I have to assume a role as an IAM user along with the other variables in the .env file, but I don't see where I am supposed to do that?
I have a python version of the sp-api working with the same credentials but with the additional role_arn parameter being passed. any idea of what I have to do to authorize this with the php library?
On this Github page for the Selling Partner API docs: https://github.com/amzn/selling-partner-api-docs/blob/main/references/catalog-items-api/catalogItemsV0.md
there's an operation called: listCatalogCategories, that provides the parent-child category list associated with a product listing. I couldn't find the API call for this in your PHP library, can anyone assist?
Basically, I'm looking for a more descriptive subcategory name for the product listing other than what: getCatalogItem provides with the 'productTypes' dataset. it might be useful to get this category tree (complete with ids?) outside of the API, since it seems pretty fair to say the category tree isn't changed very often.
Thanks in advance for any help on this!
When requesting getAuthorizationCode method, I am getting this error!!
Client error: POST https://api.amazon.com/auth/o2/token
resulted in a 400 Bad Request
response: {"error_description":"The request is missing a required parameter : refresh_token","error":"invalid_request"}
Hi Jesse,
what is the license of this library? The license in composer.json is BSD-3-Clause but the provided license file is GPL.
Thanks for clarification :-)
Cheers,
Helge
Thanks for a very useful library!
Can you possibly add an option to insert proxy host, user and password on the configuration options (or somewhere else..), and have the GuzzleHttp\Client use them to make requests?
How to get a refresh token using spapi_oauth_code ?
When using dynamic user credentials, the library should not still try to load from the .env file.
Hi,
getOrderAddress() returns missing address fields. Am I missing something?
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new SellingPartnerApi\Api\OrdersApi();
$order_id = '204-*****'; // string | An Amazon-defined order identifier, in 3-7-7 format.
try {
$result = $apiInstance->getOrderAddress($order_id);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling OrdersApi->getOrderAddress: ', $e->getMessage(), PHP_EOL;
}
(
[container:protected] => Array
(
[payload] => SellingPartnerApi\Model\Orders\OrderAddress Object
(
[container:protected] => Array
(
[amazon_order_id] => *************************
[shipping_address] => SellingPartnerApi\Model\Orders\Address Object
(
[container:protected] => Array
(
[name] =>
[address_line1] =>
[address_line2] =>
[address_line3] =>
[city] => LONDON
[county] =>
[district] =>
[state_or_region] =>
[municipality] =>
[postal_code] => *** ***
[country_code] => GB
[phone] =>
[address_type] =>
)
)
)
)
[errors] =>
)
)```
Using v 3.0.7 (latest), I'm requesting a created GET_XML_BROWSE_TREE_DATA report, it gets created through:
\SellingPartnerApi\Api\ReportsApi->createReport(...)
the report document id is retrieved through
\SellingPartnerApi\Api\ReportsApi->getReport($report_id),
\SellingPartnerApi\Api\ReportsApi->getReportDocument(...) to get the document url,
and the raw contents is retrieved in Document->download(), but when it's run through:
$maybeZippedContents = openssl_decrypt($rawContents, static::ENCRYPTION_SCHEME, $this->key, OPENSSL_RAW_DATA, $this->iv);
it returns multiple blanks, but no XML.
Is this what you are getting? Pretty sure I'm following standard protocol.
NOTE: This is for GET_XML_BROWSE_TREE_DATA report type, it is working for GET_MERCHANT_LISTINGS_ALL_DATA.
I haven't tested any of the other report types.
Hello!
I need to search asins of brand...
In amazon docs is path GET /catalog/2020-12-01/items (https://github.com/amzn/selling-partner-api-docs/blob/main/references/catalog-items-api/catalogItems_2020-12-01.md#searchcatalogitems)
Can I do this search using your library?
Thank you.
What might be the cause for this error ?
Signature expired: 20210527T091025Z is now earlier than 20210527T093851Z (20210527T094351Z - 5 min.)
Got this error on getCatalogItem();
We're downloading a report with Report Type of GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL. It's a pretty big report that includes 30 days of order (the raw data is around 60mb).
Randomly we'll receive a "DecryptionFailedException" when our script reaches this:
$report = new Document($result->getPayload(), "text/tab-separated-values");
$contents = $report->download();
Here is the file/method throwing the exception:
Jsq\EncryptionStreams\AesDecryptingStream::decryptBlock
...\vendor\jsq\psr7-stream-encryption\src\AesDecryptingStream.php:127
Calling our script again every minute or so, it eventually gets past this and the data gets downloaded, but if we call our script again on the same Report ID, it could throw the exception again, or could download the data successfully - it's random and we have not been able to guarantee reproducing it.
When I create report, I got error:
[400] {
"errors": [
{
"message": "Invalid request body: [instance type (boolean) does not match any allowed primitive type (allowed: [\"string\"])]",
"code": "InvalidInput"
}
]
}
Here is my code:
$apiInstance = new ReportsApi($config);
$body = (new \SellingPartnerApi\Model\Reports\CreateReportSpecification())
->setReportType(ReportType::GET_XML_BROWSE_TREE_DATA['name'])
->setReportOptions(['RootNodesOnly' => true])
->setMarketplaceIds($shop->marketplace_id_list);
try {
$result = $apiInstance->createReport($body);
dd($result);
} catch (\Exception $e) {
dd($e->getMessage());
}
And here is request body(JSON format):
{"reportOptions":{"reportOptions":{"RootNodesOnly":true}},"reportType":"GET_XML_BROWSE_TREE_DATA","marketplaceIds":["A2EUQ1WTGCTBG2","A1AM78C64UM0Y8","A2Q3Y263D00KWC"]}
First, my seller account level is not Professional Selling Plan.
Second, I am sure that my configuration is correct, and the evidence is that the first example in Readme.md in this repo can be executed correctly and return the result.
Now I want ask:
Please help , thank you very much.
I can create a Feed Document
and a Feed
normally following the docs but when I try to get the same Feed Document I get this:
[400] {
"errors": [
{
"code": "InvalidInput",
"message": "Invalid feedDocumentId",
"details": ""
}
]
}
I'm using a feedDocumentId
like this: amzn1.tortuga.3.65fec908-9f33-491d-477c-b46b14e085c3.T1YH3BPIW9AFIP
(the same feedDocumetId returned from FeedsApi->createFeedDocument)
Here's my code:
const CONTENT_TYPE = "text/xml";
$feedsApi = new FeedsApi($config);
// Creating feedDocument
$createFeedDocSpec = new Feeds\CreateFeedDocumentSpecification(["content_type" => CONTENT_TYPE]);
$feedDocumentInfo = $feedsApi->createFeedDocument($createFeedDocSpec);
echo '<pre>';
print_r(json_encode($feedDocumentInfo->getPayload()->jsonSerialize()));
echo '</pre>';
echo '<hr>';
// Getting file data
$documentContents = file_get_contents("./files/Product.xsd");
// Sending file data to SP-API
$docToUpload = new SellingPartnerApi\Document($feedDocumentInfo->getPayload(), CONTENT_TYPE);
$uploaded = $docToUpload->upload($documentContents);
{
"feedDocumentId": "amzn1.tortuga.3.65fec908-9f33-491d-477c-b46b14e085c3.T1YH3BPIW9AFIP",
"url": "https://tortuga-prod-na.s3-external-1.amazonaws.com/%2FNinetyDays/amzn1.tortuga.3.65fec908-9f33-491d-477c-b46b14e085c3.T1YH3BPIW9AFIP?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210610T173945Z&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Expires=300&X-Amz-Credential=...%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=...",
"encryptionDetails": {
"standard": "AES",
"initializationVector": "kgSN8v...==",
"key": "dv7/WheiES4YT8...="
}
}
$api = new SellingPartnerApi\Api\FeedsApi($config);
$feed_document_id = 'amzn1.tortuga.3.65fec908-9f33-491d-477c-b46b14e085c3.T1YH3BPIW9AFIP';
try {
$result = $api->getFeedDocumentWithHttpInfo($feed_document_id);
echo '<pre>';
print_r($result);
echo '</pre>';
} catch (Exception $e) {
echo '<h2>Error:</h2> ';
echo '<pre>';
echo $e->getMessage();
echo '</pre>';
}
[400] {
"errors": [
{
"code": "InvalidInput",
"message": "Invalid feedDocumentId",
"details": ""
}
]
}
$api = new SellingPartnerApi\Api\FeedsApi($config);
$body = new \SellingPartnerApi\Model\Feeds\CreateFeedSpecification([
'feed_type' => 'POST_PRODUCT_PRICING_DATA',
'marketplace_ids' => ['A2Q3Y263D00KWC'], // Brazil
'input_feed_document_id' => 'amzn1.tortuga.3.65fec908-9f33-491d-477c-b46b14e085c3.T1YH3BPIW9AFIP',
'feed_options' => null,
]);
$result = $api->createFeed($body);
Hi Author,
Please share working example for uploading a feed document. I have download your example but I cannot upload feed document.
Is possible to get this x-amzn-RateLimit-Limit response header from the response?
It does not look like there is support for using the restricted data tokens, which starting in September will be required for quite a few API Calls.
Thank you for this great library!
I am uploading a price and quantity feed upload. The upload content-type is text-tab/separated-values
That works great, and now I'm trying to download the results using the recommended code.
//upload feed
$feed_id = 60619018758;
$api = new FeedsApi();
$feed = $api->getFeed($feed_id);
$feed_document_id = $feed->getPayload()->getResultFeedDocumentId();
$feed_document = $api->getFeedDocument($feed_document_id);
$docToDownload = new Document($feed_document->getPayload(), "text/tab-separated-values");
$contents = $docToDownload->download();
everything seems fine until the download step, which gives me the error:
ErrorException
Undefined offset: 1
at C:\myfiles\webserver\www\myproject\vendor\jlevers\selling-partner-api\lib\Document.php:92
88▕ $header = fgetcsv($bareStream, 0, $sep);
89▕ while (($line = fgetcsv($bareStream, 0, $sep)) !== false) {
90▕ $row = [];
91▕ foreach ($line as $idx => $val) {
➜ 92▕ $row[$header[$idx]] = $val;
93▕ }
94▕ $data[] = $row;
95▕ }
96▕ $this->data = $data;
If i change the line to text/csv
then I don't get an error. But the data still seems to be in tab format when doing a dump
$docToDownload = new Document($feed_document->getPayload(), "text/csv");
outputs on dump:
"""
Feed Processing Summary:\n
\tNumber of records processed\t\t31\n
\tNumber of records successful\t\t31\n
\n
"""
so there seems to be an issue in parsing tab delimited results possibly?
thanks!
getReports() method returns rawurlencode() expects parameter 1 to be string, object given.
Hello,
First thanks for this application. I've just started using it and it works great.
We have 350k+ listings on Amazon so some of the reports for us are very large. This app is causing memory errors when attempting to build the data structure. Can you add an argument so that $this->data is not built? I made a quick change to the Document.php file that works and would not affect anyone unless they also wanted only the raw data for the report. Feel free to use it or build something similar that is more in line with your coding structure. Thanks again!
public function download($rawOnly = false): string {
Then I put the following around the switch that builds the data.
if(!$rawOnly) { }
Hi, thank you for this repo.
I am getting a 403 response on a simple getmarketplaceparticipation request, although the selling partner API policy is attached to the rule on which my application is running.
anyhow, I can make a request using the Postman AWS signature method and I am getting valid responses so I am sure my credentials are correct.
any thoughts about this ?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.