Code Monkey home page Code Monkey logo

woocommerce-rest-api-js-lib's Introduction

WooCommerce REST API - JavaScript Library

New JavaScript library for WooCommerce REST API, supports CommonJS (CJS) and Embedded System Module (ESM).

Requests are made with Axios library with support to promises.

build status dependency status npm version

Installation

npm install --save @woocommerce/woocommerce-rest-api

Getting started

Generate API credentials (Consumer Key & Consumer Secret) following this instructions http://docs.woocommerce.com/document/woocommerce-rest-api/ .

Check out the WooCommerce API endpoints and data that can be manipulated in http://woocommerce.github.io/woocommerce-rest-api-docs/.

Setup

ESM example:

import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";

const api = new WooCommerceRestApi({
  url: "http://example.com",
  consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  version: "wc/v3"
});

CJS example:

const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;

const api = new WooCommerceRestApi({
  url: "http://example.com",
  consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  version: "wc/v3"
});

Options

Option Type Required Description
url String yes Your Store URL, example: http://woo.dev/
consumerKey String yes Your API consumer key
consumerSecret String yes Your API consumer secret
wpAPIPrefix String no Custom WP REST API URL prefix, used to support custom prefixes created with the rest_url_prefix filter
version String no API version, default is v3
encoding String no Encoding, default is 'utf-8'
queryStringAuth Bool no When true and using under HTTPS force Basic Authentication as query string, default is false
port string no Provide support for URLs with ports, eg: 8080
timeout Integer no Define the request timeout
axiosConfig Object no Define the custom Axios config, also override this library options

Methods

GET

  • .get(endpoint)
  • .get(endpoint, params)
Params Type Description
endpoint String WooCommerce API endpoint, example: customers or orders/12
params Object Query strings params, example: { per_page: 20 }

POST

  • .post(endpoint, data)
  • .post(endpoint, data, params)
Params Type Description
endpoint String WooCommerce API endpoint, example: customers or orders
data Object JS object to be converted into JSON and sent in the request
params Object Query strings params

PUT

  • .put(endpoint, data)
  • .put(endpoint, data, params)
Params Type Description
endpoint String WooCommerce API endpoint, example: customers/1 or orders/1234
data Object JS object to be converted into JSON and sent in the request
params Object Query strings params

DELETE

  • .delete(endpoint)
  • .delete(endpoint, params)
Params Type Description
endpoint String WooCommerce API endpoint, example: customers/2 or orders/12
params Object Query strings params, example: { force: true }

OPTIONS

  • .options(endpoint)
  • .options(endpoint, params)
Params Type Description
endpoint String WooCommerce API endpoint, example: customers/2 or orders/12
params Object Query strings params

Example of use

// import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";
const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;

const api = new WooCommerceRestApi({
  url: "http://example.com",
  consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  version: "wc/v3"
});

// List products
api.get("products", {
  per_page: 20, // 20 products per page
})
  .then((response) => {
    // Successful request
    console.log("Response Status:", response.status);
    console.log("Response Headers:", response.headers);
    console.log("Response Data:", response.data);
    console.log("Total of pages:", response.headers['x-wp-totalpages']);
    console.log("Total of items:", response.headers['x-wp-total']);
  })
  .catch((error) => {
    // Invalid request, for 4xx and 5xx statuses
    console.log("Response Status:", error.response.status);
    console.log("Response Headers:", error.response.headers);
    console.log("Response Data:", error.response.data);
  })
  .finally(() => {
    // Always executed.
  });

// Create a product
api.post("products", {
  name: "Premium Quality", // See more in https://woocommerce.github.io/woocommerce-rest-api-docs/#product-properties
  type: "simple",
  regular_price: "21.99",
})
  .then((response) => {
    // Successful request
    console.log("Response Status:", response.status);
    console.log("Response Headers:", response.headers);
    console.log("Response Data:", response.data);
  })
  .catch((error) => {
    // Invalid request, for 4xx and 5xx statuses
    console.log("Response Status:", error.response.status);
    console.log("Response Headers:", error.response.headers);
    console.log("Response Data:", error.response.data);
  })
  .finally(() => {
    // Always executed.
  });

// Edit a product
api.put("products/1", {
  sale_price: "11.99", // See more in https://woocommerce.github.io/woocommerce-rest-api-docs/#product-properties
})
  .then((response) => {
    // Successful request
    console.log("Response Status:", response.status);
    console.log("Response Headers:", response.headers);
    console.log("Response Data:", response.data);
  })
  .catch((error) => {
    // Invalid request, for 4xx and 5xx statuses
    console.log("Response Status:", error.response.status);
    console.log("Response Headers:", error.response.headers);
    console.log("Response Data:", error.response.data);
  })
  .finally(() => {
    // Always executed.
  });

