PHP code example of tigusigalpa / ebay-php

1. Go to this page and download the library: Download tigusigalpa/ebay-php 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/ */

    

tigusigalpa / ebay-php example snippets


use Tigusigalpa\Ebay\Facades\Ebay;
use Tigusigalpa\Ebay\Enums\Site;

// OAuth URL
$url = Ebay::getConsentUrl();

// Exchange code for tokens
$tokens = Ebay::exchangeCodeForToken($code);

// Get orders
$orders = Ebay::trading()->getOrders([
    'CreateTimeFrom' => now()->subDays(30)->toIso8601String(),
]);

// Switch marketplace
Ebay::setSite(Site::UK)->trading()->getOrders();



use Tigusigalpa\Ebay\Ebay;
use Tigusigalpa\Ebay\Enums\Site;

$ebay = new Ebay([
    'environment' => 'sandbox',
    'sandbox' => [
        'app_id' => 'your-app-id',
        'cert_id' => 'your-cert-id',
        'dev_id' => 'your-dev-id',
        'runame' => 'your-runame',
    ],
    'site' => Site::US,
]);

$orders = $ebay->trading()->getOrders();

$consentUrl = Ebay::getConsentUrl(
    scopes: config('ebay.scopes'),
    state: 'your-state-parameter',
    locale: 'en-US'
);

return redirect($consentUrl);

public function callback(Request $request)
{
    $code = $request->get('code');
    $tokenData = Ebay::exchangeCodeForToken($code);
    
    // Store tokens
    auth()->user()->update([
        'ebay_access_token' => $tokenData['access_token'],
        'ebay_access_token_expires_at' => $tokenData['expires_at'],
        'ebay_refresh_token' => $tokenData['refresh_token'],
        'ebay_refresh_token_expires_at' => $tokenData['refresh_token_expires_at'],
    ]);
    
    return redirect()->route('dashboard');
}

$user = auth()->user();

Ebay::setAccessToken($user->ebay_access_token, $user->ebay_access_token_expires_at);
Ebay::setRefreshToken($user->ebay_refresh_token, $user->ebay_refresh_token_expires_at);

// Tokens refresh automatically when expired
$orders = Ebay::trading()->getOrders();

$xml = Ebay::trading()->getOrders([
    'CreateTimeFrom' => '2024-01-01T00:00:00.000Z',
    'CreateTimeTo' => '2024-12-31T23:59:59.999Z',
    'OrderStatus' => 'Active',
]);

foreach ($xml->OrderArray->Order as $order) {
    $orderId = (string) $order->OrderID;
    $total = (float) $order->Total;
}

// Get item
$item = Ebay::trading()->getItem('123456789');
$title = (string) $item->Item->Title;
$price = (float) $item->Item->SellingStatus->CurrentPrice;

// Create listing
$response = Ebay::trading()->addFixedPriceItem([
    'Title' => 'My Product Title',
    'Description' => 'Product description',
    'PrimaryCategory' => ['CategoryID' => '12345'],
    'StartPrice' => 99.99,
    'Quantity' => 10,
    'Currency' => 'USD',
    'Country' => 'US',
    'Location' => 'New York',
    'DispatchTimeMax' => 3,
    'ShippingDetails' => [
        'ShippingType' => 'Flat',
        'ShippingServiceOptions' => [
            'ShippingService' => 'USPSPriority',
            'ShippingServiceCost' => 5.00,
        ],
    ],
]);

$itemId = (string) $response->ItemID;

$categories = Ebay::trading()->getCategories([
    'CategorySiteID' => 0,
    'LevelLimit' => 2,
]);

// Get
$item = Ebay::commerce()->getInventoryItem('SKU-123');

// Update quantity
Ebay::commerce()->createOrReplaceInventoryItem($sku, [
    'availability' => ['shipToLocationAvailability' => ['quantity' => $newQuantity]],
]);

$orders = Ebay::commerce()->getFulfillmentOrders([
    'filter' => 'orderfulfillmentstatus:{NOT_STARTED|IN_PROGRESS}',
    'limit' => 50,
]);

