1

I am new to Magento 2 Platform and this my first project, I have some basic knowledge about Magento.

I am creating a custom payment method module and achieve the front end part means I can see the UI on admin and checkout also.

Steps I take.

  1. Created a block

         class Main extends  \Magento\Framework\View\Element\Template
           {
            protected $_objectmanager;
           protected $checkoutSession;
           protected $orderFactory;
           protected $urlBuilder;
            private $logger;
           protected $response;
             protected $config;
            protected $messageManager;
           protected $transactionBuilder;
        protected $inbox;
           public function __construct(Context $context,
                            Session $checkoutSession,
                            OrderFactory $orderFactory,
                            Logger $logger,
                            Http $response,
                            TransactionBuilder $tb,
                            \Magento\AdminNotification\Model\Inbox $inbox
                           ) {
    
    
    $this->checkoutSession = $checkoutSession;
    $this->orderFactory = $orderFactory;
    $this->response = $response;
    $this->config = $context->getScopeConfig();
    $this->transactionBuilder = $tb;
    $this->logger = $logger;
    $this->inbox = $inbox;
    
    $this->urlBuilder = \Magento\Framework\App\ObjectManager::getInstance()
        ->get('Magento\Framework\UrlInterface');
    parent::__construct($context);
        }
    
          public function _prepareLayout()
             {
            $method_data = array();
             $orderId = $this->checkoutSession->getLastOrderId();
             $this->logger->info('Creating Order for orderId $orderId == '.$orderId);
             $order = $this->orderFactory->create()->load($orderId);
           if ($order)
                   {
                 $billing = $order->getBillingAddress(); //get billing address
        $payment = $order->getPayment();
        $payment->setTransactionId("-1");
        $payment->setAdditionalInformation(
            [\Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS => array("Transaction is yet to complete")]
        );
        $trn = $payment->addTransaction(\Magento\Sales\Model\Order\Payment\Transaction::TYPE_CAPTURE,null,true);
        $trn->setIsClosed(0)->save();
        $payment->addTransactionCommentsToOrder(
            $trn,
            "The transaction is yet to complete."
        );
        $payment->setParentTransactionId(null);
        $payment->save();
        $order->save();
        try{
            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            $client_id = $this->config->getValue("payment/ndhk_pg/client_login",$storeScope);
            $client_secret = $this->config->getValue("payment/ndhk_pg/client_pass",$storeScope);
            $testmode = $this->config->getValue("payment/ndhk_pg/ndhk_testmode",$storeScope);
            $this->logger->info("Client ID: $client_id | Client Secret : $client_secret | Testmode: $testmode");
            $api_data['txnid'] = time() ."-". $order->getRealOrderId();
            $api_data['login'] = $client_id;
            $api_data['pass'] = $client_secret;
            $api_data['amt'] = round((int)$order->getGrandTotal(),2);
            $api_data['txncurr'] = "INR";
            $api_data['date'] = "INR";
            $string = $client_id.$client_secret.$api_data['txnid'].$order->getGrandTotal().$api_data['txncurr'];
            $hashkey = hash_hmac('sha512', $string, '35d97d4459ae1883cbd2bb8be644115');
            $api_data['signature'] =  $hashkey;
            $api_data['date'] = date('d/m/Y H:m');
            $api_data['mobile'] = "8446320942";
            $api_data['od'] = "Order Description";
            $api_data['ru'] = $this->urlBuilder->getUrl("ndhk/response");
            $this->logger->info("Date sent for creating order ".print_r($api_data,true));
            if($testmode){
                $api_data['actionUrl']  = "https://sandbox.abcpay.com/abc_Api/paymentRequest";
            }else{
                $api_data['actionUrl']  = "https://prod.abcpay.com/abc_Api/paymentRequest";
            }
    
            return $api_data;
    
    
        }catch(\CurlException $e){
            // handle exception related to connection to the sever
            $this->logger->info((string)$e);
            $method_data['errors'][] = $e->getMessage();
        }catch(\ValidationException $e){
            // handle exceptions related to response from the server.
            $this->logger->info($e->getMessage()." with ");
            if(stristr($e->getMessage(),"Authorization"))
            {
                $inbox->addCritical("NDHK Authorization Error",$e->getMessage());
            }
            $this->logger->info(print_r($e->getResponse(),true)."");
            $method_data['errors'] = $e->getErrors();
        }catch(\Exception $e)
        { // handled common exception messages which will not get caught above.
            $method_data['errors'][] = $e->getMessage();
            $this->logger->info('Error While Creating Order : ' . $e->getMessage());
        }
    }
    else
    {
        $this->logger->info('Order with ID $orderId not found. Quitting :-(');
    }
    
                 }
                 }
    
  2. Created two controllers **1. Redirect/index.php

    1. Response/index.php**

