PHP code example of rajpurohithitesh / amazon-paapi5-php-sdk

1. Go to this page and download the library: Download rajpurohithitesh/amazon-paapi5-php-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rajpurohithitesh / amazon-paapi5-php-sdk example snippets





use AmazonPaapi5\Config;

// All available configuration options with explanations:
$sdkConfig = [
    // REQUIRED: Your Amazon PAAPI Access Key.
    'access_key' => '<YOUR_ACCESS_KEY>',

    // REQUIRED: Your Amazon PAAPI Secret Key.
    'secret_key' => '<YOUR_SECRET_KEY>',

    // REQUIRED: Your Amazon Associates Partner Tag for the target marketplace.
    'partner_tag' => '<YOUR_PARTNER_TAG>',

    // REQUIRED: The Amazon marketplace you are targeting (e.g., 'www.amazon.com', 'www.amazon.co.uk').
    // This determines the API endpoint and region.
    'marketplace' => 'www.amazon.com', // Example: US marketplace

    // REQUIRED (derived from marketplace, but good to understand): The AWS region for the PAAPI endpoint.
    // The SDK can often determine this from the marketplace, but you can be explicit.
    // See `AmazonPaapi5\Marketplace` for mappings or refer to Amazon's documentation.
    'region' => 'us-east-1', // Example: Region for www.amazon.com

    // OPTIONAL but STRONGLY RECOMMENDED for security:
    // A secret key (at least 16 characters long, ideally 32) used to encrypt your
    // Access Key and Secret Key if they are stored. If not provided or empty,
    // credentials will be used directly without an extra layer of SDK-managed encryption.
    // For production, generate a strong, unique key and store it securely (e.g., env variable).
    'encryption_key' => '<YOUR_STRONG_ENCRYPTION_KEY_32_CHARS>',

    // OPTIONAL: Directory for the built-in file cache.
    // Defaults to the system's temporary directory (e.g., /tmp/amazon-paapi5-cache).
    'cache_dir' => sys_get_temp_dir() . '/my-app-amazon-cache',

    // OPTIONAL: Cache Time-To-Live in seconds for API responses.
    // Defaults to 3600 seconds (1 hour).
    'cache_ttl' => 7200, // Example: 2 hours

    // OPTIONAL: Delay in seconds between consecutive API requests to manage throttling.
    // Amazon's default limit is 1 request per second (TPS) per account.
    // Adjust based on your account's TPS limit. Defaults to 1.0 second.
    'throttle_delay' => 1.5, // Example: 1.5 seconds

    // OPTIONAL: Maximum number of retries for failed requests (e.g., due to throttling).
    // Defaults to 3. (Note: Retry logic might need custom implementation around the client call)
    'max_retries' => 3,
];

