create below files in your custom module.
The below example is used to hide the cash on delivery payment method
You can create an observer for the event payment_method_is_active
Vendor/Module/etc/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="payment_method_is_active">
<observer name="custom_payment" instance="Vendor\Module\Observer\PaymentMethodAvailable" />
</event>
</config>
Vendor/Module/Observer/PaymentMethodAvailable.php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
use \Magento\Checkout\Model\Cart;
class PaymentMethodAvailable implements ObserverInterface
{
protected $cart;
protected $logger;
public function __construct(
Cart $cart,
\Psr\Log\LoggerInterface $logger
){
$this->cart = $cart;
$this->logger = $logger;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
//shipping company field
$shippingCompanyField = $this->cart->getQuote()->getShippingAddress()->getCompany();
//Billing company field
$billingCompanyField = $this->cart->getQuote()->getBillingAddress()->getCompany();
$paymentMethod = $observer->getEvent()->getMethodInstance()->getCode();
if ($shippingCompanyField != '') {
if ($paymentMethod == "cashondelivery") {
$checkResult = $observer->getEvent()->getResult();
$checkResult->setData('is_available', false);
}
}
}
}
I just check shippingCompanyField is filled or not. you can also check the billing company field then you can check another condition.
I hope this will help you.