Magento – Magento 2 programmatically online refund

magento-2.1magento2refundsales-ordertransaction

I'm trying to make online refund using this method:

// \Magento\Sales\Model\Order\Invoice $_invoiceModel
// \Magento\Sales\Model\Order\CreditmemoFactory $_creditmemoFactory
// \Magento\Sales\Model\Service\CreditmemoService $_creditmemoService

$invoiceobj = $this->_invoiceModel->loadByIncrementId('000000073');
$creditmemoObject = $this->_creditmemoFactory->createByOrder($order);
$creditmemoObject->setInvoice($invoiceobj);
$this->_creditmemoService->refund($creditmemoObject);

And I'm receiving following error:

We don't have enough information to save the parent transaction ID.

Best Answer

Try the service layer. This interface was added in 2.1.3 for exactly this purpose:

\Magento\Sales\Api\RefundInvoiceInterface

// Inject \Magento\Sales\Api\RefundInvoiceInterface $invoiceRefunder
$invoiceRefunder->execute(
    123, // Invoice ID (NOTE: not increment ID)
    [], // Items array (default all)
    true // Online refund--send to payment gateway
);

There are several additional optional arguments for notifying the customer and adding a comment.

If you're curious, you can find the implementation here: https://github.com/magento/magento2/blob/2.1-develop/app/code/Magento/Sales/Model/RefundInvoice.php#L127

Related Topic