Below code to create credit memo programmatically

public __construct(
    \Magento\Sales\Model\Order $order,
    \Magento\Sales\Model\Order\CreditmemoFactory $creditmemoFactory,
    \Magento\Sales\Model\Order\Invoice $invoice,
    \Magento\Sales\Model\Service\CreditmemoService $creditmemoService,
    array $data = []
) {
    $this->order = $order;
    $this->creditmemoFactory = $creditmemoFactory;
    $this->creditmemoService = $creditmemoService;
    $this->invoice = $invoice; 

public function refundCode()
    $order = $this->order;

    $invoices = $order->getInvoiceCollection();
    foreach ($invoices as $invoice) {
        $invoiceincrementid = $invoice->getIncrementId();

    $invoiceobj = $this->invoice->loadByIncrementId($invoiceincrementid);
    $creditmemo = $this->creditmemoFactory->createByOrder($order);

    // Don't set invoice if you want to do offline refund


Here the function refund located at path vendor\magento\module-sales\Model\Service\CreditmemoService.php does the work, but I could not figure out how it sets the Order Status to Closed?

When a credit memo is created, it changes order status to Closed. How do I change it to Canceled?


It can be done by,


observer, it will trigger once a credit memo has been created. In this observer you can check with order status label

if ($order->getStatusLabel() == 'Closed')

then you can change it to 'Canceled'.


Try, adding following code


after $this->creditmemoService->refund($creditmemo);

This will change the order state and status or the order for which you are generating a credit memo.

  • Th question is, when a credit memo is created, it says, We refunded %amount online and it has order status 'Closed'. Here I want to change the order status to Canceled instead of Closed – Slimshadddyyy Oct 25 '18 at 15:27
  • @Slimshadddyyy to set the status to cancel use Order::STATE_CANCELED – Anshu Mishra Oct 25 '18 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.