wc_refund_payment

Try to refund the payment for an order via the gateway.

Description

(bool|WP_Error) wc_refund_payment( (WC_Order) $order, (number) $amount, (string) $reason = '' ); 

Returns (bool|WP_Error)

Parameters (3)

0. $order (WC_Order)
The order.
1. $amount (number)
The amount.
2. $reason — Optional. (string) => ''
The reason.

Usage

  1. if ( !function_exists( 'wc_refund_payment' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'woocommerce/includes/wc-order-functions.php'; 
  3.  
  4. // The order. 
  5. $order = null; 
  6.  
  7. // The amount. 
  8. $amount = null; 
  9.  
  10. // The reason. 
  11. $reason = ''; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = wc_refund_payment($order, $amount, $reason); 
  15.  

Defined (1)

The function is defined in the following location(s).

/includes/wc-order-functions.php  
  1. function wc_refund_payment( $order, $amount, $reason = '' ) { 
  2. try { 
  3. if ( ! is_a( $order, 'WC_Order' ) ) { 
  4. throw new Exception( __( 'Invalid order.', woocommerce ) ); 
  5.  
  6. $gateway_controller = WC_Payment_Gateways::instance(); 
  7. $all_gateways = $gateway_controller->payment_gateways(); 
  8. $payment_method = $order->get_payment_method(); 
  9. $gateway = isset( $all_gateways[ $payment_method ] ) ? $all_gateways[ $payment_method ] : false; 
  10.  
  11. if ( ! $gateway ) { 
  12. throw new Exception( __( 'The payment gateway for this order does not exist.', woocommerce ) ); 
  13.  
  14. if ( ! $gateway->supports( 'refunds' ) ) { 
  15. throw new Exception( __( 'The payment gateway for this order does not support automatic refunds.', woocommerce ) ); 
  16.  
  17. $result = $gateway->process_refund( $order->get_id(), $amount, $reason ); 
  18.  
  19. if ( ! $result ) { 
  20. throw new Exception( __( 'Anerroroccurred while attempting to create the refund using the payment gateway API.', woocommerce ) ); 
  21.  
  22. if ( is_wp_error( $result ) ) { 
  23. throw new Exception( $result->get_error_message() ); 
  24.  
  25. return true; 
  26.  
  27. } catch ( Exception $e ) { 
  28. return new WP_Error( error, $e->getMessage() );