Magento 1.9 – Hide Payment Method Based on Product in Cart

magento-1.9onepage-checkoutpayment-methods

I want to hide offline payment method, if some particular product is added to cart.
For those special products payment should be online, So I need to hide all the offline payment method in that case.

How can I hide payment method based on condition?

Best Answer

At last I have found the way to hide all Offline payment methods based on product in cart Please follow the below step:

Step1 : Create a "Yes/No" product attribute with code "is_offline_payment_available" and assigned to the attribute set. This attribute is used to define that the "Offline" payment option is available or not. If it is set "Yes" "Offline" available else not available;

Step2 : Create an observer in app\code\local\YourPackage\YourModule\etc\config.xml with the below code.

<frontend>
    <events>
     <payment_method_is_active>
            <observers>
                <yourmodule>
                    <type>singleton</type>
                    <class>YourPackage_YourModule_Model_Observer</class>
                    <method>hideOfflinePayment</method>
                </yourmodule>
            </observers>
        </payment_method_is_active>
      </events>
</frontend>

Step3 :Create the observer class and method in app\code\local\YourPackage\YourModule\Model\Observer.php with the following code.

<?php

class YourPackage_YourModule_Model_Observer
{

  public function hideOfflinePayment($observer){
    $instance = $observer->getMethodInstance();
    $result = $observer->getResult();
    $allPaymentMethods = $config = Mage::getConfig()->getNode('default/payment')->asArray();
    $allOfflinePayments=array();
    foreach($allPaymentMethods as $code=>$value) {
        if($value['group']=='offline'){
          $allOfflinePayments[]=$code;
        }
    }
    if (in_array($instance->getCode(), $allOfflinePayments)) {
            $cart = Mage::getSingleton('checkout/session')->getQuote();
            $flag=1;
            foreach ($cart->getAllItems() as $item) {
                $_product=Mage::getModel('catalog/product')->load($item->getProductId());
                if($_product->getIsOfflinePaymentAvailable()!=1){
                    $flag=0;
                    break;
                }
            }
            if($flag==1){
                $result->isAvailable = true;
            }
            else{
               $result->isAvailable = false;
            }
    }
  }

}
Related Topic