Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

eBay Node API in TypeScript for Node and Browser with RESTful and Traditional APIs. This library aims to implement all available eBay apis.

License

NotificationsYou must be signed in to change notification settings

hendt/ebay-api

Repository files navigation

Build Statuscodecov

GitHubnpm versionnpm

This eBay API implements both Traditional (xml) and the RESTful eBay API.It supportsclient credentials grant andauthorization code grant (Auth'N'Auth, OAuth2 and IAF). Digital Signature is supported too.

eBay Docs

Changelog

  • v9.2.0-RC.0 is the latest release.
  • Seehere for the full changelog.

Implementation status

RESTful API

APIImplemented
Buy API✔ Browse APIv1.10.0
✔ Deal APIv1.3.0
✔ Feed APIv1.3.1
✔ Marketing APIv1_beta.1.0
✔ Offer APIv1_beta.0.0
✔ Order APIv1_beta.20.0
✔ Marketplace Insights APIv1_beta.2.2
Commerce API✔ Catalog APIv1_beta.3.1
✔ Charity APIv1.2.0
✔ Identity APIv1.0.0
✔ Notification APIv1.2.0
✔ Taxonomy APIv1.0.0
✔ Translation APIv1_beta.1.4
✔ Media APIv1_beta.1.0
Developer API✔ Analytics API
Post Order API✔ Cancellation API
✔ Case Management API
✔ Inquiry API
✔ Return API
Sell API✔ Account APIv1.9.0
✔ Analytics APIv1.3.0
✔ Compliance APIv1.4.1
✔ Feed APIv1.3.1
✔ Finance APIv1.9.0
✔ Fulfillment APIv1.19.10
✔ Inventory APIv1.18.0
✔ Listing APIv1_beta.2.1
✔ Logistics APIv1_beta.0.0
✔ Marketing APIv1.17.0
✔ Metadata APIv1.7.1
✔ Negotiation APIv1.1.0
✔ Recommendation APIv1.1.0

Traditional API

APIImplemented
Finding API
Shopping API
Merchandising API
Trading API
Client Alerts API
Feedback API

Install

npm install ebay-api yarn add ebay-api

🚀 Usage & Quick start

Sign up for an API key here:Developer Account.Checkout APIexamples.

NodeJS

importeBayApifrom'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

importeBayApifrom'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.htmlmarketplaceId:eBayApi.MarketplaceId.EBAY_US,// default. required for RESTful APIsacceptLanguage:eBayApi.Locale.en_US,// defaultcontentLanguage:eBayApi.Locale.en_US,// default.// optional parameters, should be omitted if not useddevId:'-- devId --',// required for traditional Trading APIruName:'-- eBay Redirect URL name --',// 'RuName' (eBay Redirect URL name) required for authorization code grantauthToken:'--  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.

For testing purpose you can usehttps://ebay.hendt.workers.dev/ url as proxy. You can also set up your own Proxyserver. We have added a example for cloudfrontworkers:https://github.com/hendt/ebay-api/blob/master/proxy/worker.js

