Magento – How to prevent cart empty after checkout payment failure in magento 2.2.5

cartmagento-2.2.5payment

In Magento 2.2.5, after payment failure cart is going empty. I want to keep this, that if payment failed cart will not be empty, that will show last cart items.

I'm using the PayUMoney Payment Method. How can I do this?

I get a lot of example of this problem on Magento 1.9 version but didn't get any suitable solution for Magento 2.2.5.

Please help me, how I solve this issue.

Thank you

Best Answer

This is a sample code for reactivate quote when payment is failed. This is a controller where it redirect after payment failure. You need to use it in your payment module and update the code according to your requirement or module structure.

<?php 
namespace [Vendor]\[Module]\Controller\Order;

class Failure extends \Magento\Framework\App\Action\Action
{
    ...
    protected $_quoteFactory;
    protected $_checkoutSession;
    ...
    public function __construct(
        ...
        \Magento\Quote\Model\QuoteFactory $quoteFactory,
        \Magento\Checkout\Model\Session $checkoutSession,
        ...
    ){
        ...
        $this->_quoteFactory = $quoteFactory;
        $this->_checkoutSession = $checkoutSession;
        ...
    }

    public function execute()
    {
        $order = $this->_checkoutSession->getLastRealOrder();
        $quote = $this->_quoteFactory->create()->loadByIdWithoutStore($order->getQuoteId());
        if ($quote->getId()) {
            $quote->setIsActive(1)->setReservedOrderId(null)->save();
            $this->_checkoutSession->replaceQuote($quote);
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setPath('checkout/cart');
            $this->messageManager->addWarningMessage('Payment Failed.');
            return $resultRedirect;
        }
    }
}
Related Topic