Connect to WooCommerce Rest API using Javascript

Do you  know, how to get data from WooCommerce via Rest API from the client, using JavaScript? Surprisingly, tutorials on this delicate subject are seldom found on page one of search results. Moreover, as of the moment of this writing WooCommerce documentation is also missing this information.

Warning: It is never a good idea to expose API authentication credentials.

Nevertheless, in rare cases when you do end up using this frivolous setup in production, make sure that your API key is for read only.

Below are a couple working code snippets – one using jQuery and one using vanilla async/await. Both get the job done:

const wooClientKey = 'ck_00000000000000000000000000';
const wooClientSecret = 'cs_00000000000000000000000000';
const wooUrl = 'https://yoursite.com/wp-json/wc/v3/products';

function basicAuth(key, secret) {
    let hash = btoa(key + ':' + secret);
    return "Basic " + hash;
}

let auth = basicAuth(wooClientKey, wooClientSecret);

function getData(url) {
    jQuery.ajax({
        url: url,
        method: 'GET',
        beforeSend: function (req) {
            req.setRequestHeader('Authorization', auth);
        }
    })
        .done(function (data) {
            console.log(data);
            return data;
        });
}

getData(wooUrl);

While the code itself is fairly self explanatory, here’s a quick step by step breakdown:

Const

The “consts” are merely script settings, which one can generate from within their WooCommerce  API section (WP Admin area).

basicAuth

This is a helper function, introduced for clarity.

The “Basic” HTTP authentication scheme transmits access credentials – username and password, encoded using base64 (defined in RFC 7617).

Thus, all basicAuth does is uses btoa() method to create a base64 encoded ASCII string  (<key>: <secret>) and return the resulting hash along with the “Basic” identifier.

Vanilla Javascript

const wooClientKey = 'ck_00000000000000000000000000';
const wooClientSecret = 'cs_00000000000000000000000000';
const wooUrl = 'https://yoursite.com/wp-json/wc/v3/products';

function basicAuth(key, secret) {
    let hash = btoa(key + ':' + secret);
    return "Basic " + hash;
}

let auth = basicAuth(wooClientKey, wooClientSecret);

async function getProducts() {
    try {
        const response = await fetch(wooUrl + 'products', {
            headers: {"Authorization": basicAuth(wooClientKey, wooClientSecret)}
        });
        return await response.json();
    }
    catch (error) {
        // catches errors both in fetch and response.json
        console.log(error);
    }
}
Отладка. Будет убрана потом