PHP Selling Partner API Fluent SDK

website·Indexed 29 days ago

https://phpspa.com/

A PHP package providing a fluent interface for interacting with the Amazon Selling Partner API. The SDK supports various resources including Feeds, Notifications, and Fulfillment Inbound, and requires PHP ^8.0. It includes built-in handling for authentication, authorization of seller accounts, and data transfer objects for Amazon's response schemas.

Tokens
5.2K
Snippets
25
Records
34
Agent score
50%

What's inside PHP Selling Partner API Fluent SDK

  1. Overview of the PHP Selling Partner API Fluent SDK

    The PHP Selling Partner API Fluent SDK provides a fluent interface for interacting with the Amazon Selling Partner API, designed to simplify the development experience. For users of the Laravel framework, a dedicated Laravel-specific wrapper is available. Note that a commercial license is required if your worldwide annual revenue exceeds $100,000.
  2. Retrieve a notification subscription

    Use the getSubscription method to retrieve details about a specific notification subscription based on the notification type. The response is returned as a GetSubscriptionResponse DTO from the Jasara\AmznSPA\DataTransferObjects\Responses\Notifications namespace.
    $response = $spa->notifications->getSubscription($notification_type); // Returns GetSubscriptionResponse
  3. Understand the InboundShipmentPlan response schema

    The InboundShipmentPlan schema provides detailed information about a shipment plan created via the createInboundShipmentPlan operation. It includes the shipment identifier, the destination fulfillment center, shipping address, label preparation requirements, and a list of items with their respective SKUs and quantities. It also details the estimated box contents fees.
    {
      "inbound_shipment_plans": [
        {
          "shipment_id": "FBA123ABC123",
          "destination_fulfillment_center_id": "AVP1",
          "ship_to_address": {
            "name": "ACME Inc.",
            "address_line_1": "123 Sample St",
            "address_line_2": "Suite B",
            "district_or_county": "Wise County",
            "city": "New York",
            "state_or_province_code": "NY",
            "country_code": "US",
            "postal_code": "21221"
          },
          "label_prep_type": "SELLER_LABEL",
          "items": [
            {
              "seller_sku": "CR-ABC-1234",
              "fulfillment_network_sku": "X00ABC123ABC",
              "quantity": 12,
              "prep_details_list": []
            }
          ],
          "estimated_box_contents_fee": {
            "total_units": 12,
            "fee_per_unit": {
              "currency_code": "USD",
              "value": "100.00"
            }
          }
        }
      ]
    }
  4. Process API errors with ErrorListSchema

    The errors property of a response DTO is an ErrorListSchema, which is a collection of ErrorSchema objects. Because it is a collection, you can use standard Laravel collection methods (like first() or where()) or access errors via array indices.
    $subscription = $spa->notifications->getSubscription($notification_type);
    $errors = $subscription->errors; // ErrorListSchema
    
    // Get the first error
    $first_error = $subscription->errors->first(); // ErrorSchema
    // OR access via index
    $first_error = $subscription->errors[0];
    
    // Filter for a specific error code
    $invalid_client_error = $subscription->errors->where('code', 'invalid_client')->first();
  5. AddressSchema requirements for Fulfillment Inbound

    The AddressSchema is used to define the origin of an inbound shipment. The following fields are required: name (max 50), address_line_1 (max 180), city (max 30), state_or_province_code, country_code (2-character ISO 3166-1 alpha-2), and postal_code (max 30). Optional fields include address_line_2 (max 60) and district_or_county (max 25).
  6. Authorize a Seller account using Self-Authorization

    Self-authorization is the simplest method for applications that only interact with the developer's own Seller account. You must first generate an LWA refresh token following Amazon's developer guide. When providing the lwa_refresh_token in the AmznSPAConfig, the library automatically handles the generation of access tokens and adds the required signing and authentication headers to requests.
    use Jasara\AmznSPA\AmznSPA;
    use Jasara\AmznSPA\AmznSPAConfig;
    
    $config = new AmznSPAConfig(
        // ...
        lwa_refresh_token: 'Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSREXAMPLE',
    );
    
    $spa = new AmznSPA($config);
    $items = $spa->catalog_items->getCatalogItem(
        asin: 'B0020MLK00',
        marketplace_ids: ['ATVPDKIKX0DER'],
        included_data: ['images'],
    );
    
    // Retrieve the latest access token to cache for the next hour
    $lwa_access_token = $spa->getAccessToken();
  7. Generate an Amazon OAuth authorization URL

    For applications requiring authorization from third-party Sellers, use the getAuthUrl method. This generates the URL where the Seller can initiate the authorization process. You must provide a redirect_url and a state string (used to verify the redirect request later).
    $config = new AmznSPAConfig(
        // ...
        marketplace_id: 'ATVPDKIKX0DER',
        application_id: 'amzn1.sellerapps.app.0bf291215-36a6-2311-b533-EXAMPLEfcd28',
    );
    
    $redirect_uri = 'https://app.yourcompany.com/oauth/amazon/redirect';
    $state = randomString(); // Generate a unique state to verify the redirect
    
    $spa = new AmznSPA($config);
    $oauth_url = $spa->lwa->getAuthUrl($redirect_url, $state);
  8. Install php-amzn-selling-partner-api via Composer

    To use the Amazon Selling Partner API PHP library, ensure your environment meets the requirement of PHP version ^8.0. Install the package using Composer by requiring jasara/php-amzn-selling-partner-api.
    composer require jasara/php-amzn-selling-partner-api
  9. Exchange OAuth redirect parameters for access tokens

    After a Seller authorizes the application, Amazon redirects them back to your specified URL with authorization parameters. Use getTokensFromRedirect to exchange the spapi_oauth_code for a set of tokens. You should persist the refresh_token, selling_partner_id, and mws_auth_token (if applicable) to your database.
    $params = [
        'state' => $_GET['state'],
        'selling_partner_id' => $_GET['selling_partner_id'],
        'mws_auth_token' => $_GET['mws_auth_token'], // Required for hybrid applications
        'spapi_oauth_code' => $_GET['spapi_oauth_code'],
    ];
    
    $config = new AmznSPAConfig(
        // ...
        lwa_client_secret: 'Y76SDl2F',
        lwa_client_id: 'foodev',
    );
    
    $spa = new AmznSPA($config);
    $tokens = $spa->lwa->getTokensFromRedirect($original_state, $params);
    
    // $tokens is an instance of AuthTokensDTO
    $refresh_token = $tokens->refresh_token;
    $access_token = $tokens->access_token;
    $expires_at = $tokens->expires_at; // CarbonImmutable instance
  10. Migrate MWS clients to Selling Partner API by exchanging MWS tokens

    To migrate existing MWS clients to the Selling Partner API, you must exchange a valid MWS authorization token for an SP-API authorization code, and then exchange that code for a permanent LWA refresh token. This process allows you to transition clients without requiring them to re-authorize manually.
    use Jasara\AmznSPA\AmznSPAConfig;
    use Jasara\AmznSPA\AmznSPA;
    
    // 1. Initialize configuration with LWA and AWS credentials
    $config = new AmznSPAConfig(
        marketplace_id: $marketplace_id,
        application_id: $application_keys->application_id,
        aws_access_key: $application_keys->aws_access_key,
        aws_secret_key: $application_keys->aws_secret_key,
        lwa_client_id: $application_keys->lwa_client_id,
        lwa_client_secret: $application_keys->lwa_client_secret,
    );
    
    $spa = new AmznSPA($config);
    
    // 2. Exchange the MWS auth token for an SP-API authorization code
    $auth_code_response = $spa->authorization->getAuthorizationCodeFromMwsToken(
        seller_id: $client->merchant_id,
        mws_auth_token: $client->mws_auth_token,
        developer_id: $mws_developer_id,
    );
    
    // 3. Immediately exchange the authorization code for LWA tokens
    $auth_tokens = $spa->lwa->getTokensFromAuthorizationCode($auth_code_response->payload->authorization_code);
    
    // 4. Store the refresh token in permanent storage for future API calls
    $refresh_token = $auth_tokens->refresh_token;
  11. Handle Amazon API responses using Data Transfer Objects

    Endpoint methods return a typed Data Transfer Object (DTO) containing the response from Amazon. These DTOs typically contain two root keys: payload (the successful response data) and errors (an ErrorListSchema). DTOs provide type safety and can be converted to arrays using the toArray() method.
    $subscription = $spa->notifications->getSubscription($notification_type); // Returns GetSubscriptionResponse DTO
    $payload = $subscription->payload; // SubscriptionSchema
    $errors = $subscription->errors; // ErrorListSchema
    
    // Access specific data
    $subscription_id = $subscription->payload->subscription_id; // string
    
    // Convert to array
    $array = $subscription->toArray();
  12. Authenticate requests using AmznSPAConfig

    The AmznSPA library automatically handles signing and authentication headers. To authenticate, provide an AmznSPAConfig object containing the marketplace_id, application_id, and LWA tokens. If both lwa_access_token and lwa_refresh_token are provided, the library will automatically generate a new access token when the current one expires (typically after one hour).
    use Jasara\AmznSPA\AmznSPA;
    use Jasara\AmznSPA\AmznSPAConfig;
    
    $config = new AmznSPAConfig(
        marketplace_id: 'ATVPDKIKX0DER',
        lwa_refresh_token: 'Atza|AhRmHjNgHpi0U-DmIQR6CuUpSREBLjAse37rEXAMPLE',  // Optional if access token is provided and still active
        lwa_access_token: 'Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSREXAMPLE',
        application_id: 'amzn1.sellerapps.app.example-123456',
    );
    
    $spa = new AmznSPA($config);
    
    // Example request
    $items = $spa->catalog_items->getCatalogItem(
        asin: 'B0020MLK00',
        marketplace_ids: ['ATVPDKIKX0DER'],
        included_data: ['images'],
    );