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 Complete Laravel Package

caponica/amazon-mws-complete

Unified PHP client for Amazon MWS APIs. Use service-specific clients directly or simplify setup with MwsClientPool and per-seller/marketplace ClientPacks that prefill common parameters. Includes helpers that convert raw MWS responses into easier-to-use objects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require caponica/amazon-mws-complete:dev-master
    

    (Note: Use dev-master as the latest stable release is outdated.)

  2. Basic Configuration:

    use CaponicaAmazonMwsComplete\ClientPool\MwsClientPool;
    
    $clientPool = new MwsClientPool(new \Your\Logger\Implementation());
    $clientPool->setConfig([
        'amazon_site'           => MwsClientPoolConfig::SITE_US,
        'access_key'            => env('AWS_ACCESS_KEY'),
        'secret_key'            => env('AWS_SECRET_KEY'),
        'application_name'      => 'YourAppName',
        'application_version'   => '1.0',
        'seller_id'             => env('AWS_SELLER_ID'),
    ]);
    
  3. First API Call:

    $productClient = $clientPool->getProductClientPack();
    $response = $productClient->callGetCompetitivePricingForASIN('B08XYZ123');
    

Key First Use Cases

  • Product Data: Fetch competitive pricing, inventory, or listings.
  • Orders: Retrieve order details or process cancellations.
  • Reports: Parse FBA inventory or financial reports.
  • Auth: Handle MWS tokens for authenticated requests.

Implementation Patterns

Core Workflow: ClientPool Pattern

  1. Centralized Configuration:

    $clientPool = new MwsClientPool($logger);
    $clientPool->setConfig([
        'amazon_site' => MwsClientPoolConfig::SITE_DE, // Germany
        'auth_token'  => env('AWS_MWS_TOKEN'), // Optional
        // ... other keys
    ]);
    
    • Reuse the same pool for multiple API services (e.g., getProductClientPack(), getOrdersClientPack()).
  2. Service-Specific Calls:

    // Products
    $pricing = $productClient->retrieveCompetitivePricingForASIN('B08XYZ123');
    
    // Orders
    $orders = $ordersClient->retrieveOrders(['CreatedAfter' => '2023-01-01']);
    
    // Reports
    $report = $reportClient->getReport($reportType, $reportId);
    
  3. Helper Methods:

    • Use retrieveXyz() methods for parsed objects (e.g., MwsCompetitivePricing[]).
    • Fall back to callXyz() for raw API responses.

Integration Tips

  • Environment Variables: Store credentials in .env and load via Laravel’s config() helper:

    $clientPool->setConfig([
        'access_key' => config('services.amazon.access_key'),
    ]);
    
  • Service Providers: Bind the MwsClientPool to Laravel’s container:

    $this->app->singleton(MwsClientPool::class, function ($app) {
        return new MwsClientPool($app->make(\Psr\Log\LoggerInterface::class));
    });
    
  • Jobs/Queues: Offload long-running tasks (e.g., report processing) to Laravel queues:

    ProcessAmazonReport::dispatch($reportFilePath, $reportType);
    
  • API Rate Limiting: Implement middleware to throttle requests (Amazon’s limits vary by endpoint).


Gotchas and Tips

Pitfalls

  1. Deprecated APIs:

    • MWSCartService and MWSCustomerService are deprecated. Avoid using them.
    • Workaround: Check ClientLibraryVersions in the package for active APIs.
  2. Auth Token Handling:

    • The package assumes tokens are set globally via setConfig(). For dynamic tokens:
      $clientPack = $clientPool->getProductClientPack();
      $clientPack->setAuthToken($newToken); // If supported by the underlying client.
      
    • Debugging: If tokens fail, verify the MWSAuthToken is correctly passed to the underlying MwsClient.
  3. Report Parsing:

    • Not all report types are implemented. For custom reports:
      • Extend BaseMwsReport and BaseMwsReportRecord.
      • Example:
        class CustomReport extends BaseMwsReport {
            public static function getReportType() { return 'Custom_Report_Type'; }
        }
        
    • Header Validation: Always validate headers with validateHeaderRowForReportType().
  4. Logging:

    • The package expects PSR-3 loggers. For Laravel, use:
      $logger = \Log::getMonolog();
      $clientPool = new MwsClientPool($logger);
      
  5. Error Handling:

    • Wrap API calls in try-catch for MwsException or InvalidReportException.
    • Example:
      try {
          $response = $client->callGetOrder(['AmazonOrderId' => '123']);
      } catch (MwsException $e) {
          \Log::error('MWS Error: ' . $e->getMessage());
          throw new \RuntimeException('Failed to fetch order', 0, $e);
      }
      

Debugging Tips

  1. Enable Verbose Logging:

    $logger = new \Monolog\Logger('amazon', [
        new \Monolog\Handler\StreamHandler(storage_path('logs/amazon.log'), \Monolog\Logger::DEBUG)
    ]);
    
  2. Check Raw Responses: Use callXyz() to inspect unparsed responses for debugging:

    $rawResponse = $client->callGetCompetitivePricingForASIN('B08XYZ123');
    \Log::debug('Raw API Response:', ['response' => $rawResponse]);
    
  3. Validate Credentials: Test with a simple call (e.g., getMarketplaceInfo) to ensure auth works:

    $marketplaceInfo = $clientPool->getSellersClientPack()->callGetMarketplaceInfo();
    

Extension Points

  1. Custom Clients: Extend BaseMwsClient to add domain-specific methods:

    class CustomProductClient extends BaseMwsClient {
        public function getLowStockAlerts($threshold = 5) {
            // Custom logic using underlying MWS API
        }
    }
    
  2. Report Extensions: Add support for new report types by implementing:

    • ReportXyz (header validation).
    • ReportXyzRecord (row parsing).
  3. Middleware: Create Laravel middleware to:

    • Retry failed requests.
    • Transform responses (e.g., flatten nested arrays).
    class TransformAmazonResponse implements \Illuminate\Pipeline\Pipeline {
        public function handle($request, \Closure $next) {
            $response = $next($request);
            return $this->transform($response);
        }
    }
    
  4. Testing: Mock the MwsClientPool in tests:

    $mockPool = Mockery::mock(MwsClientPool::class);
    $mockPool->shouldReceive('getProductClientPack')
             ->andReturn($mockClientPack);
    
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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge