Magento 2 – How to Get All Active Payment Methods

Hello Magento Folks,

 

In this post I am going to explain how to get all active payment methods in magento 2.

If you are developing any payment related extension in Magento2 and you want to get the active Payment methods list with the multi selection option in Magento configuration, 

Follow below methods for this.

 

1. Using Dependency Injection

Add below code snippet in Block class.

protected $_paymentConfig;
protected $_scopeConfigInterface;

public function __construct(
	\Magento\Backend\Block\Template\Context $context,
	\Magento\Payment\Model\Config $paymentConfig,
	\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigInterface,
	array $data = []
) 
{
	$this->_paymentConfig = $paymentConfig;
	$this->_scopeConfigInterface = $scopeConfigInterface;
	parent::__construct($context, $data);
}

public function getAllActivePaymentMethods() {
	$activePaymentMethods = $this->_paymentConfig->getActiveMethods();
	$activeMethods = array();
	if ($activePaymentMethods && count($activePaymentMethods) > 0) {
		foreach ($activePaymentMethods as $methodCode => $paymentModel) {
			$methodTitle = $this->_scopeConfigInterface->getValue('payment/' . $methodCode . '/title');
			$activeMethods[$methodCode] = array(
				'label' => $methodTitle,
				'value' => $methodCode
			);
		}
	}
	return $activeMethods;
}

Add below code snippet in template file.

//get all active payment methods
$allActivePaymentMethods = $block->getAllActivePaymentMethods();

echo "<pre>";
print_r($allActivePaymentMethods);
echo "</pre>";

 

2. Using Object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$paymentConfig = $objectManager->get('Magento\Payment\Model\Config');
$scopeConfigInterface = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');

//get all active payment methods
$activePaymentMethods = $paymentConfig->getActiveMethods();

$activeMethods = array();

if ($activePaymentMethods && count($activePaymentMethods) > 0) {
    foreach ($activePaymentMethods as $methodCode => $paymentModel) {
        $methodTitle = $scopeConfigInterface->getValue('payment/' . $methodCode . '/title');
        $activeMethods[$methodCode] = array(
            'label' => $methodTitle,
            'value' => $methodCode
        );
    }
}

echo "<pre>";
print_r($activeMethods);
echo "</pre>";

 

Comment below If you face any trouble or suggestions. We will always be happy to assist you.

Keep learning!! Keep sharing!!

Thank You.