cancel
Showing results for 
Search instead for 
Did you mean: 

To go directly to the checkout page when adding a product to the cart

To go directly to the checkout page when adding a product to the cart

Hi,

 

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:

<?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.

1 REPLY 1

Re: To go directly to the checkout page when adding a product to the cart

Hello Fredey,

 

It depends on a configuration setting if your code will work because Magento also sets a redirect url  based on the following configuration field checkout/cart/redirect_to_cart

If this is enabled your could shouldn't work because Magento uses the following function to change the redirect after adding the product to the shopping cart:

 

 

    /**
     * Get resolved back url
     *
     * @param null $defaultUrl
     *
     * @return mixed|null|string
     */
    protected function getBackUrl($defaultUrl = null)
    {
        $returnUrl = $this->getRequest()->getParam('return_url');
        if ($returnUrl && $this->_isInternalUrl($returnUrl)) {
            $this->messageManager->getMessages()->clear();
            return $returnUrl;
        }

        $shouldRedirectToCart = $this->_scopeConfig->getValue(
            'checkout/cart/redirect_to_cart',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );

        if ($shouldRedirectToCart || $this->getRequest()->getParam('in_cart')) {
            if ($this->getRequest()->getActionName() == 'add' && !$this->getRequest()->getParam('in_cart')) {
                $this->_checkoutSession->setContinueShoppingUrl($this->_redirect->getRefererUrl());
            }
            return $this->_url->getUrl('checkout/cart');
        }

        return $defaultUrl;
    }

 

 

which is used in the following function:

 

    /**
     * Set back redirect url to response
     *
     * @param null|string $backUrl
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     */
    protected function _goBack($backUrl = null)
    {
        $resultRedirect = $this->resultRedirectFactory->create();

        if ($backUrl || $backUrl = $this->getBackUrl($this->_redirect->getRefererUrl())) {
            $resultRedirect->setUrl($backUrl);
        }

        return $resultRedirect;
    }

So your observer is called before the Magento default redirect as shown below:

            $this->_eventManager->dispatch(
                'checkout_cart_add_product_complete',
                ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
            );

            if (!$this->_checkoutSession->getNoCartRedirect(true)) {
                if (!$this->cart->getQuote()->getHasError()) {
                    $message = __(
                        'You added %1 to your shopping cart.',
                        $product->getName()
                    );
                    $this->messageManager->addSuccessMessage($message);
                }
                return $this->goBack(null, $product);
            }

So probably if you just change the configuration setting it should work. Let me know if my answer was any help solving your issue.