I was having the same issue with Woocommerce Oauth 1.0 authentication and this solution worked for me. I’m running it on localhost, so far so good.
Edit:
Let me elaborate this answer a bit more. I just started learning React last night and the best way to learn is by doing. I’ll explain as a newbie for a newbie. Here we go…
I created this Woocommerce helper object that can be called from any component and it does all the hard work for you:
Woocommerce.js
import axios from "axios";
import Oauth from "oauth-1.0a";
import CryptoJS from "crypto-js";
import jQuery from "jquery";
const ck = "ck_...";
const cs = "cs_...";
const baseURL = "http://yourdomain.com/wp-json";
const Woocommerce = {
getProducts: () => {
return makeRequest("/wc/v3/products");
},
getProductByID: id => {
return makeRequest("/wc/v3/products/" + id);
}
};
function makeRequest(endpoint, method = "GET") {
const oauth = getOauth();
const requestData = {
url: baseURL + endpoint,
method
};
const requestHTTP =
requestData.url + "?" + jQuery.param(oauth.authorize(requestData));
return axios.get(requestHTTP);
}
function getOauth() {
return Oauth({
consumer: {
key: ck,
secret: cs
},
signature_method: "HMAC-SHA1",
hash_function: function(base_string, key) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(base_string, key));
}
});
}
export default Woocommerce;
You will need to install all the necessary packages by running the commands:
npm install axios jquery crypto-js
npm install oauth-1.0a --production
How to use it
First import it to the component:
import Woocommerce from "./functions/Woocommerce";
Then from inside the component you can call it like this to get all the products:
// All products (array of objects)
state = { products: [], isLoaded: false };
componentWillMount() {
Woocommerce.getProducts().then(res =>
this.setState({ products: res.data, isLoaded: true })
);
}
Or, to get only one product by ID, you can do:
// Single product (object)
state = { product: {}, isLoaded: false };
componentWillMount() {
Woocommerce.getProductByID(123).then(res =>
this.setState({ product: res.data, isLoaded: true })
);
}
As you can probably see, you can elaborate more functions inside of the Woocommerce helper and retrieve products using the Woocommerce REST API as you wish.
Happy coding… 😉