try {
    $config = new Config($sdkConfig);
} catch (\AmazonPaapi5\Exceptions\ConfigException $e) {
    // Handle missing or invalid 

// Basic configuration - SDK automatically chooses best encryption method
$sdkConfig = [
    'access_key' => 'YOUR_AWS_ACCESS_KEY',
    'secret_key' => 'YOUR_AWS_SECRET_KEY',
    'partner_tag' => 'YOUR_PARTNER_TAG',
    'marketplace' => 'www.amazon.com',
    'encryption_key' => getenv('AMAZON_SDK_ENCRYPTION_KEY') ?: 'your-secure-32-char-key-here-123456',
];

$config = new Config($sdkConfig);
$credentialManager = new CredentialManager($config);

// Check active encryption method
echo "Using encryption: " . $credentialManager->getActiveEncryptionMethod() . "\n";

// Get detailed system information
$systemInfo = $credentialManager->getSystemInfo();
print_r($systemInfo);


use AmazonPaapi5\Client;
use AmazonPaapi5\Config;
// Assuming $config is already initialized as shown above

// Basic client initialization
$client = new Client($config);

// Client with a custom PSR-6 cache implementation (e.g., Symfony Cache with Redis)
/*
use Symfony\Component\Cache\Adapter\RedisAdapter;
$redisConnection = RedisAdapter::createConnection('redis://localhost');
$customCache = new RedisAdapter($redisConnection, 'amazon_paapi_namespace', $config->getCacheTtl());
$clientWithCustomCache = new Client($config, $customCache);
*/

// Client with a custom PSR-3 logger (e.g., Monolog)
/*
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('AmazonPAAPI');
$logger->pushHandler(new StreamHandler('path/to/your/amazon-paapi.log', Logger::DEBUG));
$clientWithLogger = new Client($config, null, $logger); // null for default cache
*/


use AmazonPaapi5\Operations\SearchItems;
use AmazonPaapi5\Models\Request\SearchItemsRequest;
// Assuming $client and $config are initialized

$searchRequest = (new SearchItemsRequest())
    ->setPartnerTag($config->getPartnerTag()) // Use partner tag from config
    ->setKeywords('PHP Programming Laptop')
    ->setSearchIndex('Electronics')
    ->setItemCount(3) // Request 3 items
    ->setResources([
        'ItemInfo.Title',
        'ItemInfo.Features',
        'Offers.Listings.Price',
        'Images.Primary.Medium',
        'BrowseNodeInfo.BrowseNodes'
    ]);

$operation = new SearchItems($searchRequest);

try {
    $response = $client->sendAsync($operation)->wait(); // Synchronous execution

    if ($response && $response->getSearchResult() && $response->getSearchResult()->getItems()) {
        echo "<h3>Search Results for 'PHP Programming Laptop':</h3>";
        foreach ($response->getSearchResult()->getItems() as $item) {
            echo "<h4>" . ($item->getItemInfo()->getTitle()->getDisplayValue() ?? 'N/A') . "</h4>";
            echo "ASIN: " . $item->getAsin() . "<br>";
            echo "Price: " . ($item->getOffers()->getListings()[0]->getPrice()->getDisplayAmount() ?? 'N/A') . "<br>";
            echo "<img src='" . ($item->getImages()->getPrimary()->getMedium()->getURL() ?? '#') . "' alt='Product Image'><br>";

            if ($item->getItemInfo()->getFeatures()) {
                echo "Features: <ul>";
                foreach($item->getItemInfo()->getFeatures()->getDisplayValues() as $feature) {
                    echo "<li>" . $feature . "</li>";
                }
                echo "</ul>";
            }
            echo "<hr>";
        }
    } else {
        echo "No items found or error in response structure.<br>";
        if ($response && $response->getErrors()) {
            // Handle API errors
            foreach ($response->getErrors() as $error) {
                echo "API Error Code: " . $error->getCode() . " - Message: " . $error->getMessage() . "<br>";
            }
        }
    }

} catch (\AmazonPaapi5\Exceptions\ApiException $e) {
    echo "API Exception: " . $e->getMessage() . "<br>";
    echo "HTTP Status Code: " . $e->getCode() . "<br>";
    if ($e->getResponseErrors()) {
        echo "Specific PAAPI Errors: <pre>" . print_r($e->getResponseErrors(), true) . "</pre><br>";
    }
} catch (\Exception $e) {
    echo "Generic Exception: " . $e->getMessage() . "<br>";
}


use AmazonPaapi5\Operations\GetItems;
use AmazonPaapi5\Models\Request\GetItemsRequest;
// Assuming $client and $config are initialized

$itemIds = ['B08X4N3DW1', 'B09F3T2K7P']; // Example ASINs

$getItemsRequest = (new GetItemsRequest())
    ->setPartnerTag($config->getPartnerTag())
    ->setItemIds($itemIds)
    ->setResources([
        'ItemInfo.Title',
        'Offers.Listings.Price',
        'Images.Primary.Large',
        'CustomerReviews.Count',
        'CustomerReviews.StarRating'
    ]);

$operation = new GetItems($getItemsRequest);

try {
    $response = $client->sendAsync($operation)->wait();

    if ($response && $response->getItemsResult() && $response->getItemsResult()->getItems()) {
        echo "<h3>Product Details:</h3>";
        foreach ($response->getItemsResult()->getItems() as $item) {
            echo "<h4>" . ($item->getItemInfo()->getTitle()->getDisplayValue() ?? 'N/A') . "</h4>";
            echo "ASIN: " . $item->getAsin() . "<br>";
            echo "Price: " . ($item->getOffers()->getListings()[0]->getPrice()->getDisplayAmount() ?? 'N/A') . "<br>";
            echo "Reviews: " . ($item->getCustomerReviews()->getCount() ?? '0') . " | Rating: " . ($item->getCustomerReviews()->getStarRating() ?? 'N/A') . " stars<br>";
            echo "<img src='" . ($item->getImages()->getPrimary()->getLarge()->getURL() ?? '#') . "' alt='Product Image' style='max-width: 200px;'><br>";
            echo "<hr>";
        }
    } else {
        echo "No items found or error in response structure for the given ASINs.<br>";
         if ($response && $response->getErrors()) {
            foreach ($response->getErrors() as $error) {
                echo "API Error Code: " . $error->getCode() . " - Message: " . $error->getMessage() . "<br>";
            }
        }
    }

} catch (\AmazonPaapi5\Exceptions\ApiException $e) {
    echo "API Exception: " . $e->getMessage() . "<br>";
} catch (\Exception $e) {
    echo "Generic Exception: " . $e->getMessage() . "<br>";
}


use AmazonPaapi5\Operations\GetVariations;
use AmazonPaapi5\Models\Request\GetVariationsRequest;
// Assuming $client and $config are initialized

$productAsin = 'B08X4N3DW1'; // ASIN of a product that has variations

$getVariationsRequest = (new GetVariationsRequest())
    ->setPartnerTag($config->getPartnerTag())
    ->setAsin($productAsin)
    ->setResources([
        'ItemInfo.Title',
        'VariationsResult.Items.ItemInfo.ContentInfo', // Example: To get variation attributes like color, size
        'VariationsResult.Items.Offers.Listings.Price',
        'VariationsResult.Items.Images.Primary.Medium',
        'VariationsResult.Items.VariationAttributes' // Key resource for variation details
    ]);

$operation = new GetVariations($getVariationsRequest);

try {
    $response = $client->sendAsync($operation)->wait();

    if ($response && $response->getVariationsResult() && $response->getVariationsResult()->getItems()) {
        echo "<h3>Product Variations for ASIN: $productAsin</h3>";
        foreach ($response->getVariationsResult()->getItems() as $variationItem) {
            echo "<h4>" . ($variationItem->getItemInfo()->getTitle()->getDisplayValue() ?? 'N/A') . "</h4>";
            echo "Variation ASIN: " . $variationItem->getAsin() . "<br>";
            echo "Price: " . ($variationItem->getOffers()->getListings()[0]->getPrice()->getDisplayAmount() ?? 'N/A') . "<br>";

            if ($variationItem->getVariationAttributes()) {
                echo "Attributes: <ul>";
                foreach ($variationItem->getVariationAttributes() as $attribute) {
                    echo "<li>" . $attribute->getName() . ": " . $attribute->getValue() . "</li>";
                }
                echo "</ul>";
            }
            echo "<img src='" . ($variationItem->getImages()->getPrimary()->getMedium()->getURL() ?? '#') . "' alt='Variation Image'><br>";
            echo "<hr>";
        }
    } else {
        echo "No variations found or error in response structure for ASIN: $productAsin.<br>";
        if ($response && $response->getErrors()) {
            foreach ($response->getErrors() as $error) {
                echo "API Error Code: " . $error->getCode() . " - Message: " . $error->getMessage() . "<br>";
            }
        }
    }

} catch (\AmazonPaapi5\Exceptions\ApiException $e) {
    echo "API Exception: " . $e->getMessage() . "<br>";
} catch (\Exception $e) {
    echo "Generic Exception: " . $e->getMessage() . "<br>";
}


use AmazonPaapi5\Operations\GetBrowseNodes;
use AmazonPaapi5\Models\Request\GetBrowseNodesRequest;
// Assuming $client and $config are initialized

$browseNodeIds = ['172282']; // Example Browse Node ID for "Electronics" in some marketplaces

$getBrowseNodesRequest = (new GetBrowseNodesRequest())
    ->setPartnerTag($config->getPartnerTag())
    ->setBrowseNodeIds($browseNodeIds)
    ->setResources([
        'BrowseNodes.Ancestor',
        'BrowseNodes.Children',
        'BrowseNodes.BrowseNodeInfo' // Provides DisplayName, ContextFreeName etc.
    ]);

$operation = new GetBrowseNodes($getBrowseNodesRequest);

try {
    $response = $client->sendAsync($operation)->wait();

    if ($response && $response->getBrowseNodesResult() && $response->getBrowseNodesResult()->getBrowseNodes()) {
        echo "<h3>Browse Node Details:</h3>";
        foreach ($response->getBrowseNodesResult()->getBrowseNodes() as $node) {
            echo "<h4>Node: " . ($node->getDisplayName() ?? 'N/A') . " (ID: " . $node->getId() . ")</h4>";
            echo "Is Root: " . ($node->getIsRoot() ? 'Yes' : 'No') . "<br>";
            echo "Context Free Name: " . ($node->getContextFreeName() ?? 'N/A') . "<br>";

            if ($node->getAncestor()) {
                echo "Ancestor: " . ($node->getAncestor()->getDisplayName() ?? 'N/A') . " (ID: " . $node->getAncestor()->getId() . ")<br>";
            }

            if ($node->getChildren()) {
                echo "Children: <ul>";
                foreach ($node->getChildren() as $childNode) {
                    echo "<li>" . ($childNode->getDisplayName() ?? 'N/A') . " (ID: " . $childNode->getId() . ")</li>";
                }
                echo "</ul>";
            }
            echo "<hr>";
        }
    } else {
        echo "No browse node information found or error in response structure.<br>";
        if ($response && $response->getErrors()) {
            foreach ($response->getErrors() as $error) {
                echo "API Error Code: " . $error->getCode() . " - Message: " . $error->getMessage() . "<br>";
            }
        }
    }

} catch (\AmazonPaapi5\Exceptions\ApiException $e) {
    echo "API Exception: " . $e->getMessage() . "<br>";
} catch (\Exception $e) {
    echo "Generic Exception: " . $e->getMessage() . "<br>";
}


// Assuming $client, $searchOperation1, $getItemsOperation2 are initialized operations

$promise1 = $client->sendAsync($searchOperation1);
$promise2 = $client->sendAsync($getItemsOperation2);

$promise1->then(
    function ($response) { // onFulfilled
        echo "SearchItems call 1 completed successfully!\n";
        // Process $response for searchOperation1
        if ($response && $response->getSearchResult() && $response->getSearchResult()->getItems()) {
            foreach ($response->getSearchResult()->getItems() as $item) {
                // ... process item
            }
        }
    },
    function ($exception) { // onRejected
        echo "SearchItems call 1 failed: " . $exception->getMessage() . "\n";
        // Handle $exception for searchOperation1
    }
);

$promise2->then(
    function ($response) { // onFulfilled
        echo "GetItems call 2 completed successfully!\n";
        // Process $response for getItemsOperation2
        if ($response && $response->getItemsResult() && $response->getItemsResult()->getItems()) {
            foreach ($response->getItemsResult()->getItems() as $item) {
                // ... process item
            }
        }
    },
    function ($exception) { // onRejected
        echo "GetItems call 2 failed: " . $exception->getMessage() . "\n";
        // Handle $exception for getItemsOperation2
    }
);

// If you need to wait for all promises to complete:
use GuzzleHttp\Promise;
$allPromises = [$promise1, $promise2];
$results = Promise\Utils::settle($allPromises)->wait(); // `settle` waits for all, regardless of success/failure

foreach ($results as $i => $result) {
    if ($result['state'] === 'fulfilled') {
        echo "Promise " . ($i+1) . " was fulfilled with value: \n";
        // $result['value'] is the response object
    } else {
        echo "Promise " . ($i+1) . " was rejected with reason: " . $result['reason']->getMessage() . "\n";
        // $result['reason'] is the exception object
    }
}

// IMPORTANT: In a typical web server environment (like Apache with mod_php or PHP-FPM),
// the script usually runs to completion for each request. True asynchronous behavior
// often 

$getItemsRequest->setItemIds(['ASIN1', 'ASIN2', 'ASIN3']); // Up to 10 for GetItems
// Then send this single GetItems operation.

$sdkConfig = [
    // ... other keys
    'marketplace' => 'www.amazon.co.uk', // Targets the UK marketplace
    // The SDK will use Marketplace::getRegion('www.amazon.co.uk') -> 'eu-west-1'
    // and Marketplace::getHost('www.amazon.co.uk') -> 'webservices.amazon.co.uk'
];
$config = new Config($sdkConfig);

$sdkConfig = [
    // ... other keys
    'throttle_delay' => 1.0, // Wait 1.0 second between requests.
                            // Increase if you encounter frequent throttling errors.
];
$config = new Config($sdkConfig);

$sdkConfig = [
    // ... other keys
    'cache_dir' => __DIR__ . '/amazon_cache', // Custom cache directory
    'cache_ttl' => 3600, // Cache responses for 1 hour (3600 seconds)
];
$config = new Config($sdkConfig);
$client = new Client($config); // Uses built-in file cache by default

use AmazonPaapi5\Client;
use AmazonPaapi5\Config;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Psr\Cache\CacheItemPoolInterface;

// Assuming $config is initialized

// Create a Redis connection (this might vary based on your Redis setup)
$redisConnection = RedisAdapter::createConnection(
    'redis://localhost:6379',
    [
        'timeout' => 3,
        'read_timeout' => 3,
        'retry_interval' => 0,
    ]
);

$psr6CachePool = new RedisAdapter(
    $redisConnection,
    'amazon_paapi_sdk_namespace', // A namespace for your cache keys
    $config->getCacheTtl() // Use TTL from your SDK config
);

$client = new Client($config, $psr6CachePool);

$sdkConfig = [
    'access_key' => 'YOUR_AWS_ACCESS_KEY',
    'secret_key' => 'YOUR_AWS_SECRET_KEY',
    'partner_tag' => 'YOUR_PARTNER_TAG',
    'marketplace' => 'www.amazon.com',
    'region' => 'us-east-1', // Or let the SDK derive it
    // Provide a strong, unique key (e.g., from an environment variable)
    'encryption_key' => getenv('MY_APP_AMAZON_SDK_ENCRYPTION_KEY') ?: 'a_default_fallback_key_min_16_chars',
];
$config = new Config($sdkConfig);
// The CredentialManager (used internally by Client) will now use the encryption_key.


use AmazonPaapi5\Client;
use AmazonPaapi5\Config;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Psr\Log\LoggerInterface;

// Assuming $config is initialized

// Create a logger instance
$logger = new Logger('AmazonPAAPI_SDK');
$logFile = __DIR__ . '/logs/amazon_paapi.log'; // Ensure this directory is writable
$logger->pushHandler(new StreamHandler($logFile, Logger::INFO)); // Log INFO level and above

// You can also log DEBUG messages for more verbosity
// $logger->pushHandler(new StreamHandler($logFile, Logger::DEBUG));

$client = new Client(
    $config,
    null,     // Pass null to use the default cache, or your PSR-6 cache instance
    $logger   // Pass your PSR-3 logger instance
);

// Now the client will log information about requests, cache hits/misses, errors, etc.
// Example log output might Exception', [
        'message' => $e->getMessage(),
        'code' => $e->getCode(),
        'response_errors' => $e->getResponseErrors()
    ]);
}


