'The payment screen total value does not matches with the total order amount in cart in prestashop 1.7

I'm implementing external payment gateway in PrestaShop 1.7. But the payment screen amount does not update or matches the cart value in total. It keeps on showing the value which i passed in the template file (for privacy purpose, i have not written the values in code below).

I think I may have made a mistake in my main.php file. And Now i learnt my validation.php file also not working. I do not know why?

What should I do in this scenario? I'm new to PrestaShop, can't figure out?

Also what is the correct code for carrying out successful redirection, handle POST parameters and what will be the notify URL, cancel URL?

Please help me and update my code if i missed something.

edit: SORRY GUYS! I'm new to StackOverflow. So I included all files in console. Hopefully You can understand. I have mentioned file name at start.

This is the .tpl file

<form action="https://lateralpayments.com/hps/hps_Payment.aspx" method="POST">

  <!--Authentication details-->
  <input type="hidden" name="Merchant_User_Id" value="" />
  <input type="hidden" name="merchantpwd" value="" />
  <!--Customer Details-->
  <input type="hidden" name="customer_firstname" value="" />
  <input type="hidden" name="customer_lastname" value="" />
  <input type="hidden" name="customer_phone" value="" />
  <input type="hidden" name="customer_email" value="" />
  <input type="hidden" name="customer_ipaddress" value="" />
  <!--Billing details-->
  <input type="hidden" name="bill_firstname" value="" />
  <input type="hidden" name="bill_lastname" value="" />
  <input type="hidden" name="bill_address1" value="" />
  <input type="hidden" name="bill_city" value="" />
  <input type="hidden" name="bill_country" value="" />
  <input type="hidden" name="bill_state" value="" />
  <input type="hidden" name="bill_zip" value="" />
  <input type="hidden" name="dateregistered" value="" />
  <!--Delivery details-->
  <input type="hidden" name="ship_to_address1" value="" />
  <input type="hidden" name="ship_to_address2" value="" />
  <input type="hidden" name="ship_to_city" value="" />
  <input type="hidden" name="ship_to_country" value="" />
  <input type="hidden" name="ship_to_phone" value="" />
  <input type="hidden" name="ship_to_state" value="" />
  <input type="hidden" name="ship_to_zip" value="" />
  <input type="hidden" name="ship_to_method" value="" />
  <input type="hidden" name="merchant_ref_number" value="" />
  <!--Purchase details-->
  <input type="hidden" name="Purchase_summary" Value="" />
  <input type="hidden" name="currencydesc" Value="" />
  <input type="hidden" name="amount" Value="" />
  <!--Security details-->
  <input type="hidden" name="transactionkey" Value="" />
  <input type="hidden" name="CardToken" Value="" />
  <input type="hidden" name="language" Value="" />
  <input type="hidden" name="theme_identifier" Value="" />
  <input type="hidden" name="processurl" Value="" />
  <input type="hidden" name="notifyurl" Value="" />
  <input type="hidden" name="cancelurl" Value="" />
  <input type="hidden" name="logoid" Value="" />
  <input type="hidden" name="surcharge" Value="" />
  <input type="hidden" name="defaultview" Value="" />
  <input type="hidden" name="Buy" Value="Buy" />
</form>

This is validation.php:

<?php

require_once dirname(__FILE__) . '/config/config.inc.php';
require_once dirname(__FILE__) . '/latpayredirect.php';
class LatpayRedirectValidationModuleFrontController extends ModuleFrontController
{
    /**
     * @see FrontController::postProcess()
     */

    public $warning = '';
    public $message = '';
    public function initContent()
    {
        parent::initContent();

        $this->context->smarty->assign(array(
          'warning' => $this->warning,
          'message' => $this->message
          ));

        $this->setTemplate('module:latpayredirect/views/templates/front/payment_return.tpl');
    }
    public function postProcess()
    {
        ob_start();
        $context = Context::getContext();

        if (is_null($context->cart)) {
            $context->cart = new Cart($context->cookie->id_cart);
        }
        if (is_null($context->cart->id_currency)) {
            $context->cart->id_currency = $context->cookie->id_currency;
        }

        $cart = $this->context->cart;

        $this->abrir("http://davivienda.com");


        if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        $customer = new Customer($cart->id_customer);

        if (!Validate::isLoadedObject($customer)) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        /*  $currencydesc = $order->order_currency;
         $merchant_ref_number = trim($order_id);
         $amount = $order->order_total;
         $salt =$this ->salt;
         $ds=$this -> process_url;
         $str =sha1($currencydesc.$amount.$merchant_ref_number.$salt); */


        // $currency = $this->context->currency;
        $currency = $cart->id_currency;
        $total = (float)$cart->getOrderTotal(true, Cart::BOTH);
        $object = new filemain();
        $order = $object->methodCreateInMain($cart->id, Configuration::get('PS_OS_PAYMENT'), $total, $currency, $customer->secure_key);

        //The order passes directly on paid status
        $this->module->validateOrder((int)$cart->id, Configuration::get('PS_OS_PAYMENT'), $total, $this->module->displayName, null, array(), (int)$currency->id, false, $customer->secure_key);
        Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)$cart->id.'&id_module='.(int)$this->module->id.'&id_order='.$this->module->currentOrder.'&key='.$customer->secure_key);
    }

    public function abrir($param)
    {
        echo" <script> window.open(URL,'ventana1,'width=300,height=300,scrollbars=NO')</script> ";
    }
}

This is main .php file

<?php


use PrestaShop\PrestaShop\Core\Payment\PaymentOption;

if (!defined('_PS_VERSION_')) {
    exit;
}

class latpayredirect extends PaymentModule
{
    protected $_html = '';
    protected $_postErrors = array();


    public function __construct()
    {
        $this->name = 'latpayredirect';
        $this->tab = 'payments_gateways';
        $this->version = 1.0;
        $this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
        $this->author = 'Latpay Development Team';
        $this->controllers = array('validation');
        $this->bootstrap = true;
        parent::__construct();

        $this->displayName = $this->trans('Latpay Redirect Payment Gateway', array(), 'Modules.Latpayredirect.Admin');
        $this->description = $this->trans('Pay Using Latpay Redirect Payment Gateway', array(), 'Modules.Latpayredirect.Admin');
        $this->confirmUninstall = $this->trans('Are you sure you want to delete these details?', array(), 'Modules.Latpayredirect.Admin');


        $merchant_id= Configuration::get('MERCHANT_ID');
        $merchant_pwd= Configuration::get('MERCHANT_PWD');
        $secret_key= Configuration::get('SECRET_KEY');
        $purchase_summary= Configuration::get('PURCHASE_SUMMARY');
        $gateway_mode= Configuration::get('GATEWAY_MODE');
        $gateway_url= Configuration::get('GATEWAY_URL');

        $this->page = basename(__FILE__, '.php');
    }

    public function install()
    {
        Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'order_state` ( `invoice`, `send_email`, `color`, `unremovable`, `logable`, `delivery`, `module_name`) VALUES  (0, 0, \'#33FF99\', 0, 1, 0, \'latpayredirect\');');
        $id_order_state = (int) Db::getInstance()->Insert_ID();
        Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'order_state_lang` (`id_order_state`, `id_lang`, `name`, `template`) VALUES ('.$id_order_state.', 1, \'Payment accepted\', \'payment\')');
        Configuration::updateValue('LATPAYREDIRECT_ID_ORDER_SUCCESS', $id_order_state);
        unset($id_order_state);

        Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'order_state`( `invoice`, `send_email`, `color`, `unremovable`, `logable`, `delivery`, `module_name`) VALUES (0, 0, \'#33FF99\', 0, 1, 0, \'latpayredirect\');');
        $id_order_state = (int) Db::getInstance()->Insert_ID();
        Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'order_state_lang` (`id_order_state`, `id_lang`, `name`, `template`) VALUES ('.$id_order_state.', 1, \'Payment Failed\', \'payment\')');
        Configuration::updateValue('LATPAYREDIRECT_ID_ORDER_FAILED', $id_order_state);
        unset($id_order_state);
        if (!parent::install() || !$this->registerHook('paymentOptions')) {
            return false;
        }
        return true;
    }

    public function uninstall()
    {
        Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'order_state_lang` WHERE id_order_state = '.Configuration::get('LATPAYREDIRECT_ID_ORDER_SUCCESS').' and id_lang = 1');
        Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'order_state_lang`  WHERE id_order_state = '.Configuration::get('LATPAYREDIRECT_ID_ORDER_FAILED').' and id_lang = 1');
        return Configuration::deleteByName('MERCHANT_ID')
        && Configuration::deleteByName('MERCHANT_PWD')
        && Configuration::deleteByName('SECRET_KEY')
        && Configuration::deleteByName('PURCHASE_SUMMARY')
        && Configuration::deleteByName('GATEWAY_URL')
        &&Configuration::get('GATEWAY_MODE')
        && parent::uninstall();
    }

    public function hookPaymentOptions($params)
    {
        if (!$this->active) {
            return;
        }

        $payment_option = new PaymentOption();
        /*  $gateway_mode= Configuration::get('GATEWAY_MODE');

         if ($gateway_mode == 'sandbox') { */
        $action = ($this->context->link->getModuleLink($this->name, 'validation', array(), true));
        /*  }
         else {
           $action = "https://lateralpayments.com/hps/hps_Payment.aspx";
         } */
        $inputs = $this->mbkpginputs();

        $payment_option->setCallToActionText($this->l('Pay by Latpayredirect Payment Gateway'))
      ->setForm($this->fetch('module:latpayredirect/views/templates/front/payment_return.tpl'))
      ->setAction($action)->setInputs($inputs)->setAdditionalInformation($this->context->smarty->fetch('module:latpayredirect/latpayredirect.tpl'));

        $payment_option->setModuleName('latpayredirect');
        return [$payment_option];
    }

    private function _postValidation()
    {
        if (Tools::isSubmit('btnSubmit')) {
            if (!Tools::getValue('GATEWAY_MODE')) {
                $this->_postErrors[] = $this->trans('Gateway mode is required.', array(), 'Modules.Latpayredirect.Admin');
            } elseif (!Tools::getValue('MERCHANT_ID') && Tools::getValue('MERCHANT_ID')) {
                $this->_postErrors[] = $this->trans('Merchant Id is required.', array(), 'Modules.Latpayredirect.Admin');
            } elseif (!Tools::getValue('MERCHANT_PWD') && Tools::getValue('MERCHANT_PWD')) {
                $this->_postErrors[] = $this->trans('Merchant Pwd is required.', array(), 'Modules.Latpayredirect.Admin');
            } elseif (!Tools::getValue('SECRET_KEY') && Tools::getValue('SECRET_KEY')) {
                $this->_postErrors[] = $this->trans('Secret Key is required.', array(), 'Modules.Latpayredirect.Admin');
            } elseif (!Tools::getValue('PURCHASE_SUMMARY') && Tools::getValue('PURCHASE_SUMMARY')) {
                $this->_postErrors[] = $this->trans('', array(), 'Modules.Latpayredirect.Admin');
            } elseif (!Tools::getValue('GATEWAY_URL') && Tools::getValue('GATEWAY_URL')) {
                $this->_postErrors[] = $this->trans('', array(), 'Modules.Latpayredirect.Admin');
            }
        }
    }

    private function _postProcess()
    {
        if (Tools::isSubmit('btnSubmit')) {
            Configuration::updateValue('GATEWAY_MODE', Tools::getValue('GATEWAY_MODE'));
            Configuration::updateValue('MERCHANT_ID', Tools::getValue('MERCHANT_ID'));
            Configuration::updateValue('MERCHANT_PWD', Tools::getValue('MERCHANT_PWD'));
            Configuration::updateValue('PURCHASE_SUMMARY', Tools::getValue('PURCHASE_SUMMARY'));
            Configuration::updateValue('GATEWAY_URL', Tools::getValue('GATEWAY_URL'));
        }
        $this->_html .= $this->displayConfirmation($this->trans('Settings updated', array(), 'Admin.Notifications.Success'));
    }

    public function getContent()
    {
        $this->_html = '';

        if (Tools::isSubmit('btnSubmit')) {
            $this->_postValidation();
            if (!count($this->_postErrors)) {
                $this->_postProcess();
            } else {
                foreach ($this->_postErrors as $err) {
                    $this->_html .= $this->displayError($err);
                }
            }
        }

        $this->_html .= $this->_displayCheck();
        $this->_html .= $this->renderForm();

        return $this->_html;
    }

    public function renderForm()
    {
        $options = array(
      array(
          'id_option' => 'production',
          'name' => 'production'
          ),
        array(
          'id_option' => 'sandbox',
          'name' => 'sandbox'
          ),
        );

        $fields_form = array(
      'form' => array(
          'legend' => array(
            'title' => $this->trans('Latpayredirect Payment Gateway details', array(), 'Modules.Latpayredirect.Admin'),
            'icon' => 'icon-envelope'
            ),
          'input' => array(
            array(
              'type' => 'select',
              'label' => $this->trans('Gateway Mode', array(), 'Modules.Latpayredirect.Admin'),
              'name' => 'GATEWAY_MODE',
              'required' => true,
              'options' => array(
                'query' => $options,
                'id' => 'id_option',
                'name' => 'name'
                )
              ),
              array(
                'type' => 'text',
                'label' => $this->trans('Merchant Id', array(), 'Modules.Latpayredirect.Admin'),
                'name' => 'MERCHANT_ID',
                'required' => true
            ),
            array(
              'type' => 'text',
              'label' => $this->trans('Merchant Password', array(), 'Modules.Latpayredirect.Admin'),
              'name' => 'MERCHANT_PWD',
              'required' => true
            ),
            array(
                'type' => 'text',
                'label' => $this->trans('Secret Key', array(), 'Modules.Latpayredirect.Admin'),
                'name' => 'SECRET_KEY',
                'required' => true
              ),
              array(
                'type' => 'text',
                'label' => $this->trans('Purchase Summary', array(), 'Modules.Latpayredirect.Admin'),
                'name' => 'PURCHASE_SUMMARY',
                'required' => false
              ),
              array(
                'type' => 'text',
                'label' => $this->trans('Gateway Url', array(), 'Modules.Latpayredirect.Admin'),
                'name' => 'GATEWAY_URL',
                'required' => false
              ),
            ),
          'submit' => array(
            'title' => $this->trans('Save', array(), 'Admin.Actions'),
            )
          ),
        );

        $helper = new HelperForm();
        $helper->show_toolbar = false;
        $helper->id = (int)Tools::getValue('id_carrier');
        $helper->identifier = $this->identifier;
        $helper->submit_action = 'btnSubmit';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->tpl_vars = array(
      'fields_value' => $this->getConfigFieldsValues(),
      );

        $this->fields_form = array();

        return $helper->generateForm(array($fields_form));
    }


    public function getConfigFieldsValues()
    {
        return array(
      'GATEWAY_MODE' => Tools::getValue('GATEWAY_MODE', Configuration::get('GATEWAY_MODE')),
      'SECRET_KEY' => Tools::getValue('SECRET_KEY', Configuration::get('SECRET_KEY')),
      'MERCHANT_PWD' => Tools::getValue('MERCHANT_PWD', Configuration::get('MERCHANT_PWD')),
      'MERCHANT_ID' => Tools::getValue('MERCHANT_ID', Configuration::get('MERCHANT_ID')),
      'PURCHASE_SUMMARY' => Tools::getValue('PURCHASE_SUMMARY', Configuration::get('PURCHASE_SUMMARY')),
      'GATEWAY_URL' => Tools::getValue('GATEWAY_URL', Configuration::get('GATEWAY_URL')),
      );
    }


    private function _displayCheck()
    {
        return $this->display(__FILE__, './views/templates/hook/infos.tpl');
    }

    protected function mbkpginputs()
    {
        global $smarty, $cart;

        $merchant_id= Configuration::get('MERCHANT_ID');
        $merchant_pwd= Configuration::get('MERCHANT_PWD');
        $secret_key= Configuration::get('SECRET_KEY');
        $gateway_mode= Configuration::get('GATEWAY_MODE');
        $purchase_summary= Configuration::get('PURCHASE_SUMMARY');
        $gateway_url= Configuration::get('GATEWAY_URL');

        $orderId = $cart->id;
        $customer = new Customer($cart->id_customer);
        $address = new Address($cart->id_address_invoice);
        $state=new State($address->id_state);
        $country=new Country($address->id_country);
        $firstName = $address->firstname;
        $lastName = $address->lastname;
        $pincode = $address->postcode;
        $email = $customer->email;
        $phone = $address->phone;
        $city = $address->city;
        ;

        $id_currency = intval(Configuration::get('PS_CURRENCY_DEFAULT'));
        $currency = new Currency(intval($id_currency));
        $currency_code =$currency->iso_code;
        $orderAmount =floor($cart->getOrderTotal()*100);

        //$currencydesc = $order->order_currency;
        //$merchant_ref_number = trim($order_id);
        //$amount = $order->order_total;
        // $salt =$this ->salt;
        //$ds=$this -> process_url;
        //$str =sha1($currencydesc.$amount.$merchant_ref_number.$salt);


        $return_url = $this->context->link->getModuleLink($this->name, 'validation', array(), true);

        $customer = new Customer($cart->id_customer);
        $address = new Address($cart->id_address_invoice);


        if ($gateway_mode == 'sandbox') {
            $action = "https://lateralpayments.com/hps/hps_Payment.aspx";
        } else {
            $action = "https://lateralpayments.com/hps/hps_Payment.aspx";
        }

        $fields = array(
      'merchantId' => $merchant_id,
      'orderId' => $orderId,
      'buyerEmail' => $email,
      'returnUrl' => $return_url,
      'buyerFirstName' => $firstName,
      'buyerLastName' => $lastName,
      'buyerAddress' => $address->address1.' '.$address->address2 ,
      'buyerCity' => $city,
      'buyerState' => $state->name,
      'buyerCountry' => $country->iso_code,
      'buyerPincode' => $pincode,
      'buyerPhoneNumber' => $phone,
      'currency' => "INR",
      'amount' => $orderAmount,
      'purpose' => '1',
      'productDescription' => 'OrderId#'.$orderId,
      );

        /*    $fields = array(
             'Merchant_User_Id' => $Merchant_User_Id,
             'merchantpwd' => $merchantpwd,
             'Purchase_summary' => $Purchase_summary,
             'currencydesc' => $order,
             'merchant_ref_number' => $merchant_ref_number,
             'customer_ipaddress' => $customer_ipaddress,
             'amount' => $order,
             'customer_firstname' => $billing_first_name,
             'customer_lastname' => $billing_last_name,
             'customer_phone' => $billing_phone,
             'customer_email' => $billing_email,
             'bill_firstname' => $billing_first_name,
             'bill_lastname' => $billing_last_name,
             'bill_address1' => $billing_address_1,
             'bill_address2' => $billing_address_2,
             'bill_city' => $billing_city,
             'bill_state' => $billing_state,
             'bill_country' => $billing_country,
             'bill_zip' => $billing_postcode,
             'ship_to_address1' => $billing_address_1,
             'ship_to_address2' => $billing_address_2,
             'ship_to_city' => $billing_city,
             'ship_to_country' => $billing_country,
             'ship_to_phone' => $billing_phone,
             'ship_to_state' => $billing_state,
             'ship_to_zip' => $billing_zip,
             'transactionkey' => $str,
             'processurl'         => home_url(''),
               'notifyurl'          => home_url(''),
               'cancelurl'          => home_url('/checkout'),
           ); */



        $all = '';

        $checksumsequence= array("amount","bankid","buyerAddress",
        "buyerCity","buyerCountry","buyerEmail","buyerFirstName","buyerLastName","buyerPhoneNumber","buyerPincode",
        "buyerState","currency","debitorcredit","merchantId","merchantIpAddress","mode","orderId",
        "product1Description","product2Description","product3Description","product4Description",
        "productDescription","productInfo","purpose","returnUrl","shipToAddress","shipToCity","shipToCountry",
        "shipToFirstname","shipToLastname","shipToPhoneNumber","shipToPincode","shipToState","showMobile","txnDate",
        "txnType","zpPayOption");


        foreach ($checksumsequence as $seqvalue) {
            if (array_key_exists($seqvalue, $fields)) {
                if (!$fields[$seqvalue]=="") {
                    if ($seqvalue != 'checksum') {
                        $all .= $seqvalue;
                        $all .="=";
                        $all .= $fields[$seqvalue];
                        $all .= "&";
                    }
                }
            }
        }


        $checksum = $this->calculateChecksum($secret_key, $all);

        $fields = array_merge($fields, array(
                'checksum' => $checksum,
            ));

        $inputs = array();
        foreach ($fields as $k => $v) {
            $inputs[$k] = array(
        'name' => $k,
        'type' => 'hidden',
        'value' => $v,
      );
        }

        return $inputs;
    }

    protected function calculateChecksum($secret_key, $all)
    {
        $hash = hash_hmac('sha256', $all, $secret_key);
        $checksum = $hash;
        return $checksum;
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source