Easy Way to Remove Payment Method in Magento 2

0
15888
How to Remove Payment in Magento 2 | MageWorx Magento Blog
Reading Time: 3 minutes

Quite often you may want to display a certain payment method to a particular group of customers while hiding it from the other ones.

Here is a step-by-step instructdion on how to quickly implement that in Magento 2.

The solution is based on the Payment Restriction module, the code of which is available below, where MageWorx is a vendor name and Payment Restriction is the name of the module.

How to disable payment method in Magento 2?

1. At the first step you need to create a directory for the module:

app/code/MageWorx/PaymentRestriction

2. When done, you may add a registration file.

app/code/MageWorx/PaymentRestriction/registration.php
<?php
/**
 * Copyright © 2016 MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'MageWorx_PaymentRestriction',
    __DIR__
);

the Composer file (just in case you may want to transfer the module with the ability to install it via Composer):

app/code/MageWorx/PaymentRestriction/composer.json
{
    "name": "mageworx/module-paymentrestriction",
    "description": "N/A",
    "require": {
        "php": "~5.6.0|~7.0.0"
    },
    "type": "magento2-module",
    "version": "1.0.0",
    "license": [
        "OSL-3.0",
        "AFL-3.0"
    ],
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "MageWorx\\PaymentRestriction\\": ""
        }
    }
}

and a file needed for the declaration of the module:

app/code/MageWorx/PaymentRestriction/etc/module.xml
<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */
-->
<config xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="MageWorx_PaymentRestriction" setup_version="1.0.0">
    </module>
</config>

At the next step, I’m going to create a di.xml file in a sharing space (note if the file is declared in the frontend scope, you won’t get the desired result) and declare our plugin there:

app/code/MageWorx/PaymentRestriction/etc/di.xml
<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */
-->
<config xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\OfflinePayments\Model\Cashondelivery">
        <plugin sortOrder="1" name="restrictByCustomer"
                type="MageWorx\PaymentRestriction\Plugin\Payment\Method\CashOnDelivery\Available"/>
    </type>
</config>

Now, let’s add the last and the main file with the plugin class that is responsible for the check:

app/code/MageWorx/PaymentRestriction/Plugin/Payment/Method/CashOnDelivery/Available.php
<?php
/**
 * Copyright © 2016 MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */

namespace MageWorx\PaymentRestriction\Plugin\Payment\Method\CashOnDelivery;

use Magento\Customer\Model\Session as CustomerSession;
use Magento\Backend\Model\Auth\Session as BackendSession;
use Magento\OfflinePayments\Model\Cashondelivery;

class Available
{

    /**
     * @var CustomerSession
     */
    protected $customerSession;

    /**
     * @var BackendSession
     */
    protected $backendSession;

    /**
     * @param CustomerSession $customerSession
     * @param BackendSession $backendSession
     */
    public function __construct(
        CustomerSession $customerSession,
        BackendSession $backendSession
    ) {
        $this->customerSession = $customerSession;
        $this->backendSession = $backendSession;
    }

    /**
     *
     * @param Cashondelivery $subject
     * @param $result
     * @return bool
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function afterIsAvailable(Cashondelivery $subject, $result)
    {
        // Do not remove payment method for admin
        if ($this->backendSession->isLoggedIn()) {
            return $result;
        }

        $isLogged = $this->customerSession->isLoggedIn();
        if (!$isLogged) {
            return false;
        }

        return $result;
    }
}

IMPORTANT! 

Please note that for some reason, the plugin created only for the frontend won’t let you delete the chosen payment method – it will anyway be shown on the checkout page. However, if a customer tries to choose it, that will trigger an error and throw a customer back to the checkout step.

That’s why to prevent this, it’s necessary to validate not only the customer’s session, but also the session of the admin. If you’re logged in as an admin, don’t change anything to get the original result.

Also, you can add an extra check for the frontend. That can be done by developing a simple module that segments the available payment methods according to customer groups.

Moreover, you can disable certain payment methods not only for the selected countries (the default option) but also for streets, phone numbers or any other location criteria.

Below is an example:

  1. The Cash on Delivery method is hidden for the not logged in customer:1
  2. The same for the logged in customer:IjcdJ
  3. Visible:5H9o3
  4. Always visible for a store Admin:

l6lgz

Some Extra Recommendations

  1. Implement the same activities in a separate module to get an ability to disable it.
  2. Change a vendor and a module name to your own.

This solution was created and tested on Magento 2.1.


Still ‘ve got troubles removing a payment method in Magento 2? Feel free to leave a comment below.

I am a huge coffee fan. If I’m not drinking it, I’m likely to be busy with getting MageWorx projects done. Fond of reading sci-fi books (especially those about dwarfs, ogres and the post-apocalyptical world). My biggest dream is to find a huge chest of gold and buy my own uninhabited island. Happy husband. Proud father. Ah... and also I'm a certified Magento developer. ;)

LEAVE A REPLY

Please enter your comment!
Please enter your name here