// Assuming $client, $operation are initialized

try {
    $response = $client->sendAsync($operation)->wait();
    // Process successful response
    // ...

} catch (\AmazonPaapi5\Exceptions\ThrottleException $e) {
    // Specific handling for throttling
    echo "Throttling Error: " . $e->getMessage() . "\n";
    echo "Suggestion: Increase throttle_delay in config or reduce request frequency.\n";
    // Optionally log $e->getResponseErrors() if available
    // You might implement a retry mechanism here with a longer delay.

} catch (\AmazonPaapi5\Exceptions\AuthenticationException $e) {
    // Errors related to AWS credentials as configured or validated by the SDK
    echo "Authentication Setup Error: " . $e->getMessage() . "\n";
    echo "Suggestion: Verify your Access Key, Secret Key, and Marketplace/Region settings in the SDK configuration.\n";

} catch (\AmazonPaapi5\Exceptions\ApiException $e) {
    // General errors from the Amazon PAAPI
    echo "Amazon PAAPI Error: " . $e->getMessage() . "\n";
    echo "HTTP Status Code: " . $e->getCode() . "\n";
    if ($e->getResponseErrors()) {
        echo "Specific API Errors:\n";
        foreach ($e->getResponseErrors() as $apiError) {
            echo " - Code: " . $apiError->getCode() . ", Message: " . $apiError->getMessage() . "\n";
        }
    }
    // Example: Check for common error codes
    // if ($e->getResponseErrors() && $e->getResponseErrors()[0]->getCode() === 'InvalidParameterValue') { ... }

} catch (\AmazonPaapi5\Exceptions\ConfigException $e) {
    echo "SDK Configuration Error: " . $e->getMessage() . "\n";
    // Fix your Config object initialization.

} catch (\AmazonPaapi5\Exceptions\RequestException $e) {
    echo "SDK Request Error: " . $e->getMessage() . "\n";
    // Check how you built the request object.

} catch (\GuzzleHttp\Exception\ConnectException $e) {
    // Network connectivity issues
    echo "Network Error: Could not connect to Amazon API. " . $e->getMessage() . "\n";

} catch (\Exception $e) {
    // Catch-all for any other unexpected exceptions
    echo "An unexpected error occurred: " . $e->getMessage() . "\n";
    // Log the full exception details for debugging
    // error_log($e->getTraceAsString());
}