Saturday, January 8, 2022

[FIXED] How to trigger woocommerce callback function?

Issue

I am trying to test that my callback function works by visiting the callback URL in my browser http://localhost:90/wordpress-payment-demo/wc-api/callback_handler/ but I keep getting -1. Here is my callback function.

$this->id = 'paymentplugin';

add_action( 'woocommerce_api_wc_' . $this->id , array( $this, 'callback_handler' ) );

function callback_handler() { 
    header( 'HTTP/1.1 200 OK' );
    echo "callback";
    die();
}

I also tried posting to the URL with Postman and I get a status code of 400 bad request.


Solution

This looks like a webhook for a custom WooCommerce payment gateway. In this case you probably don't need the _wc_ in the add_action function.

Example:

$this->id = 'paymentplugin';

add_action( 'woocommerce_api_' . $this->id , array( $this, 'webhook' ) );

function webhook() { 
    header( 'HTTP/1.1 200 OK' );
    echo "callback";
    die();
}

You also need not to end execution, because this is done by WooCommerce, hence you will probably want to remove the die() function:

$this->id = 'paymentplugin';

add_action( 'woocommerce_api_' . $this->id , array( $this, 'webhook' ) );

function webhook() { 
    header( 'HTTP/1.1 200 OK' );
    echo "callback";
}

Another thing to consider are headers. I don't know if they need to be sent but I recently created a custom gateway which only has this code in the webhook and it works perfectly:

function webhook() {
  $order_id = isset($_GET['order_id']) ? $_GET['order_id'] : null;
  $order = wc_get_order( $order_id );
  $order->payment_complete();
  wc_reduce_stock_levels($order_id);
}

The payment provider basically sends an IPN containing the order ID which I previously sent, so I can confirm that the order was paid.

Here is a link to the custom gateway I recently created, hopefully it can help:

https://github.com/usainicola/weldpay-woocommerce



Answered By - Nicola

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.