Magento 2 How to restrict existing customer to allow guest checkout

By | April 9, 2024
Spread the love

In Magento 2, by default, customers are allowed to checkout as guests or log in if they already have an account. However, if you want to restrict existing customers from checking out as guests and force them to log in, you’ll need to customize your Magento 2 installation.

Create events.xml file in app/code/Techgroup/Addon

<?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="sales_order_place_before">
        <observer name="addon_order_place_before" instance="Techgroup\Addon\Observer\OrderPlaceBefore"/>
    </event>  
</config>

Create observer file in app/code/Techgroup/Addon/Observer

<?php

namespace Techgroup\Addon\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Store\Model\ScopeInterface;

class OrderPlaceBefore implements ObserverInterface
{
    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;

    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $customerSession;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var \Magento\Framework\App\State
     */
    protected $state;

    /**
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Customer\Model\CustomerFactory $customerFactory
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Framework\App\State $state
     */
    public function __construct(
        \Psr\Log\LoggerInterface $logger,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\App\State $state
    ) {
        $this->_logger             = $logger;
        $this->customerFactory     = $customerFactory;
        $this->customerSession     = $customerSession;
        $this->scopeConfig         = $scopeConfig;
        $this->state               = $state;
    }

    /**
     * {@inheritDoc}
     * @see \Magento\Framework\Event\ObserverInterface::execute()
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        try {
            $order  = $observer->getEvent()->getOrder();
            if (! $order ){
                return $this;
            }
                
            $websiteid   = $order->getStore()->getWebsiteId();
            
            $userRestict = $this->scopeConfig->getValue('checkout/options/checkout_user_restict_as_guest', ScopeInterface::SCOPE_STORE);
            $userRestictMessage = $this->scopeConfig->getValue('checkout/options/checkout_user_restict_as_guest_message', ScopeInterface::SCOPE_STORE);
            
            if (! $order || ! $userRestict || $this->state->getAreaCode() != \Magento\Framework\App\Area::AREA_FRONTEND) {
                return $this;
            }
            
            if(!$this->customerSession->isLoggedIn()) 
            {
                $customer = $this->customerFactory->create();
                $customer->setWebsiteId($websiteid);
                $customer->loadByEmail($order->getCustomerEmail());

                if ($customer->getId()) {
                    if($userRestictMessage == ""){
                         $userRestictMessage = "Customer account is already exists with entered email address. Please login.";
                    }
                    
                    $this->_logger->alert($userRestictMessage);
                    throw new \Magento\Framework\Exception\LocalizedException(
                        __($userRestictMessage.$this->state->getAreaCode())
                    );
                }   
            }
        } 
        catch (\Magento\Framework\Exception\LocalizedException $e) {
            throw new \Magento\Framework\Exception\LocalizedException(
                __($e->getMessage())
            );
        }
        catch (\Exception $e) {
           throw new \Exception($e->getMessage());
        }
    }
}