$translated = Ebay::commerce()->translate(
    text: 'Brand New iPhone',
    fromLanguage: 'en',
    toLanguage: 'de',
    context: 'ITEM_TITLE'
);

$aspects = Ebay::commerce()->getItemAspectsForCategory('0', '12345');

foreach ($aspects['aspects'] as $aspect) {
    echo $aspect['localizedAspectName'];
}

use Tigusigalpa\Ebay\Http\Resources\Fulfillment\{Order, OrderSearchPagedCollection};

// Get single order
$order = Ebay::fulfillment()->getOrder('12-34567-89012');
echo $order->orderId;
echo $order->orderFulfillmentStatus;
echo $order->pricingSummary?->total?->value;

// Get multiple orders with filters
$orders = Ebay::fulfillment()->getOrders([
    'filter' => 'creationdate:[2024-01-01T00:00:00.000Z..]',
    'limit' => 50,
    'offset' => 0,
]);

foreach ($orders->orders as $order) {
    echo $order->orderId;
    echo $order->buyer?->username;
}

// Filter by order status
$orders = Ebay::fulfillment()->getOrders([
    'filter' => 'orderfulfillmentstatus:{NOT_STARTED|IN_PROGRESS}',
]);

// Get specific orders by IDs
$orders = Ebay::fulfillment()->getOrders([
    'orderIds' => '12-34567-89012,12-34567-89013',
]);

// Include tax breakdown
$order = Ebay::fulfillment()->getOrder('12-34567-89012', [
    'fieldGroups' => 'TAX_BREAKDOWN',
]);

use Tigusigalpa\Ebay\Enums\ReasonForRefundEnum;

// Full refund
$refund = Ebay::fulfillment()->issueRefund('12-34567-89012', [
    'reasonForRefund' => ReasonForRefundEnum::BUYER_CANCEL->value,
    'comment' => 'Customer requested cancellation',
    'orderLevelRefundAmount' => [
        'value' => '99.99',
        'currency' => 'USD',
    ],
]);

// Partial refund for specific line items
$refund = Ebay::fulfillment()->issueRefund('12-34567-89012', [
    'reasonForRefund' => ReasonForRefundEnum::DEFECTIVE_ITEM->value,
    'refundItems' => [
        [
            'lineItemId' => '123456789',
            'refundAmount' => [
                'value' => '25.00',
                'currency' => 'USD',
            ],
        ],
    ],
]);

echo $refund->refundId;
echo $refund->refundStatus;

// Create shipping fulfillment
$fulfillmentId = Ebay::fulfillment()->createShippingFulfillment('12-34567-89012', [
    'lineItems' => [
        [
            'lineItemId' => '123456789',
            'quantity' => 1,
        ],
    ],
    'shippedDate' => now()->toIso8601String(),
    'shippingCarrierCode' => 'USPS',
    'trackingNumber' => '1234567890123456',
]);

// Get single fulfillment
$fulfillment = Ebay::fulfillment()->getShippingFulfillment(
    '12-34567-89012',
    $fulfillmentId
);

echo $fulfillment->shipmentTrackingNumber;
echo $fulfillment->shippingCarrierCode;

// Get all fulfillments for order
$fulfillments = Ebay::fulfillment()->getShippingFulfillments('12-34567-89012');

foreach ($fulfillments->fulfillments as $fulfillment) {
    echo $fulfillment->trackingNumber;
}

use Tigusigalpa\Ebay\Enums\{DisputeStatusEnum, EvidenceTypeEnum};

// Get dispute summaries
$disputes = Ebay::fulfillment()->getPaymentDisputeSummaries([
    'payment_dispute_status' => DisputeStatusEnum::OPEN->value,
    'limit' => 50,
]);

foreach ($disputes->paymentDisputeSummaries as $summary) {
    echo $summary->paymentDisputeId;
    echo $summary->reason;
    echo $summary->amount?->value;
}

// Get full dispute details
$dispute = Ebay::fulfillment()->getPaymentDispute('5001234567890');

