Magento 2: How to restore the cart after canceled/failed payment?
-
15-04-2021 - |
Pregunta
I used following code, but it doesn't work, I still get an empty cart.
$comment = __('Payment has been canceled.');
if ($order->getId() && $order->getState() != Order::STATE_CANCELED) {
$order->registerCancellation($comment)->save();
}
$session->restoreQuote();
$this->messageManager->addNoticeMessage($comment);
$this->_redirect('checkout/cart');
Solución
Check this one, it works for me in Magento 2.4: (inspired by this answer)
<?php
namespace Vendor\Extension\Controller;
use Magento\Framework\App\Action\Action;
use Magento\Checkout\Model\Session;
use Magento\Quote\Model\QuoteFactory;
class MyAction extends Action
{
public function __construct(
Context $context,
Session $checkoutSession,
QuoteFactory $quoteFactory
) {
parent::__construct($context);
$this->checkoutSession = $checkoutSession;
$this->quoteFactory = $quoteFactory;
}
public function execute()
{
$id = $this->checkoutSession->getLastQuoteId();
$quote = $this->quoteFactory->create()->loadByIdWithoutStore($id);
if (!$quote->getId()) {
// enter your code on fail (if quote not found) here.
// action method must return Result object, not boolean.
return false;
}
$quote->setIsActive(true)->setReservedOrderId(null)->save();
$this->checkoutSession->replaceQuote($quote);
// action method must return Result object, not boolean.
// write your redirect, JSON, or other result here.
return true;
}
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange