Magento 2 Disable Payment method for frontend only.

Magento 2 You can disable payment method for frontend only using programmatically.

You can show the payment method in the admin area only and disable in the frontend area.

You need to create a simple module for the disable payment method in frontend. We disable the Cash on a delivery payment method from the frontend and enable the payment method in admin only.

Magento contain Magento\Payment\Model\MethodList class and Class used getAvailableMethods() function to check available method on frontend.

Now start with basic module creation, Registration.php file is to register our module.  Create the registration.php file,

Full Path,  app/code/Rbj/DisableFrontPayment/registration.php,

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Rbj_DisableFrontPayment',
    __DIR__
);

Create a module.xml file, Path: app/code/Rbj/DisableFrontPayment/etc/module.xml,

<?xml version="1.0" ?>
<!--
/**
 * @author Rakesh Jesadiya
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Rbj_DisableFrontPayment">
        <sequence>
            <module name="Magento_Payment"/>
            <module name="Magento_OfflinePayments" />
        </sequence>
    </module>
</config>

Now create the di.xml file for global scope,
Path: app/code/Rbj/DisableFrontPayment/etc/di.xml

<?xml version="1.0"?>
<!--
/**
 * @author Rakesh Jesadiya
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
	<!-- Plugin used for disable offline payment method in frontend -->
    <type name="Magento\Payment\Model\MethodList">
        <plugin sortOrder="5" name="disableCashondelivery" type="Rbj\DisableFrontPayment\Plugin\Model\Method\MethodAvailable" disabled="false" />
    </type>
</config>

Now create MethodAvailable.php file at a location.
Path: app/code/Rbj/DisableFrontPayment/Plugin/Model/Method/MethodAvailable.php

<?php
/**
 * MethodAvailable class
 *
 * @author  Rakesh Jesadiya
 * @package Rbj_DisableFrontPayment
 */

namespace Rbj\DisableFrontPayment\Plugin\Model\Method;

class MethodAvailable
{
    /**
     * @param Magento\Payment\Model\MethodList $subject
     * @param $result
     * @return array
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterGetAvailableMethods(\Magento\Payment\Model\MethodList $subject, $result)
    {
        foreach ($result as $key=>$_result) {
            if ($_result->getCode() == "cashondelivery") {
                unset($result[$key]);
            }
        }
        return $result;
    }
}

Now run the command to enable module,

php bin/magento setup:upgrade

When you check the frontend you cant see cash on delivery method.