Giter Club home page Giter Club logo

selling-partner-api's Introduction

Selling Partner API for PHP

A PHP library for connecting to Amazon's Selling Partner API.

Sponsors

Powering companies like...


If you've found this library useful, please consider becoming a Sponsor, or making a one-time donation via the button below. I appreciate any and all support you can provide!

paypal

Features

  • Supports all Selling Partner API operations (for Sellers and Vendors) as of 7/2/2021 (see here for links to documentation for all calls)
  • Supports applications made with both IAM user and IAM role ARNs (docs)
  • Automatically generates Restricted Data Tokens for all calls that require them -- no extra calls to the Tokens API needed
  • Includes a Document helper class for uploading and downloading feed/report documents

Installation

composer require jlevers/selling-partner-api

Getting Started

Prerequisites

You need a few things to get started:

  • A Selling Partner API developer account
  • An AWS IAM user or role configured for use with the Selling Partner API
  • A Selling Partner API application

If you're looking for more information on how to set those things up, check out this blog post. It provides a detailed walkthrough of the whole setup process.

Setup

The Configuration constructor takes a single argument: an associative array with all the configuration information that's needed to connect to the Selling Partner API:

$config = new SellingPartnerApi\Configuration([
    "lwaClientId" => "<LWA client ID>",
    "lwaClientSecret" => "<LWA client secret>",
    "lwaRefreshToken" => "<LWA refresh token>",
    "awsAccessKeyId" => "<AWS access key ID>",
    "awsSecretAccessKey" => "<AWS secret access key>",
    // If you're not working in the North American marketplace, change
    // this to another endpoint from lib/Endpoint.php
    "endpoint" => SellingPartnerApi\Endpoint::NA,
]);

If you created your Selling Partner API application using an IAM role ARN instead of a user ARN, pass that role ARN in the configuration array:

$config = new SellingPartnerApi\Configuration([
    "lwaClientId" => "<LWA client ID>",
    "lwaClientSecret" => "<LWA client secret>",
    "lwaRefreshToken" => "<LWA refresh token>",
    "awsAccessKeyId" => "<AWS access key ID>",
    "awsSecretAccessKey" => "<AWS secret access key>",
    // If you're not working in the North American marketplace, change
    // this to another endpoint from lib/Endpoint.php
    "endpoint" => SellingPartnerApi\Endpoint::NA,
    "roleArn" => "<Role ARN>",
]);

$config can then be passed into the constructor of any SellingPartnerApi\Api\*Api class. See the Example section for a complete example.

Configuration options

