1.0.1 • Published 3 years ago

woocommerce-api-client v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

Minimal WooCoommerce REST API Client

Since I wasn't able to find any - here's simple implementation with ZERO dependecies of authenticated client for WooCommerce REST API.

Usage

GET

const WoocommerceApiClient = require("woocommerce-api-client").default;

const client = new WoocommerceApiClient({
    url: "http://localhost",
    consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXX",
    consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXX",
});

async function getCustomers() {
    const response = await client.get("/wp-json/wc/v1/custormes");
    if (response.statusCode != 200) {
        console.error(response.statusMessage);
        return null;
    }
    return JSON.parse(await response.content());
}

getCustomers().then(console.log); // Should print array of customers

POST

const { default: WoocommerceRestApiClient } = require("woocommerce-api-client").default;

const api = new WoocommerceRestApiClient({
    consumerKey: "ck_40d1c02af01eba0dbc55238b3feeb0093d0bbe22",
    consumerSecret: "cs_27d03c8a61b6203adc3c1da1db17d61e90d8d225",
    url: "http://localhost"
});

async function createCustomer() {
    const request = await api.post("/wp-json/wc/v1/customers", {
        body: JSON.stringify({
            email: "test@test.com",
            username: "test",
            firstName: "test",
            lastName: "testifisberg",
        }),
    });
    if (request.statusCode != 201) {
        console.error(JSON.parse(await request.content()));
        return null;
    }
    const customer = JSON.parse(await request.content());
    return customer;
}

createCustomer();

PUT (etc.)

const { default: WoocommerceRestApiClient } = require("woocommerce-api-client");

const api = new WoocommerceRestApiClient({
    consumerKey: "ck_40d1c02af01eba0dbc55238b3feeb0093d0bbe22",
    consumerSecret: "cs_27d03c8a61b6203adc3c1da1db17d61e90d8d225",
    url: "http://localhost"
});

async function updateCustomer() {
    const customer_id = 15;
    const request = await api.request(`/wp-json/wc/v1/customers/${customer_id}`, {
        method: "PUT",
        body: JSON.stringify({
            firstName: "test",
            lastName: "testifisberg",
        }),
    });
    if (request.statusCode != 200) {
        console.error(JSON.parse(await request.content()));
        return null;
    }
    const customer = JSON.parse(await request.content());
    return customer;
}

updateCustomer();