I was recently working with a client to develop a custom WooCommerce rest API endpoint, they wanted to get a list of orders for a customer, and ONLY that customers data, so we restricted access to the normal order endpoint and created a custom endpoint to authenticate users.
In this video I’ll show you how you can create your own custom REST API endpoint on your WooCommerce store to send custom data back to users using REST API call.
You may want to do this when you want to send custom data to third parties or restrict what the WooCommerce rest api offers.
Video
Code
Here’s the code I walk through.
/* custom end points Neil Matthews Aug 2024 */
add_action( 'rest_api_init', function () {
register_rest_route( 'nm/v1', '/listorders/', array(
'methods' => 'GET',
'callback' => 'nm_list_orders',
'permission_callback' => '__return_true'
) );
} );
function nm_list_orders($request){
$jwt_issuer="";
$queryParams = $request->get_query_params();
$token=$queryParams['jwt'];
$jwt_decode=json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', $token)[1]))));
$jwt_issuer=$jwt_decode->iss;
$jwt_valid_issuer = get_field('jwt_valid_issuer', 'option');
if($jwt_issuer){
if(!str_contains($jwt_issuer, $jwt_valid_issuer)){
$error=array("jwt_error","JWT Issuer incorrect");
return $error;
}
}
if(strtotime("now") > $jwt_decode->exp){
$error=array("jwt_error","JWT Token has expired");
return $error;
}else{
$useremail=$jwt_decode->email;
$userid =$jwt_decode->id;
}
echo nm_get_customer_orders($userid);
}
function nm_get_customer_orders($customer_id) {
$store_url = "https://neilmatthews.com/";
$consumer_key = "REMOVED in the real code I added these as ACF Fields";
$consumer_secret = "REMOVED in the real code I added these as ACF Fields";
// API endpoint to fetch orders by customer ID
$endpoint = $store_url . '/wp-json/wc/v3/orders?customer=' . $customer_id;
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $consumer_key . ":" . $consumer_secret);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// Execute the request and fetch the response
$response = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
echo 'cURL error: ' . curl_error($ch);
return;
}
// Close the cURL session
curl_close($ch);
// Return the orders as a JSON string
return $response;
}
Wrap Up
Next up I’ll talk about disabling certain REST API endpoints depending upon the role a user has.
If you would like to work with me to develop a custom end point for your WooCommerce store get in touch.