By default when guest checkout is disabled in Magento 2.
No matter where a user is trying to go they're forwarded to their account after login, including if they've already added items to their cart and have clicked checkout in their mini-cart.
I feel like this is a hindrance to the sales pipeline.
I'm attempting to make an observer that redirects a user to their cart/checkout
if that was their intended purpose.
Even if they need to create an account in between.
Currently, I'm working on step one. Simply redirecting someone to their cart after logging in. The problem is that it seems none of the various redirect techniques have worked except for those that use exit(); or die(); in their methods.
In the notes of these suggestions, there are warnings not to use these functions as it interrupts the application.
Is there a good way to redirect a customer after they've logged in? Here is what I have so far:
=> etc/events.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_login">
<observer name="made_up_name_seems_to_work" instance="Vendor\NameSpace\Observer\Redirect" />
</event>
</config>
=> Observer/Redirect.php:
<?php
namespace Vendor\NameSpace\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class Redirect implements \Magento\Framework\Event\ObserverInterface
{
protected $_responseFactory;
protected $_url;
protected $_session;
public function __construct(
\Magento\Customer\Model\Session $session,
\Magento\Framework\App\ResponseFactory $responseFactory,
\Magento\Framework\UrlInterface $url
) {
$this->_session = $session;
$this->_responseFactory = $responseFactory;
$this->_url = $url;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$isCustomerLoggedIn = $this->_session->isLoggedIn();
if ($isCustomerLoggedIn) {
$event = $observer->getEvent();
$CustomRedirectionUrl = $this->_url->getUrl('checkout/cart');
$this->_responseFactory->create()->setRedirect($CustomRedirectionUrl)->sendResponse();
\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug('URL: ' . $CustomRedirectionUrl);
return $this;
}
}
}
The above redirect isn't working at all even with Exit() or die() however, it reflects where I'm at currently.
Is there a good(or proper) way to redirect from this observer?