I am writing an extension which allows to go directly to the checkout page when clicking on the add-to-cart button on the product page. I found a solution for Magento 1 here and I tried to adapt it to Magento 2. Here are my files:
File etc/frontend/events.xml:
<?xml version="1.0" encoding="utf-8" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_add_product_complete">
<observer
name="mycompany_go_to_checkout"
instance="MyCompany\GoToCheckout\Observer\GoToCheckout" />
</event>
</config>
File Observer/GoToCheckout.php:
namespace MyCompany\GoToCheckout\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class GoToCheckout implements ObserverInterface
{
protected $_url;
public function execute(Observer $observer)
{
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$url = $urlInterface->getUrl('checkout');
$observer->getControllerAction()->getResponse()->setRedirect($url);
}
}
What should I change or add to make it work?
Any guidance will be appreciated.