I am looking for a way to programmatically refund part of an order within a custom module.
I have been following this blog post (https://www.rakeshjesadiya.com/create-creditmemo-for-order-item-in-magento-2/) but there is no creditmemo id being generated when the load()
method id called on line 41.
I'm not entirely sure this is the correct way to go about it any more either, as this blog post dates back to AUGUST 9, 2018, so I was wondering if anyone knows of a better way to approach this at all?
Cheers guys
Update
So I'm using the Magento\Sales\Api\RefundOrderInterface
class to call the execute() method which requires the 2nd parameter to be an array of items of type Magento\Sales\Api\Data\CreditmemoItemCreationInterface
.
I've added the Magento\Sales\Model\Order\Creditmemo\ItemCreationFactory
class and I'm setting my items in a loop as follows:
$creditmemoItems = [];
foreach ($order->getAllVisibleItems() as $item) {
$creditmemoItem = $this->creditmemoItemFactory->create();
$creditmemoItem->setOrderItemId($item->getId());
$creditmemoItem->setQty($item->getQtyOrdered());
$creditmemoItems[] = $creditmemoItem;
}
After that, I call the execute method for the refundOrder class:
$this->refundOrder->execute(
$order->getId(),
$creditmemoItems ,
true,
false
);
the operation fails and throws the following error in the logs
Exception #0 (Magento\Sales\Exception\DocumentValidationException): Creditmemo Document Validation Error(s): The order does not allow a creditmemo to be created. The most money available to refund is 0.