Search code examples
phpwordpresswoocommercecallback

WooCommerce - Enable asynchronous callback URL


Environment
Standard WordPress/WooCommerce (WP/WC) deployment with custom payment plugin. On click "Place order" button, the checkout page is blocked awaiting customer interaction. Once received through external server callback the checkout process could continue or be canceled.

Goal
Enable WP/WC callback URL for receiving asynchronous responses from external server so the checkout page and process could be updated accordingly.

Request
WC_API – The WooCommerce API Callback seems like the way to go, however I am unable to get it working and need a step by step guidance or a pointer to a description on how to do that.


Solution

  • If you already read the WC_API documentation of woocommerce then I will explain it to you using an example. The doc might be a little subtle at first(I have been there).

    1. First thing is first let's name your callback function. Let's call it callback_handler.
    2. Second thing you need to name your api path endpoint. Let's call it callback_path.
    3. Now we have a handler function and an api path that leads to your api. Let's connect the two. Meaning when a call is made using that api path it is directed to the handler function. To create that you need to create a hook like below.

    add_action('woocommerce_api_callback_path', 'callback_handler');

    Remember that your callback path needs to be prefixed with woocommerce_api.

    1. Let's call your domain name example.com. Now when a request is made to http://example.com/wc-api/callback_path you will be able to see what is being sent from your callback_handler function. If the request is a form data, you can use php global variables (like $_GET or $_POST) to retrieve the request. If the request is a json or a plain text you can use file_get_contents('php://input'); to retrieve the request.

    Additional note: If you are hooking inside a php class you need to hook your function like below

    add_action('woocommerce_api_callback_path', array($this, 'callback_handler'));