How to mark an order failed programmatically - Magento

How to mark an order failed programmatically - Magento

September 11, 2026 · Illustrated author avatarBy Stefan Bogdanescu
How to mark an order failed programmatically - Magento

Understanding Order Status Modifications in Magento

As an experienced developer, I often encounter situations where clients need to handle order status programmatically based on specific business rules or payment gateway responses. In this blog post, we’ll explore how to mark a Magento order as failed and retain the cart information for future use.

The core challenge is to set the correct order status that triggers the failureAction() method in the app/code/core/Mage/Checkout/controller/OnepageController.php file. This action is responsible for handling failed orders and redirecting customers accordingly.

To achieve this, we need to understand the available order statuses in Magento and how they can be modified programmatically. Here’s a comprehensive approach to address your requirements:

Setting Order Status Programmatically

Understanding Available Order Statuses

Magento provides several built-in order statuses out of the box, including “pending”, “processing”, “complete”, “closed”, “canceled”, and “holded”. Each status represents a specific stage in the order lifecycle.

For failed orders, we typically use either the “canceled” or “holded” status, depending on your business rules. The “canceled” status signifies that the order has been explicitly canceled by the system or store admin, while the “holded” status is used when an order requires manual intervention before being processed further.

Modifying Order Status Programmatically

To set the order status programmatically, you can use the setStatus() method provided by the Mage_Sales_Model_Order class. Here’s a basic example:

$order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
$order->setState(Mage_Sales_Model_Order::STATE_CANCELED, 'canceled', 'Payment transaction failed.', false)->save();

In this example, we use the loadByIncrementId() method to retrieve an order by its increment ID. Then, we call the setState() method with the desired state (“cancelled”) and status (“canceled”). The third parameter is a custom comment describing the reason for the cancellation.

Retaining Cart Information

To retain cart information after setting the order status to “canceled”, you need to ensure that the associated quote remains active. By default, when an order is canceled or saved with a specific status like “pending_payment”, Magento automatically sets the corresponding quote as inactive.

To overcome this behavior and keep the cart active, you can manually set the is_active flag of the quote back to 1 before saving it. Here’s how you can achieve this:

$quote = Mage::getModel('sales/quote')->load($order->getQuoteId());
$quote->setIsActive(true)->save();

Improving Cart Retention Logic

In your provided code, you’re already attempting to set the quote as active using $quote->setIsActive(1)->save(). However, it seems that you’re facing issues with this approach.

To ensure proper cart retention and avoid any conflicts, I recommend following these best practices:

  1. Check if the order is in a specific state (e.g., “pending_payment”) before attempting to save the quote as active. This prevents unnecessary flag changes for orders already marked as canceled or processed.
  2. Use try-catch blocks around your quote saving logic to handle any exceptions that may occur, such as duplicate primary key issues when multiple processes attempt to update the same quote simultaneously.

Here’s an improved version of your code snippet:

public function implementOrderStatus($event)
{
    $order = $event->getEvent()->getOrder();

    if ($this->_getPaymentMethod($order) == 'mypaymentmodule') {
        try {
            $quote = Mage::getModel('sales/quote')->load($order->getQuoteId());

            if ($order->getPayment()->getCcTransId() === NULL && $order->getState() != Mage_Sales_Model_Order::STATE_CANCELED) {
                // Set order status to canceled
                $order->cancel();
                $order->setStatus('canceled');
                $order->save();

                // Save the quote as active
                $quote->setIsActive(true)->save();

                // Add error message and redirect to cart page
                Mage::getSingleton('checkout/session')->addError('Sorry, either of your card information (billing address or card validation digits) did not match. Please try again');
                Mage::app()->getFrontController()->getResponse()->setRedirect('checkout/cart/')->sendResponse();
            } elseif ($order->canInvoice()) {
                $this->_processOrderStatus($order);
            }
        } catch (Exception $e) {
            // Handle any exceptions that may occur during quote saving
            Mage::logException($e);
        }
    }

    return $this;
}

Conclusion

In summary, to mark an order as failed programmatically in Magento and retain the cart information for future use, you need to understand the available order statuses and modify them accordingly.

By using the setStatus() method of the Mage_Sales_Model_Order class and properly handling quote activation, you can achieve the desired behavior while ensuring a seamless user experience.

Remember to implement proper exception handling and consider your specific business requirements when modifying order status programmatically. Following best practices like checking state conditions before saving quotes will help prevent conflicts and ensure data integrity.

For more advanced customizations or if you need further assistance with Magento development, feel free to reach out to our team at Laravel Company. We specialize in providing expert consulting services for eCommerce platforms like Magento.

Checkout Admin Configuration Orders

Our network