Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to Restrict Order in Magento 2

Vinh Jacker | 09-17-2024

How to Restrict Order in Magento 2 How to Restrict Order in Magento 2

The Most Popular Extension Builder for Magento 2

With a big catalog of 224+ extensions for your online store

If you want to succeed in the e-commerce business, you should ensure smooth operations in managing orders. Magento 2 provides a range of features that meet diverse business needs. However, in some cases, you should restrict orders in the Magento 2 store to create a more personalized shopping experience. This can be achieved by offering exclusive products or services to specific customer segments.

In this article, we’ll explore how to restrict orders in Magento 2 and enhance your store’s management.

A Detailed Guide to Restrict Orders in Magento 2

Before implementing order restrictions, ensure you create the necessary customer groups. You can achieve this by following the steps below:

  • Navigate to Customers > Customer Groups.

customer-group

  • Click on Add New Customer Group and create the groups you need, such as Wholesale, Retail, VIP, etc.

add-new-customer-group

Step 1: Create a Custom Module

Firstly, you need to create a custom module. Let’s call it Vendor_CustomerGroupRestriction.

  • Set up the module directory structure: app/code/Vendor/CustomerGroupRestriction/
├── registration.php
├── etc
│   ├── module.xml
│   └── di.xml
└── Plugin
    ├── GuestPaymentInformationManagementPlugin.php
    └── PaymentInformationManagementPlugin.php

Step 2: Configure The Module

  • Register the module: registration.php

  • Configure the module: etc/module.xml

Step 3. Create Plugins

In Magento 2, the plugins allow you to modify behavior. You need to create three plugins:

  • Dependency Injection Configuration: etc/di.xml

Run the code as given below:


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Api\GuestPaymentInformationManagementInterface">
        <plugin name="guest_payment_information_management_plugin" type="Vendor\CustomerGroupRestriction\Plugin\GuestPaymentInformationManagementPlugin"/>
    </type>
    <type name="Magento\Checkout\Api\PaymentInformationManagementInterface">
        <plugin name="payment_information_management_plugin" type="Vendor\CustomerGroupRestriction\Plugin\PaymentInformationManagementPlugin"/>
    </type>
</config>

```

* **Guest Payment Information Management Plugin**

Patch: ``Plugin/GuestPaymentInformationManagementPlugin.php``

This plugin restricts guest users based on customer group conditions. Add the below-mentioned code.

```
<?php

namespace Vendor\CustomerGroupRestriction\Plugin;

use Magento\Checkout\Api\GuestPaymentInformationManagementInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;

class GuestPaymentInformationManagementPlugin
{
    protected $cartRepository;
    protected $customerRepository;

    public function __construct(
        CartRepositoryInterface $cartRepository,
        CustomerRepositoryInterface $customerRepository
    ) {
        $this->cartRepository = $cartRepository;
        $this->customerRepository = $customerRepository;
    }

    public function beforeSavePaymentInformationAndPlaceOrder(
        GuestPaymentInformationManagementInterface $subject,
        $cartId,
        $email,
        \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
        \Magento\Quote\Api\Data\AddressInterface $billingAddress
    ) {
        $quote = $this->cartRepository->getActive($cartId);
        $customerId = $quote->getCustomerId();
        
        if ($customerId) {
            $customer = $this->customerRepository->getById($customerId);
            $customerGroupId = $customer->getGroupId();

            // Check if the customer group is allowed to place the order
            if (!$this->isAllowedCustomerGroup($customerGroupId)) {
                throw new LocalizedException(__('You are not allowed to place orders.'));
            }
        }

        return [$cartId, $email, $paymentMethod, $billingAddress];
    }

    protected function isAllowedCustomerGroup($customerGroupId)
    {
        // Add your custom logic to determine if the customer group is allowed
        $allowedCustomerGroups = [1, 2]; // Example: Only allow customer groups with IDs 1 and 2
        return in_array($customerGroupId, $allowedCustomerGroups);
    }
}

```

* **Payment Information Management Plugin**


Patch: ``Plugin/PaymentInformationManagementPlugin.php``

This plugin restricts registered users based on customer group conditions.

```

<?php

namespace Vendor\CustomerGroupRestriction\Plugin;

use Magento\Checkout\Api\PaymentInformationManagementInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;

class PaymentInformationManagementPlugin
{
    protected $cartRepository;
    protected $customerRepository;

    public function __construct(
        CartRepositoryInterface $cartRepository,
        CustomerRepositoryInterface $customerRepository
    ) {
        $this->cartRepository = $cartRepository;
        $this->customerRepository = $customerRepository;
    }

    public function beforeSavePaymentInformationAndPlaceOrder(
        PaymentInformationManagementInterface $subject,
        $cartId,
        \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
        \Magento\Quote\Api\Data\AddressInterface $billingAddress
    ) {
        $quote = $this->cartRepository->getActive($cartId);
        $customerId = $quote->getCustomerId();

        if ($customerId) {
            $customer = $this->customerRepository->getById($customerId);
            $customerGroupId = $customer->getGroupId();

            // Check if the customer group is allowed to place the order
            if (!$this->isAllowedCustomerGroup($customerGroupId)) {
                throw new LocalizedException(__('You are not allowed to place orders.'));
            }
        }

        return [$cartId, $paymentMethod, $billingAddress];
    }

    protected function isAllowedCustomerGroup($customerGroupId)
    {
        // Add your custom logic to determine if the customer group is allowed
        $allowedCustomerGroups = [1, 2]; // Example: Only allow customer groups with IDs 1 and 2
        return in_array($customerGroupId, $allowedCustomerGroups);
    }
}

Conclusion

By executing the steps outlined in this article, you can successfully restrict orders in Magento 2. This will help you manage inventory effectively and tailor your e-commerce store to different customer segments. Remember to test your restrictions thoroughly to ensure a seamless shopping process for your customers.

Feel free to contact us if you have any further questions or need additional assistance!

Table of content
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services