// Delete a product
api.delete("products/1", {
  force: true, // Forces to delete instead of move to the Trash
})
  .then((response) => {
    // Successful request
    console.log("Response Status:", response.status);
    console.log("Response Headers:", response.headers);
    console.log("Response Data:", response.data);
  })
  .catch((error) => {
    // Invalid request, for 4xx and 5xx statuses
    console.log("Response Status:", error.response.status);
    console.log("Response Headers:", error.response.headers);
    console.log("Response Data:", error.response.data);
  })
  .finally(() => {
    // Always executed.
  });

Changelog

See changelog for details

woocommerce-rest-api-js-lib's People

Contributors

barryhughes avatar claudiosanches avatar climba03003 avatar lsinger avatar pihvi avatar renovate-bot avatar renovate[bot] avatar tbhaxor 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

woocommerce-rest-api-js-lib's Issues

Does it has support for subscription?

There is no mention regarding support for subscription in the documentation. I just want to know if its already integrated in this version.

Thanks!

Parameters are been sent but not properly on the URL

Hello,

I'm using a simple call to get all the products using this library:
"@woocommerce/woocommerce-rest-api": "^1.0.1"

I add the parameter as suggested in the documentation to get only 2 or 5 products per page to test it out. I do get the parameter is been sent but not on the URL so the response is the same.

Attaching my code and a screenshot of the resulting request.

`const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;

const api = new WooCommerceRestApi({
url: "https://example.com/",
consumerKey: "ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
consumerSecret: "cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
version: "wc/v3"
});

let categories = [];

// Get all categories.
api.get("products/categories", {
per_page : 5,
})
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
console.log("Total of pages:", response.headers['x-wp-totalpages']);
console.log("Total of items:", response.headers['x-wp-total']);
categories = response.data;
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
console.log('Done getting categories.');
console.log('Size of categories', categories.length);
});`

error-api

Hope this can be resolved!
Thanks.

401 error - Invalid signature - provided signature does not match

Hi,

Following error gets returned when calling an endpoint.

{
code: 'woocommerce_rest_authentication_error',
message: 'Invalid signature - provided signature does not match.',
data: { status: 401 }
}

I am providing valid consumerKey and consumerSecret values.
Can someone take a look?

Thanks!

post delete put function success but it did not add delete or change product

post delete put function success but it did not add delete or change product

So I am trying to add a product to my woo-commerce shop using the woocommerce-rest-api. I can successfully retrieve a list of the products using the WooCommerce.get("products") method, but when I used the post method to add a new product. It successfully give me a response (showing the list of products) but it did not add the new product.

//CONFIG
const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;
const WooCommerce = new WooCommerceRestApi({
  url: "https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.com",
  consumerKey: "ck_xxxxxxxxxxxxxxxxxxxxxxxxxxx",
  consumerSecret: "cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  version: "wc/v3",
  queryStringAuth: true,
});
//NEW PRODUCT

const data = {
  name: "Premium Quality", // See more in https://woocommerce.github.io/woocommerce-rest-api-docs/#product-properties
  type: "simple",
  regular_price: "21.99",
};
//POST
WooCommerce.post("products", data)
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error.response.data);
  });

Refused to set unsafe header "User-Agent"

sample code

const api = new WooCommerceRestApi({
  url: "http://my-personal-store.com",
  consumerKey: "ck_xxxxxxxxxx",
  consumerSecret: "cs_xxxxxxxx",
  version: "wc/v3"
});

const { data : categories } = await api.get(`products/categories`)

fires successfully and return the response but it also spit errors in Chrome console

Refused to set unsafe header "User-Agent"

It is also taking a lot of time to fetch (2-3s) due to throwing and catching (i guess)

Post not work as expected

const W = require("@woocommerce/woocommerce-rest-api").default;

const wooAPI = new W({
url: "URL",
consumerKey: "...",
consumerSecret: "...",
version: "wc/v3",
wpAPI: true,
queryStringAuth: true
});

let data = {...}

wooAPI.post("orders", data)
.then(response => {
// Successful request
console.log("Respuesta:", response.data);
})
.catch(error => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
});

always return a list of orders instead create new order, its very broken this part, its not useful.

Slow response time

I have a store with 2285 products and 2434 product variations, and I'm using Flatsome. The server average response time is about 200ms.
But when I'm making requests with the REST API, my response time increases to 10s.
And if I test a sequence of GETs in postman, the response time for each request increases almost to 30s.
I saw some people discussing the API and how It works. And I want to know if the problem is some plugin, my host, or some problem with the REST API.

