How to Make a Payment Method Only Visible in Admin
Usually a payment method is visible in checkout and sometimes also in admin area. Let's see today together the case of being visible only in admin area.
After a small break we are back on our regularly post about Magento 2. All payment methods have some features which can be defined in the payment's method model class and can be found in the abstract class Magento\Payment\Model\Method\AbstractMethod. If you check the abstract class you can find out all these feature variables that can be defined. For us the important ones are the $_canUseInternal and $_canUseCheckout which define where the payment method should be visible, in admin or in checkout. Except from your payment's method model class that you can define them, they can also be defined in the config.xml file explicit for the payment method we want.
But if you want to make an already existing payment method only visible in admin like the Magento's default "Check / Money order", the best practice will be to create a plugin for the function isAvailable, instead of overwriting the payment's method model class to override these variables. The isAvailable is a function of the above abstract method. We will use the after plugin to customise the functionality of the method, adding a check if an admin user is logged in. If this is true, it means that we are in creating an order from Magento admin and we will return the default result of the isAvailable function. Otherwise we will return false. So your plugin class should look like below.
The full example as extension can be found here.
Feel free to share this post and ask your questions in the comments below.
Till next time!