How to Cancel Order Programmatically in Magento 2?

How to Cancel Order Programmatically in Magento 2?

A while ago, Magento did not allow you to cancel an order. The only way to do so was programmatically. While Magento does allow you to cancel pending orders now, it is still useful to learn how to can an order programmatically in Magento 2.

Why Cancel an Order?

You’ll need to cancel an order for various reasons, including:

1. Customer Request

In some cases, the customer may have placed the order incorrectly. For instance, they ordered the wrong product. There’s also a possibility that the customer may no longer require the product.

2. Out of Stock

As a store owner, you try your best to ensure product availability. Even then there’s a chance that a customer ends up ordering a product which is out of stock. If there are no plans to restock the order or you cannot deliver it by the customer’s selected date, you have no choice but to cancel their order.

If you frequently experience issues with products running out of stock, consider our Magento 2 Out of Stock Notification Extension. If a product is out of stock, customers can sign up for a notification. As soon as the product is available again, they’ll get an automatic reminder. This ensures minimal loss of sales due to product unavailability.

Magento by default does not allow you to cancel an order on the frontend. So if you want to cancel an order due to whatever reason, you have to do it either using a third party extension or writing code for it.

Steps to Cancel Order Programmatically in Magento 2

The code to cancel a processing order in Magento 2 includes the following two steps.
  1. Creating a controller
  2. Executing method

Creating a controller

<php 
namespace VendorName\ModuleName\Controller\Action; 
 
use \Magento\Framework\App\Action\Action 
 
 class Cancelmyorder extends \Magento\Framework\App\Action\Action 
 { 
 //Var $orderMgt : Order Management 
 protected $orderMgt; 

 //Var $messageManager : Message Manager 
 protected $messageManager; 
 
 public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Sales\Api\OrderManagementInterface $orderMgt, \Magento\Framework\Message\ManagerInterface $messageManager ) { 
 
 $this--->orderMgt = $orderMgt; 
 $this->messageManager = $messageManager; 
 parent::__construct($context); 
 } 

 public function execute() 
 { 
 // Initiate Object Manager 
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 

 // Fetch Logged in User Session 
 $customerSession = $objectManager->get('Magento\Customer\Model\Session'); 

 // Check is User Logged in or Not 
 if(!$customerSession->isLoggedIn()) { $this->_redirect('/'); die; } 

 // Get request parameters 
 $cid = $customerSession->getCustomer()->getId(); 

 $oid = $this->getRequest()->getParam('order_id'); 
 // Get request parameters 

 $order = $objectManager->create('Magento\Sales\Model\Order')->load($oid); 
 // Fetch Order Data 

 $orderdata = $order->getData(); 
 // Get Order Status 

 $order_status = $orderdata["status"]; 
 // Get Customer Id of Order 

 $cus_id = $orderdata["customer_id"]; 
 // Check if logged in user & Order customer is same or not 

 if($cid != $cus_id) { $this->messageManager->addError("Sorry, We cant cancel your order right now.") ; } 
 // Check Order Status 

 if($order_status == "pending") 
 { 
 $this->orderMgt->cancel($oid); 
 $this->messageManager->addSuccess("Your order has been cancelled successfully.") ; 
 } 
 else
 { 
 $this->messageManager->addError("Sorry, We cant cancel your order right now.") ; 
 } 
 } 
 } 

Execute Method

Now, call the method by passing valid id in template file.
$order_id = 110; 
$this->cancelmyorder($order_id);
You will get a success or an error message when the code is executed.

Cancel Order with a Ready Made Extension

If you’re looking for an instant solution, then use our ready-made extension “Magento 2 Cancel Order” which enables the customers to cancel orders in a single click.

That’s all about cancelling order programmatically in Magento 2. This is as straightforward as it seems. However, no question is a wrong question so don’t hesitate to contact us in case you have any questions related to this article.