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.

out-of-stock

Of course, this extension does a lot more than sending automatic alerts to customers. For more information, book a live demo.

Payment Issues

After getting an order, you may realise that the customer’s payment is not coming through. If the customer fails to send through the payment, order cancellation is inevitable.

Shipping Issues

Furthermore, shipping issues can force an order cancellation. For example, during extreme weather conditions, sellers often stop taking on orders and inform customers about potential delays. In some instances, the shipper may not deliver to the customer’s selected location.

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.

About the Cancel Order Extension

Instead of handling order cancellations yourself, you can let the customers do it themselves through this extension.

cancel-order-list

As the store owner, you can approve or reject their request. You can personalise the order cancel button to suit your individual requirements. This is shown below.

cancel-order-button

The extension allows you to set up a customisable email to inform them about their cancellation request.

order-cancellation-email-template

If you wish to know more about this extension, book a live demo or contact our support team.

Conclusion

That’s all about cancelling order programmatically in Magento 2. This is as straightforward as it seems. If you encounter any problems with order cancellation in Magento 2 programmatically, reach out to us.