Code Monkey home page Code Monkey logo

ebay-oauth-nodejs-client's Introduction

Ebay Oauth Client

This code allows developers to fetch an OAuth token that can be used to call the eBay Developer REST APIs. The code is intended for use with Node.js.

npm version Build Status

Table of Contents

What is OAuth

OAuth 2.0 is the most widely used standard for authentication and authorization for API based access. The complete end to end documentation on how eBay OAuth functions may be used is available at developer.ebay.com. See: https://developer.ebay.com/api-docs/static/oauth-tokens.html

Installation

Using npm:

npm install ebay-oauth-nodejs-client

Using yarn:

yarn add ebay-oauth-nodejs-client

Usage

EbayAuthToken(config)

Create a new instance of EbayAuthToken with a relevant config.

const EbayAuthToken = require('ebay-oauth-nodejs-client');

const ebayAuthToken = new EbayAuthToken({
    clientId: '<your_client_id>',
    clientSecret: '<your_client_secret>',
    redirectUri: '<redirect uri>'
});
ebayAuthToken.getApplicationToken(environment)

Generate client credential token.

(async () => {
    const token = await ebayAuthToken.getApplicationToken('PRODUCTION');
    console.log(token);
})();
ebayAuthToken.generateUserAuthorizationUrl(environment, scopes[, options])

Generate user consent authorization url.

(() => {
    const authUrl = ebayAuthToken.generateUserAuthorizationUrl('PRODUCTION', scopes);
    console.log(authUrl);
})();

You can also provide optional values:
state: An opaque value used by the client to maintain state between the request and callback.
prompt: Force a user to log in when you redirect them to the Grant Application Access page, even if they already have an existing user session.

The method call above could also be done as

(() => {
    const options = { state: 'custom-state-value', prompt: 'login' };
    const authUrl = ebayAuthToken.generateUserAuthorizationUrl('PRODUCTION', scopes, options);
    console.log(authUrl);
})();
ebayAuthToken.exchangeCodeForAccessToken(environment, code)

Getting a User access token.

(async () => {
    const accessToken = await ebayAuthToken.exchangeCodeForAccessToken('PRODUCTION', code);
    console.log(accessToken);
})();
ebayAuthToken.getAccessToken(environment, refreshToken, scopes)

Using a refresh token to update a User access token (Updating the expired access token).

(async () => {
    const accessToken = await ebayAuthToken.getAccessToken('PRODUCTION', refreshToken, scopes);
    console.log(accessToken);
})();

Library Setup and getting started

  1. Invoke the oauth ebay library as given below
const EbayAuthToken = require('ebay-oauth-nodejs-client');
const ebayAuthToken = new EbayAuthToken({
    filePath: 'demo/eBayJson.json' // input file path.
})

OR

const ebayAuthToken = new EbayAuthToken({
    clientId: '<your_client_id>',
    clientSecret: '<your_client_secret>',
    redirectUri: '<redirect_uri_name>'
});
  1. If you want to get your application credentials such as AppId, DevId, and CertId. Refer to Creating eBay Developer Account for details on how to get these credentials.
  2. You can refer to example.js for an example of how to use credentials.
  3. For Authorization code grant
    1. Get User consent url using ebayAuthToken.generateUserAuthorizationUrl()
    2. Open the generateUserAuthorizationUrl in the browser, which allows you to login in to ebay site. You will get a authorization code, or if you are using express, use res.direct(generateUserAuthorizationUrl);
    3. Pass the authorization code retrieved in the above step to exchangeCodeForAccessToken method using ebayAuthToken.exchangeCodeForAccessToken(environment, code)

Configure credentials

Create a config JSON file in your application. The config file should contain your eBay applications keys: App Id, Cert Id & Dev Id. A sample config file is available at demo/ebay-config-sample.json. Learn more about creating application keys.

{
    "SANDBOX": {
        "clientId": "---Client Id---",
        "clientSecret": "--- client secret---",
        "devid": "-- dev id ---",
        "redirectUri": "-- redirect uri ---",
        "baseUrl": "api.sandbox.ebay.com" //don't change these values
    },
    "PRODUCTION": {
        "clientId": "---Client Id---",
        "clientSecret": "--- client secret---",
        "devid": "-- dev id ---",
        "redirectUri": "-- redirect uri ---",
        "baseUrl": "api.ebay.com" //don't change these values
    }
}

Types of Tokens

There are mainly two types of tokens in usage.

Application Token

An application token contains an application identity which is generated using client_credentials grant type. These application tokens are useful for interaction with application specific APIs such as usage statistics etc.,

User Token

A user token (access token or refresh token) contains a user identity and the application’s identity. This is usually generated using the authorization_code grant type or the refresh_token grant type.

Supported Grant Types for OAuth

All of the regular OAuth 2.0 specifications such as client_credentials, authorization_code, and refresh_token are supported. Refer to eBay Developer Portal

Client Credentials

