Skip to content

Instantly share code, notes, and snippets.

@ariona
Last active April 13, 2024 21:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ariona/4e163d516c729396e1bb1089e1a97003 to your computer and use it in GitHub Desktop.
Save ariona/4e163d516c729396e1bb1089e1a97003 to your computer and use it in GitHub Desktop.
Authenticate WooCommerce RestAPI with oAuth 1.0a

Axios interceptor to Authenticate WooCommerce REST API

This module will intercept request to WooCommerce Rest API and authenticate it using oAuth 1.0a.

Originally used in nuxt project

import OAuth from 'oauth-1.0a';
import CryptoJS from 'crypto-js';
// Consumer Key
const ck = "ck_c7796f3a7c4eaedde188c78107cd907a41944ac6";
// Consumer Secret
const cs = "cs_d7a23c04e4c1939fb38fd966ea16be0dced185de";
const oauth = 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) );
}
});
function serialize(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
function authorize(url, method){
const requestData = {
url,
method
}
return serialize(oauth.authorize(requestData));
}
export default function ({ $axios, redirect }) {
$axios.interceptors.request.use(function (config) {
// console.log(config);
const concat_str = config.url.indexOf("?") > -1 ? "&" : "?";
const url = config.baseURL + config.url;
config.url = url + concat_str + serialize( oauth.authorize({url,method:config.method}))
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment