1

I am working on a payment module using Magento 2.3.1. I have already implemented CsrfAwareActionInterface and 2 of its methods (createCsrfValidationException() & validateForCsrf()) in my controller just before execute() function. It redirects me to the payment gateway website successfully and makes the purchase.

However, I have set this below URL as my Return URL:

https://website.com/checkout/onepage/success/

But Magento 2.3.1 redirects to the homepage and throws Invalid Form Key. Please refresh the page error. I have tried to search for all possible solutions but to no avail.

I have already confirmed it from the payment gateway side, and it is perfectly returning to my mentioned above URL. I am not sure that if there's something wrong with Magento 2.3 because before implementing CsrfAwareActionInterface, the code was working correctly on previous Magento 2 versions.

Here is the controller's code:

<?php
namespace PayAxis\PayAxisPaymentModule\Controller\Index;

use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Request\InvalidRequestException;
use \Magento\Framework\App\Action\Action;
use Psr\Log\LoggerInterface;

class Index extends Action implements CsrfAwareActionInterface
{
    /** @var \Magento\Framework\View\Result\PageFactory  */
    protected $resultPageFactory;
    private $orderFactory;
    protected $_checkoutSession;
    protected $scopeConfig;

    public $currency;
    public $Amount;
    public $ExpiryTime;
    public $_TxnRefNumber;
    public $_TxnDateTime;
    public $_Description;