Redirect/index

class Index extends  \Magento\Framework\App\Action\Action
{
    protected $pageFactory;
     public function __construct(Context $context,PageFactory $pageFactory) {
        $this->pageFactory = $pageFactory;

        parent::__construct($context);

    }

    public function execute()
    {
         return $this->pageFactory->create();
    }
}

Response

class Index extends  \Magento\Framework\App\Action\Action
{
    protected $_objectmanager;
    protected $_checkoutSession;
    protected $_orderFactory;
    protected $urlBuilder;
    private $logger;
    protected $response;
    protected $config;
    protected $messageManager;
    protected $transactionRepository;
    protected $cart;
    protected $inbox;

    public function __construct( Context $context,
            Session $checkoutSession,
            OrderFactory $orderFactory,
            Logger $logger,
            ScopeConfigInterface $scopeConfig,
            Http $response,
            TransactionBuilder $tb,
             \Magento\Checkout\Model\Cart $cart,
             \Magento\AdminNotification\Model\Inbox $inbox,
             \Magento\Sales\Api\TransactionRepositoryInterface $transactionRepository
        ) {


        $this->checkoutSession = $checkoutSession;
        $this->orderFactory = $orderFactory;
        $this->response = $response;
        $this->config = $scopeConfig;
        $this->transactionBuilder = $tb;
        $this->logger = $logger;                    
        $this->cart = $cart;
        $this->inbox = $inbox;
        $this->transactionRepository = $transactionRepository;
        $this->urlBuilder = \Magento\Framework\App\ObjectManager::getInstance()
                            ->get('Magento\Framework\UrlInterface');

        parent::__construct($context);
    }

    public function execute()
    {
  //RESPONSE
}
}

contents.phtml

<div class='ndhk'>
    <div class='errors'>
        <?php if($this->getMessages()){ ?>
        <?php foreach($this->getMessages() as $message): ?>
        <div class='alert alert-danger'>
            <p style='color:red'>
                <?= $message ?>
            </p>
        </div>
        <?php endforeach; ?>
        <?php }else{ ?>

        <?php
            $alldata = $block->_prepareLayout();
            // print_r($alldata);
        ?>


        <div style="width:200px;margin:auto;margin-top:20px">
            <img style="width:100%" src="<?php echo $block->getViewFileUrl('NDHK_PaymentGateway::images/spinner.gif'); ?>">
            <center>Redirecting you to NDHK Payment Gateway</center>
        </div>
        <form name='ndhkpaymentredirect' method="post" action='<?= $alldata['actionUrl']; ?>'>
            <input type='hidden' name='login' value='<?= $alldata['login']; ?>'>
            <input type='hidden' name='pass' value='<?= $alldata['pass']; ?>'>
            <input type='hidden' name='amt' value='<?= $alldata['amt']; ?>'>
            <input type='hidden' name='txnid' value='<?= $alldata['txnid']; ?>'>
            <input type='hidden' name='txncurr' value='<?= $alldata['txncurr']; ?>'>
            <input type='hidden' name='signature' value='<?= $alldata['signature']; ?>'>
            <input type='hidden' name='date' value='<?= $alldata['date']; ?>'>
            <input type='hidden' name='ru' value='<?= $alldata['ru']; ?>'>
            <input type='hidden' name='od' value='<?= $alldata['od']; ?>'>
        </form>
        <script>
            document.ndhkpaymentredirect.submit();
        </script>
        <?php } ?>
    </div>

</div>

** view/frontend/layout/ndhk_redirect_index.xml **

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <body>
        <referenceContainer name="content">
            <block cacheable="false"  name='ndhk_block' class="NDHK\PaymentGateway\Block\Main" template="NDHK_PaymentGateway::contents.phtml"/>
        </referenceContainer>
    </body>
</page>

Problem

Whenever I click on place order it takes me to ndhk/redirect and shows me the page in contents.phtml but it doesnot redirect me to payment gateway provider as written in contents.phtml and after sometime it redirects to homepage.

I do not know where i am doing wrong or what I should try.

Kindly help me if anyone.

Rv Singh
  • 1,617
  • 15
  • 34
Ankit S.
  • 111
  • 3

0 Answers0