Edit: Another related issue

Request handling error

(node:19193) UnhandledPromiseRejectionWarning: Error: socket hang up
at createHangUpError (_http_client.js:323:15)
at Socket.socketOnEnd (_http_client.js:426:23)
at Socket.emit (events.js:194:15)
at endReadableNT (_stream_readable.js:1103:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
(node:19193) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:19193) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

param query per_page not working

I have a problem retrieving the products list, i want to return 20 item for request get products. I tried

const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;

const api = new WooCommerceRestApi({
  url: "http://myurl.com",
  consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  version: "wc/v3"
});

api.get("products", {
  per_page: 20
})
  .then((response) => {
       console.log(response.data.length);
  })
  .catch((error) => {
    console.log("Response Data:", error.response.data);
  })
  .finally(() => {
    // Always executed.
  });

but the request doesn't seem to receive per_page=20, it return default 10 items
can anyone help me to solve this problem?
many thanks

Pass along cookie with order request

I'm using a Lambda function to send the order request to WooCommerce. I need to be able to send along a cookie to define which currency the order is made in (using Aelia's multi currency plugin). Unfortunately I have not been able to find a working solution yet.

This should be possible trough a custom axios config but so far nothing is working.. any ideas will be helpful.

Hi.

Hi.
I could not make this plugin work with IONIC 4

i use woocommerce-api and works fine!!

npm i woocommerce-api

https://www.npmjs.com/package/woocommerce-api

must update a file
@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.js

line 91
node: false,
to
node: { crypto: true, stream: true, fs: "empty", net: "empty", tls: "empty" },

Originally posted by @guntercn in #40 (comment)

The above solution works on Android, l tried to do the same on a Mac running the app on browser. the moment you install woo commerce API and edit the browser.js file crypto: true the local storage will not work. I am struggling right now as we speak below is my setup.

Ionic:

Ionic CLI : 5.4.5 (/usr/local/lib/node_modules/ionic)
Ionic Framework : @ionic/angular 5.3.1
@angular-devkit/build-angular : 0.901.12
@angular-devkit/schematics : 9.1.12
@angular/cli : 9.1.12
@ionic/angular-toolkit : 2.3.0

Utility:

cordova-res : not installed
native-run : not installed

System:

NodeJS : v12.18.3 (/usr/local/bin/node)
npm : 6.14.6
OS : macOS Catalina

Critical: Response Body Is Empty

Appears empty when using the orders call. As you see, I get Satus, Headers (incl. vlaues "x-wp-total" and "x-wp-totalpages") but response.data is totally empty.

I've tried this "orders" endpoint using Postman and a straight axios implementation, both with Basic Auth and with keys as query params in the url, but on the /orders endpoint I'm always getting data empty.

NOTE:
We've had this issue since 16 June. Then when I swapped out my axios implementation to using this module instead (woocommerce-rest-api) it worked for a couple of requests yesterday evening. But now it doesn't at all!

Are there API request limits? Please help as our app is down as a result of this.

Request

const api = new WooCommerceRestApi({
            url: url,
            consumerKey: consumerKey,
            consumerSecret: consumerSecret,
            version: "wc/v3"
        });

        api.get("orders", {
            after: today,
            before: endOfToday
        })
            .then((response: any) => {
                // Successful request
                console.log("Response:", response);
                console.log("Response Status:", response.status);
                console.log("Response Headers:", response.headers);
                console.log("Response Data:", response.data);
                console.log("Total of pages:", response.headers['x-wp-totalpages']);
                console.log("Total of items:", response.headers['x-wp-total']);
                resolve(response.data);
            })
            .catch((error: any) => {
                // Invalid request, for 4xx and 5xx statuses
                console.log("Response Status:", error.response.status);
                console.log("Response Headers:", error.response.headers);
                console.log("Response Data:", error.response.data);
                reject(error);
            });

Response

