skip to Main Content

im trying to add a product to cart with Woocommerce API with this url /wp-json/wc/store/v1/cart/add-item.

i use postman to send request but it returs 403 Forbidden error:

{
  "code": "woocommerce_rest_invalid_nonce",
  "message": "کلید سرّی نامعتبر است.",
  "data": {
    "status": 403
  }
}

Also i use swagger plugin in wordpress for API.

how can fix this problem.

2

Answers


  1. you need the nonce key.

    you can GET site.com/wp-json/wc/store/v1/cart

    which will have the nonce in a header, and pass it back for your future requests.

    Login or Signup to reply.
  2. You need to create a nonce. You can achieve that by making some changes in your function.php file which you can find in themes folder.
    In wp you can achieve like this

    $nonce = wp_create_nonce('wc_store_api');
    

    and if you are working with CMS or Rest APIs of Woocommerce then you will need an api to create a nonce every time you make a call to add product in the cart which you can do like this

    $nonce = wp_create_nonce('wc_store_api');
    
    function expose_nonce() {
    $nonce = wp_create_nonce('wc_store_api');
    return $nonce;
    }
    
    add_action('rest_api_init', function () {
     register_rest_route('my-nonce/v1', '/get-nonce', array(
      'methods' => 'GET',
      'callback' => 'expose_nonce',
      ));
    });
    

    Now, your api will be something like this wp-json/my-nonce/v1/get-nonce to use response nonce in frontend for passing in /wp-json/wc/store/cart/add-item

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search