How to add hook after order payment completed in WooCommerce

How to add hook after order payment completed in WooCommerce
1417 Views

I want to discuss three separate WooCommerce hooks that are used after a transaction has been completed.

  • woocommerce_pre_payment_complete,
  • woocommerce_payment_complete,
  • woocommerce_payment_complete_order_status

woocommerce_pre_payment_complete

The first hook, woocommerce_pre_payment_complete, is used right away and is independent of the order status.

<?php
add_action( 'woocommerce_pre_payment_complete', 'cxc_pre_payment_order_status_completed' );

function cxc_pre_payment_order_status_completed( $order_id ) {
	
	$order = wc_get_order( $order_id );
	$user = $order->get_user();
	if( $user ){
        // get the order data and do anything
	}

}
?>

woocommerce_payment_complete

The next event, woocommerce_payment_complete, will only be triggered if an order is on hold, pending, failed, or cancelled. However, keep in mind that this list of statuses can also be filtered using the woocommerce_valid_order_statuses_for_payment_complete event.

WooCommerce will modify the order status to either processing or finished before the hook takes effect, and this change in status may be filtered using the woocommerce_payment_complete_order_status filter.

<?php
add_action( 'woocommerce_payment_complete', 'cxc_woocommerce_order_status_completed' );

function cxc_woocommerce_order_status_completed( $order_id ) {
	
	$order = wc_get_order( $order_id );
	$user = $order->get_user();
    if( $user ){
        // do something with the user
    }
	
}
?>

woocommerce_payment_complete_order_status

And last but not least, for the remaining order statuses, woocommerce_payment_complete_order_status will be fired.

<?php
add_action( 'woocommerce_payment_complete_order_status_processing', 'cxc_payment_order_complete_for_status' );
add_action( 'woocommerce_payment_complete_order_status_completed', 'cxc_payment_order_complete_for_status' );
add_action( 'woocommerce_payment_complete_order_status_pending', 'cxc_payment_order_complete_for_status' );
add_action( 'woocommerce_payment_complete_order_status_failed', 'cxc_payment_order_complete_for_status' );
// Note that it's woocommerce_order_status_on-hold, and NOT on_hold.
add_action( 'woocommerce_payment_complete_order_status_on-hold', 'cxc_payment_order_complete_for_status' );
add_action( 'woocommerce_payment_complete_order_status_refunded', 'cxc_payment_order_complete_for_status' );
add_action( 'woocommerce_payment_complete_order_status_cancelled', 'cxc_payment_order_complete_for_status' );

function cxc_payment_order_complete_for_status( $order_id ){
	
	// do anything
	
}
?>

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published. Required fields are marked *