Site icon MageComp Blog

How to get Active Payment Method list in Frontend Custom Form of Magento 2

How to get Active Payment Method list in Frontend Custom Form of Magento 2

Your online Ecommerce business is incomplete without having appropriate payment methods. Using a single payment method is not enough for your customers because they love their convenience of paying using the favorite payment methods which may vary depending on country & location and this is how your list of active payment method is increasing.

But if this is not enough several time you came across the situation of custom development where you need to fetch a list of active payment methods and display in the frontend. Recently one of our customers wants their customer to make a selection of their preferred default payment gateway during store signup. So, here is the code for the same purpose that will help you to display a list of active payment method list in store frontend. If you want to Get Active Payment Methods with Multi-select in Backend you can refer our old blog.

First, we need to create one “Paymentmethods.php” block file at the following location.
app\code\Vendor\Extension\Block\Paymentmethods.php

<?php
namespace Vendor\Extension\Block;
 
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Payment\Model\Config;
 
class Paymentmethods extends \Magento\Framework\View\Element\Template
{
	protected $scopeConfig;
	protected $paymentmodelconfig; 
 
	public function __construct(Config $paymentmodelconfig, ScopeConfigInterface $scopeConfig){
        $this->paymentmodelconfig = $paymentmodelconfig;
        $this->scopeConfig = $scopeConfig;
	}
 
	public function getActivePaymentMethod()
	{
    	$payments = $this->paymentmodelconfig->getActiveMethods();
    	$methods = array();
    	foreach ($payments as $paymentCode => $paymentModel)
    	{
        	$paymentTitle = $this->scopeConfig->getValue('payment/'.$paymentCode.'/title');
            $methods[$paymentCode] = array(
            	'label' => $paymentTitle,
            	'value' => $paymentCode
        	);
    	}
    	return $methods;
	}
}

Now, navigate to your phtml file where you want to call this function and paste add this short code.
$block-> getActivePaymentMethod();

This one line code will return the array of list of active payment methods along with title and code. You can also customize this code according to your development needs.

That’s it! After implementing the above code, it will automatically list active payment methods.

Lastly, If you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends.

And, Let us know if you are facing an issue while implementing this code.

Happy Coding!

Exit mobile version