Magento 1.9 – How to Cancel Magento Order Programmatically

magento-1.9ordersPHPprogrammatically

I want to change the order status to 'canceled' when payment failed.
I've tried the code below but the order status gets saved as processing:

        $orderId = $number8; //order id
        $order = Mage::getModel('sales/order')->load($orderId); //load order
        $order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save();
        $state = 'canceled';
        $status = $state;
        $comment = "Changing state to $state and status to $status Status";
        $isCustomerNotified = false; //whether customer to be notified
        $order->setState($state, $status, $comment, $isCustomerNotified);
        $order->addStatusHistoryComment("Payment Failed",
            Mage_Sales_Model_Order::STATE_CANCELED);
        $order->setStatus($status);    
       $order->save();


        $this->loadLayout();
        $this->_initLayoutMessages('checkout/session')->addError(Mage::helper('checkout')->__($errorMessage));
        $this->renderLayout();

Please assist.
I have a condition in my model if(payment fails) execute code above but the order gets saved as processing instead of canceled.

Best Answer

Use only following lines of code no need to save order again & aganin:

$orderId = $number8; //order id
$order = Mage::getModel('sales/order')->load($orderId);
$order->cancel()->setState(Mage_Sales_Model_Order::STATE_CANCELED, 'canceled', 'Payment Failed', false)->save();

Second last argument is commnet & Last boolean parameter is $isCustomerNotified false in your case.

What ever payment method you are using it should have cancelAction in it you need to write following code in it:

public function cancelAction()
    {
        $orderId = $this->getRequest()->getParam('orderId');
        if ($orderId) {
            $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
            if ($order->getId()) {
                // Flag the order as 'cancelled' and save it
                $order->cancel()->setState(Mage_Sales_Model_Order::STATE_CANCELED, 'canceled', 'Gateway has declined the payment.')->save();
                Mage_Core_Controller_Varien_Action::_redirect('onestepcheckout/index/index/cc/back', array('_secure' => true));
            }
        }
    }

In my case I have this redirect path

onestepcheckout/index/index/cc/back

Put yours

Related Topic