0

I have a WooCommerce website with a specialized plugin that syncs orders to a delivery company. This plugin adds a button next to each order in the orders table, which, when clicked, triggers a sync. The sync request can be inspected in the browser as:

https://mywebsite.com/wp-admin/admin-ajax.php?action=sync_order&order_id=69461

After triggering the sync, the URL changes to: https://mywebsite.com/wp-admin/edit.php?post_type=shop_order&sync_to_hfd=1

It's important to note that this URL works only when logged in as an admin; it returns '0' when accessed incognito.

Attempted Solution

To automate this process, I attempted to use the WordPress/WooCommerce REST API to register a custom endpoint and create a function to trigger the request:

add_action('rest_api_init', 'register_api_hooks');

function register_api_hooks() {
  register_rest_route(
    'wp/v2', '/sync-order/(?P<order_id>\d+)', array(
      'methods'  => 'GET',
      'callback' => 'sync_order',
    )
  );
}

function sync_order($data) {
  $order_id = $data['order_id'];
  
  $response = wp_remote_get("https://mywebsite.com/wp-admin/admin-ajax.php?action=sync_order&order_id=$order_id");
  
  if (is_wp_error($response)) {
    return array('success' => false, 'error' => $response->get_error_message());
  } else {
    return array('success' => true, 'order_id' => $order_id);
  }
}

I was able to access the endpoint successfully, but the admin-ajax.php response was a 'bad request'.

Questions

  • Is there something I am missing or doing incorrectly that is causing the 'bad request' response?

    Is there a more efficient or secure method to achieve this order sync via the API?

Any guidance or suggestions would be greatly appreciated!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.