Skip to content

How to hide and show the payment method based on shipping address country to sort the payment method

This code has worked to hide and show the payment method based on the shipping address country.

public function execute(MagentoFrameworkEventObserver $observer)
{
//shipping company field
$shippingCompanyField = $this->cart->getQuote()->getShippingAddress()->getCountryId();

    $paymentMethod = $observer->getEvent()->getMethodInstance()->getCode();

    if ($shippingCompanyField == 'IN') {
        if ($paymentMethod == "multisafepay_giropay") {
            $checkResult = $observer->getEvent()->getResult();
            $checkResult->setData('is_available', false);
        }
    }else{
        if ($paymentMethod == "multisafepay_giropay") {
            $checkResult = $observer->getEvent()->getResult();
            $checkResult->setData('is_available', true);
        }
    }
    
}

If the customer address chooses a different country based on that it will hide and show, Initially “multisafepay_giropay” has second position after hiding then show the same payment gateway it will show on the last position in “multisafepay_giropay”, we need to show the same position, not the last position.
how to maintain the position(sort_order) in Magento 2.3?
Admin configuration payment gateway sort order is not working in this scenario.