'Update order total price by payment method after order was placed

I've created a specific method of payment to manage approval or decline of orders for specific products.

Once order was approved I set order in status "Waiting for payment" and send an email to customer with link to pay.

The problem is that for some payment method I have to apply a discount.

I'm able to apply discount before order was placed ( I use it for order that doesn't require approval), but I don't know how to recalcultate the total in this moment.

For do that I use this code:

add_action( 'woocommerce_cart_calculate_fees','payment_method_discount', 20, 1 );
function payment_method_discount( $cart_object ) {

    if ( is_admin() && !defined( 'DOING_AJAX' ) ) return;

    foreach($cart_object->cart_contents as $cart_item_id => $cart_item) {        
      $payment_method_arr = array('ppcp-gateway');
      foreach($payment_method_arr as $payment_method) {
        $percent = 25; 
        $chosen_payment_method = WC()->session->get('chosen_payment_method');

        if( $payment_method == $chosen_payment_method ) {   
          WC()->cart->add_fee( 'PayPal fee', 0 - $discount );
        }        
      }    
    }
}

To trigger the update I used:

add_action( 'woocommerce_review_order_before_payment', 'refresh_payment_methods', 20, 1 );
function refresh_payment_methods() {
    ?>
    <script type="text/javascript">
        (function($){ 
            $( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
              $('body').trigger('update_checkout');                            
            });
        })(jQuery);
    </script>
    <?php
}

I've tried also to add the function refresh_payment_methods to wp_footer hook.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source