ebay-api for Node and Browser

repository·master·Indexed 42 days ago

https://github.com/hendt/ebay-api

A TypeScript eBay API client for Node.js and browsers supporting both modern RESTful APIs (Buy, Commerce, Developer, Post Order, and Sell) and legacy XML-based Traditional APIs (Shopping, Merchandising, Trading, Client Alerts, and Feedback). Version 10.0.1 supports multiple authentication flows including OAuth2 (client credentials and authorization code grants) and Digital Signatures.

Tokens
54K
Snippets
189
Records
261
Agent score
52%

What's inside ebay-api

  1. Overview of eBay API implementation

    master

    The ebay-api package provides a TypeScript implementation of eBay's APIs with support for both Node.js and Browser environments. It covers two primary communication styles:

    1. RESTful APIs: Modern JSON-based APIs including Buy, Commerce, Developer, Post Order, and Sell APIs.
    2. Traditional APIs: XML-based APIs including Shopping, Merchandising, Trading, Client Alerts, and Feedback APIs.

    The library supports multiple authentication flows:

    • client credentials grant
    • authorization code grant (supporting Auth'N'Auth, OAuth2, and IAF)
    • Digital Signature
  2. v10 Breaking Changes and Behavior Updates

    master

    Several internal behaviors and interfaces have changed in v10:

    • IEBayApiRequest: Now requires a patch(url, data?, config?) method. If providing a custom request implementation, you must implement this.
    • eBay.commerce.media.uploadVideo: Now sends Content-Type: application/octet-stream and accepts an optional headers argument for resumable uploads.
    • eBay.sell.logistics.downloadLabelFile: Now requests application/pdf and returns a raw buffer (responseType: 'arraybuffer').
    • Header Precedence: Per-request headers now correctly override client-wide defaults (fixing issues with multipart/form-data uploads).
    • Sell Finances Filters: Parameters like getPayouts and getTransactions now accept string | string[] for filters.
    • Renamed Method: eBay.commerce.notification.test(subscriptionId) is now eBay.commerce.notification.testSubscription(subscriptionId).
  3. Handle Token Refreshing

    master

    The library supports automatic token refreshing when autoRefreshToken is set to true (default).

    Listening for refreshes: Use the OAuth2 event emitter to capture new tokens and persist them (e.g., to a database).

    • refreshAuthToken: Emitted when a user access token is refreshed.
    • refreshClientToken: Emitted when a client token is refreshed.

    Manual refreshing:

    • eBay.OAuth2.refreshToken(): Automatically picks the correct method to refresh based on provided credentials (requires refresh_token to be set).
    • eBay.OAuth2.refreshUserAccessToken(): Manually refresh user token.
    • eBay.OAuth2.obtainApplicationAccessToken(): Manually refresh client token.
    // Listen for refreshes
    eBay.OAuth2.on('refreshAuthToken', (token) => {
      console.log(token);
      // Store this token in DB
    });
    
    // Manual refresh
    const token = await eBay.OAuth2.refreshToken();
  4. Configure Traditional XML parsing and building

    master

    The library uses fast-xml-parser for Traditional API requests and responses.

    Global Configuration: Set parseOptions in the eBayApi constructor to apply settings to all Traditional API responses.

    Per-call Configuration: Pass parseOptions or xmlBuilderOptions as the second argument to a Traditional API method.

    Important: XML Text Nodes When an element has both attributes and text content, you MUST use the #value key for the text content (not #text). The XML builder is configured with textNodeName: '#value'.

    Example: Parsing JSON Arrays to XML Lists To produce a repeated XML element list from a JS array, use xmlBuilderOptions: { oneListGroup: true }.

    // Global parse options
    const eBay = new eBayApi({
      parseOptions: {
        processEntities: { maxTotalExpansions: 20000 }
      }
    });
    
    // Per-call XML building for arrays
    eBay.trading.SetNotificationPreferences({
      UserDeliveryPreferenceArray: [{
        NotificationEnable: { EventType: 'ItemListed', EventEnable: 'Enable' }
      }]
    }, { xmlBuilderOptions: { oneListGroup: true }});
    
    // Correct way to handle attributes + text
    // Use '#value' instead of '#text'
    const item = {
      StartPrice: { '@_currencyID': 'EUR', '#value': '20.00' }
    };
  5. Understand eBay access token types

    master

    The library supports three main authentication methods depending on your use case:

    1. User access token (Authorization code grant flow):

      • Recommended for most API calls.
      • Required for any interface that accesses or modifies user-owned data (e.g., account info, orders).
      • Obtained via user consent.
    2. Application access token (Client credentials grant flow):

      • Recommended for requesting application-level data (e.g., GET requests for public data).
      • If no other token is provided, the library will attempt to obtain this automatically when calling a RESTful API.
    3. Auth'N'Auth:

      • The legacy method used only with Traditional APIs.
      • Used in the Single User Model where the application supports only one user.
  6. Use ebay-api in the Browser

    master
    Because of eBay's CORS restrictions, you cannot call the API directly from a browser without a Proxy server. You can use a public proxy like https://ebay.hendt.workers.dev/ for testing, or set up your own (e.g., using Cloudflare Workers or CORS Anywhere).
  7. Use custom subdomains (apix/apiz) and endpoints

    master

    For APIs using apix or apiz subdomains, you can access them using the .apix or .apiz property before the method call. You can also configure any custom subdomain using the .api() method.

    // Use apix subdomain
    eBay.buy.browse.apix.getItem(); 
    
    // Use apiz subdomain
    eBay.buy.browse.apiz.getItem(); 
    
    // Use a custom subdomain
    eBay.buy.browse.api({subdomain: 'apiy'}).getItem();
  8. Add additional request headers

    master

    You can add custom headers (like X-EBAY-SOA-GLOBAL-ID) using three different methods depending on the API type and scope:

    1. RESTful API: Pass a headers object within the .api() configuration.
    2. Traditional API: Pass a headers object as the second argument to the method call.
    3. Global (Low level): Use an Axios interceptor to inject headers into every request made by the instance.
    // RESTful API
    eBay.buy.browse.api({
      headers: {
        'X-EBAY-SOA-GLOBAL-ID': 'EBAY-DE'
      }
    }).getItem('...');
    
    // Traditional API
    eBay.trading.AddFixedPriceItem({
      Item: { /* ... */ }
    }, {
      headers: {
        'X-EBAY-SOA-GLOBAL-ID': 'EBAY-DE'
      }
    });
    
    // Global via Axios interceptor
    import eBayApi from 'ebay-api';
    const eBay = new eBayApi();
    
    eBay.req.instance.interceptors.request.use((request) => {
      request.headers['X-EBAY-SOA-GLOBAL-ID'] = 'EBAY-DE';
      return request;
    });
  9. Handle EBayApiError

    master

    Errors from eBay can be caught and inspected using the EBayApiError class. The errorCode property is extracted from the first error in the API response. You can also inspect error.meta.res.status for HTTP status codes and error.firstError for detailed error information.

    import eBayApi from 'ebay-api';
    import { EBayApiError } from 'ebay-api/lib/errors';
    
    try {
      const result = await eBay.trading.GetItem({ ItemID: 'itemId' });
    } catch (error) {
      if (error instanceof EBayApiError && error.errorCode === 17) {
        // Item not found
      } else if (error instanceof EBayApiError && error.meta?.res?.status === 404) {
        console.log(error?.firstError);
      } else {
        throw error;
      }
    }
  10. Use Digital Signatures for EU/UK Sellers

    master

    Signatures are required for EU- or UK-domiciled sellers when using specific APIs.

    Required APIs/Methods:

    • All eBay.sell.finances methods
    • eBay.sell.fulfillment.sign.issueRefund()
    • eBay.trading.GetAccount(null, { sign: true })
    • Post-Order methods: issueInquiryRefund, issueReturnRefund, processReturnRequest, createCancellation, and approveCancellationRequest (all under the .sign. namespace).

    Setup Steps:

    1. Create a signing key using eBay.developer.keyManagement.createSigningKey('ED25519').
    2. Apply the signature either globally via eBay.setSignature(signingKey) or during instantiation in the eBayApi constructor.
    // 1. Create signing key
    const signingKey = await eBay.developer.keyManagement.createSigningKey('ED25519');
    
    // 2. Set the signature globally
    eBay.setSignature(signingKey);
    
    // OR in constructor
    const eBay = new eBayApi({
       appId: '...',
       certId: '...',
       signature: {
          jwe: signingKey.jwe,
          privateKey: signingKey.privateKey
       }
    });
    
    // 3. Use the 'sign' keyword for RESTful or 'sign' parameter for Traditional
    const summary = await eBay.sell.finances.sign.getSellerFundsSummary();
    const account = await eBay.trading.GetAccount(null, {sign: true});