Response Status: 200
>  Response Headers: {
>    connection: 'close',
>    'x-powered-by': 'PHP/7.2.31',
>    'content-type': 'application/json; charset=UTF-8',
>    'x-robots-tag': 'noindex',
>    'x-content-type-options': 'nosniff',
>    'access-control-expose-headers': 'X-WP-Total, X-WP-TotalPages',
>    'access-control-allow-headers': 'Authorization, Content-Type',
>    expires: 'Wed, 11 Jan 1984 05:00:00 GMT',
>    'cache-control': 'no-transform, no-cache, no-store, must-revalidate',
>    'x-wp-total': '34',
>    'x-wp-totalpages': '4',
>    link: '<https://not-real-domain.com/wp-json/wc/v3/orders?after=2020-06-17T00%3A00%3A00.000Z&before=2020-06-17T23%3A59%3A59.999Z&status%5B0%5D=any&dp=0&page=2>; rel="next"',
>    allow: 'GET, POST',
>    'content-length': '0',
>    date: 'Fri, 10 Jul 2020 05:44:59 GMT',
>    server: 'LiteSpeed',
>    vary: 'User-Agent,User-Agent',
>    'alt-svc': 'quic=":443"; ma=2592000; v="43,46", h3-Q043=":443"; ma=2592000, h3-Q046=":443"; ma=2592000, h3-Q050=":443"; ma=2592000, h3-25=":443"; ma=2592000, h3-27=":443"; ma=2592000'
>  }
>  Response Data: 
>  Total of pages: 4
>  Total of items: 34

SyntaxError: The string did not match the expected pattern

I am trying to use this library with jest and typescript, but I get error: "SyntaxError: The string did not match the expected pattern". Works fine if I just run javascript. Here are my files:

woo.js

const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default

const api = new WooCommerceRestApi({
  url: "http://example.com",
  consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  version: "wc/v3"
})

return api.get("").then((res) => console.log(res))

This works fine!

Then I try to make a small unit test using typescript and jest:

// woo.ts
import WooCommerceRestApi from '@woocommerce/woocommerce-rest-api'

export async function testWoo(): Promise<any> {
  const api = new WooCommerceRestApi({
      url: "http://example.com",
      consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      version: "wc/v3"
  })

  return api.get("")
}

// woo.test.ts
import { testWoo } from './'

describe("woo", () => {
  test("testWoo", async () => {
    const result = await testWoo()

    console.log(result)
  })
})

Returns SyntaxError: The string did not match the expected pattern.

Any ideas? 🙂

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • Update dependency eslint to v6.8.0
  • Update dependency del-cli to v5
  • Update dependency eslint to v9
  • Update dependency eslint-config-prettier to v9
  • Update dependency eslint-config-standard to v17
  • Update dependency eslint-plugin-jest to v28
  • Update dependency eslint-plugin-prettier to v5
  • Update dependency eslint-plugin-promise to v6
  • Update dependency eslint-plugin-standard to v5
  • Update dependency husky to v9
  • Update dependency lint-staged to v15
  • Update dependency prettier to v3
  • 🔐 Create all rate-limited PRs at once 🔐

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

npm
package.json
  • axios ^1.6.0
  • create-hmac ^1.1.7
  • oauth-1.0a ^2.2.6
  • url-parse ^1.4.7
  • @babel/cli 7.6.0
  • @babel/core 7.6.0
  • @babel/plugin-transform-modules-commonjs 7.6.0
  • @babel/preset-env 7.6.0
  • babel-jest 24.9.0
  • del-cli 3.0.0
  • eslint 6.4.0
  • eslint-config-prettier 6.3.0
  • eslint-config-standard 14.1.0
  • eslint-plugin-import 2.18.2
  • eslint-plugin-jest 22.17.0
  • eslint-plugin-node 10.0.0
  • eslint-plugin-prettier 3.1.1
  • eslint-plugin-promise 4.2.1
  • eslint-plugin-standard 4.0.1
  • husky 3.0.5
  • jest 24.9.0
  • lint-staged 9.3.0
  • nock 11.3.5
  • prettier 1.18.2
  • node >=8.0.0
travis
.travis.yml
  • node 8
  • node 9
  • node 10

  • Check this box to trigger a request for Renovate to run again on this repository

Wrong generated url get using params (per_page, page)

Describe the bug
When requesting data to the WooComerce REST API with params the generated link is wrongly created.

To Reproduce
Make an api call with like this:
WooCommerce.get("products", {
per_page : 99,
page: 1
})... // continues
// Inside the callback...
console.log(response)
// "response" being the list of 99 products in page 1

The url generated is: http://example.com/wp-json/wc/v3/products?page=1&per_page=99&function%20()%7Breturn%20this.filter(a)%7D=undefined

The result of console.log(response) is "undefined"

Expected behavior
There should be an object containing the 99 prods of page 1, among other important data.

I have

  • This bug happens using nodejs and the v3 version of Woocommerce REST API
  • I can reproduce this bug consistently using the steps above.

Various requests return different errors

Using this library the only thing that seems to be working is GET requests.

PUT requests return 200, though no data is modified.
POST requests with no data return 200.
POST requests with data return 401 unauthorized.
DELETE requests return 501 not implemented.

Using Postman, all of these requests work.

Any suggestions/advice would be much appreciated.

Order by Price?

How to get items Ordered by Price?