echo $dispute->paymentDisputeStatus?->value;
echo $dispute->respondByDate;
echo $dispute->revision; // Required for contesting

// Get dispute activity history
$history = Ebay::fulfillment()->getActivities('5001234567890');

foreach ($history->activities as $activity) {
    echo $activity->activityType;
    echo $activity->activityDate;
}

// Upload evidence file
$uploadResponse = Ebay::fulfillment()->uploadEvidenceFile(
    '5001234567890',
    file_get_contents('/path/to/tracking-proof.pdf')
);

$fileId = $uploadResponse->fileId;

// Add evidence
$evidenceResponse = Ebay::fulfillment()->addEvidence('5001234567890', [
    'evidenceType' => EvidenceTypeEnum::PROOF_OF_DELIVERY->value,
    'files' => [
        ['fileId' => $fileId],
    ],
    'lineItems' => [
        [
            'itemId' => '123456789',
            'lineItemId' => '987654321',
        ],
    ],
]);

$evidenceId = $evidenceResponse->evidenceId;

// Update evidence
Ebay::fulfillment()->updateEvidence('5001234567890', [
    'evidenceId' => $evidenceId,
    'evidenceType' => EvidenceTypeEnum::PROOF_OF_DELIVERY->value,
    'files' => [
        ['fileId' => $fileId],
    ],
]);

// Contest dispute
Ebay::fulfillment()->contestPaymentDispute('5001234567890', [
    'revision' => $dispute->revision,
    'returnAddress' => [
        'addressLine1' => '123 Main St',
        'city' => 'New York',
        'stateOrProvince' => 'NY',
        'postalCode' => '10001',
        'countryCode' => 'US',
        'fullName' => 'Your Company',
    ],
]);

// Accept dispute
Ebay::fulfillment()->acceptPaymentDispute('5001234567890');

// Download evidence file
$fileContent = Ebay::fulfillment()->fetchEvidenceContent(
    '5001234567890',
    $evidenceId,
    $fileId
);

file_put_contents('evidence.pdf', $fileContent);

// Orders created in date range
$orders = Ebay::fulfillment()->getOrders([
    'filter' => 'creationdate:[2024-01-01T00:00:00.000Z..2024-12-31T23:59:59.999Z]',
]);

// Orders by fulfillment status
$orders = Ebay::fulfillment()->getOrders([
    'filter' => 'orderfulfillmentstatus:{NOT_STARTED}',
]);

// Disputes by buyer
$disputes = Ebay::fulfillment()->getPaymentDisputeSummaries([
    'buyer_username' => 'buyer123',
]);

// Disputes by order ID
$disputes = Ebay::fulfillment()->getPaymentDisputeSummaries([
    'order_id' => '12-34567-89012',
]);

// Disputes opened in date range
$disputes = Ebay::fulfillment()->getPaymentDisputeSummaries([
    'open_date_from' => '2024-01-01T00:00:00.000Z',
    'open_date_to' => '2024-12-31T23:59:59.999Z',
]);

'scopes' => [
    'https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly',
    'https://api.ebay.com/oauth/api_scope/sell.fulfillment',
    'https://api.ebay.com/oauth/api_scope/sell.finances',
    'https://api.ebay.com/oauth/api_scope/sell.payment.dispute',
],

use Tigusigalpa\Ebay\Http\Resources\Logistics\{ShippingQuote, Shipment};

// Create a shipping quote to get available rates
$quote = Ebay::logistics()->createShippingQuote([
    'orderId' => '12-12345-12345',
    'packageSpecification' => [
        'dimensions' => [
            'length' => '10',
            'width' => '10',
            'height' => '5',
            'unit' => 'INCH',
        ],
        'weight' => [
            'value' => '2',
            'unit' => 'POUND',
        ],
    ],
    'shipFrom' => [
        'fullName' => 'John Seller',
        'contactAddress' => [
            'addressLine1' => '123 Main St',
            'city' => 'San Jose',
            'stateOrProvince' => 'CA',
            'postalCode' => '95131',
            'countryCode' => 'US',
        ],
        'primaryPhone' => [
            'phoneNumber' => '555-1234',
        ],
        'email' => '[email protected]',
    ],
    'shipTo' => [
        'fullName' => 'Jane Buyer',
        'contactAddress' => [
            'addressLine1' => '456 Oak Ave',
            'city' => 'Austin',
            'stateOrProvince' => 'TX',
            'postalCode' => '78701',
            'countryCode' => 'US',
        ],
    ],
]);

echo $quote->shippingQuoteId;
echo $quote->expirationDate;

// Review available rates
foreach ($quote->rates ?? [] as $rate) {
    echo $rate->shippingServiceName;
    echo $rate->shippingCost?->value;
    echo $rate->shippingCost?->currency;
    echo $rate->minEstimatedDeliveryDate;
    echo $rate->maxEstimatedDeliveryDate;
    
    // Check rate recommendations
    if (in_array('CHEAPEST_RATE', $rate->rateRecommendation ?? [])) {
        echo "This is the cheapest option!";
    }
}

// Retrieve an existing shipping quote
$quote = Ebay::logistics()->getShippingQuote($shippingQuoteId);

echo $quote->shippingQuoteId;
echo $quote->orderId;

foreach ($quote->rates ?? [] as $rate) {
    echo $rate->rateId;
    echo $rate->carrierId;
    echo $rate->shippingCarrierCode;
}

// Select a rate and create the shipment
$rateId = $quote->rates[0]->rateId; // Pick the first rate

$shipment = Ebay::logistics()->createFromShippingQuote([
    'shippingQuoteId' => $quote->shippingQuoteId,
    'rateId' => $rateId,
    'labelSize' => '4"x6"',
    'labelCustomMessage' => 'Thank you for your purchase!',
]);

echo $shipment->shipmentId;
echo $shipment->shipmentTrackingNumber;
echo $shipment->labelStatus; // OPEN, PURCHASED, EXPIRED, CANCELLED
echo $shipment->creationDate;
echo $shipment->labelExpirationDate;

// Download label as PDF (default)
$labelPdf = Ebay::logistics()->downloadLabelFile($shipment->shipmentId);
file_put_contents('shipping-label.pdf', $labelPdf);

// Download label as ZPL (for thermal printers)
$labelZpl = Ebay::logistics()->downloadLabelFile(
    $shipment->shipmentId,
    'application/zpl'
);
file_put_contents('shipping-label.zpl', $labelZpl);

// Retrieve shipment information
$shipment = Ebay::logistics()->getShipment($shipmentId);

echo $shipment->shipmentId;
echo $shipment->shipmentTrackingNumber;
echo $shipment->labelStatus;
echo $shipment->labelCustomMessage;

// Access rate details
echo $shipment->rate?->shippingServiceCode;
echo $shipment->rate?->shippingCost?->value;
echo $shipment->rate?->carrierId;

// Access addresses
echo $shipment->shipFrom?->fullName;
echo $shipment->shipFrom?->contactAddress?->city;
echo $shipment->shipTo?->fullName;
echo $shipment->returnTo?->contactAddress?->addressLine1;

// Cancel a shipment before label expiration
Ebay::logistics()->cancelShipment($shipmentId);

// After cancellation, labelStatus changes to CANCELLED
$shipment = Ebay::logistics()->getShipment($shipmentId);
echo $shipment->labelStatus; // CANCELLED

// Step 1: Create shipping quote
$quote = Ebay::logistics()->createShippingQuote([
    'orderId' => '12-12345-12345',
    'packageSpecification' => [
        'dimensions' => ['length' => '10', 'width' => '10', 'height' => '5', 'unit' => 'INCH'],
        'weight' => ['value' => '2', 'unit' => 'POUND'],
    ],
    'shipFrom' => [
        'fullName' => 'Your Store',
        'contactAddress' => [
            'addressLine1' => '123 Warehouse Rd',
            'city' => 'Los Angeles',
            'stateOrProvince' => 'CA',
            'postalCode' => '90001',
            'countryCode' => 'US',
        ],
    ],
    'shipTo' => [
        'fullName' => 'Customer Name',
        'contactAddress' => [
            'addressLine1' => '789 Customer St',
            'city' => 'New York',
            'stateOrProvince' => 'NY',
            'postalCode' => '10001',
            'countryCode' => 'US',
        ],
    ],
]);

// Step 2: Find the cheapest rate
$cheapestRate = null;
$lowestCost = PHP_FLOAT_MAX;

foreach ($quote->rates ?? [] as $rate) {
    $cost = (float) ($rate->shippingCost?->value ?? 0);
    if ($cost < $lowestCost) {
        $lowestCost = $cost;
        $cheapestRate = $rate;
    }
}

// Step 3: Create shipment with selected rate
$shipment = Ebay::logistics()->createFromShippingQuote([
    'shippingQuoteId' => $quote->shippingQuoteId,
    'rateId' => $cheapestRate->rateId,
    'labelSize' => '4"x6"',
]);

// Step 4: Download and save label
$labelPdf = Ebay::logistics()->downloadLabelFile($shipment->shipmentId);
$filename = "label-{$shipment->shipmentId}.pdf";
Storage::put("shipping-labels/{$filename}", $labelPdf);

// Step 5: Update order with tracking number
Ebay::fulfillment()->createShippingFulfillment($quote->orderId, [
    'lineItems' => [/* ... */],
    'shippedDate' => now()->toIso8601String(),
    'shippingCarrierCode' => $shipment->rate?->shippingCarrierCode,
    'trackingNumber' => $shipment->shipmentTrackingNumber,
]);

Log::info('Shipping label created', [
    'shipment_id' => $shipment->shipmentId,
    'tracking_number' => $shipment->shipmentTrackingNumber,
    'cost' => $shipment->rate?->shippingCost?->value,
]);

'scopes' => [
    'https://api.ebay.com/oauth/api_scope/sell.logistics',
    // ... other scopes
],

use Tigusigalpa\Ebay\Enums\{ConversationType, ConversationStatus};

$result = Ebay::message()->getConversations([
    'conversation_type' => ConversationType::FROM_MEMBERS->value,
    'conversation_status' => ConversationStatus::UNREAD->value,
    'limit' => 25,
]);

foreach ($result['conversations'] as $conversation) {
    echo $conversation->conversationTitle;
    echo $conversation->latestMessage?->messageBody;
}

// Start new conversation
$message = Ebay::message()->sendMessage([
    'otherPartyUsername' => 'buyer_username',
    'messageText' => 'Thank you for your question.',
    'reference' => [
        'referenceId' => '123456789',
        'referenceType' => 'LISTING',
    ],
]);

// Reply to conversation
$message = Ebay::message()->sendMessage([
    'conversationId' => 'c1234567890',
    'messageText' => 'Here is the information you requested.',
]);

// Mark as read
Ebay::message()->updateConversation([
    'conversationId' => 'c1234567890',
    'conversationType' => ConversationType::FROM_MEMBERS->value,
    'read' => true,
]);

// Archive multiple conversations
$result = Ebay::message()->bulkUpdateConversation([
    'conversations' => [
        [
            'conversationId' => 'c1111111111',
            'conversationType' => ConversationType::FROM_MEMBERS->value,
            'conversationStatus' => 'ARCHIVE',
        ],
    ],
]);

use Tigusigalpa\Ebay\Enums\Site;

// Set marketplace
Ebay::setSite(Site::UK);
Ebay::setSite(Site::GERMANY);
Ebay::setSite(Site::AUSTRALIA);

// Marketplace information
$site = Site::US;
$site->title();        // "United States"
$site->code();         // "us"
$site->url();          // "https://ebay.com"
$site->locale();       // "en-US"
$site->marketplace();  // "EBAY_US"
$site->currency()->symbol(); // "$"

// Find by code
$site = Site::fromCode('uk');           // Site::UK
$site = Site::fromMarketplace('EBAY_DE'); // Site::GERMANY

// List on multiple marketplaces
foreach ([Site::UK, Site::GERMANY, Site::FRANCE] as $site) {
    Ebay::setSite($site)->trading()->addFixedPriceItem($itemData);
}

use Tigusigalpa\Ebay\Enums\{
    Site, 
    Currency, 
    ListingStatus, 
    OrderStatus, 
    PaymentStatus, 
    ListingType,
    ReasonForRefundEnum,
    DisputeStatusEnum,
    EvidenceTypeEnum,
    SellerDecisionEnum
};

// Currency
$currency = Currency::USD;
$currency->symbol();      // "$"
$currency->htmlEntity();  // "&#36;"
$currency->title();       // "US Dollar"

// Listing Status
$status = ListingStatus::ACTIVE;
$status->title();         // "Active"
$status->description();

// Listing Type
$listingType = ListingType::FIXED_PRICE;
$listingType->description(); // "Buy It Now format with a fixed price"

// Fulfillment API Enums
$reason = ReasonForRefundEnum::BUYER_CANCEL;
$reason->title();         // "Buyer Cancel"

$disputeStatus = DisputeStatusEnum::OPEN;
$disputeStatus->title();  // "Open"

$evidenceType = EvidenceTypeEnum::PROOF_OF_DELIVERY;
$evidenceType->title();   // "Proof of Delivery"

use Tigusigalpa\Ebay\Http\Resources\{Order, Item};
use Tigusigalpa\Ebay\Http\Resources\Fulfillment\{
    Order as FulfillmentOrder,
    ShippingFulfillment,
    PaymentDispute
};

// Trading API DTOs
$xml = Ebay::trading()->getOrders();
foreach ($xml->OrderArray->Order as $orderXml) {
    $order = Order::fromXml($orderXml);
    
    echo $order->orderId;
    echo $order->total;
    echo $order->orderStatus->title();
}

// Fulfillment API DTOs (immutable with readonly properties)
$order = Ebay::fulfillment()->getOrder('12-34567-89012');

// Access nested DTOs
echo $order->buyer?->username;
echo $order->pricingSummary?->total?->value;
echo $order->pricingSummary?->total?->currency;

// Line items
foreach ($order->lineItems ?? [] as $lineItem) {
    echo $lineItem->title;
    echo $lineItem->lineItemCost?->value;
    echo $lineItem->quantity;
}

// Payment disputes
$dispute = Ebay::fulfillment()->getPaymentDispute('5001234567890');
echo $dispute->paymentDisputeStatus?->title();
echo $dispute->amount?->value;

// All DTOs use static fromArray() factory method
$orderData = ['orderId' => '12-34567-89012', /* ... */];
$order = FulfillmentOrder::fromArray($orderData);

use Tigusigalpa\Ebay\Exceptions\{EbayApiException, AuthenticationException, InvalidConfigurationException};

try {
    $orders = Ebay::trading()->getOrders();
} catch (AuthenticationException $e) {
    Log::error('eBay auth failed', [
        'error_code' => $e->getErrorCode(),
        'message' => $e->getMessage(),
    ]);
} catch (EbayApiException $e) {
    foreach ($e->getErrors() as $error) {
        echo $error['code'] . ': ' . $error['message'];
    }
} catch (InvalidConfigurationException $e) {
    Log::error('Invalid eBay configuration', ['message' => $e->getMessage()]);
}

// config/ebay.php
'cache' => [
    'enabled' => true,
    'ttl' => 3600,
],

RateLimiter::attempt('ebay-api', $perMinute = 5000, function() {
    // API calls
});

dispatch(new SyncEbayOrdersJob($dateRange));
dispatch(new UpdateInventoryJob($products));

$itemIds = ['123', '456', '789'];
foreach ($itemIds as $itemId) {
    $items[] = Ebay::trading()->getItem($itemId);
    usleep(100000); // Rate limiting
}

Ebay::setRefreshToken($refreshToken, $expiresAt);

'logging' => ['enabled' => true],
bash
composer 
bash
php artisan vendor:publish --tag=ebay-config
bash
git clone https://github.com/tigusigalpa/ebay-php.git
cd ebay-php
composer install
composer test
composer check-style