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

Ngnfeed Ebay Laravel Package

d4m/ngnfeed-ebay

PHP library for integrating with eBay’s Trading API. Install via Composer from Packagist to add eBay Trading operations to your project. Inspired by the legacy PEAR eBay library and developed by raul782.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require d4m/ngnfeed-ebay
    

    Ensure your composer.json includes "minimum-stability": "dev" if the package is in development.

  2. Configuration Create a config file at config/ebay.php (publish with php artisan vendor:publish --provider="D4M\NGNFeed\Ebay\EbayServiceProvider"):

    return [
        'app_id' => env('EBAY_APP_ID'),
        'cert_id' => env('EBAY_CERT_ID'),
        'dev_id' => env('EBAY_DEV_ID'),
        'auth_token' => env('EBAY_AUTH_TOKEN'),
        'sandbox' => env('EBAY_SANDBOX', false),
        'timeout' => 30,
    ];
    
  3. First Use Case: Fetching Categories

    use D4M\NGNFeed\Ebay\Ebay;
    
    $ebay = new Ebay();
    $categories = $ebay->getCategories(['CategoryParentID' => '0']); // Root categories
    dd($categories);
    
  4. Environment Variables Add to .env:

    EBAY_APP_ID=your_app_id
    EBAY_CERT_ID=your_cert_id
    EBAY_DEV_ID=your_dev_id
    EBAY_AUTH_TOKEN=your_auth_token
    EBAY_SANDBOX=true # For testing
    

Implementation Patterns

Core Workflows

1. Authentication & Token Management

  • OAuth Flow: Use Ebay::getAuthToken() for initial token generation (if not pre-configured).
  • Token Refresh: Implement a refreshToken() method in a service class to handle expiry:
    public function refreshEbayToken()
    {
        $ebay = new Ebay();
        $ebay->setAuthToken($ebay->getAuthToken()); // Auto-refreshes
        return $ebay->getAuthToken();
    }
    

2. Listing Management

  • Create/Update Listings:
    $listing = [
        'Item' => [
            'Title' => 'Laravel Developer T-Shirt',
            'CategoryID' => '267', // Electronics > Apparel
            'StartPrice' => '19.99',
            'Quantity' => 10,
            'Description' => 'Handcrafted for Laravel devs.',
        ],
    ];
    $ebay->createListing($listing);
    
  • Batch Operations: Use Ebay::getListings() with filters (e.g., ['ItemID' => '12345']).

3. Order & Transaction Handling

  • Fetch Orders:
    $orders = $ebay->getOrders(['CreatedTimeFrom' => '2023-01-01']);
    foreach ($orders as $order) {
        // Process order (e.g., update DB, trigger fulfillment)
    }
    
  • Webhook Integration: Extend the package to log webhook payloads to a ebay_webhooks table:
    $ebay->setWebhookCallback(function ($payload) {
        \App\Models\EbayWebhook::create([
            'event' => $payload['eventType'],
            'data' => $payload,
        ]);
    });
    

4. Search & Analytics

  • Search Items:
    $results = $ebay->searchItems([
        'Keyword' => 'Laravel',
        'SortOrder' => 'EndTimeDescending',
    ]);
    
  • Competitor Analysis: Cache search results in Redis for performance:
    $cacheKey = "ebay:search:laravel:{$results['searchResult']['@count']}";
    Cache::put($cacheKey, $results, now()->addHours(1));
    

Integration Tips

Laravel Service Container

Bind the Ebay class to the container for dependency injection:

// In a service provider
$this->app->bind(Ebay::class, function ($app) {
    $config = $app['config']['ebay'];
    return new Ebay($config);
});

Usage in controllers:

public function __construct(private Ebay $ebay) {}

Queued Jobs

Offload long-running operations (e.g., bulk listing updates) to queues:

// In a job class
public function handle()
{
    $ebay = new Ebay();
    $ebay->updateListing($this->listingId, $this->updateData);
}

Dispatch with:

UpdateEbayListingJob::dispatch($listingId, $updateData);

API Rate Limiting

Implement middleware to throttle requests:

// app/Http/Middleware/ThrottleEbayRequests.php
public function handle($request, Closure $next)
{
    return $next($request)->throttle([
        'ebay' => 10, // 10 requests per minute
    ]);
}

Gotchas and Tips

Pitfalls

  1. Sandbox vs. Production

    • Issue: Forgetting to toggle EBAY_SANDBOX can lead to real API calls.
    • Fix: Use a .env.production file for production credentials and validate the environment:
      if (!$ebay->isSandbox() && !app()->environment('production')) {
          throw new \RuntimeException('Production API called in non-production environment!');
      }
      
  2. Token Expiry

    • Issue: Silent failures if the auth token expires.
    • Fix: Wrap API calls in a try-catch and auto-refresh:
      try {
          $response = $ebay->getOrders([]);
      } catch (\D4M\NGNFeed\Ebay\Exceptions\AuthException $e) {
          $ebay->refreshToken();
          return $this->handle($request); // Retry
      }
      
  3. XML Namespace Quirks

    • Issue: The package uses XML namespaces (e.g., ns="urn:ebay:apis:eBLBaseComponents"). Incorrect namespace handling can break requests.
    • Fix: Validate XML structure before sending:
      $xml = $ebay->buildXml($data);
      if (!str_contains($xml, 'ns="urn:ebay:apis:eBLBaseComponents"')) {
          throw new \InvalidArgumentException('Invalid XML namespace');
      }
      
  4. Pagination Limits

    • Issue: Ebay’s API paginates results (e.g., 200 items/page). Missing pagination can truncate data.
    • Fix: Implement recursive fetching:
      public function getAllOrders()
      {
          $orders = $this->ebay->getOrders(['Pagination' => ['EntriesPerPage' => 200]]);
          $nextPage = $orders['paginationResult']['@nextPageId'] ?? null;
          if ($nextPage) {
              $orders['orders'] = array_merge(
                  $orders['orders'],
                  $this->getAllOrders($nextPage)
              );
          }
          return $orders;
      }
      

Debugging Tips

  1. Enable Verbose Logging Configure the package to log raw requests/responses:

    $ebay = new Ebay();
    $ebay->setDebug(true); // Logs to storage/logs/ebay.log
    
  2. Validate XML Payloads Use PHP’s SimpleXMLElement to validate responses:

    $xml = simplexml_load_string($response);
    if ($xml === false) {
        throw new \RuntimeException('Invalid XML response');
    }
    
  3. Common Error Codes

    • 10001: Invalid token → Refresh token.
    • 10002: Insufficient permissions → Check cert_id and app_id.
    • 15000: Invalid XML → Use Ebay::validateXml() helper.

Extension Points

  1. Custom Response Mappers Extend the D4M\NGNFeed\Ebay\ResponseMapper class to transform raw XML into custom objects:

    class CustomOrderMapper extends ResponseMapper
    {
        public function mapOrder($order)
        {
            return [
                'id' => $order['OrderID'],
                'total' => $order['OrderTotal']['GrandTotal'],
                'items' => collect($order['OrderDetail']['OrderItem'])->map(function ($item) {
                    return [
                        'sku' => $item['SKU'],
                        'price' => $item['QuantityPurchased'] * $item['ItemTotal']['QuantityPurchased'],
                    ];
                }),
            ];
        }
    }
    
  2. Webhook Handlers Extend the Ebay class to support custom webhook events:

    class ExtendedEbay extends Ebay
    {
        protected $webhookHandlers = [
            'OrderCreated' => function ($payload) {
                // Custom logic for order
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky