<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.") ; } } }
You will get a success or an error message when the code is executed.$order_id = 110; $this->cancelmyorder($order_id);
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.