The array passed to the Configuration constructor accepts the following keys:

  • lwaClientId (string): Required. The LWA client ID of the SP API application to use to execute API requests.
  • lwaClientSecret (string): Required. The LWA client secret of the SP API application to use to execute API requests.
  • lwaRefreshToken (string): The LWA refresh token of the SP API application to use to execute API requests. Required, unless you're only using the Configuration instance to call grantless operations.
  • awsAccessKeyId (string): Required. AWS IAM user Access Key ID with SP API ExecuteAPI permissions.
  • awsSecretAccessKey (string): Required. AWS IAM user Secret Access Key with SP API ExecuteAPI permissions.
  • endpoint (array): Required. An array containing a url key (the endpoint URL) and a region key (the AWS region). There are predefined constants for these arrays in lib/Endpoint.php: (NA, EU, FE, and NA_SANDBOX, EU_SANDBOX, and FE_SANDBOX. See here for more details.
  • accessToken (string): An access token generated from the refresh token.
  • accessTokenExpiration (int): A Unix timestamp corresponding to the time when the accessToken expires. If accessToken is given, accessTokenExpiration is required (and vice versa).
  • onUpdateCredentials (callable|Closure): A callback function to call when a new access token is generated. The function should accept a single argument of type SellingPartnerApi\Credentials.
  • roleArn (string): If you set up your SP API application with an AWS IAM role ARN instead of a user ARN, pass that ARN here.

Example

This example assumes you have access to the Seller Insights Selling Partner API role, but the general format applies to any Selling Partner API request.

<?php
require_once(__DIR__ . '/vendor/autoload.php');

use SellingPartnerApi\Api;
use SellingPartnerApi\Configuration;
use SellingPartnerApi\Endpoint;

$config = new Configuration([
    "lwaClientId" => "amzn1.application-oa2-client.....",
    "lwaClientSecret" => "abcd....",
    "lwaRefreshToken" => "Aztr|IwEBI....",
    "awsAccessKeyId" => "AKIA....",
    "awsSecretAccessKey" => "ABCD....",
    // If you're not working in the North American marketplace, change
    // this to another endpoint from lib/Endpoint.php
    "endpoint" => Endpoint::NA
]);

$api = new Api\SellersApi($config);
try {
    $result = $api->getMarketplaceParticipations();
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling SellersApi->getMarketplaceParticipations: ', $e->getMessage(), PHP_EOL;
}

?>

Supported API segments

Seller APIs

Vendor APIs

Uploading and downloading documents

The Feeds and Reports APIs include operations that involve uploading and downloading documents to and from Amazon. Amazon encrypts all documents they generate, and requires that all uploaded documents be encrypted. The SellingPartnerApi\Document class handles all the encryption/decryption, given an instance of one of the Model\Reports\ReportDocument, Model\Feeds\FeedDocument, or Model\Feeds\CreateFeedDocumentResponse classes. Instances of those classes are in the response returned by Amazon when you make a call to the getReportDocument, getFeedDocument, and createFeedDocument endpoints, respectively.

Downloading a report document

use SellingPartnerApi\Api\ReportsApi;
use SellingPartnerApi\ReportType;

// Assume we've already fetched a report document ID, and that a $config object was defined above
$documentId = 'foo.1234';
$reportType = ReportType::GET_FLAT_FILE_OPEN_LISTINGS_DATA;

$reportsApi = new ReportsApi($config);
$reportDocumentInfo = $reportsApi->getReportDocument($documentId, $reportType['name']);

$docToDownload = new SellingPartnerApi\Document($reportDocumentInfo, $reportType);
$contents = $docToDownload->download();  // The raw report text
/*
 * - Array of associative arrays, (each sub array corresponds to a row of the report) if content type is ContentType::TAB or ContentType::CSV
 * - A nested associative array (from json_decode) if content type is ContentType::JSON
 * - The raw report data if content type is ContentType::PLAIN or ContentType::PDF
 * - PHPOffice Spreadsheet object if content type is ContentType::XLSX
 * - SimpleXML object if the content type is ContentType::XML
 */
$data = $docToDownload->getData();
// ... do something with report data

Uploading a feed document

use SellingPartnerApi\Api\FeedsApi;
use SellingPartnerApi\FeedType;
use SellingPartnerApi\Model\Feeds;

$feedType = FeedType::POST_PRODUCT_PRICING_DATA;
$feedsApi = new FeedsApi($config);

// Create feed document
$createFeedDocSpec = new Feeds\CreateFeedDocumentSpecification(['content_type' => $feedType['contentType']]);
$feedDocumentInfo = $feedsApi->createFeedDocument($createFeedDocSpec);
$feedDocumentId = $feedDocumentInfo->getFeedDocumentId();

// Upload feed contents to document
$feedContents = file_get_contents('<your/feed/file.xml>');
$docToUpload = new SellingPartnerApi\Document($feedDocumentInfo, $feedType);
$docToUpload->upload($feedContents);

// ... call FeedsApi::createFeed() with $feedDocumentId

Models

Most operations have one or more models associated with it. These models are classes that contain the data needed to make a certain kind of request to the API, or contain the data returned by a given request type. All of the models share the same general interface: you can either specify all the model's attributes during initialization, or use setter methods to set each attribute after the fact. Here's an example using the Service API's Buyer model (docs, (source).

The Buyer model has four attributes: buyer_id, name, phone, and is_prime_member. (If you're wondering how you would figure out which attributes the model has on your own, check out the docs link above.) To create an instance of the Buyer model with all those attributes set:

$buyer = new SellingPartnerApi\Model\Service\Buyer([
    "buyer_id" => "ABCDEFGHIJKLMNOPQRSTU0123456",
    "name" => "Jane Doe",
    "phone" => "+12345678901",
    "is_prime_member" => true
]);

Alternatively, you can create an instance of the Buyer model and then populate its fields:

$buyer = new SellingPartnerApi\Model\Service\Buyer();
$buyer->setBuyerId("ABCDEFGHIJKLMNOPQRSTU0123456");
$buyer->setName("Jane Doe");
$buyer->setPhone("+12345678901");
$buyer->setIsPrimeMember(true);

Each model also has the getter methods you might expect:

$buyer->getBuyerId();        // -> "ABCDEFGHIJKLMNOPQRSTU0123456"
$buyer->getName();           // -> "Jane Doe"
$buyer->getPhone();          // -> "+12345678901"
$buyer->getIsPrimeMember();  // -> true

Models can (and usually do) have other models as attributes:

$serviceJob = new SellingPartnerApi\Model\Service\Buyer([
    // ...
    "buyer" => $buyer,
    // ...
]);

$serviceJob->getBuyer();             // -> [Buyer instance]
$serviceJob->getBuyer()->getName();  // -> "Jane Doe"

selling-partner-api's People

Contributors

jlevers avatar cpiggott avatar deyvidholz avatar pkiman avatar nilanth avatar ivaaaan avatar ludofloria avatar denisneuf avatar

Stargazers

Roman avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.