I found this.
https://www.storeurl.com/wc-api/v3/products?filter[order]=asc&filter[orderby]=meta_value_num&filter[orderby_meta_key]=_regular_price

But not sure how to use filter inside params object:

api.get("products", {
  per_page: 20
})

Thanks

TypeError: WooCommerceRestApi is not a constructor

I was using NPM @woocommerce/woocommerce-rest-api successfully to manage API requests to Woocommerce/ WP website.

Was using babel and CJS version:
`
const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;

const api = new WooCommerceRestApi({
url: "http://example.com",
consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
version: "wc/v3"
});`

But since Node 14 is offering a simple way to use ESM I have added the following configuration to the package.json, so I can use the import statement: "type": "module"

So I should have been able to use this format:

`import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";

const api = new WooCommerceRestApi({
url: "http://example.com",
consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
version: "wc/v3"
});`

But now I get this error:

`file:///xxxxxx/test.js:5
const api = new WooCommerceRestApi({
^

TypeError: WooCommerceRestApi is not a constructor
at file:///xxxxxxxx/test.js:5:13
at ModuleJob.run (internal/modules/esm/module_job.js:138:23)
at async Loader.import (internal/modules/esm/loader.js:178:24)`

Why would that happen?

is_paying_customer not working?

When does is_paying_customer return true and when false?

We use Woo Subscriptions and the results of is_paying_customer seem completely random.

Is this library compatible with Woo Subscriptions?

CORS Pre-flight check failing

What I'm trying to do:
Im trying to update meta_data of a product. Below is the sample code

import WooCommerceRestApi from '@woocommerce/woocommerce-rest-api';

const WC = new WooCommerceRestApi({
  url: 'http://localhost:8888/wordpress', // Your store URL
  consumerKey: <key>, // Your consumer key
  consumerSecret: <secret>, // Your consumer secret
  version: 'wc/v3', // WooCommerce WP REST API version
});

export const fetchProducts = () => new Promise((resolve, reject) => {
  const params = {
    per_page: 50,
    meta: true,
  };

  WC.get('products', params).then((response) => {
    resolve(response.data);
  }).catch((error) => {
    reject(error.response.data);
  });
});

export const updateProduct = (id, data) => new Promise((resolve, reject) => {
  // data param contains an object {meta_data: [{},{},....,{}]}
  WC.put(`products/${id}`, data).then((response) => {
    console.log(response.data);
    resolve(response.data);
  }).catch((error) => {
    console.log(error);
    reject();
  });
})

I am able to fetch products without any issues through get request. But when I try to update meta_data, I get following error.

Access to XMLHttpRequest at 'http://localhost:8888/wordpress/wp-json/wc/v3/products/816?oauth_consumer_key=1111222233334444&oauth_nonce=E3kDMWQOzCMwnmq1fFQR2QKNpETKdRYW&oauth_signature_method=HMAC-SHA256&oauth_timestamp=1566826887&oauth_version=1.0&oauth_signature=b05%2FvJVrAANDckfdPnjOpLJDmYVdtxBJNifGwYIgkHk%3D' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Can you please help me get through this. Regards.

how to make it work in ionic4

Hi,

I try to make it work in ionic 4

import { Component, OnInit } from '@angular/core';
import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";

@Component({
  selector: 'app-productlist',
  templateUrl: './productlist.page.html',
  styleUrls: ['./productlist.page.scss'],
})
export class ProductlistPage {


