Skip to content

Instantly share code, notes, and snippets.

@growdev
Created June 14, 2021 21:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save growdev/64b7eaf04acfa663c47ec378ab0dd267 to your computer and use it in GitHub Desktop.
Save growdev/64b7eaf04acfa663c47ec378ab0dd267 to your computer and use it in GitHub Desktop.
Bulk Refund WooCommerce Orders using CSV file input.
<?php
/**
* Bulk Refund Orders
*
* This script expects a csv file with following columns:
* - Order ID 1002
* - Reason for refund 'Item was oversold.'
* - Amount to refund '34.56'
* - Refund payment true/false
* - Restock item true/false
*
* Run the script from the root directory:
* wp eval-file private-scripts/refund/refund.php filename.csv
*
*/
if ( false === ( $handle = fopen( $args[0],'r' ) ) ) {
die( 'File not found' );
}
WP_CLI::log( "Start..." );
while ( ( $cols = fgetcsv( $handle ) ) !== FALSE ) {
// Get values from row
$order_id = $cols[0];
$reason = $cols[1];
$amount = $cols[2];
$refund = $cols[3];
$restock = $cols[4];
$args = array(
'amount' => $amount,
'reason' => $reason,
'order_id' => $order_id,
'refund_payment' => $refund,
'restock_items' => $restock,
);
$order = wc_get_order( $order_id );
if ( ! $order ) {
WP_CLI::log( "Order $order_id does not exist!" );
continue;
}
if ( ! $order->get_total() ) {
WP_CLI::log( "Order $order_id total is zero." );
continue;
}
if ( $order->has_status( 'refunded' ) ) {
WP_CLI::log( "Order $order_id already refunded." );
continue;
}
// Is amount below total?
if ( $amount > $order->get_total() ) {
WP_CLI::log( $order_id . ' refund amount more than order total - csv: ' . $amount . ', order: ' . $order->get_total() );
continue;
}
// Process the refund
$result = 0;
try {
$result = wc_create_refund( $args );
} catch ( Exception $e ) {
WP_CLI::log( 'Error refunding order: ' . $e->getMessage() );
}
if ( is_wp_error( $result ) ) {
WP_CLI::log( 'An error occurred: ' . $result->get_error_message() . ' ' . $order_id );
} else {
WP_CLI::success( 'Refund successful ' . $order_id );
}
}
WP_CLI::success( 'Done' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment