Magento – Magento 2 – Create partial Credit Memo programmatically

creditmemomagento2.3orderssales-order

I can create Credit Memo for invoice as given in this link.

Can anyone please help me to create Credit Memo with partial products and not returning all the products in invoice.

Best Answer

In Magento, if you want to create a credit memo, then you need to use below class:

  • \Magento\Sales\Api\RefundOrderInterface
  • \Magento\Sales\Api\InvoiceRepositoryInterface
  • \Magento\Sales\Api\Data\ CreditmemoItemInterfaceFactory

Example:

<?php


namespace {namespace};

class {ClassName}  
{

    /**
     * @var \Magento\Sales\Api\Data\CreditmemoItemInterfaceFactory
     */
    private $CreditmemoItemCreationFactory;

    /**
     * @var \Magento\Sales\Api\InvoiceRepositoryInterface
     */
    private $invoiceRepository;

    /**
     * @var \Magento\Sales\Api\RefundOrderInterface
     */
    private $refundOrder;



    public function __construct(
         \Magento\Sales\Api\RefundOrderInterface $refundOrder,
         \Magento\Sales\Api\InvoiceRepositoryInterface $invoiceRepository,
         \Magento\Sales\Api\Data\CreditmemoItemInterfaceFactory $CreditmemoItemCreationFactory 
        ) {
        $this->refundOrder = $refundOrder;
        $this->invoiceRepository = $invoiceRepository;
        $this->CreditmemoItemCreationFactory = $CreditmemoItemCreationFactory;
    }
    public function execute() 
    {
        $invoiceId = 5;
        try{
            
            $invoice= $this->invoiceRepository->get($invoiceId);
        } catch (\Magento\Framework\Exception\NoSuchEntityException $ex) {
            return ;
        }
        
        $invoiceItems = $invoice->getItems();
        $items = [];
        $orderId = $invoice->getOrderId();
        
        foreach ($invoiceItems as $invoiceItem) {
            

            if($invoiceItem->getOrderItem()->getParentItem()){
                continue;
            }
            
            $productId = $invoiceItem->getProductId();
            $invoiceSku = $invoiceItem->getSku();
            
            /**
             * If product id match then create Credit memo for that order
             */
            if($productId === 2030){
                $creditmemoItemCreation = $this->CreditmemoItemCreationFactory->create();
                $items[] = $creditmemoItemCreation->setQty($invoiceItem->getQty())
                         ->setOrderItemId($invoiceItem->getOrderItemId());                
            }
            


            
                    
        }

        

        /**
         * Create Credit Memo
         */
        
        $this->refundOrder->execute($orderId, $items, true, false);
    }

}
Related Topic