Don't save order on webservice failure response displaying a notice in WooCommerce

Viewed 341

I have a requirement to send order details to an internal company DB. I want to be able to only Save the order if the call to the DB returns a success response. If not, I want to stop the order and show a message on the checkout screen.

I'm trying to hook into woocommerce_checkout_create_order and if the response is false, return false and stop the order process:

add_action( 'woocommerce_checkout_create_order', 'process_new_order_details',  10, 2  );
  function process_new_order_details( $order ) {
     ......

     if($json_response->success == 1) {

       // We got a success message back from internal DB
       return $order;

     } else {

       // Could not save in internal DB
       return false;

  }

But it always save the order to database regardless of the webservice response. Any thoughts?

How can I avoid the order to be saved when a webservice response isn't "success" displaying a custom error notice?

1 Answers

You will use the following:

add_action( 'woocommerce_checkout_create_order', 'process_new_order_details',  10, 2  );
function process_new_order_details( $order, $data ) {

    # ...... / ......

    if($json_response->success == 1) {

        return $order;

    } else { // Throw an error notice 

        $error_text = __("My custom error notice", "wocommerce" );

        throw new Exception( $error_text );
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

enter image description here

Related