I was working on a payment gateway for WooCommerce and had to create a special URL that will then load the specified class method. Sometimes the information does not reach all parties e.g. if you close the browser and the status of the payment between the payment’s and merchant’s server remains unclear. The WooCommerce API allows you to create a callback URL.
Creating a callback URL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class WC_Gateway_My_Gateway extends WC_Payment_Gateway { public function __construct() { add_action( 'woocommerce_api_'. strtolower( get_class($this) ), array( $this, 'callback_handler' ) ); } public function callback_handler() { $raw_post = file_get_contents( 'php://input' ); $decoded = json_decode( $raw_post ); if ( isset( $decoded->TransactionId ) ) { if ( $response_data->Authorized == true ) { // Set order status to processing $order->update_status( 'processing', sprintf( __( 'Authorized %s %s on credit card.', 'woocommerce-my-payment-gateway' ), get_woocommerce_currency(), $order->get_total() ) ); } else { // Set order status to payment failed $order->update_status( 'failed', sprintf( __( 'Card payment failed.', 'woocommerce-my-payment-gateway' ) ) ); } } } die(); } } |
Calling a callback URL
Before WooCommerce 2.0, you could use:
In WoCommerce 2.0+:
http://yoursite.com/wc-api/wc_gateway_my_gateway/
How to get the $order->get_total() in callback url. I am exactly looking for this solution i am getting response in javascript event i need to process the payment through ajax. Please help me out. how to get the $order_id in call back url
Hi Gopinathan, The payment provider submits the callback url and sends you the data via HTTP POST method. Usually, by doing this $data = file_get_contents(“php://input”); You can see the order id and other info. When you have the order ID, you can do $order = new WC_Order( $order_id ); , then get $order->get_total(). Try to log the response (POST) from your payment provider in a file. However, not every payment provider includes order_id, sometimes you only get the transaction ID and you need to do an extra call to their API to get the order id and other info. Hope this helps, good luck!
I am getting transaction id in javascript event and need to process the payment through call back handler via jquery ajax.
How to create multiple call back handler in a class woocommerce?
I had an issue of the page only showing a -1 no matter what I did. Thanks for this article. It solved my problem
Hi dominykas, I try your tutorial, but when i hit callback url, it show shop page not firing my function, can you help? thx.
okay, I found my problem, case close. thx