### Initialize SDK and Get Catalog Item Source: https://github.com/amazon-php/sp-api-sdk/blob/7.x/README.md Example demonstrating the full initialization of the Selling Partner SDK, including setting up configuration for IAM User authentication, a logger, and then making a call to retrieve a catalog item. It includes basic error handling for API exceptions. ```php pushHandler(new StreamHandler(__DIR__ . '/sp-api-php.log', Logger::DEBUG)); $sdk = SellingPartnerSDK::create($client, $factory, $factory, $configuration, $logger); $accessToken = $sdk->oAuth()->exchangeRefreshToken('seller_oauth_refresh_token'); try { $item = $sdk->catalogItem()->getCatalogItem( $accessToken, Regions::NORTH_AMERICA, $asin = 'B07W13KJZC', $marketplaceId = [Marketplace::US()->id()] ); dump($item); } catch (ApiException $exception) { dump($exception->getMessage()); } ``` -------------------------------- ### Example IAM Policy for SP-API Access Source: https://github.com/amazon-php/sp-api-sdk/blob/7.x/README.md This JSON policy grants the necessary permissions for executing SP API actions. It allows the 'execute-api:Invoke' action on all resources, which is a broad permission recommended for initial setup. Ensure this policy is attached to the IAM user or role that will be making API calls. ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:*:*:*" } ] } ``` -------------------------------- ### Retrieve Financial Events using PHP SDK Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Access financial data from Amazon, including order payments, refunds, and fees, using the Selling Partner API SDK. This example demonstrates how to authenticate, fetch financial events within a specified date range, process shipment and refund data, and handle pagination. It includes error handling for API exceptions. ```php oAuth()->exchangeRefreshToken('seller-refresh-token'); // Dummy accessToken for example completeness $accessToken = 'YOUR_ACCESS_TOKEN'; // Get financial events for the last 30 days $postedAfter = (new \DateTime())->modify('-30 days')->format('c'); // Assuming $sdk is initialized and configured // $financialEvents = $sdk->financialEvents()->listFinancialEvents( // $accessToken, // Regions::NORTH_AMERICA, // null, // maxResultsPerPage // $postedAfter, // null, // postedBefore // null // nextToken // ); // Dummy response for example completeness echo "Fetching financial events..."; // $payload = $financialEvents->getPayload(); $payload = null; // Replace with actual payload processing // Process shipment events if ($payload && $payload->getFinancialEvents()) { $events = $payload->getFinancialEvents(); // Order payments if ($events->getShipmentEventList()) { foreach ($events->getShipmentEventList() as $shipmentEvent) { echo "Order: " . $shipmentEvent->getAmazonOrderId() . "\n"; echo "Posted Date: " . $shipmentEvent->getPostedDate() . "\n"; // Item charges and fees foreach ($shipmentEvent->getShipmentItemList() as $item) { echo " SKU: " . $item->getSellerSku() . "\n"; echo " Quantity: " . $item->getQuantityShipped() . "\n"; // Item price if ($item->getItemChargeList()) { foreach ($item->getItemChargeList() as $charge) { echo " Charge (" . $charge->getChargeType() . "): "; echo $charge->getChargeAmount()->getCurrencyAmount() . " "; echo $charge->getChargeAmount()->getCurrencyCode() . "\n"; } } // Item fees if ($item->getItemFeeList()) { foreach ($item->getItemFeeList() as $fee) { echo " Fee (" . $fee->getFeeType() . "): "; echo $fee->getFeeAmount()->getCurrencyAmount() . " "; echo $fee->getFeeAmount()->getCurrencyCode() . "\n"; } } } echo "---\n"; } } // Refund events if ($events->getRefundEventList()) { foreach ($events->getRefundEventList() as $refund) { echo "Refund for Order: " . $refund->getAmazonOrderId() . "\n"; echo "Posted Date: " . $refund->getPostedDate() . "\n"; } } } // Handle pagination if ($payload && $payload->getNextToken()) { $nextToken = $payload->getNextToken(); echo "Next token available for pagination: " . $nextToken . "\n"; // Use in next call to get more events } } catch (ApiException $e) { echo "Financial events error: " . $e->getMessage() . "\n"; } ?> ``` -------------------------------- ### Submit Feed to Update Inventory or Listings Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt This endpoint allows you to upload data to Amazon to update product listings, inventory quantities, prices, or perform other bulk operations. The example demonstrates submitting an inventory update feed using XML. ```APIDOC ## POST /feeds ### Description Upload data to Amazon to update product listings, inventory quantities, prices, or other bulk operations. ### Method POST ### Endpoint /feeds ### Parameters #### Query Parameters - **access_token** (string) - Required - The access token obtained via OAuth. - **region** (string) - Required - The AWS region to send the request to (e.g., 'northamerica'). #### Request Body - **feed_type** (string) - Required - The type of feed to create (e.g., 'POST_INVENTORY_AVAILABILITY_DATA'). - **marketplace_ids** (array) - Required - A list of marketplace IDs where the feed should be applied. - **input_feed_document_id** (string) - Required - The ID of the feed document that contains the feed content. ### Request Example ```php oAuth()->exchangeRefreshToken('seller-refresh-token'); // Prepare feed content (inventory update example in XML format) $feedContent = <<
1.01 YOUR_MERCHANT_ID
Inventory 1 Update MY-SKU-001 100 2
XML; // Create feed document to get upload destination $createDocSpec = new \AmazonPHP\SellingPartner\Model\Feeds\CreateFeedDocumentSpecification([ 'content_type' => 'text/xml; charset=UTF-8' ]); $feedDocument = $sdk->feeds()->createFeedDocument( $accessToken, Regions::NORTH_AMERICA, $createDocSpec ); $uploadUrl = $feedDocument->getUrl(); $feedDocumentId = $feedDocument->getFeedDocumentId(); // Upload feed content using cURL $ch = curl_init($uploadUrl); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $feedContent); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/xml; charset=UTF-8']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $uploadResult = curl_exec($ch); curl_close($ch); echo "Feed document uploaded\n"; // Create feed $feedSpec = new CreateFeedSpecification([ 'feed_type' => 'POST_INVENTORY_AVAILABILITY_DATA', 'marketplace_ids' => [Marketplace::US()->id()], 'input_feed_document_id' => $feedDocumentId, ]); $createFeedResponse = $sdk->feeds()->createFeed( $accessToken, Regions::NORTH_AMERICA, $feedSpec ); $feedId = $createFeedResponse->getFeedId(); echo "Feed submitted with ID: {$feedId}\n"; // Monitor feed processing status (example: wait for 60 seconds) sleep(60); $feedStatus = $sdk->feeds()->getFeed( $accessToken, Regions::NORTH_AMERICA, $feedId ); echo "Feed processing status: " . $feedStatus->getProcessingStatus() . "\n"; } catch (ApiException $e) { echo "Feed submission error: " . $e->getMessage() . "\n"; } ?> ``` ### Response #### Success Response (200) - **feedId** (string) - The ID of the submitted feed. - **processingStatus** (string) - The current processing status of the feed. #### Response Example ```json { "feedId": "9876543210", "processingStatus": "IN_QUEUE" } ``` ``` -------------------------------- ### Get FBA Inventory Summaries Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Retrieves Fulfilled by Amazon (FBA) inventory levels and status across fulfillment centers for a given marketplace. ```APIDOC ## GET /inventory/v1/summaries ### Description Retrieves Fulfilled by Amazon (FBA) inventory levels and status across fulfillment centers. This endpoint allows you to get a summary of your FBA inventory, including quantities like fulfillable, inbound, reserved, and unfulfillable. ### Method GET ### Endpoint /inventory/v1/summaries ### Parameters #### Query Parameters - **marketplaceIds** (string array) - Required - A list of Marketplace IDs for which to get inventory summaries. Example: `["ATVPDKIKX0DER"]` - **granularityType** (string) - Required - The granularity type for the inventory summary. Must be `Marketplace`. - **region** (string) - Required - The AWS region to which the request should be sent. Example: `"na-east-1"` - **startDateTime** (string) - Optional - The date and time after which to get inventory summaries. Format: ISO 8601. - **sellerSkus** (string array) - Optional - A list of SellerSKUs for which to get inventory summaries. - **nextToken** (string) - Optional - A token to retrieve the next page of inventory summaries. - **details** (boolean) - Optional - A flag indicating whether to include detailed inventory information. Defaults to `false`. ### Request Example ```php $accessToken = $sdk->oAuth()->exchangeRefreshToken('seller-refresh-token'); $inventoryResponse = $sdk->fbaInventory()->getInventorySummaries( $accessToken, Regions::NORTH_AMERICA, // e.g., Regions::NORTH_AMERICA true, // granularityType: Marketplace [Marketplace::US()->id()], // e.g., [Marketplace::US()->id()] null, // startDateTime null, // sellerSkus null, // nextToken null // details ); ``` ### Response #### Success Response (200) - **inventorySummaries** (array) - A list of inventory summaries. - **asin** (string) - The Amazon Standard Identification Number. - **sellerSku** (string) - The seller's SKU. - **fnSku** (string) - The Fulfillment Network Stock Keeping Unit. - **condition** (string) - The condition of the inventory item. - **totalQuantity** (integer) - The total quantity of the item in FBA inventory. - **inventoryDetails** (object) - Details about the inventory quantities. - **fulfillableQuantity** (integer) - Quantity that is fulfillable. - **inboundWorkingQuantity** (integer) - Quantity that is inbound and working. - **inboundShippedQuantity** (integer) - Quantity that is inbound and shipped. - **inboundReceivingQuantity** (integer) - Quantity that is inbound and receiving. - **reservedQuantity** (integer) - Quantity that is reserved. - **unfulfillableQuantity** (integer) - Quantity that is unfulfillable. - **nextToken** (string) - A token to retrieve the next page of results, if available. #### Response Example ```json { "inventorySummaries": [ { "asin": "B0EXAMPLE1", "sellerSku": "SKU123", "fnSku": "X00EXAMPLE1", "condition": "NewItem", "totalQuantity": 100, "inventoryDetails": { "fulfillableQuantity": 90, "inboundWorkingQuantity": 0, "inboundShippedQuantity": 0, "inboundReceivingQuantity": 10, "reservedQuantity": 0, "unfulfillableQuantity": 0 } } ], "nextToken": "someNextToken" } ``` #### Error Response (4xx/5xx) - **errors** (array) - A list of error responses. - **code** (string) - The error code. - **message** (string) - The error message. - **details** (string) - Additional details about the error. ``` -------------------------------- ### Get FBA Inventory Summaries (PHP) Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Retrieves Fulfilled by Amazon (FBA) inventory levels and status across specified fulfillment centers for a given region. This function requires an access token and supports filtering by marketplace, date, and seller SKUs. It returns detailed inventory information including quantities for fulfillable, inbound, reserved, and unfulfillable items, along with pagination tokens for large result sets. ```php oAuth()->exchangeRefreshToken('seller-refresh-token'); // Get FBA inventory summaries $inventoryResponse = $sdk->fbaInventory()->getInventorySummaries( $accessToken, Regions::NORTH_AMERICA, true, // granularityType: Marketplace [Marketplace::US()->id()], null, // startDateTime null, // sellerSkus null, // sellerSku null, // nextToken null // details ); $summaries = $inventoryResponse->getPayload(); if ($summaries && $summaries->getInventorySummaries()) { foreach ($summaries->getInventorySummaries() as $summary) { echo "ASIN: " . $summary->getAsin() . "\n"; echo "SKU: " . $summary->getSellerSku() . "\n"; echo "FNSKU: " . $summary->getFnSku() . "\n"; echo "Condition: " . $summary->getCondition() . "\n"; // Total quantity if ($summary->getTotalQuantity()) { echo "Total Quantity: " . $summary->getTotalQuantity() . "\n"; } // Inventory details if ($summary->getInventoryDetails()) { $details = $summary->getInventoryDetails(); echo "Fulfillable: " . ($details->getFulfillableQuantity() ?? 0) . "\n"; echo "Inbound Working: " . ($details->getInboundWorkingQuantity() ?? 0) . "\n"; echo "Inbound Shipped: " . ($details->getInboundShippedQuantity() ?? 0) . "\n"; echo "Inbound Receiving: " . ($details->getInboundReceivingQuantity() ?? 0) . "\n"; echo "Reserved: " . ($details->getReservedQuantity() ?? 0) . "\n"; echo "Unfulfillable: " . ($details->getUnfulfillableQuantity() ?? 0) . "\n"; } echo "---\n"; } // Pagination if ($summaries->getNextToken()) { $nextToken = $summaries->getNextToken(); // Use in next call } } } catch (ApiException $e) { echo "FBA Inventory error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Initialize PHP SDK with IAM Role Authentication Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Sets up the Selling Partner SDK using IAM Role authentication, the recommended method for production. It involves using an STSClient to assume an IAM role, obtaining temporary credentials, and then configuring the SDK with these credentials along with LWA client details. The code also demonstrates how to refresh credentials when they expire. ```php assumeRole( 'aws-access-key-id', 'aws-secret-access-key', 'arn:aws:iam::123456789012:role/YourSellingPartnerRole' ); // Configure SDK with IAM Role $configuration = Configuration::forIAMRole( 'your-lwa-client-id', 'your-lwa-client-secret', $roleCredentials ); // Create SDK instance $sdk = SellingPartnerSDK::create( $client, $factory, $factory, $configuration, new NullLogger() ); // Credentials can be refreshed when they expire $newCredentials = $stsClient->assumeRole( 'aws-access-key-id', 'aws-secret-access-key', 'arn:aws:iam::123456789012:role/YourSellingPartnerRole' ); $configuration->updateIAMRoleCredentials($newCredentials); ``` -------------------------------- ### Initialize PHP SDK with IAM User Authentication Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Configures and initializes the Selling Partner SDK using IAM User credentials. This method requires LWA client ID and secret, along with AWS access key ID and secret access key. It sets up PSR-compatible factories, an HTTP client, and a logger for API interactions. ```php pushHandler(new StreamHandler('./sp-api.log', Logger::DEBUG)); // Create SDK instance $sdk = SellingPartnerSDK::create( $client, $factory, $factory, $configuration, $logger ); // The SDK is now ready to use // Access any API through the facade methods $ordersApi = $sdk->orders(); $reportsApi = $sdk->reports(); $catalogApi = $sdk->catalogItem(); ``` -------------------------------- ### Enable Sandbox Mode for API Testing (PHP) Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Test your API integrations without impacting live data by enabling sandbox mode. This is achieved by calling the `$configuration->setSandbox()` method on your `Configuration` object before creating the `SellingPartnerSDK` instance. The SDK will then direct all API calls to sandbox endpoints instead of production ones. You can verify if sandbox mode is active using `$configuration->isSandbox()`. To return to production, call `$configuration->setProduction()` and create a new SDK instance. ```php setSandbox(); // Check if sandbox is enabled if ($configuration->isSandbox()) { echo "Running in sandbox mode\n"; } // Create SDK with sandbox configuration $sdk = SellingPartnerSDK::create( $client, $factory, $factory, $configuration, $logger ); // All API calls will now hit sandbox endpoints // Example: sellingpartnerapi-na.amazon.com becomes sandbox.sellingpartnerapi-na.amazon.com // Switch back to production $configuration->setProduction(); // Create a fresh SDK instance for production $productionSdk = SellingPartnerSDK::create( $client, $factory, $factory, $configuration, $logger ); ``` -------------------------------- ### Retrieve Catalog Item Information using PHP Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Fetches detailed product information from Amazon's catalog for a given ASIN. It requires an access token and specifies the region, ASIN, marketplaces, and the type of data to include (summaries, attributes, images, sales ranks). The output includes item details, images, and sales rank information, or an error message if the retrieval fails. ```php oAuth()->exchangeRefreshToken('seller-refresh-token'); // Get catalog item details for an ASIN $asin = 'B08N5WRWNW'; $catalogItem = $sdk->catalogItem()->getCatalogItem( $accessToken, Regions::NORTH_AMERICA, $asin, [Marketplace::US()->id()], ['summaries', 'attributes', 'images', 'salesRanks'], // includedData null // locale ); if ($catalogItem->getAsin()) { echo "ASIN: " . $catalogItem->getAsin() . "\n"; // Access summaries if ($catalogItem->getSummaries()) { foreach ($catalogItem->getSummaries() as $summary) { echo "Title: " . $summary->getItemName() . "\n"; echo "Brand: " . $summary->getBrand() . "\n"; echo "Marketplace: " . $summary->getMarketplaceId() . "\n"; } } // Access images if ($catalogItem->getImages()) { foreach ($catalogItem->getImages() as $imageSet) { foreach ($imageSet->getImages() as $image) { echo "Image URL: " . $image->getLink() . "\n"; } } } // Access sales ranks if ($catalogItem->getSalesRanks()) { foreach ($catalogItem->getSalesRanks() as $rankSet) { foreach ($rankSet->getDisplayGroupRanks() as $rank) { echo "Sales Rank: " . $rank->getRank() . " in " . $rank->getTitle() . "\n"; } } } } } catch (ApiException $e) { echo "Failed to retrieve catalog item: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Enable Sandbox Mode in PHP SDK Source: https://github.com/amazon-php/sp-api-sdk/blob/7.x/README.md Enable sandbox mode for the Selling Partner API SDK using the configuration object. This is useful for testing API interactions without affecting live data. Ensure your environment is set up with credentials via a .env file for functional tests. ```php $configuration->setSandbox(); ``` -------------------------------- ### Create and Monitor Reports using PHP Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Generates and monitors reports for extracting bulk data from Amazon, such as inventory or sales reports. It defines the report type, marketplace, and time range, requests report creation, and polls for completion. Upon successful completion, it downloads the report content to a local file. Handles errors during report generation. ```php oAuth()->exchangeRefreshToken('seller-refresh-token'); // Create report specification $reportSpec = new CreateReportSpecification([ 'report_type' => 'GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL', 'marketplace_ids' => [Marketplace::US()->id()], 'data_start_time' => (new \DateTime())->modify('-30 days')->format('c'), 'data_end_time' => (new \DateTime())->format('c'), ]); // Request report creation $createReportResponse = $sdk->reports()->createReport( $accessToken, Regions::NORTH_AMERICA, $reportSpec ); $reportId = $createReportResponse->getReportId(); echo "Report requested with ID: {$reportId}\n"; // Poll for report completion $maxAttempts = 30; $attempt = 0; while ($attempt < $maxAttempts) { sleep(30); // Wait 30 seconds between checks $reportStatus = $sdk->reports()->getReport( $accessToken, Regions::NORTH_AMERICA, $reportId ); $status = $reportStatus->getProcessingStatus(); echo "Report status: {$status}\n"; if ($status === 'DONE') { $documentId = $reportStatus->getReportDocumentId(); // Get document download information $document = $sdk->reports()->getReportDocument( $accessToken, Regions::NORTH_AMERICA, $documentId ); $downloadUrl = $document->getUrl(); // Download report content $reportContent = file_get_contents($downloadUrl); file_put_contents("./report_{$reportId}.csv", $reportContent); echo "Report downloaded successfully\n"; break; } elseif ($status === 'FATAL' || $status === 'CANCELLED') { echo "Report generation failed: {$status}\n"; break; } $attempt++; } } catch (ApiException $e) { echo "Report error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Configure Logging and PII Protection (PHP) Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Manages logging behavior for the Selling Partner API SDK, allowing control over log levels per API/operation and protection of sensitive information. This includes setting default and specific log levels, disabling logging for sensitive endpoints, and managing skipped headers. ```php setDefaultLogLevel(LogLevel::INFO); // Set specific log level for an API operation $configuration->setLogLevel( OrdersSDK::API_NAME, OrdersSDK::OPERATION_GETORDERS, LogLevel::DEBUG ); // Disable logging for specific API (useful for PII-sensitive endpoints) $configuration->setSkipLogging(TokensSDK::API_NAME); // Disable logging for specific operation only $configuration->setSkipLogging( OrdersSDK::API_NAME, OrdersSDK::OPERATION_GETORDER ); // Re-enable logging for specific API $configuration->setEnableLogging(TokensSDK::API_NAME); // Add custom sensitive header to ignore in logs $configuration->loggingAddSkippedHeader('x-custom-secret-key'); // Remove header from skip list $configuration->loggingRemoveSkippedHeader('x-custom-secret-key'); // Get list of headers currently skipped in logging $skippedHeaders = $configuration->loggingSkipHeaders(); // Default includes: 'authorization', 'x-amz-access-token', 'x-amz-security-token', etc. // Check if logging is enabled for specific API if ($configuration->loggingEnabled(OrdersSDK::API_NAME)) { echo "Orders API logging is enabled\n"; } ``` -------------------------------- ### Configure Logging and PII Protection Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Control the logging behavior of the SDK, including setting log levels for specific APIs or operations, and protecting Personally Identifiable Information (PII) from being logged. ```APIDOC ## SDK Configuration - Logging ### Description Configure logging behavior, set log levels per API/operation, and protect sensitive information from logs. ### Method SDK Configuration ### Endpoint N/A (SDK internal configuration) ### Parameters No direct API parameters, uses SDK configuration methods. ### Request Example ```php setDefaultLogLevel(LogLevel::INFO); // Set specific log level for an API operation $configuration->setLogLevel( OrdersSDK::API_NAME, OrdersSDK::OPERATION_GETORDERS, LogLevel::DEBUG ); // Disable logging for specific API (useful for PII-sensitive endpoints) $configuration->setSkipLogging(TokensSDK::API_NAME); // Disable logging for specific operation only $configuration->setSkipLogging( OrdersSDK::API_NAME, OrdersSDK::OPERATION_GETORDER ); // Re-enable logging for specific API $configuration->setEnableLogging(TokensSDK::API_NAME); // Add custom sensitive header to ignore in logs $configuration->loggingAddSkippedHeader('x-custom-secret-key'); // Remove header from skip list $configuration->loggingRemoveSkippedHeader('x-custom-secret-key'); // Get list of headers currently skipped in logging $skippedHeaders = $configuration->loggingSkipHeaders(); // Default includes: 'authorization', 'x-amz-access-token', 'x-amz-security-token', etc. // Check if logging is enabled for specific API if ($configuration->loggingEnabled(OrdersSDK::API_NAME)) { echo "Orders API logging is enabled\n"; } ?> ``` ### Response N/A (SDK configuration changes affect internal behavior, not direct API responses). #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Generate SDK Code Source: https://github.com/amazon-php/sp-api-sdk/blob/7.x/README.md Command to regenerate the PHP SDK code, typically used when API definitions change. This process leverages OpenAPI Generator and subsequent upgrades by RectorPHP and code standardization by PHP CS Fixer. ```bash composer generate ``` -------------------------------- ### Retrieve Orders from Amazon (PHP) Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Fetches order information from Amazon for a specified marketplace and time range using the SP-API. This function requires a valid access token and retrieves orders created within the last seven days by default. It iterates through the retrieved orders, displaying key details such as Order ID, status, total amount, and buyer email, and includes logic for handling pagination to retrieve subsequent pages of results. API and HTTP client exceptions are also managed. ```php oAuth()->exchangeRefreshToken('seller-refresh-token'); // Get orders created in the last 7 days $createdAfter = (new \DateTime())->modify('-7 days')->format('c'); $ordersResponse = $sdk->orders()->getOrders( $accessToken, Regions::NORTH_AMERICA, [Marketplace::US()->id()], $createdAfter, null, // createdBefore null, // lastUpdatedAfter null, // lastUpdatedBefore null, // orderStatuses null, // fulfillmentChannels null, // paymentMethods null, // buyerEmail null, // sellerOrderId null, // maxResultsPerPage null, // easyShipShipmentStatuses null, // electronicInvoiceStatuses null, // nextToken null, // amazonOrderIds null, // actualFulfillmentSupplySourceId null, // isISPU null // storeChainStoreId ); if ($ordersResponse->getPayload()) { $orders = $ordersResponse->getPayload()->getOrders(); foreach ($orders as $order) { echo "Order ID: " . $order->getAmazonOrderId() . "\n"; echo "Status: " . $order->getOrderStatus() . "\n"; echo "Total: " . $order->getOrderTotal()->getAmount() . " " . $order->getOrderTotal()->getCurrencyCode() . "\n"; echo "Buyer: " . $order->getBuyerInfo()?->getBuyerEmail() . "\n"; echo "---\n"; } // Handle pagination if ($ordersResponse->getPayload()->getNextToken()) { $nextToken = $ordersResponse->getPayload()->getNextToken(); // Use $nextToken in subsequent call to get next page } } } catch (ApiException $e) { echo "API Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Manage Marketplaces and Regions in PHP Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Use helper classes to identify and utilize Amazon marketplaces and regions for API calls. This avoids hardcoding marketplace IDs and provides easy access to marketplace details like ID, region, name, country code, and Seller Central URL. It also demonstrates how to retrieve all available marketplaces and validate region identifiers. ```php id() . "\n"; // ATVPDKIKX0DER echo "US Region: " . $usMarketplace->region() . "\n"; // us-east-1 echo "US Name: " . $usMarketplace->name() . "\n"; // United States of America echo "US Country Code: " . $usMarketplace->countryCode() . "\n"; // US echo "Seller Central URL: " . $usMarketplace->sellerCentralUrl() . "\n"; // Get marketplace from country code string $marketplace = Marketplace::fromCountry('CA'); // Canada echo "Canada ID: " . $marketplace->id() . "\n"; // A2EUQ1WTGCTBG2 // Get marketplace from marketplace ID $marketplace = Marketplace::fromId('A1PA6795UKMFR9'); // Germany echo "Country: " . $marketplace->countryCode() . "\n"; // DE // Get all available marketplaces $allMarketplaces = Marketplace::all(); foreach ($allMarketplaces as $mp) { echo "{$mp->name()} ({$mp->countryCode()}): {$mp->id()}\n"; } // Use regions in API calls $region = Regions::NORTH_AMERICA; // us-east-1 $region = Regions::EUROPE; // eu-west-1 $region = Regions::FAR_EAST; // us-west-2 // Validate region if (Regions::isValid($region)) { echo "Valid region: {$region}\n"; } // Make API call with marketplace and region // Assuming $sdk, $accessToken, and $createdAfter are defined elsewhere /* $orders = $sdk->orders()->getOrders( $accessToken, Regions::NORTH_AMERICA, [Marketplace::US()->id(), Marketplace::CA()->id()], // Multiple marketplaces $createdAfter ); */ ``` -------------------------------- ### Register Custom Extensions for API Request Hooks (PHP) Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Implement custom logic to execute before and after each API request by creating a class that implements the `Extension` interface. This allows for functionalities like monitoring, custom logging, or rate limit tracking. The `preRequest` method can be used to modify requests or add headers (though modifications won't affect the actual request), while `postRequest` can process responses, extract information like rate limits from headers, and trigger alerts if rate limits are exceeded. Register the custom extension using `$configuration->registerExtension($instance);`. ```php getUri() . "\n"; // Add custom headers or modify request // Note: Request modifications won't affect the actual request } public function postRequest( string $api, string $operation, RequestInterface $request, ResponseInterface $response ): void { $statusCode = $response->getStatusCode(); // Extract rate limit information from response headers $rateLimit = $response->getHeader('x-amzn-RateLimit-Limit'); $rateLimitHeader = !empty($rateLimit) ? $rateLimit[0] : 'N/A'; echo "[POST] {$api}::{$operation} completed\n"; echo "[POST] Status: {$statusCode}\n"; echo "[POST] Rate Limit: {$rateLimitHeader}\n"; // Store rate limit info for monitoring $this->rateLimits["{$api}::{$operation}"] = [ 'limit' => $rateLimitHeader, 'timestamp' => time(), ]; // Alert if rate limited if ($statusCode === 429) { echo "[WARNING] Rate limit exceeded for {$api}::{$operation}\n"; } } public function getRateLimits(): array { return $this->rateLimits; } } // Register extension with configuration $rateLimitMonitor = new RateLimitMonitor(); $configuration->registerExtension($rateLimitMonitor); // Now all API calls will trigger the extension hooks $accessToken = $sdk->oAuth()->exchangeRefreshToken('seller-refresh-token'); $ordersResponse = $sdk->orders()->getOrders( $accessToken, Regions::NORTH_AMERICA, [Marketplace::US()->id()], (new \DateTime())->modify('-7 days')->format('c') ); // Check collected rate limit information $rateLimits = $rateLimitMonitor->getRateLimits(); print_r($rateLimits); ``` -------------------------------- ### Submit Feed to Update Inventory/Listings (PHP) Source: https://context7.com/amazon-php/sp-api-sdk/llms.txt Uploads data to Amazon to update product listings, inventory quantities, prices, or other bulk operations using XML feeds. It involves creating a feed document, uploading content via cURL, and then submitting the feed for processing. ```php oAuth()->exchangeRefreshToken('seller-refresh-token'); // Prepare feed content (inventory update example in XML format) $feedContent = <<
1.01 YOUR_MERCHANT_ID
Inventory 1 Update MY-SKU-001 100 2
XML; // Create feed document to get upload destination $createDocSpec = new \AmazonPHP\SellingPartner\Model\Feeds\CreateFeedDocumentSpecification([ 'content_type' => 'text/xml; charset=UTF-8' ]); $feedDocument = $sdk->feeds()->createFeedDocument( $accessToken, Regions::NORTH_AMERICA, $createDocSpec ); $uploadUrl = $feedDocument->getUrl(); $feedDocumentId = $feedDocument->getFeedDocumentId(); // Upload feed content $ch = curl_init($uploadUrl); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $feedContent); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/xml; charset=UTF-8']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $uploadResult = curl_exec($ch); curl_close($ch); echo "Feed document uploaded\n"; // Create feed $feedSpec = new CreateFeedSpecification([ 'feed_type' => 'POST_INVENTORY_AVAILABILITY_DATA', 'marketplace_ids' => [Marketplace::US()->id()], 'input_feed_document_id' => $feedDocumentId, ]); $createFeedResponse = $sdk->feeds()->createFeed( $accessToken, Regions::NORTH_AMERICA, $feedSpec ); $feedId = $createFeedResponse->getFeedId(); echo "Feed submitted with ID: {$feedId}\n"; // Monitor feed processing status sleep(60); $feedStatus = $sdk->feeds()->getFeed( $accessToken, Regions::NORTH_AMERICA, $feedId ); echo "Feed processing status: " . $feedStatus->getProcessingStatus() . "\n"; } catch (ApiException $e) { echo "Feed submission error: " . $e->getMessage() . "\n"; } ```