    const XML_PATH_ACTIONURL = 'payment/payaxispaymentmethod/actionurl';
    const XML_PATH_MERCHANTID = 'payment/payaxispaymentmethod/merchantid';
    const XML_PATH_PASSWORD = 'payment/payaxispaymentmethod/password';
    const XML_PATH_RETURNURL = 'payment/payaxispaymentmethod/returnurl';
     const XML_PATH_IntegritySalt = 'payment/payaxispaymentmethod/IntegritySalt';
      const XML_PATH_ExpiryHours = 'payment/payaxispaymentmethod/ExpiryHours';

public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Sales\Model\Order $salesOrderFactory,
       \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,        
        \Magento\Checkout\Model\Session $checkoutSession
        /* array $data = [] */
    ) {
        $this->_checkoutSession = $checkoutSession;
        $this->_orderFactory = $salesOrderFactory;
        $this->scopeConfig = $scopeConfig;
        //$data = [];
        parent::__construct($context);
    }

    public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
    {
        return null;
    }

    public function validateForCsrf(RequestInterface $request): ?bool
    {
        return true;
    }

    public function execute()
    {
        $orderId = $this->_checkoutSession->getLastOrderId();
        $order =  $this->_orderFactory->load($orderId);
         $orderItems = $order->getdata();  
         $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;

        $ActionURL = $this->scopeConfig->getValue(self::XML_PATH_ACTIONURL, $storeScope);
               $MerchantID = $this->scopeConfig->getValue(self::XML_PATH_MERCHANTID, $storeScope);
                      $Password = $this->scopeConfig->getValue(self::XML_PATH_PASSWORD, $storeScope);
                             $ReturnURL = $this->scopeConfig->getValue(self::XML_PATH_RETURNURL, $storeScope);
                              $IntegritySalt = $this->scopeConfig->getValue(self::XML_PATH_IntegritySalt, $storeScope);
                               $ExpiryHours = $this->scopeConfig->getValue(self::XML_PATH_ExpiryHours, $storeScope);

      foreach($order->getAllItems() as $item)
      {
         $ProdustIds[]= $item->getProductId(); 
         $proName[] = $item->getName(); // product name
      }



        $_Description = implode(",", $proName);
        $currency = $orderItems['base_currency_code'];
        $Amount= $orderItems['grand_total'];
        $final_orderid = $orderItems['increment_id'];
        $_AmountTmp = $Amount*100;
        $_AmtSplitArray = explode('.', $_AmountTmp);
        $_FormattedAmount = $_AmtSplitArray[0];
        $ExpiryTime = date('YmdHis', strtotime("+".$ExpiryHours." hours"));
     //   $ExpiryTime = date('YmdHis', strtotime("+5 days"));
        $_TxnRefNumber = "TXN1". date('YmdHis');
        $_TxnDateTime =   date('YmdHis');
        $pp_language = 'EN';
        $pp_version = '1.1';

        //Calculating Hash
        $SortedArrayOld =$IntegritySalt.'&'.$_FormattedAmount.'&'.$final_orderid.'&'.$_Description.'&'.$pp_language.'&'.$MerchantID.'&'.$Password.'&'.$ReturnURL.'&'.$currency.'&'.$_TxnDateTime.'&'.$ExpiryTime.'&'.$_TxnRefNumber.'&'.$pp_version.'&'.'1'.'&'.'2'.'&'.'3'.'&'.'4'.'&'.'5';
        $pp_securehash = hash_hmac('sha256', $SortedArrayOld, $IntegritySalt);


        $RequestLog ="Request sent to Payment Gateway : Start \n" ;
        $RequestLog .="pp_Version :".$pp_version."\n";
        $RequestLog .= "pp_TxnType  : \n";
        $RequestLog .= "pp_Language  :".$pp_language."\n";
        $RequestLog .= "pp_MerchantID  :".$MerchantID."\n";
        $RequestLog .= "pp_SubMerchantID  : \n";
        $RequestLog .= "pp_Password  :".$Password."\n";
        $RequestLog .= "pp_BankID  : \n";
        $RequestLog .= "pp_ProductID  : \n";
        $RequestLog .= "pp_TxnRefNo  :".$_TxnRefNumber."\n";
        $RequestLog .= "pp_Amount  :".$_FormattedAmount."\n";
        $RequestLog .= "pp_TxnCurrency  :".$currency."\n";
        $RequestLog .= "pp_TxnDateTime  :".$_TxnDateTime."\n";
        $RequestLog .= "pp_BillReference  :".$final_orderid."\n";
        $RequestLog .= "pp_Description  :".$_Description."\n";
        $RequestLog .= "pp_TxnExpiryDateTime  :".$ExpiryTime."\n";
        $RequestLog .= "pp_ReturnURL  :".$ReturnURL."\n";
        $RequestLog .= "pp_SecureHash :".$pp_securehash."\n";

        $RequestLog .= "ppmpf_1  : 1\n";
        $RequestLog .= "ppmpf_2  : 2\n";
        $RequestLog .= "ppmpf_3  : 3\n";
        $RequestLog .= "ppmpf_4  : 4\n";
        $RequestLog .= "ppmpf_5  : 5\n";
        $RequestLog .="Request sent to Payment Gateway : End \n";

        $this->_objectManager->get('Psr\Log\LoggerInterface')->addDebug($RequestLog);

        echo "<body onload=\"submitForm()\"></body>";
          echo "<script>function submitForm() { document.jsform.submit(); }</script>";
            echo "<form name=\"jsform\" method=\"post\" action=\"$ActionURL\">";
              //echo "<input type='hidden' name='".htmlentities($a)."' value='".htmlentities($b)."'>";
               echo "<input type='hidden' name='pp_Version' value='1.1' >";
                 echo "<input type='hidden' name='pp_TxnType' value=''>";
                   echo "<input type='hidden' name='pp_Language' value='EN'>";
                     echo "<input type='hidden' name='pp_MerchantID' value='".$MerchantID."' >";
                       echo "<input type='hidden' name='pp_SubMerchantID' value='' >";
                         echo "<input type='hidden' name='pp_Password' value='".$Password."' >";
                           echo "<input type='hidden' name='pp_BankID' value=''>";
                             echo "<input type='hidden' name='pp_ProductID' value=''>";
                               echo "<input type='hidden' name='pp_TxnRefNo' value='".$_TxnRefNumber."'>";
                                 echo "<input type='hidden' name='pp_Amount' value='".$_FormattedAmount."'>";
                                  echo "<input type='hidden' name='pp_TxnCurrency' value='".$currency."'>";
                                     echo "<input type='hidden' name='pp_TxnDateTime' value='".$_TxnDateTime."'>";
                                       echo "<input type='hidden' name='pp_BillReference' value='".$final_orderid."'>";
                                         echo "<input type='hidden' name='pp_Description' value='".$_Description."'>";
                                           echo "<input type='hidden' name='pp_TxnExpiryDateTime' value='".$ExpiryTime."'>";

                                               echo "<input type='hidden' name='pp_ReturnURL' value='".$ReturnURL."' >";
                                               echo "<input type='hidden' name='pp_SecureHash' value='".$pp_securehash."' >";

                                                echo "<input type='hidden' name='ppmpf_1' value='1'>";
                                                echo "<input type='hidden' name='ppmpf_2' value='2'>";
                                                 echo "<input type='hidden' name='ppmpf_3' value='3'>";
                                                 echo "<input type='hidden' name='ppmpf_4' value='4'>";
                                                  echo "<input type='hidden' name='ppmpf_5' value='5'>";
                                                  echo "</form>";
                                                  echo "<script type=\"text/javascript\">document.jsform.submit();</script>";
   }
}
3
  • Sir I'm facing exactly the same issue even we both have the same class I'm using it for JazzCash Sir did you get the solution??? if Yes then Please Share with me I'm almost working on this error around two days
    – Asad Khan
    Nov 21, 2019 at 6:50
  • n for me it was working perfectly on M 2.2.10 but on M 2.3.2 it sending me to homepage with the same error
    – Asad Khan
    Nov 21, 2019 at 6:53
  • Sir I need a bit of help in the above scenario... can you please help me a bit?
    – Asad Khan
    Nov 26, 2019 at 10:11

1 Answer 1

2

Magento 2.3.0: Implement below code to skip the CSRF check on your custom route called outside Magento environment. This implementation does not break core frontend/adminhtml routes

Vender/Module/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\App\Request\CsrfValidator">
        <plugin name="csrf_validator_skip" type="Module\Vendor\Plugin\CsrfValidatorSkip" />
    </type>
</config>

Vender/Module/Plugin/CsrfValidatorSkip.php

<?php
namespace Vendor\Module\Plugin;

class CsrfValidatorSkip
{
    /**
     * @param \Magento\Framework\App\Request\CsrfValidator $subject
     * @param \Closure $proceed
     * @param \Magento\Framework\App\RequestInterface $request
     * @param \Magento\Framework\App\ActionInterface $action
     */
    public function aroundValidate(
        $subject,
        \Closure $proceed,
        $request,
        $action
    ) {
        /* Magento 2.1.x, 2.2.x */
        if ($request->getModuleName() == 'Your_Module_frontName_Here') {
            return; // Skip CSRF check
        }
        /* Magento 2.3.x */
        if (strpos($request->getOriginalPathInfo(), 'Add_Controller_frontName') !== false) {
            return; // Skip CSRF check
        }
        $proceed($request, $action); // Proceed Magento 2 core functionalities
    }
}

copied from This I hope it will also work for you as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.