403 error rest_'cookie_invalid_nonce' on API Request

I'm currently developing a Plugin in which I'm in need of retrieving information from a third-party plugin API.

To authenticate my users, I am trying to use the vanilla authentication via cookie as explained in the official documentation, but every request is refused with a 403 rest_cookie_invalid_nonce code.

I cannot understand what I'm doing wrong.

My code:

function makeRequest(){
  $url = 'https://xxxxxx.com.br/wp-json/wcfmmp/v1/orders/';
  $nonce = wp_create_nonce('wp_rest');
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'X-WP-Nonce:'. $nonce,
    'Content-Type: application/json',
  ));
  $result = curl_exec($curl);
  if(!$result) {
    die(Connection Failure);
  }
  curl_close($curl);
  return $result + var_dump($nonce);
}

Topic wp-api rest-api plugin-development Wordpress

Category Web


Same site

As commented by Fränk request the same site it is better to use

$request = new WP_REST_Request( 'GET', '/wcfmmp/v1/orders/' );
$response = rest_do_request( $request );
var_dump( $response->get_data() );

Remote WP site

A great answer is written here for question How do I correctly setup an AJAX nonce for WordPress REST API?

Querying a remote site needs Application password as described in Application Passwords: Integration Guide

When developing locally make sure to set define('WP_ENVIRONMENT_TYPE', 'local');

curl

This will fail as the user and application password is not known on given site.

USER=admin
APP_PASS="abcd EFGH 1234 ijkl MNOP 6789"
BASE64=`echo $USER:$APP_PASS | base64`

curl \
  --header "Accept: application/json" \
  --header "Authorization: Basic $BASE64" \
  https://wordpress.org/wp-json/wp/v2/

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.