In this post I am going to explain how to get all active payment methods in magento 2.
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>";Thats it. Enjoy Magento 2!!
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


May 6, 2020 at 3:20 pm
Thanks for sharing the useful post here.