Steps to cancel order programmatically in Magento 2

Steps to cancel order programmatically in Magento 2

As we know that Magento is an powerful ecommerce platform these days which offers managed marketing, catalog-management, seo tools and many more. But magento doesn't provide some of the essential features of a ecommerce platform. Similarly order cancellation from front end is not possible without custom programmaticallyhack in coding. It's a great feature to build up customer trust factor on ecommerce website. In this article, we are going to elaborate steps to cancel a order programmaticallyin magento 2 and for implementation of this functionality you don't need to install any module or patch in magento setup.

Step 1 : Create a new Controller

We need to initialize our code with controller which would contains a constructor & execute interface method. In constructor, we need to pass a argument of orderManagement type.

orderMgt = $orderMgt;
	$this->messageManager = $messageManager;
  public function execute() {
	// Initiate Object Manager
	$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    // Fetch Loggedin 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->messageManager->addSuccess("Your order has been cancelled successfully.") ;
	} else {
		$this->messageManager->addError("Sorry, We cant cancel your order right now.") ;

Step 2 : Execute Method

In this step, we will call method by passing valid order id in template file.

$order_id = 123;

Now, you are ready with custom script to cancel order programmatically. Once, code will get execute, you'll get a sucess or error message.