WooCommerce REST API AJAX Auth – 401 response


I need to implement vuejs to load the categories of my store. I’ve read that the woocoomerce rest api need authenticate requets to work, so I’m trying to get the categories using oauth on localhost with https enabled:

// This is in my functions file to pass the parameters
// wp_localize_script( 'main', 'woo', 
    //   array(
    //     'ajaxurl' => 'wp-ajax.php',
    //     'timestamp' => time(),
    //     'hash' => hash_hmac(),
    //     'nonce'
    //   )
    // );


// This is the JS part
        //method: 'GET',
        //url: 'wp-json/wc/v3/products/categories&oauth_consumer_key="+woo.consumer_key+"&oauth_signature_method="HMAC-SHA1&oauth_timestamp="+woo.timestamp+"&oauth_nonce="+woo.nonce+"&oauth_signature=+woo.hash',
        // beforeSend: function (xhr) {
        //   xhr.setRequestHeader ("Authorization", "OAuth " + btoa(username + ":" + password));
        // },

I get always a 401 response code, I’m not able to authenticate using ajax. I want to use the wp_localize_script to pass the needed timestamp and auth, but I’m not able to find how to do it correctly.
Any example will be appreciated.


I rewrite the che code using sally suggestion but I still get the 401 error response code.
Here is the updated code


wp_register_script('main', get_template_directory_uri().'/assets/js/main.js', array('jquery'), null );
    $localize = array(
       'ajaxurl' => admin_url('admin-ajax.php'),
       // Securing your WordPress plugin AJAX calls using nonces
       'auth' => base64_encode('ck_32a46b36d90680e574e9de6456746a11cf07945:cs_0a6bd199a45c0b96e848a1401a14b18444fa46d8'),
    wp_localize_script('main', 'wp', $localize);


    const app = new Vue({
      el: '#app',
      data: {},
      created: function(){
          method: 'GET',
          url: 'wp-json/wc/v3/products/categories',
          headers: {
             'Authorization': "Basic "+ wp.auth
          success: function(response){
      destroyed: {},
      mounted: {},

I’m on localhost with a self signed cert to have the https, maybe this can be the problem?

, , , sialfa 4 years 2020-02-23T08:38:29-05:00 0 Answers 74 views 0

Leave an answer