Or use [https://github.com/Rob--W/cors-anywhere](CORS Anywhere is a NodeJS proxy) (works very well with heroku.com).

ESM

<scripttype="module">importeBayApifrom'https://cdn.jsdelivr.net/npm/ebay-api@latest/dist/ebay-api.min.mjs';// orimporteBayApiEsmfrom'https://esm.sh/ebay-api';</script>

UMD

<scripttype="text/javascript"src="https://cdn.jsdelivr.net/npm/ebay-api@latest/lib/ebay-api.min.js"></script><script>consteBay=neweBayApi({appId:'appId',certId:'certId',sandbox:false});// eBay.req.instance is AxiosInstance per defaulteBay.req.instance.interceptors.request.use((request)=>{// Add Proxyrequest.url='https://ebay.hendt.workers.dev/'+request.url;returnrequest;});eBay.buy.browse.getItem('v1|254188828753|0').then(item=>{console.log(JSON.stringify(item,null,2));}).catch(e=>{console.error(e);});</script>

🔧 eBayApi Config

The first (required) parameter in eBayApi instance takes an object with following properties:

NameOccurrenceDescription
appIdRequiredApp ID (Client ID) fromApplication Keys.
certIdRequiredCert ID (Client Secret) fromApplication Keys.
devIdConditionallyThe Dev Id fromApplication Keys.
sandboxRequired
Default:false
If true, theSandbox Environment will be used.
ruNameConditionallyThe redirect_url value.More info.
autoRefreshTokenRequired
Default:true
Auto refresh the token if it's expired.
siteId
Traditional
Required
Default:SiteId.EBAY_US
eBay site to which you want to send the request (Trading API, Shopping API).
authToken
Traditional
OptionalThe Auth'N'Auth token. The traditional authentication and authorization technology used by the eBay APIs.
marketplaceId
RESTful
Required
Default:MarketplaceId.EBAY_US
Docs 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.
scope
RESTful
Conditionally
Default:
['https://api.ebay.com/oauth/api_scope']
The scopes assigned to your application allow access to different API resources and functionality.
endUserCtx
RESTful
Conditionally recommended
RESTful
Docs X-EBAY_C_ENDUSERCTX provides various types of information associated with the request.
contentLanguage
RESTful
Conditionally required
Default:Locale.en_US
DocsContent-Language indicates the locale preferred by the client for the response.
acceptLanguage
RESTful
Optional
Default:Locale.en_US
Docs 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.

Load config from environment

UseeBayApi.fromEnv() to load data from environment variables.

NameValue
appIdprocess.env.EBAY_APP_ID
certIdprocess.env.EBAY_CERT_ID
devIdprocess.env.EBAY_DEV_ID
authTokenprocess.env.EBAY_AUTH_TOKEN
siteIdprocess.env.EBAY_SITE_ID
marketplaceIdprocess.env.EBAY_MARKETPLACE_ID
ruNameprocess.env.EBAY_RU_NAME
sandboxprocess.env.EBAY_SANDBOX === 'true'

🐞 Debug

To see node debug logs useDEBUG=ebay:* environment variable.

🔑 Access token types

See the full Documentationhere.

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 asuser 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 theirbehalf. This process is called user consent. With the user consent flow, each User token contains the set of scopesforwhich the user has granted theirpermission(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 obtainedautomatically 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 theAuth'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

eBay Docs

importeBayApifrom'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 parametercode

Express example

This is how it would look like if you useexpress:

importeBayApifrom'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:

importeBayApifrom'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 })))
  • The following methods in the Post-Order API:
    • Issue Inquiry Refund -> (eBay.postOrder.inquiry.sign.issueInquiryRefund())
    • Issue case refund -> (eBay.postOrder.inquiry.sign.issueCaseRefund())
    • Issue return refund -> (eBay.postOrder.inquiry.sign.issueReturnRefund())
    • Process Return Request -> (eBay.postOrder.inquiry.sign.processReturnRequest())
    • Create Cancellation Request -> (eBay.postOrder.inquiry.sign.createCancellation())
    • Approve Cancellation Request -> (eBay.postOrder.inquiry.sign.approveCancellationRequest())

How to use Digital Signature

// 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});

RESTful API

How to set the Scope

consteBay=neweBayApi({// ...scope:['https://api.ebay.com/oauth/api_scope']});// Or: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']);

Use apix.ebay.com or apiz.ebay.com (beta) endpoints

For some APIs, eBay use aapix/apiz subdomain. To use these subdomains you can use.apix/.apiz before the apicall 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

IfautoRefreshToken is set to true (default value) the token will be automatically refreshed when eBay responsewithinvalid 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 useeBay.OAuth2.refreshAuthToken() and for the clienttoken useeBay.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-IDX-EBAY-SOA-GLOBAL-ID.You have multiple options to do this.

RESTful API headers

consteBay=neweBayApi();eBay.buy.browse.api({headers:{'X-EBAY-SOA-GLOBAL-ID':'EBAY-DE'}}).getItem('v1|382282567190|651094235351').then((item)=>{console.log(item)})

Traditional API headers

You can pass headers directly in the method call in the second parameter:

eBay.trading.AddFixedPriceItem({Item:{Title:'title',Description:{__cdata:'<div>test</div>'}}},{headers:{'X-EBAY-SOA-GLOBAL-ID':'EBAY-DE'}})

Low level: use the Axios interceptor to manipulate the request

importeBayApifrom'ebay-api';consteBay=neweBayApi(/* {  your config here } */);eBay.req.instance.interceptors.request.use((request)=>{// Add Headerrequest.headers['X-EBAY-SOA-GLOBAL-ID']='EBAY-DE';returnrequest;})

Handle JSON GZIP response e.g fetchItemAspects

You need a decompress library installed likezlib.

npm install zlib# or yarn add zlib
importeBayApifrom'ebay-api';importzlibfrom'zlib';consttoString=(data)=>newPromise((resolve)=>{zlib.gunzip(data,(err,output)=>{if(err)throwerr;resolve(output.toString());});});consteBay=neweBayApi(/* {  your config here } */);try{constdata=awaiteBay.commerce.taxonomy.fetchItemAspects(/* categoryTreeId */);constresult=awaittoString(data);console.log(result)}catch(error){console.error(error);}

Handling errors

importeBayApifrom'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(errorinstanceofEBayApiError&&error.errorCode===17){// Item not found}else{throwerror;}// in error there is also the field "meta" with the responseif(errorinstanceofEBayApiError&&error.meta?.res?.status===404){// not found// The first errorconsole.log(error?.firstError);}}

TheerrorCode is extracted from the first error in the API response.

Controlling Traditional XML request and response

The second parameter in the traditional API has the following options:

exporttypeOptions={raw?:boolean// return raw XMLparseOptions?:X2jOptions// https://github.com/NaturalIntelligence/fast-xml-parserxmlBuilderOptions?:XmlBuilderOptions// https://github.com/NaturalIntelligence/fast-xml-parseruseIaf?:boolean// use IAF in header instead of Bearerheaders?: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 parseoption toparseOptions parameter.

Parse JSON Array

eBay.trading.SetNotificationPreferences({UserDeliveryPreferenceArray:[{NotificationEnable:{EventType:'ItemListed',EventEnable:'Enable',}},{NotificationEnable:{EventType:'ItemSold',EventEnable:'Enable',},}],},{xmlBuilderOptions:{oneListGroup:true}})

Will produce:

<UserDeliveryPreferenceArray>  <NotificationEnable>    <EventType>ItemListed</EventType>    <EventEnable>Enable</EventEnable>  </NotificationEnable>  <NotificationEnable>    <EventType>ItemSold</EventType>    <EventEnable>Enable</EventEnable>  </NotificationEnable></UserDeliveryPreferenceArray>

Examples

Trading - AddFixedPriceItem (CDATA)

You can submit your description using CDATA if you want to use HTML or XML.

eBay.trading.AddFixedPriceItem({Item:{Title:'title',Description:{__cdata:'<div>test</div>'}}})

Trading - ReviseFixedPriceItem (Update the price of an item)

eBay.trading.ReviseFixedPriceItem({Item:{ItemID:'itemId',StartPrice:'startPrice'}})

Buy - getItem

eBay.buy.browse.getItem('v1|382282567190|651094235351').then(a=>{console.log(a);}).catch(e=>{console.log(e)});

Post-Order - getReturn

eBay.postOrder.return.getReturn('5132021997').then(a=>{console.log(a);}).catch(e=>{console.log(e)});

Finding - findItemsByProduct (use XML attributes and value)

eBay.finding.findItemsByProduct({productId:{'@_type':'ReferenceID','#value':'53039031'}})// will produce:// <productId type="ReferenceID">53039031</productId>

Finding - findItemsIneBayStores

eBay.finding.findItemsIneBayStores({storeName:'HENDT'},{raw:true}).then(result=>{// Return raw XMLconsole.log(result);});

Finding - findItemsAdvanced (findItemsByKeywords)

eBay.finding.findItemsAdvanced({itemFilter:[{name:'Seller',value:'hendt_de'}],keywords:'katze'}).then(result=>{console.log(result);});

Trading - GetMyeBaySelling

eBay.trading.GetMyeBaySelling({SoldList:{Include:true,Pagination:{EntriesPerPage:20,PageNumber:1}}}).then(data=>{console.log(data.results)});

FAQ

  1. Do I need theeBay OAuth Client dependency?

No. This library has already all authentication implemented and support also auto refreshing token.

  1. What does IAF mean?

IAF stands for IDENTITY ASSERTION FRAMEWORK.The traditional API supports IAF. That means you can use the OAuth2 token with the traditional APIs.

  1. Is it possible to Upload Pictures directly to EPS?

Yes. Checkout theBrowser exampleandNode Example here.

  1. itemAffiliateWebUrl is missing in eBay.buy.browse.search callYou have to setendUserCtx.

Contribution

Checkhere

Supported By

hendt.de
rootle.de

📝 License

MIT.

About

eBay Node API in TypeScript for Node and Browser with RESTful and Traditional APIs. This library aims to implement all available eBay apis.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp