GithubHelp home page GithubHelp logo

georgicodes / etsy-js Goto Github PK

View Code? Open in Web Editor NEW
35.0 3.0 26.0 106 KB

etsy-js is an asynchronous nodeJS wrapper for the etsy v2 api.

Home Page: https://www.npmjs.org/package/etsy-js

JavaScript 27.22% CoffeeScript 72.78%

etsy-js's Introduction

etsy-js

etsy-js is an asynchronous nodeJS wrapper for the etsy v2 api.

Installation

Install the latest stable version

$ npm install etsy-js

Bleeding edge version

$ git clone https://github.com/GeorgiCodes/etsy-js.git
$ cd etsy-js
$ npm install

Usage

Public Mode

The Etsy API has two modes: public, and authenticated. Public mode only requires an API key (available from http://developer.etsy.com ).

var etsyjs = require('etsy-js');
var client = etsyjs.client('your_api_key');

// direct API calls (GET / PUT / POST / DELETE)
client.get('/users/sparkleprincess', {}, function (err, status, body, headers) {
  console.log(body); //json object
});

// or you can use some convenience methods
var etsyUser = client.user('sparkleprincess');
var etsySearch = client.search();
var etsyShop = client.shop('shopALot');

etsyUser.find(function(err, body, headers) {
  console.log(body); //json object
});

You can make any non-authenticated calls to the API that you need.

Authenticated Mode

The Etsy API has support for both retrieval of extended information and write support for authenticated users. Authentication can be performed from within a web application.

In authenticated mode, you need to set a client, secret and callbackURL.

var etsyjs = require('etsy-js');

var client = etsyjs.client({
  key: 'key',
  secret: 'secret',
  callbackURL: 'http://localhost:3000/authorise'
});

In this mode, you'll need to store the request token and secret before redirecting to the verification URL. A simple example in coffeescript using Express and Express Sessions:

express = require('express')
session = require('express-session')
cookieParser = require('cookie-parser')
url = require('url')
etsyjs = require('etsy-js')

# instantiate client with key and secret and set callback url
client = etsyjs.client
  key: nconf.get('key')
  secret: nconf.get('secret')
  callbackURL: 'http://localhost:3000/authorise'

app = express()
app.use(cookieParser('secEtsy'))
app.use(session())

app.get '/', (req, res) ->
  client.requestToken (err, response) ->
    return console.log err if err
    req.session.token = response.token
    req.session.sec = response.tokenSecret
    res.redirect response.loginUrl

app.get '/authorise', (req, res) ->
  # parse the query string for OAuth verifier
  query = url.parse(req.url, true).query;
  verifier = query.oauth_verifier

  # final part of OAuth dance, request access token and secret with given verifier
  client.accessToken req.session.token, req.session.sec, verifier, (err, response) ->
    # update our session with OAuth token and secret
    req.session.token = response.token
    req.session.sec = response.tokenSecret
    res.redirect '/find'

app.get '/find', (req, res) ->
  # we now have OAuth credentials for this session and can perform authenticated requests
  client.auth(req.session.token, req.session.sec).user("etsyjs").find (err, body, headers) ->
    console.log err if err
    console.dir(body) if body
    res.send body.results[0] if body

server = app.listen 3000, ->
  console.log 'Listening on port %d', server.address().port

API Callback Strucutre

All the callbacks fwill take first an error argument, then a data argument, like this:

etsyUser.find(function(err, body, headers) {
  console.log("error: " + err);
  console.log("data: " + body);
  console.log("headers:" + headers);
});

Pagination

Pagination is supported, simply pass through params as follows:

var params = {
  keywords: "rainbow"
  offset: 1,
  limit: 25
};

client.search().findAllUsers(params, function(err, body, headers) {
  console.log("data: " + body);
});

Etsy authenticated user api

More examples to come...

Get information about the user (GET /user)
etsyUser.find(callback); //json

Development

Running the tests

$ grunt test

Contributions & Bugs

Please submit and bugs to this project and I will fix them. Pull requests also welcome.

Acknowledgements

Thanks to the ruby etsy api wrapper as I used their fixture tests data for the etsy-js tests and README outline. Thanks to octonode for the inspiration to make this API in coffeescript.

Next Steps

  • integrate with travis properly
  • pass in scope?
  • Rate limiting helper method
  • More helper methods!!
  • Flesh out me.coffee (should just call user with SELF) with tests
  • use logging not console

etsy-js's People

Contributors

georgicodes avatar gsabran avatar httpnick avatar kwakuzigah avatar team-pie 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

Watchers

 avatar  avatar  avatar

etsy-js's Issues

Problem with require OAuth in client.js?

Disclaimer: Totally new to js, this module, and node in general, so I may be way off base here.

I kept running into the error:

Error: Cannot find module 'OAuth'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (/var/www/node_modules/etsy-js/lib/etsyjs/client.js:9:11)
at Object. (/var/www/node_modules/etsy-js/lib/etsyjs/client.js:255:4)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)