  constructor() {
    
    const api = new WooCommerceRestApi({
      url: 'http://localhost/wordpress',
      consumerKey: 'my consumerkey',
      consumerSecret: 'my secretkey',
      version: 'wc/v3'
    });
    
   }
  ngOnInit() {

and I received this error

ERROR Error: Uncaught (in promise): ReferenceError: Cannot access 'ProductlistPageModule' before initialization
ReferenceError: Cannot access 'ProductlistPageModule' before initialization

I guess I missing something ...

Regards

The AWS Lambda returns "Error: connect ETIMEDOUT **.****.***.***:443"

I have to services, Admin Panel(Laravel) и Online Shop(Woocommerce). TH relation between these to services was realized with "AWS Lambda"

when I try to send an updating product request from my ADmin panel to online shop, time to time the lambda couldn't connect to the Woocomerce API.
On time when the system is not updating the product, lambda returns the error "Error: connect ETIMEDOUT"

I originally thought that the Wordpress didn't have enought time for updating process. And decided to increase the lambda's timeout (60000 ms).
But it didn't help. I still found the ETIMEDOUT errors in logs.

By the way, the time period between sending the updating request to woocommerce and showing an error is 2 min.
If I right understand, the lambda had enought time for getting the answer from woocommerce.

Another strage thing. According the lambda's logs, on time when lambda got an error, the woocommerce API was available. It seems like something disconnects the internet on time when lambda is sending the request.

My question is, why lambda cannot send to woocommerce API the reuqest. Why it happens time to time ?

P.S. Below I added the example of lambda's logs.


The log on starting sending the uptading request.

2021-08-14T18:23:48.692Z b228455b-45a8-5cbf-8160-1cc INFO Inside edit Online List {
status: '1',


is_delete: 0,
name: 'Omega Speedmaster Moonwatch Chronograph 42mm ',
price_on_request: 0,
on_sale: 0
}

The log with error.

2021-08-14T18:25:58.299Z b228455b-45a8-5cbf-8aae6 INFO WooCommerce editOnlineStock err::: { Error: connect ETIMEDOUT ...:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14)
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
address: '
...',
port: 443,
config:
{ url:
'https://domain.com/wp-json/wc/v3/products/
',
method: 'put',
params: {},
data:
'{"name":"Omega Speedmaster Moonwatch Chronograph 42mm ","type":"simple"
',
headers:
{ Accept: 'application/json',
'Content-Type': 'application/json;charset=utf-8',
'User-Agent': 'WooCommerce REST API - JS Client/1.0.1',
'Content-Length': 681 },
auth:
{ username: 'ck_
',
password: 'cs_
********' },
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 60000,
adapter: [Function: httpAdapter],
responseType: 'json',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
****************************

TypeError: argument entity is required

Hi,

I'm getting the error 'TypeError: argument entity is required'

Any idea what this relates to?

This is my code@

import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";

const api = new WooCommerceRestApi({
  url: process.env.WP_API,
  consumerKey: process.env.WOO_CONSUMER_KEY,
  consumerSecret: process.env.WOO_CONSUMER_SECRET,
  version: 'wc/v3'
})

// Get FAB Defense Items
export const getFabProducts = async () => {
  api
    .get("products", { per_page: 10 })
    .then(res => console.log(res.data))
    .catch(err => console.warn(err))
}

order param not allowed with the memberships endpoint

When trying to perform a GET request against memberships/members providing an order parameter throws an error.

{"code":"rest_invalid_param","message":"Invalid parameter(s): order","data":{"status":400,"params":{"order":"order is not of type integer."},"details":{"order":{"code":"rest_invalid_type","message":"order is not of type integer.","data":{"param":"order"}}}}}

For some reason it is expecting an integer as opposed to a string like asc or desc

Woocommerce Image SRC not working

Hi Everyone, i'm trying to insert a product image inside the image object.
I receive a base64 string that i save inside the data.image.src, but i retrieve always a placeholder (an url) by default, and not my image.
Do you know what i sould upload inside this field?
Thank you in advance!

Possiblity to configure non global axios instance

To be able to have different axios configurations beyond axiosConfig (ie. interceptors) it should be possible to assign a an axios instance which will be used in place of the global axios, which remains the default.

One example of such use would be to use a separate logger and interceptors for logging WC requests.

`
let wcAxiosInstance = axios.create();

wcAxiosInstance.interceptors.request.use(req => {
    wcApiLogger.debug(`Request   ${req.method} ${req.url}`);
    wcApiLogger.debug(`Headers > ${JSON.stringify(req.headers)}`)
    return req;
});

wcAxiosInstance.interceptors.response.use(res => {
    wcApiLogger.debug(`Response ${res.config.method} ${res.config.url} ${res.status}`);
    wcApiLogger.debug(`Headers  < ${JSON.stringify(res.headers)}`)
    return res;
});

let wcApi = new WooCommerceRestApi({
url: ...,
consumerKey: ...,
consumerSecret: ...,
axiosInstance: wcAxiosInstance
});

`

Unable to build using webpack: unexpected token: name

Hello!

I'm trying to use this module for api requests however when I go to bundle my app using webpack + babel, I keep getting this error

ERROR in SingleProduct-browser.js from UglifyJs Unexpected token: name «woocommerce_rest_api_WooCommerceRestApi», expected: punc «;» [SingleProduct-browser.js:9470,6]

My webpack config looks like this:

const path = require("path")
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const glob = require("glob")

module.exports = {
  entry: {
    "HomePage-server": glob.sync("./src/templates/HomePage/entry-server.js"),
    "HomePage-browser": glob.sync("./src/templates/HomePage/entry-browser.js"),
    "Header-server": glob.sync("./src/templates/Header/entry-server.js"),
    "Header-browser": glob.sync("./src/templates/Header/entry-browser.js"),
    "SingleProduct-server": glob.sync("./src/templates/SingleProduct/entry-server.js"),
    "SingleProduct-browser": glob.sync("./src/templates/SingleProduct/entry-browser.js"),
  },
  output: {
    filename: "[name].js",
    path: path.join(__dirname, "./build/templates/"),
  },
  externals: {
    // Use external version of React
    "react": "React",
    "react-dom": "ReactDOM"
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: '../',
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ],
      },
      {
        test: /\.(js|jsx|mjs)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        },
      },
    ],
  },
  plugins: [new UglifyJsPlugin({
    "uglifyOptions":
    {
        warnings: false,
        sourceMap: true
    }
  }), new MiniCssExtractPlugin({
    // Options similar to the same options in webpackOptions.output
    // all options are optional
    filename: '[name].css',
    chunkFilename: '[id].css',
    ignoreOrder: false, // Enable to remove warnings about conflicting order
  })],
}

