eBay TypeScript/JavaScript API for Browser and Node
Last updated
This eBay API implements both Traditional (xml) and the RESTful eBay API. It supports client credentials grant and authorization code grant (Auth'N'Auth, OAuth2 and IAF). Digital Signature is supported too.
✔ Browse API v1.10.0
✔ Deal API v1.3.0
✔ Feed API v1.3.1
✔ Marketing API v1_beta.1.0
✔ Offer API v1_beta.0.0
✔ Order API v1_beta.20.0
✔ Marketplace Insights API v1_beta.2.2
Commerce API
✔ Catalog API v1_beta.3.1
✔ Charity API v1.2.0
✔ Identity API v1.0.0
✔ Notification API v1.2.0
✔ Taxonomy API v1.0.0
✔ Translation API v1_beta.1.4
✔ Media API v1_beta.1.0
Developer API
✔ Analytics API
Post Order API
✔ Cancellation API
✔ Case Management API
✔ Inquiry API
✔ Return API
Sell API
✔ Account API v1.9.0
✔ Analytics API v1.3.0
✔ Compliance API v1.4.1
✔ Feed API v1.3.1
✔ Finance API v1.9.0
✔ Fulfillment API v1.19.10
✔ Inventory API v1.18.0
✔ Listing API v1_beta.2.1
✔ Logistics API v1_beta.0.0
✔ Marketing API v1.17.0
✔ Metadata API v1.7.1
✔ Negotiation API v1.1.0
✔ Recommendation API v1.1.0
import eBayApi from'ebay-api';// or:// const eBayApi = require('ebay-api')consteBay=neweBayApi({ appId:'-- also called Client ID --', certId:'-- also called Client Secret --', sandbox:false});constitem=awaiteBay.buy.browse.getItem('v1|254188828753|0');console.log(JSON.stringify(item,null,2));
Detailed configuration example
import eBayApi from'ebay-api';consteBay=neweBayApi({ appId:'-- also called Client ID --', certId:'-- also called Client Secret --', sandbox:false, siteId:eBayApi.SiteId.EBAY_US,// required for traditional APIs, see https://developer.ebay.com/DevZone/merchandising/docs/Concepts/SiteIDToGlobalID.html marketplaceId:eBayApi.MarketplaceId.EBAY_US,// default. required for RESTful APIs acceptLanguage:eBayApi.Locale.en_US,// default contentLanguage:eBayApi.Locale.en_US,// default.// optional parameters, should be omitted if not used devId:'-- devId --',// required for traditional Trading API ruName:'-- eBay Redirect URL name --',// 'RuName' (eBay Redirect URL name) required for authorization code grant authToken:'-- Auth\'n\'Auth for traditional API (used by trading) --',// can be set to use traditional API without code grant});
Browser
Check out live example: https://hendt.github.io/ebay-api/. Because of the eBay CORS problems a Proxy server is required to use the API in the Browser.
Client credentials grant flow mints a new Application access token. Authorization code grant flow mints a new User access token.
User access token (authorization code grant flow)
👉 Recommended for all API Calls.
You must employ a User token to call any interface that accesses or modifies data that is owned by the user (such as user information and account data). To get a User token, the users of your app must grant your application the permissions it needs to act upon their behalf. This process is called user consent. With the user consent flow, each User token contains the set of scopes for which the user has granted their permission (eBay Token Types).
Application access token (client credentials grant flow)
👉 Recommended for API calls that will only request application data (GET method, and it's also restricted).
Application tokens are general-use tokens that give access to interfaces that return application data. For example, many GET requests require only an Application token for authorization. (eBay Token Types)
If no other token is set, this token will be obtained automatically in the process of calling an RESTful API.
Auth'N'Auth
In the Single User Model, the application supports only a single user. In this model, you need only one Auth'n'Auth token. 👉 The "old" way. Only works with Traditional API. Checkout the Auth'N'Auth example.
You can also generate the token on eBay developer page and use it directly (see Detailed configuration example).
OAuth2: Exchanging the authorization code for a User access token
import eBayApi from'ebay-api';// 1. Create new eBayApi instance and set the scope.consteBay=eBayApi.fromEnv();eBay.OAuth2.setScope(['https://api.ebay.com/oauth/api_scope','https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly','https://api.ebay.com/oauth/api_scope/sell.fulfillment']);// 2. Generate and open Url and Grant Accessconsturl=eBay.OAuth2.generateAuthUrl();console.log('Open URL', url);
After you granted success, eBay will redirect you to your 'Auth accepted URL' and add a query parameter code
Express example
This is how it would look like if you use express:
import eBayApi from'ebay-api';// This is your RUName endpoint like https://your-ebay.app/successapp.get('/success',asyncfunction (req, res) {// 3. Get the parameter code that is placed as query parameter in redirected pageconstcode=req.query.code; // this is provided from eBayconsteBay=eBayApi.fromEnv(); // or use new eBayApi()try {consttoken=awaiteBay.OAuth2.getToken(code);eBay.OAuth2.setCredentials(token);// store this token e.g. to a sessionreq.session.token = token// 5. Start using the APIconstorders=awaiteBay.sell.fulfillment.getOrders()res.send(orders); } catch (error) {console.error(error)res.sendStatus(400) }});
If token is already in session:
import eBayApi from'ebay-api';app.get('/orders/:id',asyncfunction (req, res) {constid=req.params.id;consteBay=eBayApi.fromEnv(); // or use new eBayApi(...)consttoken=req.session.token;if (!token) {returnres.sendStatus(403); }eBay.OAuth2.setCredentials(token);// If token get's refreshedeBay.OAuth2.on('refreshAuthToken', (token) => {req.session.token = token; });try {// 5. Start using the APIconstorder=awaiteBay.sell.fulfillment.getOrder(id);res.send(order); } catch (error) {console.error(error)res.sendStatus(400) }});
Digital Signature
Signatures are required when the call is made for EU- or UK-domiciled sellers, and only for the following APIs/methods:
All methods in the Finances API -> (eBay.finances.XXX.sign.YYY())
issueRefund in the Fulfillment API -> (eBay.sell.fulfillment.sign.issueRefund())
GetAccount in the Trading API -> (eBay.trading.GetAccount(null, { sign: true })))
// 1. Create singning key and save it appropriatlyconstsigningKey=awaiteBay.developer.keyManagement.createSigningKey('ED25519');// 2. Set the signatureeBay.setSignature(signingKey)// or in constructoreBay =neweBayApi({ appId:'...', certId:'...', signature: { jwe:signingKey.jwe, privateKey:signingKey.privateKey }});// 3. Use the 'sign' keyword in Restful APIconstsummary=awaiteBay.sell.finances.sign.getSellerFundsSummary();// 3. Or the 'sign' parameter in traditional APIconstaccount=awaiteBay.trading.GetAccount(null, {sign:true});
Use apix.ebay.com or apiz.ebay.com (beta) endpoints
For some APIs, eBay use a apix/apiz subdomain. To use these subdomains you can use .apix/.apiz before the api call like this:
eBay.buy.browse.apix.getItem() // now it will use https://apix.ebay.comeBay.buy.browse.apiz.getItem() // now it will use https://apiz.ebay.com
In any case eBay adds a new subdomain, it's also possible to configure whatever you want:
eBay.buy.browse.api({subdomain:'apiy'}).getItem() // now it will use https://apiy.ebay.com
Return raw RESTful API response
eBay.buy.browse.api({ returnResponse:true,// return the response instead of data}).getItem();
How to refresh the token
If autoRefreshToken is set to true (default value) the token will be automatically refreshed when eBay response with invalid access token error.
Use Event Emitter to get the token when it gets successfully refreshed.
eBay.OAuth2.on('refreshAuthToken', (token) => {console.log(token)// Store this token in DB});// for client tokeneBay.OAuth2.on('refreshClientToken', (token) => {console.log(token)// Store this token in DB});
To manual refresh the auth token use eBay.OAuth2.refreshAuthToken() and for the client token use eBay.OAuth2.refreshClientToken(). Keep in mind that you need the 'refresh_token' value set.
consttoken=awaiteBay.OAuth2.refreshToken();// will refresh Auth Token if set, otherwise the client token if set.
Additional request headers
Sometimes you want to add additional headers to the request like a GLOBAL-ID X-EBAY-SOA-GLOBAL-ID. You have multiple options to do this.
import eBayApi from'ebay-api';import { EBayApiError } from'ebay-api/lib/errors';consteBay=neweBayApi(/* { your config here } */);try {constresult=awaiteBay.trading.GetItem({ ItemID:'itemId', });console.log(result);} catch (error) {if (error instanceofEBayApiError&&error.errorCode ===17) {// Item not found } else {throw error; }// in error there is also the field "meta" with the responseif (error instanceofEBayApiError&&error.meta?.res?.status ===404) {// not found// The first errorconsole.log(error?.firstError); }}
The errorCode is extracted from the first error in the API response.
The second parameter in the traditional API has the following options:
exporttypeOptions= { raw?:boolean// return raw XML parseOptions?:X2jOptions// https://github.com/NaturalIntelligence/fast-xml-parser xmlBuilderOptions?:XmlBuilderOptions// https://github.com/NaturalIntelligence/fast-xml-parser useIaf?:boolean// use IAF in header instead of Bearer headers?:Headers// additional Headers (key, value)hook?: (xml) =>BodyHeaders// hook into the request to modify the body and headers};
Fast XML is used to parse the XML. You can pass the parse option to parseOptions parameter.
REST HTTP Header. X-EBAY-C-MARKETPLACE-ID identifies the user's business context and is specified using a marketplace ID value. Note that this header does not indicate a language preference or consumer location.
X-EBAY_C_ENDUSERCTX provides various types of information associated with the request.
Content-Language indicates the locale preferred by the client for the response.
Accept-Language indicates the natural language the client prefers for the response. This specifies the language the client wants to use when the field values provided in the request body are displayed to consumers.