This grant type can be performed by simply using ebayAuthToken.getApplicationToken(). Read more about this grant type at oauth-client-credentials-grant.

Authorization Code

This grant type can be performed by a two step process. Call ebayAuthToken.generateUserAuthorizationUrl(environment, scopes, state) to get the Authorization URL to redirect the user to. Once the user authenticates and approves the consent, the callback needs to be captured by the redirect URL setup by the app and then call ebayAuthToken.exchangeCodeForAccessToken(environment, code) to get the refresh and access tokens.

Read more about this grant type at oauth-authorization-code-grant.

Refresh Token

This grant type can be performed by simply using ebayAuthToken.getAccessToken(environment, refreshToken, scopes). Usually access tokens are short lived and if the access token is expired, the caller can use the refresh token to generate a new access token. Read more about it at Using a refresh token to update a user access token

Questions/problems?

you've found an bug/issue, please file it on GitHub.

References

  1. https://developer.ebay.com/api-docs/static/oauth-tokens.html

  2. https://developer.ebay.com/api-docs/static/oauth-quick-ref-user-tokens.html

  3. https://developer.ebay.com/api-docs/static/oauth-gen-app-token.html

  4. https://developer.ebay.com/my/keys

License

Copyright (c) 2019 eBay Inc.

Use of this source code is governed by a Apache-2.0 license that can be found in the LICENSE file or at https://opensource.org/licenses/Apache-2.0.

Useful links

ebay-oauth-nodejs-client's People

Contributors

dependabot[bot] avatar fmunirdev avatar lokeshrishi avatar olliechick avatar pajaydev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ebay-oauth-nodejs-client's Issues

Support passing credentials via constructor

Right now this library takes the filePath, it would be easy if we can able to pass the credentials through the constructor like below.

const ebayAuthToken = new EbayAuthToken({
    "clientId": "---Client Id---",
     "clientSecret": "--- client secret---",
     "devid": "-- dev id ---",
     "redirectUri": "-- redirect uri ---",
})

`getApplicationToken(...) is not a function` is definitely a function

I am having some trouble implementing this library. I think the readme could use some clarification. One of the pieces of data I am getting back in found in the console output as described in my gist:

EbayOauthToken {
  credentials: {
    PRODUCTION: {
        ...
        env: 'PRODUCTION',
        baseUrl: 'api.ebay.com'
    }
  },
  grantType: ''
}

I saw from another issue open that these properties (env, baseURL) need to be overridden.

Latest version not published to NPM

Trying to use this library and I'm getting some strange behaviour when passing options into generateUserAuthorizationUrl, only to find the changes in #8 are not currently released. Could the latest master branch be released?

STAGING not supported

Hi! πŸ‘‹

Firstly, thanks for your work on this project! πŸ™‚

Today I used patch-package to patch [email protected] for the project I'm working on.

Add support for STAGING

Here is the diff that solved my problem:

diff --git a/node_modules/ebay-oauth-nodejs-client/demo/ebay-config-sample.json b/node_modules/ebay-oauth-nodejs-client/demo/ebay-config-sample.json
index 87cb57e..8106cac 100644
--- a/node_modules/ebay-oauth-nodejs-client/demo/ebay-config-sample.json
+++ b/node_modules/ebay-oauth-nodejs-client/demo/ebay-config-sample.json
@@ -12,5 +12,13 @@
         "devid": "-- dev id ---",
         "redirectUri": "-- redirect uri ---",
         "baseUrl": "api.ebay.com"
+    },
+    "STAGING": {
+        "clientId": "---Client Id---",
+        "clientSecret": "--- client secret---",
+        "devid": "-- dev id ---",
+        "redirectUri": "-- redirect uri ---",
+        "baseUrl": "apima.qa.ebay.com"
     }
 }
+
diff --git a/node_modules/ebay-oauth-nodejs-client/src/constants.js b/node_modules/ebay-oauth-nodejs-client/src/constants.js
index f00c96c..391f57e 100644
--- a/node_modules/ebay-oauth-nodejs-client/src/constants.js
+++ b/node_modules/ebay-oauth-nodejs-client/src/constants.js
@@ -18,6 +18,7 @@ module.exports.OAUTHENVIRONMENT_WEBENDPOINT_PRODUCTION = 'https://auth.ebay.com/
 module.exports.OAUTHENVIRONMENT_WEBENDPOINT_SANDBOX = 'https://auth.sandbox.ebay.com/oauth2/authorize';
 
 // API End Point
+module.exports.OAUTHENVIRONMENT_APIENDPOINT_STAGING = 'https://apima.qa.ebay.com/identity/v1/oauth2/token';
 module.exports.OAUTHENVIRONMENT_APIENDPOINT_SANDBOX = 'https://api.sandbox.ebay.com/identity/v1/oauth2/token';
 module.exports.OAUTHENVIRONMENT_APIENDPOINT_PRODUCTION = 'https://api.ebay.com/identity/v1/oauth2/token';
 
