How To Create Credit Memo Programmatically in Magento 2

If would like to make a refund, how can I Create Credit Memo Programmatically in Magento 2?
We will need to get invoice and order object first , then use class – CreditmemoService to create credit memo.
$order = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Sales\Model\Order');
$creditmemoFactory = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Sales\Model\Order\CreditmemoFactory');
$invoice = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Sales\Model\Order\Invoice');
$creditmemoService = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Sales\Model\Service\CreditmemoService');

$order->load(1);
$invoices = $order->getInvoiceCollection();
foreach ($invoices as $invoice) {
    $invoiceincrementid = $invoice->getIncrementId();
}
$invoicedata = $invoice->loadByIncrementId($invoiceincrementid);
$creditmemo = $creditmemoFactory->createByOrder($order);
$creditmemo->setInvoice($invoicedata );
$creditmemoService->refund($creditmemo); 
 

Leave a Reply

avatar
  Subscribe  
Notify of