and my babelrc file looks like this

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}

Have you run into this issue before?

Thanks!

Throws exception when using environment variables via dotenv pacakge

I've noticed that using .env files makes the package throw an exception.

I'm setup in an express server, loading env via dotenv. Woo wrapper is working perfectly when I state my URL, key & secret but as soon as I load them into my server via process.env.API_URL or similar then I get an exception, starting with

"URL is required"

Typescript definitions not included in npm package

Although merged in #35 npm package does not include ts definitions. Version 1.0.1

package.json from installed module for reference:

{
  "_from": "@woocommerce/woocommerce-rest-api",
  "_id": "@woocommerce/[email protected]",
  "_inBundle": false,
  "_integrity": "sha512-YBk3EEYE0zax/egx6Rhpbu6hcCFyZpYQrjH9JO4NUGU3n3T0W9Edn7oAUbjL/c7Oezcg+UaQluCaKjY/B3zwxg==",
  "_location": "/@woocommerce/woocommerce-rest-api",
  "_phantomChildren": {},
  "_requested": {
    "type": "tag",
    "registry": true,
    "raw": "@woocommerce/woocommerce-rest-api",
    "name": "@woocommerce/woocommerce-rest-api",
    "escapedName": "@woocommerce%2fwoocommerce-rest-api",
    "scope": "@woocommerce",
    "rawSpec": "",
    "saveSpec": null,
    "fetchSpec": "latest"
  },
  "_requiredBy": [
    "#USER",
    "/"
  ],
  "_resolved": "https://registry.npmjs.org/@woocommerce/woocommerce-rest-api/-/woocommerce-rest-api-1.0.1.tgz",
  "_shasum": "112b998e8e3758203a71d5e3e0b24efcb1cff842",
  "_spec": "@woocommerce/woocommerce-rest-api",
  "_where": "/Users/florian/Github Repositories/jarvis-serverless",
  "author": {
    "name": "Automattic"
  },
  "bugs": {
    "url": "https://github.com/woocommerce/woocommerce-rest-api-js/issues"
  },
  "bundleDependencies": false,
  "dependencies": {
    "axios": "^0.19.0",
    "create-hmac": "^1.1.7",
    "oauth-1.0a": "^2.2.6",
    "url-parse": "^1.4.7"
  },
  "deprecated": false,
  "description": "WooCommerce REST API - JavaScript Library",
  "devDependencies": {
    "@babel/cli": "7.5.5",
    "@babel/core": "7.5.5",
    "@babel/plugin-transform-modules-commonjs": "7.5.0",
    "@babel/preset-env": "7.5.5",
    "babel-jest": "24.8.0",
    "del-cli": "2.0.0",
    "eslint": "6.1.0",
    "eslint-config-prettier": "6.0.0",
    "eslint-config-standard": "13.0.1",
    "eslint-plugin-import": "2.18.2",
    "eslint-plugin-jest": "22.14.1",
    "eslint-plugin-node": "9.1.0",
    "eslint-plugin-prettier": "3.1.0",
    "eslint-plugin-promise": "4.2.1",
    "eslint-plugin-standard": "4.0.0",
    "husky": "3.0.2",
    "jest": "24.8.0",
    "lint-staged": "9.2.1",
    "nock": "10.0.6",
    "prettier": "1.18.2"
  },
  "engines": {
    "node": ">=8.0.0"
  },
  "files": [
    "index.js",
    "index.mjs"
  ],
  "homepage": "https://github.com/woocommerce/woocommerce-rest-api-js-lib",
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "keywords": [
    "wordpress",
    "woocommerce",
    "rest",
    "promise",
    "node"
  ],
  "license": "MIT",
  "lint-staged": {
    "*.{js,mjs}": [
      "eslint --fix",
      "prettier --write",
      "git add"
    ]
  },
  "main": "index",
  "name": "@woocommerce/woocommerce-rest-api",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/woocommerce/woocommerce-rest-api-js.git"
  },
  "scripts": {
    "build": "del index.js && babel index.mjs --out-dir .",
    "format": "prettier --write \"*.mjs\" \"test.js\"",
    "lint": "eslint *.mjs",
    "postversion": "git push && git push --tags",
    "prepare": "npm run build",
    "prepublishOnly": "npm test && npm run lint",
    "preversion": "npm run lint",
    "test": "jest",
    "version": "npm run format && git add -A"
  },
  "version": "1.0.1"
}