until I changed OAuth = require('OAuth'); to OAuth = require('oauth');

Am I doing something wrong, or does npm now look for 'oauth' instead of 'OAuth' ?

How can I get the variations for a listing ?

As per Etsy API docs, the url to be used is /listings/:listing_id/variations. Using this API, I am not able to find a way to fetch the variations. Would really appreciate a documentation for the same.

OAuth Error - No ApiKeyIndex for keystring= service=v2_prod

Hi,

I have been using this gem for over a year and it's always worked great. Today I started getting a 400 error during OAuth token request. I have not changed any code.

After searching online I could only find one other occurrence of someone having this issue - but it was posted today by someone else on the Etsy API Google Group: https://groups.google.com/g/etsy-api-v2/c/xEBB2RDjJ5Y/m/kC9UuOQlAgAJ

Here is the rails code:
HttpLogger.log_headers = true # Default: false
HttpLogger.log_request_body = true # Default: true
Etsy.protocol = "https"
Etsy.api_key = 'REDACTED'
Etsy.api_secret = 'REDACTED'
Etsy.permission_scopes = ['transactions_r','transactions_w'];
@request = Etsy.request_token
Etsy.verification_url

Here is what I am seeing:
HTTP POST (82.33ms) https://openapi.etsy.com:443/v2/oauth/request_token?scope=transactions_r+transactions_w
HTTP request header Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3
HTTP request header Accept: /
HTTP request header User-Agent: OAuth gem v0.4.7
HTTP request header Content-Length: 0
HTTP request header Authorization: OAuth oauth_body_hash="2jmj7l5rSw0yVb%2FvlWAYkK%2FYBwk%3D", oauth_callback="oob", oauth_consumer_key="REDACTED", oauth_nonce="x24KXJ5YYIb3diI8FaIeqfgxu6C2sChYMzehgShLMJ0", oauth_signature="JvkGn1QAEDvwZogUyn73R7r%2F2Ro%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1664554043", oauth_version="1.0"
HTTP request header Connection: close
HTTP request header Host: openapi.etsy.com
HTTP request header Content-Type: application/x-www-form-urlencoded
Response status Net::HTTPBadRequest (400)
HTTP response header Connection: close
HTTP response header Content-Length: 45
HTTP response header Server: Apache
HTTP response header X-Cloud-Trace-Context: e6f729b1ff536c7ab1baaee9a2034f8c/17264494395272533402;o=0
HTTP response header X-Etsy-Request-Uuid: EuN0FTurxst1QFMezeU-qqVxLZ08
HTTP response header X-Error-Detail: No ApiKeyIndex for keystring= service=v2_prod
HTTP response header Cache-Control: private
HTTP response header Set-Cookie: user_prefs=soX7TiViCeG4_sbil80U5WVVZIpjZACCZHMRaxgdnVeak6NDHhHLAAA.; expires=Sat, 30-Sep-2023 16:07:23 GMT; Max-Age=31535999; path=/; domain=.etsy.com
HTTP response header Content-Type: text/plain;charset=UTF-8
HTTP response header Via: 1.1 google, 1.1 varnish
HTTP response header Accept-Ranges: bytes
HTTP response header Date: Fri, 30 Sep 2022 16:07:24 GMT
HTTP response header X-Served-By: cache-pao17450-PAO
HTTP response header X-Cache: MISS
HTTP response header X-Cache-Hits: 0
HTTP response header X-Timer: S1664554044.976567,VS0,VE58
Response body No ApiKeyIndex for keystring= service=v2_prod

