npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@cczbby/woocommerce-rest-ts-api

v7.0.2

Published

WooCommerce REST API - Type Script Library

Downloads

8

Readme

Updates Test CI npm npm License: MIT Known Vulnerabilities

WooCommerce REST API - TypeScript Library

This is alternative library which provides a set of TypeScript classes that can be used to interact with the WooCommerce REST API. However, it is not a complete implementation of the API, but rather a subset of the API that is useful for.

New TypeScript library for WooCommerce REST API. Supports CommonJS (CJS) and ECMAScript (ESM)

Fixing the issues [Triggered Date: 2022-11-15]

  1. This new package was to fixe the issue with the official WooCommerce REST API JavaScript library, which is not compatible with the security features for some packages used for.
  2. Axios package used by them, had a Cricital vulnerability which seems not beeing updated often.

Requests are made with Axios library with support to promises.

Installation

npm install --save woocommerce-rest-ts-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,{WooRestApiOptions} from "woocommerce-rest-ts-api";
const opt:WooRestApiOptions = {
    url: "http://example.com" ,
    consumerKey:  "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    consumerSecret:  "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    version: "wc/v3",
    queryStringAuth: false // Force Basic Authentication as query string true and using under
}
const api = new WooCommerceRestApi(opt);

CJS example:

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

const api = new WooCommerceRestApi({
  url: "http://example.com",
  consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  version: "wc/v3",
  queryStringAuth: false // Force Basic Authentication as query string true and using under HTTPS
});

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?: Partial

| 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)
  • data: Record<string, unknown>
  • params?: Partial

| 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)
  • data: Record<string, unknown>
  • params?: Partial

| 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)
  • data: Pick<WooRestApiParams, "force">,
  • params: Pick<WooRestApiParams, "id">

| 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?: Partial

| Params | Type | Description | |------------|----------|-----------------------------------------------------------------| | endpoint | String | WooCommerce API endpoint, example: customers/2 or orders/12 | | params | Object | Query strings params |

Example of use

import WooCommerceRestApi,{CouponsParams, ProductsMainParams, OrdersMainParams, WooRestApiOptions} from "woocommerce-rest-ts-api";
// const WooCommerceRestApi = require("woocommerce-rest-ts-api").default;

const api = new WooCommerceRestApi({
  url: "http://example.com",
  consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  version: "wc/v3",
  queryStringAuth: false // Force Basic Authentication as query string true and using under HTTPS
});

// List products
const products = await api.get("products", {
  per_page: 20, // 20 products per page
});
products.status; // 200
product.headers.get('x-wp-totalpages')
products.headers.get('x-wp-total')
products.headers.forEach((header) => {
  console.log(header);
});
products.data.forEach((product) => {
  console.log(product.name);
});

// Create a product
// See more in https://woocommerce.github.io/woocommerce-rest-api-docs/#product-properties
const data:ProductsMainParams = {
            name: "Premium Quality",
            type: "simple",
            regular_price: "21.99",
            description: "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.",
            short_description: "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.",
            categories: [
                {
                    id: 9
                },
                {
                    id: 14
                }
            ],
            images: [
                {
                    src: "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg"
                },
                {
                    src: "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg"
                }
            ]
        };
const products = await api.post("products", data);
products.status; // 201
products.data; // { id: 11, ... }
products.headers.get('x-wp-totalpages')
products.headers.get('x-wp-total')

// Edit/Update a product
  const data:ProductsMainParams = {
      name: "Premium Quality Updated-" + randomstring.generate({length:4, capitalization:"uppercase", charset: "alphanumeric"}),
      type: "simple",
      regular_price: "30.22",
      description: "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.",
      short_description: "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.",
      categories: [
          {
              id: 9
          },
          {
              id: 14
          }
      ],
      images: [
          {
              src: "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg"
          },
          {
              src: "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg"
          }
      ]
  };
  const products = await api.put("products", data, {id: 11});
  products.status; // 201
  products.data; // { id: 11, ... }
  products.headers.get('x-wp-totalpages')
  products.headers.get('x-wp-total')

// Delete a product
const products = await wooCommerce.delete("products", {force: true}, {id: 11});
products.status; // 201
products.data; // { id: 11, ... }
products.headers.get('x-wp-totalpages')
products.headers.get('x-wp-total')

// Create a order
const data:OrdersMainParams = {
      payment_method: "bacs",
      payment_method_title: "Direct Bank Transfer",
      set_paid: true,
      billing: {
          first_name: `John ${Math.random()}`,
          last_name: "Doe",
          address_1: "969 Market",
          address_2: "",
          city: "San Francisco",
          state: "CA",
          postcode: "94103",
          country: "US",
          email: "[email protected]",
          phone: "85996859001",
          company: "WooCommerce"
      },
      shipping: {
          first_name: "John",
          last_name: "Doe",
          address_1: "969 Market",
          address_2: "",
          city: "San Francisco",
          state: "CA",
          postcode: "94103",
          country: "US",
          company: "WooCommerce"
      },
      line_items: [
          {
              product_id: 93,
              quantity: 2
          },
          {
              product_id: 22,
              variation_id: 23,
              quantity: 1
          }
      ],
      shipping_lines: [
          {
              method_id: "flat_rate",
              method_title: "Flat Rate",
              total: "10.00"
          }
      ]
  };
const order = await api.post("orders", data);
order.status; // 201
order.data; // { id: 11, ... }
order.headers.get('x-wp-totalpages')
order.headers.get('x-wp-total')

// Edit/Update a order
const data:OrdersMainParams = {
      payment_method: "bacs",
      payment_method_title: "Direct Bank Transfer",
      set_paid: true,
      billing: {
          first_name: `Yuri ${Math.random()}`,
          last_name: "Doe",
          address_1: "969 Market",
          address_2: "",
          city: "San Francisco",
      },
  };
const order = await api.put("orders", data, {id: 11});
order.status; // 201
order.data; // { id: 11, ... }
order.headers.get('x-wp-totalpages')
order.headers.get('x-wp-total')

// Delete a order
const order = await api.delete("orders", {force: true}, {id: 11});
order.status; // 201
order.data; // { id: 11, ... }
order.headers.get('x-wp-totalpages')
order.headers.get('x-wp-total')

Changelog

See changelog for details

Thanks / Credits / Bibliography

Contact

Atention If you email me, please use as a email subject, the name of the project, in this case: (WooCommerce TS Library) - INFO

| Name | Email | Mobile/Whatsapp | |-------|--------|---------| | Yuri Lima | [email protected] | +353 83 419.1605 |