HPE_INVALID_HEADER_TOKEN - NodeJS v12

All my requests using NodeJS v12 are returning Parse Error, and I think this is probably because of space in the header.

There are some discussions related here.

I had to downgrade my NodeJS to v10 and use the flag --insecure-http-parser to make it work.

[Question]: Stable to use in production?

Hi, we have an existing node app in which we are looking to pull in woocommerce data including all products, orders, customer info, etc. Is this library stable to use in production?

Thanks

Exposing secret & key in javascript code?

Most likely there something I misunderstand, but how can it be safe to expose the consumer secret and key in the code? People could inspect source code and retrieve it, no? Or what am I missing here..

[Feature Request] Typescript Decoration File

Using Typescript to enforce type checking in JavaScript project is the normal behavior nowadays.
Providing a Typescript Decoration file for the people who use this official API lib is important for the programmers.

I have written a template decoration file for my own project and you may take it as a reference. Some part may not be correct.

declare module '@woocommerce/woocommerce-rest-api' {
  export type WooCommerceRestApiVersion = 'wc/v3' | 'wc/v2' | 'wc/v1' | 'wc-api/v3' | 'wc-api/v2' | 'wc-api/v1'
  export type WooCommerceRestApiEncoding = 'utf-8' | 'ascii'
  export type WooCommerceRestApiMethod = 'get' | 'post' | 'put' | 'delete' | 'options'

  export interface IWooCommerceRestApiOptions {
    url: string
    consumerKey: string
    consumerSecret: string
    wpAPIPrefix?: string
    version?: WooCommerceRestApiVersion
    encoding?: WooCommerceRestApiEncoding
    queryStringAuth?: boolean
    port?: number
    timeout?: number
    axiosConfig?: any
  }

  export interface IWooCommerceRestApiQuery {
    [key: string]: string
  }

  class OAuth {}

  export class WooCommerceRestApi {
    protected classVersion: string
    protected url: string
    protected consumerKey: string
    protected consumerSecret: string
    protected wpAPIPrefix: string
    protected version: WooCommerceRestApiVersion
    protected encoding: WooCommerceRestApiEncoding
    protected queryStringAuth: boolean
    protected port: number
    protected timeout: number
    protected axiosConfig: any

    constructor(opt: IWooCommerceRestApiOptions | WooCommerceRestApi)

    private _setDefaultsOptions(opt: IWooCommerceRestApiOptions): void

    private _parseParamsObject(params: any, query: any): IWooCommerceRestApiQuery

    private _normalizeQueryString(url: string, params: any): string

    private _getUrl(endpoint: string, params: any): string

    private _getOAuth(): OAuth

    private _request(method: WooCommerceRestApiMethod, endpoint: string, data: any, params: any): any

    public get(endpoint: string): any
    public get(endpoint: string, params: any): any

    public post(endpoint: string, data: any): any
    public post(endpoint: string, data: any, params: any): any

    public put(endpoint: string, data: any): any
    public put(endpoint: string, data: any, params: any): any

    public delete(endpoint: string): any
    public delete(endpoint: string, params: any): any

    public options(endpoint: string): any
    public options(endpoint: string, params: any): any
  }

  export class OptionsException {
    public name: string
    public message: string

    constructor(message: string)
  }

  export default WooCommerceRestApi
}

Cannot run on React Native

I cannot integrate this module with React Native App. After I installed the module, the error happened:

image

I'm using version:
"react-native": "0.60.5",
"@woocommerce/woocommerce-rest-api": "^1.0.1",

Post method not working properly

When I make a post request with the JS library, the response that I get is the list of all the elements of the endpoint, as if I would be using a get. I have tried with multiple endpoints and always the result is the same; even with the same example of the ReadMe, the only response that I got is a get of all the products.

If I make the post request in postman or with Axios, it works fine.

Woocommerce Subscriptions status

Woocommerce Subscriptions has the following statuses:

  • Active
  • Expired
  • Pending Cancellation
  • Cancelled

Is it possible to query these fields with this library?

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.