Search code examples
phpwordpresswoocommercekeyorders

Show an error if the order key is changed manually in URL on Woocommerce thankyou


I have developed a web page and integrated Cc Avenue gateway for payment and it is working fine.

My problem is, after a successful payment from bank customer gets redirected to thank you page which will have details like order no, date, customer details etc. The URL looks something like: https://mysite/checkout/order-received/785/?key=wc_order_5b909f1966e92

If I manually change key=wc_order_5b909f1966e92 to key=wc_order_5b909f1966e81 it should show error on 'thank you' page like "invalid order". Instead it is showing "Thank you. Your order has been received." without any order details on the page.

Before changing key:

https://imgur.com/a/c68Q8og

After changing key:

enter image description here


Solution

  • The following function will check order key validity. If the order key doesn't match, it will display a custom error notice (and optionally redirect to shop page if needed):

    add_action( 'template_redirect', 'check_thankyou_order_key' );
    function check_thankyou_order_key() {
        if( is_wc_endpoint_url('order-received') && isset($_GET['key']) ) {
            global $wp;
    
            $order_id  = absint( $wp->query_vars['order-received'] );
            $order     = wc_get_order( $order_id );
    
            if( $order->get_order_key() != wc_clean($_GET['key']) ){
                // Display a custom error notice
                wc_add_notice( __('Oups! The order key is invalid…', 'woocommerce'), 'error');
    
                // Optionally redirect to shop page (uncomment code below)
                // wp_redirect( get_permalink( wc_get_page_id( 'shop' ) ) );
                // exit();
            }
        }
    }
    

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

    enter image description here

    With the optional redirection to shop page:

    enter image description here