Magento 2 – Cart Empty After Successful Payment Fix

cartmagento2order-success-pagepaymentquote

I have a custom payment method, after successful payment; payment page return to a controller where it updates order status and truncate current cart items like this:

$this->quote->load($orders->getQuoteId());

$this->quote->setReservedOrderId(null);
$this->quote->setIsActive(true);
$this->quote->removePayment();
$this->quote->save();

$this->cart->truncate();
$this->cart->saveQuote();

Where $this->quote is object of Magento\Quote\Model\Quote
and $this->cart is object of Magento\Checkout\Model\Cart

The cart is truncating properly, but the cart summery count is still appearing on header, and when I go to view cart, it is showing empty cart with previous order total, as shown in image below

enter image description here

My question is, how can I fully empty my cart data after successful payment?

Best Answer

You may try to use checkout session Model to clear quote data (i.e Magento\Checkout\Model\Session.php ).

Update your payment module controller code as follow.

I assume your custom payment module controller file name is MypaymentController.php

classs MypaymentController    extends \Magento\Framework\App\Action\Action
{

    /**
     * @var \Magento\Checkout\Model\Session
     */
    private $checkoutSession;


      public function __construct(
        ........................
        ........................
        SessionManagerInterface $checkoutSession,
        ........................
        ........................
      ){

        ........................
        $this->checkoutSession = $checkoutSession;
        ........................
      }



    public function execute()
    {
       ........................
       $this->_checkoutSession->clearQuote();
       $this->_checkoutSession->clearStorage();
       $this->_checkoutSession->restoreQuote();
       ........................

    }    

}

** Note:**

If your payment module controller already injected the Checkout Session Model (i.e \Magento\Checkout\Model\Session) then do not reinject Session Model, just try to use the functions below in your controller code block.

$this->_checkoutSession->clearQuote();
$this->_checkoutSession->clearStorage();
$this->_checkoutSession->restoreQuote();
Related Topic