It seems likely that Etsy made a change on their end but that is now messing up Oauth1 in the gem.

Any advice on how to fix would be greatly appreciated.

Tom

API key not being used

I tried running the very first example in the README and it failed.

index.js:

var etsyjs = require('etsy-js');
var client = etsyjs.client('IPUTMYAPIKEYHERE');

// direct API calls (GET / PUT / POST / DELETE)
client.get('/users/sparkleprincess', {}, function (err, status, body, headers) {
  console.log(body); //json object
});

Running it:

$ node index.js
'==> Client get request with params [object Object]'
'==> Perform unauthenticated GET request'
'API URL is https://openapi.etsy.com/v2/users/sparkleprincess '
'Error parsing response: API request missing api_key or valid OAuth parameters'
undefined
$

I verified that if I take the same URL and add ?api_key=....... to it in a browser, it works fine. So seems that client is not including the api_key header?

Adding scopes

Hi, I'm a student at a bootcamp in vancouver, I've been trying to figure out how to add permission scopes to the client.requestToken when my api authenticates but can't seem to get it working. I see its on your Next Steps but I was wondering if you had any suggestions for now? I was hoping to at least add get listing_w.

edit: Nvm I fixed it, went into your lib and added them manually. Thanks for the contribution btw.. Etsy Api has been very difficult.

Problem with OAuth consumer_key_unknown

I am trying out the example provided in the documentation but getting the following error:

{ statusCode: 401, data: 'oauth_problem=consumer_key_unknown' }

Any idea what's wrong ?

shop client API post not found problem

When invoking client.shop find method for a store which doesn't exist Etsy API returns a string message

'xyz' is not a valid shop name

The client class expects a JSON string to be returned and in that case throws a general error related to failing JSON parse without the original error

client.shop(ctx.params.storeId).find(function (err, body, headers) {
//err is Unexpected token s in JSON at position 0 without any information on original error
});

The solution can be addressed at etsy-js/src/etsyjs/client.coffee -> handleResponse method in the JSON.parse handling

return callback(err)

Tip: Add escape characters to selected_variations in paramDictionery

Tip: querystring.stringify() in oauth package drops nested objects.
Putting selected_variations in addToCart into a string and adding escape characters fixed it.
Solution found via Postman app.

var paramsDict = {
       listing_id : listingID,
       selected_variations : "{\"513\" : 153659624324, \"514\" : 246605444116}"
    }

return client.auth(req.session.token, req.session.sec).post("/users/userID/carts", paramsDict, function(err, status, body, headers) {
      if (err) {
        console.log(err);
      }
      if (body) {
        console.dir(body);
      }
      if (body) {
        return res.send(body.results[0]);
      }
    });

Uploading Images

hi
do you have a example of like Uploading Images for a Listing?
thank you

problem with the constructor for class etsyjs.client('your_api_key');

Hi Georgi

Usage:

var etsyjs = require('etsy-js');
var client = etsyjs.client('your_api_key');

by i see is that in the file client.js, the constructor receives two params

module.exports = function(apiKey, options) {
return new Client(apiKey, options);
};

and when create of new client only receive one param

Client = (function() {
function Client(options) {
this.options = options;
this.apiKey = this.options.key;
this.apiSecret = this.options.secret;
this.callbackURL = this.options.callbackURL;
this.request = request;
this.etsyOAuth = new OAuth.OAuth('https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20profile_r%20profile_w%20address_r%20address_w', 'https://openapi.etsy.com/v2/oauth/access_token', "" + this.apiKey, "" + this.apiSecret, '1.0', "" + this.callbackURL, 'HMAC-SHA1');
}

how in the variant options arrives a string, never initializes this variant this.apiKey...

thank you for attention given

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.