Discounting not Working properly.
-
So I am creating a function which will add 5% discount when a certain payment gateway is selected.
// Add the discount if the Razorpay payment method is selected function razorpay_online_payment_discount( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { return; } $chosen_payment_method = WC()->session->get('chosen_payment_method'); // Check if payment method is set if ( ! isset( $chosen_payment_method ) ) { return; } $discount_percentage = 5; // Remove existing fee if any foreach ( $cart->get_fees() as $fee_key => $fee ) { if ( 'online_payment_discount' === $fee->get_id() ) { $cart->remove_fee( $fee_key ); break; } } if ( 'razorpay' === $chosen_payment_method ) { // Only consider the subtotal for calculating the discount $subtotal = $cart->subtotal; $discount = round( $subtotal * ( $discount_percentage / 100 ), 2 ); $cart->add_fee( __( 'Online Payment Discount', 'woocommerce' ), -$discount, false ); } } add_action( 'woocommerce_cart_calculate_fees', 'razorpay_online_payment_discount', 10, 1 ); // Update the cart/checkout page when the payment method is changed function razorpay_online_payment_discount_refresh() { if ( ! is_checkout() && ! is_cart() ) { return; } wc_clear_notices(); // Clear any displayed notices WC()->session->set( 'refresh_totals', true ); // Trigger update of totals ?> <script type="text/javascript"> (function( $ ) { $(document.body).on('change', 'input[name="payment_method"]', function() { $('body').trigger('update_checkout'); }); })(jQuery); </script> <?php } add_action( 'wp_footer', 'razorpay_online_payment_discount_refresh', 50 );Now this code is working fine but tere is an issue. Lets say the cart value is 798.00 then 5% of it should be 39.90 but the code is making it 41.10
I tried another code where instead of using add_fee function i tried to do it outside just to show textif ( 'razorpay' === $chosen_payment_method ) { $subtotal = WC()->cart->subtotal + WC()->cart->shipping_total; $discount = round( $subtotal * ( $discount_percentage / 100 ), 2 ); // Round the discount amount to two decimal places $formatted_discount = wc_price( $discount ); echo '<tr class="discount-row">'; echo '<th>' . __( 'Online Payment Discount', 'woocommerce' ) . '</th>'; echo '<td>- ' . $formatted_discount . '</td>'; echo '</tr>'; }This code works fine and gives me proper 39.90 value. Something is happening in the backend which i am not able to figure out how to solve this.
I am using these settings in woocommerce:
- Prices entered with tax -> Yes, I will enter prices inclusive of tax
- Rounding -> Rounding Round tax at subtotal level, instead of rounding per line
- Display prices during cart and checkout -> Including Tax
Any help would be appreciated to find what can be done to debug this.
Here is a cart var_dump if this helps – https://pastebin.com/raw/47LKk0VR
The topic ‘Discounting not Working properly.’ is closed to new replies.