PHP SDK Sample: Partial Refund Order

The following sample will generate a 50% refund on an order which is common during "save a sale" customer service interactions.

<?php
require_once __DIR__ . '/vendor/autoload.php';

// Configure API key authorization: ultraCartSimpleApiKey
ultracart\v2\Configuration::getDefaultConfiguration()->setApiKey('x-ultracart-simple-key', 'YOUR KEY HERE');

// Disable SSL verification if we're having issues with this PHP install not having the proper CA installed.  Fix your CA for a production environment!
// Set debug to true if you need more information on request/response
$client = new GuzzleHttp\Client(['verify' => false, 'debug' => false]);

$api_instance = new ultracart\v2\api\OrderApi(
    $client,
    ultracart\v2\Configuration::getDefaultConfiguration(),
    new ultracart\v2\HeaderSelector("2016-10-01")
);

$_expand = "item,payment,shipping,summary,taxes";

$orderResponse = $api_instance->getOrder("DEMO-2019079613", $_expand);
$order = $orderResponse->getOrder();

// Accumulate the amount of item cost that is being refunded
$refundedAmount = 0;

// Go through the items and refund 50% of each line
$refundPercentage = 0.5;
for ($i = 0; $i < count($order->getItems()); $i++) {
    $orderItem = $order->getItems()[$i];

    $totalRefunded = new ultracart\v2\models\Currency();
    $totalRefunded->setValue(round($orderItem->getTotalCostWithDiscount()->getValue() * $refundPercentage, 2, PHP_ROUND_HALF_UP));

    $orderItem->setTotalRefunded($totalRefunded);
    $orderItem->setQuantityRefunded(0); // We're just refunding the amount, so we'll set the quantity refunded to zero

    // Update the accumulated refund amount
    $refundedAmount = $refundedAmount + $totalRefunded->getValue();
}

// If there were taxes on the order, calculate the amount of tax to refund as well
if ($order->getTaxes() != null && $order->getTaxes()->getTaxRate() != null) {

    $taxRefunded = new ultracart\v2\models\Currency();
    $taxRefunded->setValue(round($refundedAmount & $order->getTaxes()->getTaxRate(), 2, PHP_ROUND_HALF_UP));

    $order->getSummary()->getTaxRefunded($taxRefunded);
}

// Initiate the refund
$rejectAfterRefund = false;
$skipCustomerNotification = false;
$autoOrderCancel = false;
// Mark it manually refunded for PO payment method
$manualRefund = strcasecmp("Purchase Order", $order->getPayment()->getPaymentMethod()) == 0;
if ($manualRefund) {
    echo "Marking as manual refund because of payment method.";
}
$reverseAffiliateTransactions = false;
$orderResponse = $api_instance->refundOrder($orderResponse->getOrder(), $order->getOrderId(), $rejectAfterRefund, $skipCustomerNotification, $autoOrderCancel, $manualRefund, $reverseAffiliateTransactions, $_expand);

if ($orderResponse->getSuccess()) {
    echo "Successful refund.";
} else {
    echo "Error: " . var_dump($orderResponse->getError());
}

?>