General

How to Lock Customer Account if They belong to Specific Customer Group in Magento 2

Requirements differ from business to business and the one who fulfills every need can be known as ultimate. When it comes to eCommerce, Magento does provide a one-stop solution to the store owner to fulfill customer needs and serve a seamless shopping experience to their shoppers. And definitely store owner’s requirement is endless but Magento never failed.
Recently one of our customers wanted to create one customer group inside his Magento 2 store and when he adds any customer to that group, their account should be automatically get locked and it should not be accessible anymore. He got this idea to prevent spamming inside his store. To end his search he came to us and being helping hands to our customers is a core value. Maybe you have come across a situation in the past or looking for the same. So here is code that will help you to lock your customer account when it falls in a specific group of Magento 2.
For this purpose, we have to make use of the customer_login event observer to collect customer group after login and then logout.
To do the same first you need to open the “Events.xml” file located at the below path.

app\code\Vendor\Extensionetc\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="customer_login_observer" instance="Vendor\Module\Observer\CustomerLogin" />
    </event>
</config>

Now you need to create one more file named “Customerlogin.php” file at the below path.

app\code\Vendor\Extension\Observer\CustomerLogin.php

<?php
namespace Vendor\Extension\Observer;
use Magento\Framework\Event\ObserverInterface;
class CustomerLogin implements ObserverInterface
{
    /**
     * @var \Magento\Framework\App\ResponseFactory
     */    private $responseFactory;
    /**
     * @var \Magento\Framework\UrlInterface
     */    private $url;
    private $customerSession;
    private $messageManager;

    public function __construct(
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\Message\ManagerInterface $messageManager
    ) {
        $this->responseFactory = $responseFactory;
        $this->url = $url;
        $this->customerSession= $customerSession;
        $this->messageManager = $messageManager;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $customer = $observer->getEvent()->getCustomer();
        $customerGroup = $customer->getGroupId();
        if($customerGroup==22)
        {
            $this->customerSession->logout();
            $this->messageManager->addErrorMessage(__('You are Locked'));
            $redirectionUrl = $this->url->getUrl('[SET YOUR URL HERE]');
            $this->responseFactory->create()->setRedirect($redirectionUrl)->sendResponse();
            return $this;
        }
    }
}

That’s it. Now extension works flawlessly to lock customer account if they fall into a specified customer group and they will get the message that “You are Locked” if they try to log in and get redirected to a specified URL.

Lastly, if you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends and Let us know if you are facing any issues while implementing this code.

Happy Coding!

Click to rate this post!
[Total: 7 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

10 hours ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

10 hours ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

1 day ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

2 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

4 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

4 days ago