Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Amazon Mws Bundle Laravel Package

caponica/amazon-mws-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add to composer.json:

    "require": {
        "caponica/amazon-mws-bundle": "dev-master"
    }
    

    Run composer update.

  2. Register the Bundle Add to AppKernel.php:

    new Caponica\AmazonMwsBundle\CaponicaAmazonMwsBundle(),
    
  3. Configure Parameters Define credentials in app/config/parameters.yml:

    caponica_amazon_mws_config_<marketplace>:
        seller_id:           "YOUR_SELLER_ID"
        access_key:          "YOUR_ACCESS_KEY"
        secret_key:          "YOUR_SECRET_KEY"
        application_name:    "YourAppName"
        application_version: "1.0"
        amazon_site:         "US|UK|DE|FR|IT|ES|JP|CA|IN|BR|MX|AU|CN|SG|TR|PL|NL|IT|SE|BE|CH|AT"
    
  4. Define the Service Configure the service in app/config/services.yml:

    services:
        amazon_mws.<marketplace>:
            class: Caponica\AmazonMwsBundle\Service\AmazonMwsService
            calls:
                - [setConfig, [%caponica_amazon_mws_config_<marketplace>%]]
    
  5. First Use Case Inject the service into a controller or command and call an MWS API method:

    use Caponica\AmazonMwsBundle\Service\AmazonMwsService;
    
    class MyController extends Controller
    {
        public function __construct(AmazonMwsService $amazonMws)
        {
            $this->amazonMws = $amazonMws;
        }
    
        public function getOrders()
        {
            $result = $this->amazonMws->getOrders([
                'CreatedAfter' => date('Y-m-d\TH:i:s\Z', strtotime('-7 days')),
                'CreatedBefore' => date('Y-m-d\TH:i:s\Z')
            ]);
            return $this->renderOrders($result);
        }
    }
    

Implementation Patterns

Common Workflows

  1. Multi-Marketplace Integration Define separate services for each marketplace (e.g., amazon_mws.us, amazon_mws.uk) and inject the required one based on context (e.g., user location, product origin).

  2. Command-Line Automation Use Symfony commands to automate MWS tasks (e.g., order processing, inventory updates):

    namespace App\Command;
    
    use Caponica\AmazonMwsBundle\Service\AmazonMwsService;
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class SyncInventoryCommand extends Command
    {
        protected static $defaultName = 'amazon:sync_inventory';
    
        private $amazonMws;
    
        public function __construct(AmazonMwsService $amazonMws)
        {
            $this->amazonMws = $amazonMws;
            parent::__construct();
        }
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $output->writeln('Syncing inventory...');
            $result = $this->amazonMws->listInventorySupply([
                'Query' => 'Available',
                'Condition' => 'All'
            ]);
            // Process $result
        }
    }
    
  3. Event-Driven Integration Trigger MWS actions in response to Symfony events (e.g., kernel.request for real-time order updates):

    $container->get('event_dispatcher')->addListener('kernel.request', function () use ($container) {
        $amazonMws = $container->get('amazon_mws.us');
        $orders = $amazonMws->getOrders(['Status' => 'Unshipped']);
        foreach ($orders as $order) {
            // Process unshipped orders
        }
    });
    
  4. Data Transformation Use Symfony’s serializer or custom mappers to transform MWS responses into domain objects:

    $orders = $this->amazonMws->getOrders(['Status' => 'Unshipped']);
    $serializer = $this->container->get('serializer');
    $domainOrders = $serializer->deserialize(
        json_encode($orders),
        'array<App\Entity\Order>',
        'json'
    );
    
  5. Rate Limiting and Retries Implement a decorator pattern to handle MWS rate limits and retries:

    class AmazonMwsRateLimiterDecorator implements AmazonMwsServiceInterface
    {
        private $decorated;
        private $maxRetries = 3;
    
        public function __construct(AmazonMwsService $decorated)
        {
            $this->decorated = $decorated;
        }
    
        public function getOrders(array $params)
        {
            $retries = 0;
            while ($retries < $this->maxRetries) {
                try {
                    return $this->decorated->getOrders($params);
                } catch (Exception $e) {
                    if ($retries === $this->maxRetries - 1) {
                        throw $e;
                    }
                    sleep(2 ** $retries); // Exponential backoff
                    $retries++;
                }
            }
        }
    }
    

Integration Tips

  • Dependency Injection: Always prefer injecting AmazonMwsService via constructor for testability.
  • Configuration Validation: Validate parameters.yml entries (e.g., amazon_site must be a valid MWS marketplace code).
  • Logging: Wrap MWS calls in a logger to track API usage and errors:
    $this->logger->info('Fetching orders', ['params' => $params]);
    $result = $this->amazonMws->getOrders($params);
    $this->logger->debug('Orders response', ['response' => $result]);
    
  • Caching: Cache frequent MWS responses (e.g., product listings) using Symfony’s cache component:
    $cache = $this->container->get('cache.app');
    $cacheKey = 'amazon_products_' . md5(json_encode($params));
    if (!$cache->has($cacheKey)) {
        $products = $this->amazonMws->listMatchingProducts($params);
        $cache->set($cacheKey, $products, 3600); // Cache for 1 hour
    } else {
        $products = $cache->get($cacheKey);
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package

    • The bundle is last updated in 2016 and may not support newer PHP/Symfony versions or MWS API changes.
    • Mitigation: Fork the repository and update dependencies (e.g., amazon-mws/php-sdk to a maintained version like ^3.0).
  2. No Built-in Service

    • The bundle does not auto-register services. You must manually define each service in services.yml.
    • Tip: Use Symfony’s parameters to dynamically generate service configurations:
      services:
          _defaults:
              public: false
          amazon_mws.%amazon_mws.config%:
              class: Caponica\AmazonMwsBundle\Service\AmazonMwsService
              calls:
                  - [setConfig, [%caponica_amazon_mws_config.%amazon_mws.config%]]
      
  3. Error Handling

    • MWS errors (e.g., AWS.MWS.Error.InvalidParameter) are thrown as exceptions but may lack context.
    • Tip: Extend the service to add custom error handling:
      try {
          $result = $this->amazonMws->getOrders($params);
      } catch (Exception $e) {
          $this->logger->error('MWS Error', [
              'message' => $e->getMessage(),
              'code' => $e->getCode(),
              'params' => $params
          ]);
          throw new \RuntimeException('Failed to fetch orders: ' . $e->getMessage(), 0, $e);
      }
      
  4. Marketplace-Specific Quirks

    • Some MWS APIs (e.g., ListOrders) behave differently per marketplace (e.g., DE vs. US).
    • Tip: Test thoroughly across all target marketplaces and document differences.
  5. Authentication Rotations

    • MWS credentials (e.g., secret_key) may expire or require rotation.
    • Tip: Store credentials in environment variables or a secure vault (e.g., Symfony’s ParameterBag with encrypted values).

Debugging Tips

  • Enable MWS Debugging: Set AWS_MWS_DEBUG environment variable to log raw API requests/responses:
    export AWS_MWS_DEBUG=1
    
  • Validate XML Responses: MWS APIs return XML. Use DOMDocument or SimpleXMLElement to inspect responses:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui