Skip to content

Instantly share code, notes, and snippets.

@growdev

growdev/refund.php

Created Jun 14, 2021
Embed
What would you like to do?
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