How To

How to Restrict Payment Method Based on Shipping selection in Magento 2

Magento 2 is never failed to meet your Ecommerce store requirements they have tons of preloaded options built-in while customizations can be covered with coding. Considering international businesses many time, it happens that you have to restrict some payment or shipping options for different countries. Because not shipping and payment charges are the same for all locations, depending on distance and amount of transactions it may vary. Adding those charges to the product price is not a solution nor can be bared by store owners. At that time all you need to do is restrict payment methods based on the shipping method.
For example, if your customer selects the “Flat Rate” shipping method, you don’t want your customer to select the “Cash on delivery” payment method and hide it from checkout. There is no such in Magento 2 backend configurations, however, you can try 3rd party Magento Extensions such as Shipping & Payment Restrictions for Customer Groups in Magento 2. But if you want to do it on your own, you have to code for it.
So, we are back with another blog using which you can restrict any payment method based on your customer shipping method selections in Magento 2. Just follow the below steps and you are done.
First, you need to create “di.xml” file inside your extension folder.
app\code\Vendor\Extension\etc\di.xml

<?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\Payment\Model\MethodList">
        <plugin name="restrict_payment_on_shippingmethod" type="Vendor\Extension\Plugin\Model\MethodList" sortOrder="10"/>
    </type>
</config>

 
     
 

After that you need to create “MethodList.php” file inside your extension folder and add below code inside that file.
app\code\Vendor\Extension\Plugin\Model\MethodList.php

namespace Vendor\Extension\Plugin\Model;
 
class MethodList
{
 public function afterGetAvailableMethods(
        \Magento\Payment\Model\MethodList $subject,
     $availableMethods,
     \Magento\Quote\Api\Data\CartInterface $quote = null
 ) {
     $shippingMethod = $this->getShippingMethodFromQuote($quote);
     foreach ($availableMethods as $key => $method) {
         // Here we will hide CashonDeliver method while customer select FlateRate Shipping Method
            if(($method->getCode() == 'cashondelivery') && ($shippingMethod == 'flatrate_flatrate')) {
                unset($availableMethods[$key]);
         }
     }
 
     return $availableMethods;
 }
 
 /**
  * @param \Magento\Quote\Api\Data\CartInterface $quote
  * @return string
  */ private function getShippingMethodFromQuote($quote)
 {
     if($quote) {
         return $quote->getShippingAddress()->getShippingMethod();
     }
 
     return '';
 }
}

That’s it. You are free to manipulate this code according to your need to restrict and hide multiple payment methods based on your customer’s shipping method selection. Also, check out Shipping and Payment Method per Customer Group Extension which allows the store owner to manage shipping and payment method for the specific customer groups.

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 issue while implementing this code.
Happy Coding!

Click to rate this post!
[Total: 17 Average: 4.9]
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.🏏

View Comments

  • Hey, you've a bug in the example, calling the wrong method.
    $shippingMethod = $this->getShippingMethod($quote) has to be $this->getShippingMethodFromQuote($quote).

  • I am trying to use your article to hide cash on delivery payment if customer select aramex shipping method but it gives me this error message after click on next button i got the error "Something is went wrong with your request, please try again later"

  • Hello Thank you for your post, thats exactly what i need fast and small extension for the shipping and payment depending.
    what i have done so far:
    i successfully could make own extension as described on magento wiki

    and add your files but, while compiling i get

    Plugin class ITSolOn\ShipPay\Plugin\Model\MethodList doesn't exist

    could you please help me to find the mistake i surely did?

    • Please confirm you are creating file into the following location : TSolOn\ShipPay\Plugin\Model\MethodList
      And given the proper namespace into this file,

      Because according to compilation, it show this class does not exist, so above things can be the point of the issue.

      • Thank you for your fast answer, i have seen it today. And i should have replied faster.
        Issue still not solved
        i have following file structure

        ITSolOn/ShipPay/ with file: registration.php
        ITSolOn/ShipPay/etc with files: di.xml and module.xml
        ITSolOn/ShipPay/Plugin/Model/ with file MethodList.php
        alternatively i tried
        ITSolOn/ShipPay/Plugin/Model/MethodList/ with file MethodList.php

        but still compile error:

        In PluginList.php line 182:
        Plugin class ITSolOn\ShipPay\Plugin\Model\MethodList doesn't exist

        Thank you for your appreciated help

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

1 day ago

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…

3 days 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…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

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

4 days 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…

5 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.…

1 week ago