I created a WordPress REST API custom endpoint to be used as a Webhook URL in WooCommerce in order to convert the received data and then send it to a third party system, but the endpoint apparently is not receiving any data. I tested the code by sending some JSON data to my custom endpoint using Postman and it works only after installing another P;ugin to enable Basic Auth. I wonder if the problem is because probably the webhook needs authentication in order to be able to POST the data to the same domain? If that would be the case I have no idea where to setup basic authentication in the Webhook setting in WooCommerce.
this is my code:
function woocbz_CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data) {
$url = sprintf("%s?%s", $url, http_build_query($data));
}
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
function woocbz_order_created(WP_REST_Request $request)
{
$method = 'POST';
$url = 'https://webhook.site/2e5e23db-68ef-4d03-b9ec-687309d35166';
$data = $request->get_json_params();
$user_data = array(
'order_id' => $data['id'],
'memo' => $data['order_key'],
'status' => $data['status']
);
$resultado = woocbz_CallAPI($method, $url, $user_data);
return $data;
}
add_action(
'rest_api_init',
function () {
register_rest_route(
'woocbz/v1',
'/new-order',
array(
'methods' => 'POST',
'callback' => 'woocbz_order_created',
'permission_callback' => function () {
return true;
}
)
);
}
);
Any help will be greatly appreciated.