Programmatically: How to create custom Magento payment gateways
Step 1: Create a new module
Create a new directory MyCompany/CustomGateway under the app/code/local directory. Inside this directory, create the following files: CustomGateway.php (module declaration) etc/config.xml (module configuration) Model/Payment/Gateway.php (payment gateway model) Helper/Data.php (payment gateway helper) CustomGateway.php
use Magento\Framework\Module\AbstractModule;
class MyCompany_CustomGateway_Model_Module extends AbstractModule
{
public function __construct(
\Magento\Framework\App\ObjectManager $objectManager,
\Magento\Framework\Module\Manager $moduleManager
) {
parent::__construct($objectManager, $moduleManager);
}
public function register() {
// Register the payment gateway
$this->getterRegistry->register('my_custom_gateway', 'MyCompany\\CustomGateway\\Model\\Payment\\Gateway');
}
}
etc/config.xml
true
Magento_Sales
Model/Payment/Gateway.php
namespace MyCompany\CustomGateway\Model\Payment;
class Gateway extends \Magento Payment Model\Gateway
{
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\DB\Adapter\Zend_Db_Adapter_Pdo_Mysql $connection,
\Magento\Sales\Model\Order\Payment\ConfigInterface $paymentConfig,
array $data = []
) {
parent::__construct($context, $registry, $scopeConfig, $connection, $paymentConfig, $data);
}
public function canCapture()
{
return true;
}
public function capture(array $ignoreInvalidOrder = false)
{
// Your custom payment processing logic here
// ...
}
}
Helper/Data.php
namespace MyCompany\CustomGateway\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public function getPaymentMethodLabel()
{
return 'My Custom Payment Method';
}
}
Step 2: Add the payment gateway to the payment method list
In the payment.xml file under the app/design/frontend/YourTheme/Magento_Sales/etc/design_config.xml directory, add the following code:
-
1
Step 3: Configure the payment method in the backend
Go to System > Configuration > Sales > Payment Methods and add a new payment method with the name "My Custom Payment Method".
Step 4: Test your custom payment gateway
Now you should be able to select your custom payment method during checkout. When you click "Place Order", the payment gateway will be triggered and your custom logic will be executed.