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.
Installation
composer require d4m/ngnfeed-ebay
Ensure your composer.json includes "minimum-stability": "dev" if the package is in development.
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,
];
First Use Case: Fetching Categories
use D4M\NGNFeed\Ebay\Ebay;
$ebay = new Ebay();
$categories = $ebay->getCategories(['CategoryParentID' => '0']); // Root categories
dd($categories);
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
Ebay::getAuthToken() for initial token generation (if not pre-configured).refreshToken() method in a service class to handle expiry:
public function refreshEbayToken()
{
$ebay = new Ebay();
$ebay->setAuthToken($ebay->getAuthToken()); // Auto-refreshes
return $ebay->getAuthToken();
}
$listing = [
'Item' => [
'Title' => 'Laravel Developer T-Shirt',
'CategoryID' => '267', // Electronics > Apparel
'StartPrice' => '19.99',
'Quantity' => 10,
'Description' => 'Handcrafted for Laravel devs.',
],
];
$ebay->createListing($listing);
Ebay::getListings() with filters (e.g., ['ItemID' => '12345']).$orders = $ebay->getOrders(['CreatedTimeFrom' => '2023-01-01']);
foreach ($orders as $order) {
// Process order (e.g., update DB, trigger fulfillment)
}
ebay_webhooks table:
$ebay->setWebhookCallback(function ($payload) {
\App\Models\EbayWebhook::create([
'event' => $payload['eventType'],
'data' => $payload,
]);
});
$results = $ebay->searchItems([
'Keyword' => 'Laravel',
'SortOrder' => 'EndTimeDescending',
]);
$cacheKey = "ebay:search:laravel:{$results['searchResult']['@count']}";
Cache::put($cacheKey, $results, now()->addHours(1));
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) {}
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);
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
]);
}
Sandbox vs. Production
EBAY_SANDBOX can lead to real API calls..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!');
}
Token Expiry
try {
$response = $ebay->getOrders([]);
} catch (\D4M\NGNFeed\Ebay\Exceptions\AuthException $e) {
$ebay->refreshToken();
return $this->handle($request); // Retry
}
XML Namespace Quirks
ns="urn:ebay:apis:eBLBaseComponents"). Incorrect namespace handling can break requests.$xml = $ebay->buildXml($data);
if (!str_contains($xml, 'ns="urn:ebay:apis:eBLBaseComponents"')) {
throw new \InvalidArgumentException('Invalid XML namespace');
}
Pagination Limits
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;
}
Enable Verbose Logging Configure the package to log raw requests/responses:
$ebay = new Ebay();
$ebay->setDebug(true); // Logs to storage/logs/ebay.log
Validate XML Payloads
Use PHP’s SimpleXMLElement to validate responses:
$xml = simplexml_load_string($response);
if ($xml === false) {
throw new \RuntimeException('Invalid XML response');
}
Common Error Codes
cert_id and app_id.Ebay::validateXml() helper.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'],
];
}),
];
}
}
Webhook Handlers
Extend the Ebay class to support custom webhook events:
class ExtendedEbay extends Ebay
{
protected $webhookHandlers = [
'OrderCreated' => function ($payload) {
// Custom logic for order
How can I help you explore Laravel packages today?