@@ -25,5 +26,6 @@ module.exports.OAUTHENVIRONMENT_APIENDPOINT_PRODUCTION = 'https://api.ebay.com/i
 module.exports.CLIENT_CRED_SCOPE = 'https://api.ebay.com/oauth/api_scope';
 
 // Environments
+module.exports.STAGING_ENV = 'STAGING';
 module.exports.PROD_ENV = 'PRODUCTION';
 module.exports.SANDBOX_ENV = 'SANDBOX';
diff --git a/node_modules/ebay-oauth-nodejs-client/src/request.js b/node_modules/ebay-oauth-nodejs-client/src/request.js
index f0100b6..9615cb7 100644
--- a/node_modules/ebay-oauth-nodejs-client/src/request.js
+++ b/node_modules/ebay-oauth-nodejs-client/src/request.js
@@ -27,6 +27,7 @@ const base64Encode = (encodeData) => {
 const postRequest = (data, ebayAuthToken) => {
     const encodedStr = base64Encode(`${ebayAuthToken.clientId}:${ebayAuthToken.clientSecret}`);
     const auth = `Basic ${encodedStr}`;
+
     return new Promise((resolve, reject) => {
         const request = https.request({
             headers: {
diff --git a/node_modules/ebay-oauth-nodejs-client/src/utils.js b/node_modules/ebay-oauth-nodejs-client/src/utils.js
index bd4da71..b41d41e 100644
--- a/node_modules/ebay-oauth-nodejs-client/src/utils.js
+++ b/node_modules/ebay-oauth-nodejs-client/src/utils.js
@@ -20,6 +20,7 @@ const fs = require('fs');
 const path = require('path');
 const sandboxBaseUrl = 'api.sandbox.ebay.com';
 const prodBaseUrl = 'api.ebay.com';
+const stagingBaseUrl = 'apima.qa.ebay.com';
 
 const readJSONFile = (fileName) => {
     try {
@@ -32,7 +33,7 @@ const readJSONFile = (fileName) => {
 };
 
 const validateParams = (environment, scopes, credentials) => {
-    if (!environment) throw new Error('Kindly provide the environment - PRODUCTION/SANDBOX');
+    if (!environment) throw new Error('Kindly provide the environment - PRODUCTION/SANDBOX/STAGING');
     if (!scopes) throw new Error('scopes is required');
     if (!credentials) throw new Error('credentials configured incorrectly');
 };
@@ -40,7 +41,17 @@ const validateParams = (environment, scopes, credentials) => {
 const readOptions = (options) => {
     const credentials = {};
     if (!options.env) options.env = 'PRODUCTION';
-    options.baseUrl = options.env === 'PRODUCTION' ? prodBaseUrl : sandboxBaseUrl;
+    switch (options.env) {
+        case 'SANDBOX':
+            options.baseUrl = sandboxBaseUrl;
+            break;
+        case 'STAGING':
+            options.baseUrl = stagingBaseUrl;
+            break;
+        default:
+            options.baseUrl = prodBaseUrl;
+            break;
+    }
     credentials[options.env] = { ...options };
     return credentials;
 };

This issue body was partially generated by patch-package.

Having trouble opening the browser authorization URL to retrieve authorization code

I'm running this code in my server.js:

let authUrl = ebayAuthToken.generateUserAuthorizationUrl('PRODUCTION', scopes, options);
    authUrl = authUrl.split(" ")
    res.redirect(authUrl[0]);

But I keep getting this error in my console:

Access to XMLHttpRequest at 'https://auth.ebay.com/oauth2/authorize?client_id=---CLIENT-ID---&response_type=code&scope=https://auth.ebay.com/oauth2/authorize?client_id=---CLIENT-ID---&response_type=code&redirect_uri=---REDIRECT-URI---=https://api.ebay.com/oauth/api_scope' (redirected from 'https://localhost:3000/ebay-user-auth') from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I switched out my client IDs and the URI with placeholders. I am using Express js but not AJAX.

Any ideas on how to fix this error?

Unable to use sandbox environment

Hi there,

When attempting to fetch a token using the sandbox environment, the lib throws an error:

const encodedStr = base64Encode(`${ebayAuthToken.clientId}:${ebayAuthToken.clientSecret}`);
                                                     ^

TypeError: Cannot read property 'clientId' of undefined

Code I'm using w/ my sandbox creds:

const EbayAuthToken = require('ebay-oauth-nodejs-client');

const ebayAuthToken = new EbayAuthToken({
  clientId: '',
  clientSecret: '',
  redirectUri: '',
});

(async () => {
  const token = await ebayAuthToken.getApplicationToken('SANDBOX');
  console.log(token);
})();

Any way to access my own ebay account history through a script?

Thanks for this library, it makes dealing with the ebay API significantly easier.

I was trying to access my own ebay account programmatically.

I am able to use this code to get the URL for the user login, but it seems that the only way I can provide credentials to get a user token is to go through a browser. Is there a way to provide credentials to my script so I can get a user authorization, and be able to download my ebay user's history, etc?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.