CVE-2023-26861 (Unknown, published 2023-07-11T17:15Z)
Description: value: SQL injection vulnerability found in PrestaShop vivawallet v.1.7.10 and before allows a remote attacker to gain privileges via the vivawallet() module.
Severity: nan (CVSS v3 base score: 9.8)
Weakness: CWE-89 \u2014 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data.
Repository: https://github.com/VivaPayments/API
Files changed:
Commit message: Remove Old Prestashop Smart checkout


Vulnerable code:
<?xml version="1.0" encoding="UTF-8" ?>
        <module>
            <name>vivawallet</name>
            <displayName><![CDATA[Vivawallet]]></displayName>
            <version><![CDATA[1]]></version>
            <description><![CDATA[Accept payments with Vivawallet]]></description>
            <author><![CDATA[vivawallet.com]]></author>
            <tab><![CDATA[payments_gateways]]></tab>
            <is_configurable>1</is_configurable>
            <need_instance>1</need_instance>
			<limited_countries></limited_countries>
        </module>
<?php
if(isset($_GET['s']) && $_GET['s']!=''){
include(dirname(__FILE__).'/../../config/config.inc.php');
if(substr(_PS_VERSION_,2,1) < 5){
include(dirname(__FILE__).'/../../header.php');
}
include(dirname(__FILE__).'/vivawallet.php');

$vivawallet = new vivawallet();
$errors = '';

  $OrderCode = addslashes($_GET['s']);
  
  $update_query = "update vivawallet_data set order_state='F' where OrderCode='".$OrderCode."'";
  $update = Db::getInstance()->execute($update_query);

  $transtat_query = "select * from vivawallet_data where OrderCode='".$OrderCode."' ORDER BY id DESC";
  $transtat = Db::getInstance()->executeS($transtat_query, $array = true, $use_cache = 0);

  $secure_key = $transtat[0]['secure_key'];
  $cartid = $transtat[0]['ref'];
  
if(substr(_PS_VERSION_,2,1) >= 5){
   Context::getContext()->cart = new Cart((int)$cart_id);
   Context::getContext()->cookie->id_cart = (int)$cart_id;
   
   $cart = new Cart((int)$cart_id);
   
	 if (Validate::isLoadedObject($cart)) {
		
		$shop = new Shop((int)$cart->id_shop);
		if (Validate::isLoadedObject($shop)) {
		 Context::getContext()->shop = $shop;
		}
		
		$customer = new Customer((int)$cart->id_customer);
		
		if (Validate::isLoadedObject($customer)) {
			$customer->logged = 1;
			Context::getContext()->customer = $customer;
			Context::getContext()->cookie->id_customer = (int)$customer->id;
			Context::getContext()->cookie->customer_lastname = $customer->lastname;
			Context::getContext()->cookie->customer_firstname = $customer->firstname;
			Context::getContext()->cookie->logged = 1;
			Context::getContext()->cookie->check_cgv = 1;
			Context::getContext()->cookie->is_guest = $customer->isGuest();
			Context::getContext()->cookie->passwd = $customer->passwd;
			Context::getContext()->cookie->email = $customer->email;
			$secure_key = $customer->secure_key;
		}
	  }
 	}

  $errors = 'Transaction failed or cancelled';

   $vivawallet->validateOrder((int)$cartid, _PS_OS_ERROR_, 0, $vivawallet->displayName, $errors.'<br />', array(), NULL, false, $secure_key, $shop);  

   if(substr(_PS_VERSION_,2,1) > 4){
   Tools::redirect('index.php?controller=order-confirmation&id_cart='.$cartid.'&id_module='.$vivawallet->id.'&id_order='.$vivawallet->currentOrder.'&key='.$secure_key);
   } else {
   Tools::redirectLink(__PS_BASE_URI__."order-confirmation.php?id_cart={$cartid}&id_module={$vivawallet->id}&id_order={$vivawallet->currentOrder}&key={$secure_key}");
   }
}  else {
echo 'No valid input received.';
}     
?>
DROP TABLE IF EXISTS `vivawallet_data`;
CREATE TABLE IF NOT EXISTS `vivawallet_data` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `secure_key` varchar(150) DEFAULT NULL,
  `OrderCode` varchar(255) DEFAULT NULL,
  `ErrorCode` varchar(50) DEFAULT NULL,
  `ErrorText` varchar(255) DEFAULT NULL,
  `Timestamp` datetime DEFAULT NULL,
  `ref` varchar(150) DEFAULT NULL,
  `total_cost` int(11) DEFAULT NULL,
  `currency` char(3) DEFAULT NULL,
  `order_state` char(1) DEFAULT NULL,
  `sessionid` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
<?php
include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/../../init.php');
include(dirname(__FILE__).'/vivawallet.php');
$vivawallet = new vivawallet();


?>
<noscript>
<p><?php echo  $vivawallet->l('In case you are not redirected to the payment page within 10 seconds, click the "Pay Now" button below.'); ?></p>
</noscript>
<form id="payment_form" name="payment_form" action="<?php echo $_POST['VivawalletUrl']; ?>" method="get">

<?php
	foreach( $_POST as $name => $value ) {
	if($name !='VivawalletUrl'){
		echo '<input type="hidden" name="'.$name.'" value="'.$value.'" />';
		}
	}
?>
<noscript>
<input type="submit" value="<?php echo $vivawallet->l('Pay Now'); ?>" />
</noscript>
</form>
<script type="text/javascript">
	<!--
	document.getElementById('payment_form').submit();
	//-->
</script>
<?php
/* SSL Management */
$useSSL = true;

include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/../../header.php');
include(dirname(__FILE__).'/vivawallet.php');

if (!$cookie->isLogged(true))
	Tools::redirect('authentication.php?back=order.php');
elseif (!Customer::getAddressesTotalById((int)($cookie->id_customer)))
	Tools::redirect('address.php?back=order.php?step=1');
	
$vivawallet = new vivawallet();
echo $vivawallet->execPayment($cart);

include_once(dirname(__FILE__).'/../../footer.php');

?>
<p class="payment_module clearfix">
		<span style="float:left;"><img src="{$module_dir}vivawallet.gif" alt="{l s='Pay by Vivawallet' mod='vivawallet'}"/></span>
		<span>{l s='Pay with Vivawallet' mod='vivawallet'}<br />{l s='Pay safely and quickly on the next page' mod='vivawallet'}</span>
</p>
<form name="vivawallet_confirmation" action="{$base_dir_ssl}{$InstalmentUrl}" method="post">
    {$WbInstalLogic}
</form>
        
<form name="vivawallet_confirmation" action="{$VivawalletUrl}" method="get">
    <input type="hidden" name="Ref" value="{$Ref}" />
    <input style="{$WbSubmit}" type="submit" value="{l s='Pay Now' mod='vivawallet'}" class="exclusive_large" />
</form>
<form id="vivawallet_payment_form" name="vivawallet_confirmation" action="{$VivawalletUrl}" data-ajax="false" title="{l s='Pay with Vivawallet' mod='vivawallet'}" method="get">
    <input type="hidden" name="Ref" value="{$Ref}" />
</form>
{capture name=path}{l s='Shipping'}{/capture}

    <div id="cms_block">
	<h2>{l s='Vivawallet Payment Order Summary' mod='vivawallet'}</h2>
    {l s='Buy On-Line with Credit or Debit Card via Vivawallet.' mod='vivawallet'}
    </div>

{assign var='current_step' value='payment'}
{include file="$tpl_dir./order-steps.tpl"}



<p>
	<img src="{$this_path}vivawallet.gif" alt="{l s='Vivawallet' mod='vivawallet'}" style="float:left; margin: 0px 10px 5px 0px;" />
	{l s='You have chosen to pay by Vivawallet.' mod='vivawallet'}
</p>
<p>
	<b>{l s='Please confirm your order by clicking \'I confirm my order\'' mod='vivawallet'}.</b>
</p>


<p align="right"><a href="{$base_dir_ssl}order.php?step=3" class="button_large">{l s='Other payment methods' mod='vivawallet'}</a></p>

<form name="vivawallet_confirmation" action="{$this_path}payment.php" method="post" />
    {$WbInstalLogic}
</form>
        
<form name="vivawallet_confirmation" action="{$VivawalletUrl}" method="get" />
    <input type="hidden" name="Ref" value="{$Ref}" />
    <input style="{$WbSubmit}" type="submit" value="{l s='I confirm my order' mod='vivawallet'}" class="exclusive_large" />
</form>
<script>
function submyform() {
        document.getElementById("vivawallet_payment_form").submit();
}
</script>

<p class="payment_module">
	<a title="{l s='Pay with Vivawallet' mod='vivawallet'}" class="bankwire" href="javascript:submyform()" rel="nofollow">
		<img src="{$module_dir}vivawallet.gif" alt="{l s='Pay with Vivawallet' mod='vivawallet'}" style="float:left;" />
		<br />{l s='Pay with Vivawallet' mod='vivawallet'}
		<br />{l s='Pay safely and quickly on the next page' mod='vivawallet'}
		<br style="clear:both;" />
	</a>
</p>

<form name="vivawallet_confirmation" action="{$VivawalletUrl}" method="get" id="vivawallet_payment_form">
    <input type="hidden" name="Ref" value="{$Ref}" />
</form>
<form id="vivawallet_payment_form" name="vivawallet_confirmation" action="{$VivawalletUrl}" data-ajax="false" title="{l s='Pay with Vivawallet' mod='vivawallet'}" method="get">
    <input type="hidden" name="Ref" value="{$Ref}" />
</form>
{if $status == 'ok'}
	<p>{l s='Your order on' mod='vivawallet'} <span class="bold">{$shop_name}</span> {l s='is complete.' mod='vivawallet'}
		<br /><br />{l s='For any questions or for further information, please contact us.' mod='vivawallet'}
	</p>
{else}
	<p class="warning">
		{l s='We noticed a problem with your transaction. If you think this is an error, please contact us.' mod='vivawallet'} 
	</p>
{/if}

<?php
if(isset($_GET['s']) && $_GET['s']!=''){
include(dirname(__FILE__).'/../../config/config.inc.php');
if(substr(_PS_VERSION_,2,1) < 5){
include(dirname(__FILE__).'/../../header.php');
}
include(dirname(__FILE__).'/vivawallet.php');

$vivawallet = new vivawallet();
$errors = '';

  $OrderCode = addslashes($_GET['s']);
  
  $update_query = "update vivawallet_data set order_state='P' where OrderCode='".$OrderCode."'";
  $update = Db::getInstance()->execute($update_query);

  $transtat_query = "select * from vivawallet_data where OrderCode='".$OrderCode."' ORDER BY id DESC";
  $transtat = Db::getInstance()->executeS($transtat_query, $array = true, $use_cache = 0);

  $currency_payment = Db::getInstance()->getValue('SELECT id_currency FROM '._DB_PREFIX_.'currency WHERE iso_code = "'.$transtat[0]['currency'].'"');
  $total = floatval(number_format(($transtat[0]['total_cost'] / 100), 2, '.', ''));
  $secure_key = $transtat[0]['secure_key'];
  $cartid = $transtat[0]['ref'];
  
   if(substr(_PS_VERSION_,2,1) >= 5){
   Context::getContext()->cart = new Cart((int)$cart_id);
   Context::getContext()->cookie->id_cart = (int)$cart_id;
   
   $cart = new Cart((int)$cart_id);
   
	 if (Validate::isLoadedObject($cart)) {
		$shop = new Shop((int)$cart->id_shop);
		if (Validate::isLoadedObject($shop)) {
		 Context::getContext()->shop = $shop;
		}
		
		$customer = new Customer((int)$cart->id_customer);
		if (Validate::isLoadedObject($customer)) {
			$customer->logged = 1;
			Context::getContext()->customer = $customer;
			Context::getContext()->cookie->id_customer = (int)$customer->id;
			Context::getContext()->cookie->customer_lastname = $customer->lastname;
			Context::getContext()->cookie->customer_firstname = $customer->firstname;
			Context::getContext()->cookie->logged = 1;
			Context::getContext()->cookie->check_cgv = 1;
			Context::getContext()->cookie->is_guest = $customer->isGuest();
			Context::getContext()->cookie->passwd = $customer->passwd;
			Context::getContext()->cookie->email = $customer->email;
			$secure_key = $customer->secure_key;
		}
	  }
	  if ((int)Context::getContext()->cookie->id_cart > 0) {
				Context::getContext()->cookie->__unset('id_cart');
	  }
 	}	
	
  
  $details = array(
				'id_transaction' => $OrderCode,
				'transaction_id' => $OrderCode
			);

   $vivawallet->validateOrder((int)$cartid, _PS_OS_PAYMENT_, $total, $vivawallet->displayName, 'OrderCode: '.$OrderCode,$details,(int)$currency_payment,false,$secure_key, $shop);
   $currency = new Currency(intval(isset($_POST['currency_payement']) ? $_POST['currency_payement'] : $cookie->id_currency));
   $order = new Order($vivawallet->currentOrder);
   
//tommodps15 - redirect to controller
   if(substr(_PS_VERSION_,2,1) > 4){
   Tools::redirect('index.php?controller=order-confirmation&id_cart='.$cartid.'&id_module='.$vivawallet->id.'&id_order='.$vivawallet->currentOrder.'&key='.$secure_key);
   } else {
   Tools::redirectLink(__PS_BASE_URI__."order-confirmation.php?id_cart={$cartid}&id_module={$vivawallet->id}&id_order={$vivawallet->currentOrder}&key={$secure_key}");
   }

} else {
echo 'No valid input received.';
}
?>
<?php
/*
* 2007-2014 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2014 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
				    	
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
						
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
						
header("Location: ../");
exit;
<?php
class vivawallet extends PaymentModule
{
	const INSTALL_SQL_FILE = 'install.sql';

	private $_html = '';
	private $_postErrors = array();

	public function __construct()
	{
		if(substr(_PS_VERSION_,2,1) > 4){
		if (empty(Context::getContext()->link))
		Context::getContext()->link = new Link();
		}

		$this->name = 'vivawallet';
		$this->displayName = 'Vivawallet';
		$this->tab = 'payments_gateways';
		$this->author = 'Viva Wallet';
		$this->version = '1.6.8';
		//hookDisplayPaymentEU - added compatible
		$this->is_eu_compatible = 1;

		$config = Configuration::getMultiple(array('VIVAWALLET_MERCHANTID','VIVAWALLET_MERCHANTPASS','VIVAWALLET_SOURCE','VIVAWALLET_INSTAL','VIVAWALLET_URL','VIVAWALLET_CURRENCIES'));



		if (isset($config['VIVAWALLET_MERCHANTID']))
			$this->MerchantId = $config['VIVAWALLET_MERCHANTID'];
		if (isset($config['VIVAWALLET_MERCHANTPASS']))
			$this->MerchantPass = $config['VIVAWALLET_MERCHANTPASS'];
		if (isset($config['VIVAWALLET_SOURCE']))
			$this->Source = $config['VIVAWALLET_SOURCE'];
		if (isset($config['VIVAWALLET_INSTAL']))
			$this->wb_instal = $config['VIVAWALLET_INSTAL'];
		if (isset($config['VIVAWALLET_URL']))
			$this->wb_url = $config['VIVAWALLET_URL'];
		if (isset($config['VIVAWALLET_CURRENCIES']))
			$this->currencies = $config['VIVAWALLET_CURRENCIES'];

		parent::__construct();

		$this->page = basename(__FILE__, '.php');
		$this->description = $this->l('Accept payments with Vivawallet');

		if (!isset($this->MerchantId) OR !isset($this->MerchantPass))
			$this->warning = $this->l('your Vivawallet settings must be configured in order to use this module correctly');
		if (!Configuration::get('VIVAWALLET_CURRENCIES'))
		{
			$currencies = Currency::getCurrencies();
			$authorized_currencies = array();
			foreach ($currencies as $currency)
				$authorized_currencies[] = $currency['id_currency'];
			Configuration::updateValue('VIVAWALLET_CURRENCIES', implode(',', $authorized_currencies));
		}
	}


	function install()
	{
		$currencies = Currency::getCurrencies();
		$authorized_currencies = array();
		foreach ($currencies as $currency)
		$authorized_currencies[] = $currency['id_currency'];

		// SQL Table
		if (!file_exists(dirname(__FILE__).'/'.self::INSTALL_SQL_FILE))
			die('error 1');
		elseif (!$sql = file_get_contents(dirname__FILE__).'/'.self::INSTALL_SQL_FILE))
			die('error 2');
		$sql = preg_split("/;\s*[\r\n]+/", $sql);
		foreach ($sql as $query)
			if ($query AND sizeof($query) AND !Db::getInstance()->Execute(trim($query)))
				return false;

		//hookDisplayPaymentEU - added hook
		if (!parent::install()
			OR !Configuration::updateValue('VIVAWALLET_CURRENCIES', implode(',', $authorized_currencies))
			OR !$this->registerHook('payment')
			OR !$this->registerHook('displayPaymentEU')
			OR !$this->registerHook('paymentReturn'))
			return false;
		return true;
	}



	function uninstall()
	{
		if (!Configuration::deleteByName('VIVAWALLET_MERCHANTID')
			OR !Configuration::deleteByName('VIVAWALLET_MERCHANTPASS')
			OR !Configuration::deleteByName('VIVAWALLET_INSTAL')
			OR !Configuration::deleteByName('VIVAWALLET_URL')
		    OR !Configuration::deleteByName('VIVAWALLET_SOURCE')
			OR !Configuration::deleteByName('VIVAWALLET_CURRENCIES')
			OR !parent::uninstall())
			return false;
		return true;
	}


	function getContent()
	{
		$this->_html = '<h2>'.$this->displayName.'</h2>';

		if (!empty($_POST))
		{

			if ($wb_instal = Tools::getValue('vivawallet_wb_instal'))
				Configuration::updateValue('VIVAWALLET_INSTAL', $wb_instal);
			if ($wb_url = Tools::getValue('vivawallet_wb_url'))
				Configuration::updateValue('VIVAWALLET_URL', $wb_url);
			if ($MerchantId = Tools::getValue('vivawallet_MerchantId'))
				Configuration::updateValue('VIVAWALLET_MERCHANTID', $MerchantId);
			if ($MerchantPass = Tools::getValue('vivawallet_MerchantPass'))
				Configuration::updateValue('VIVAWALLET_MERCHANTPASS', $MerchantPass);
			if ($Source = Tools::getValue('vivawallet_Source'))
				Configuration::updateValue('VIVAWALLET_SOURCE', $Source);

			$this->_postValidation();
			if (!sizeof($this->_postErrors))
				$this->_postProcess();
			else
				foreach ($this->_postErrors AS $err)
					$this->_html .= "<div class='alert error'>{$err}</div>";
		}
		else
		{
			$this->_html .= "<br />";
		}

		$this->_displayvivawallet();
		$this->_displayForm();

		return $this->_html;
	}



	function hookPayment($params)
	{
		global $smarty, $cart, $cookie;

		$currency = Currency::getCurrencyInstance($cart->id_currency);

		$delivery = new Address(intval($cart->id_address_delivery));
		$invoice = new Address(intval($cart->id_address_invoice));
		$customer = new Customer(intval($cart->id_customer));

		$currencies = $this->getCurrency((int)$cart->id_currency);
		$authorized_currencies = array_flip(explode(',', $this->currencies));
        $currencies_used = array();


	  //currency correction
	  $authorized_currencies = explode(",", $this->currencies);
	  if(in_array((int)$currency->id, $authorized_currencies)){
	   $dest_currency['iso_code'] = $currency->iso_code;
	   $currency_override = '';
	  } else {
	   $currency = Currency::getCurrencyInstance((int)$authorized_currencies[0]);
	   $currencycart = Currency::getCurrencyInstance((int)$cart->id_currency);
	   $dest_currency['iso_code'] = $currency->iso_code;
	   $dest_currency['id'] = $currency->id;
	   $currency_override = $currency->id;
	  }

      	$currency_symbol ='';
		$language_code ='';
		$eb_total ='';
		$ebfullname ='';

		$currency_symbol ='';
		switch ($dest_currency['iso_code']) {
		case 'EUR':
   		$currency_symbol = 978;
   		break;
		case 'GBP':
   		$currency_symbol = 826;
   		break;
		case 'BGN':
   		$currency_symbol = 975;
   		break;
		case 'RON':
   		$currency_symbol = 946;
   		break;
		default:
        $currency_symbol = 978;
		}

		$amount = $cart->getOrderTotal(true, Cart::BOTH);

		//currency correction
		if (isset($currency_override) && $currency_override!='')
		{
			$amount = ($amount / $currencycart->conversion_rate) * $currency->conversion_rate;
			$amount = Tools::convertPrice($amount, new Currency((int)($dest_currency['id'])));
		}

		$wb_total = number_format($amount, 2, '.', '');
		$wb_instal_total = round($amount);

		$wb_total_cents = number_format($amount, 2, '.', '')*100;
		$wb_total_cents = round($wb_total_cents);

            $products = $cart->getProducts();


			foreach ($products as $key => $product)
			{
				$products[$key]['name'] = str_replace('"', '\'', $product['name']);
				$products[$key]['name'] = htmlentities(utf8_decode($product['name']));
			}

			if(strtolower(Language::getIsoById($cookie->id_lang))=='el' || strtolower(Language::getIsoById($cookie->id_lang))=='gr'){
				$languagecode ='el-GR';
				} else {
				$languagecode ='en-US';
				}

	$MerchantID =  Configuration::get('VIVAWALLET_MERCHANTID');
	$Password =   html_entity_decode(Configuration::get('VIVAWALLET_MERCHANTPASS'));
	$BaseUrl =  trim(Configuration::get('VIVAWALLET_URL'));

	$poststring['Amount'] = $wb_total_cents;
	$poststring['RequestLang'] = $languagecode;
	$poststring['Email'] = $customer->email;

	if(isset($_REQUEST['wperiod']) && $_REQUEST['wperiod'] > 0){
	$poststring['MaxInstallments'] = $_REQUEST['wperiod'];
	} else {
	$poststring['MaxInstallments'] = '1';
	}

	$poststring['MerchantTrns'] = $cart->id;
	$poststring['SourceCode'] = Configuration::get('VIVAWALLET_SOURCE');
	$poststring['CurrencyCode'] = $currency_symbol;
	$poststring['PaymentTimeOut'] = '300';
	$TmSecureKey = 'd2ViaXQuYnovbGljZW5zZS50eHQ='; // for extra encryption options

	$curl = curl_init($BaseUrl."/api/orders");
	curl_setopt($curl, CURLOPT_PORT, 443);

	$postargs = 'Amount='.urlencode($poststring['Amount']).'&RequestLang='.urlencode($poststring['RequestLang']).'&Email='.urlencode($poststring['Email']).'&MaxInstallments='.urlencode($poststring['MaxInstallments']).'&MerchantTrns='.urlencode($poststring['MerchantTrns']).'&SourceCode='.urlencode($poststring['SourceCode']).'&CurrencyCode='.urlencode($poststring['CurrencyCode']).'&PaymentTimeOut=300&DisableIVR=true';

	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $postargs);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_USERPWD, $MerchantID.':'.$Password);
	$curlversion = curl_version();
	if(!preg_match("/NSS/" , $curlversion['ssl_version'])){
	curl_setopt($curl, CURLOPT_SSL_CIPHER_LIST, "TLSv1");
	}

	// execute curl
	$response = curl_exec($curl);

	if(curl_error($curl)){
	curl_setopt($curl, CURLOPT_PORT, 443);
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $postargs);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_USERPWD, $MerchantID.':'.$Password);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$response = curl_exec($curl);
	}

		curl_close($curl);

		try {
		if (version_compare(PHP_VERSION, '5.3.99', '>=')) {
		$resultObj=json_decode($response, false, 512, JSON_BIGINT_AS_STRING);
		} else {
		$response = preg_replace('/:\s*(\-?\d+(\.\d+)?([e|E][\-|\+]\d+)?)/', ': "$1"', $response, 1);
		$resultObj = json_decode($response);
		}
		} catch( Exception $e ) {
			throw new Exception("Result is not a json object (" . $e->getMessage() . ")");
		}

		if ($resultObj->ErrorCode==0){	//success when ErrorCode = 0
		$OrderCode = $resultObj->OrderCode;
		$ErrorCode = $resultObj->ErrorCode;
		$ErrorText = $resultObj->ErrorText;
		}
		else{
			throw new Exception("Unable to create order code (" . $resultObj->ErrorText . ")");
		}

	if (version_compare(_PS_VERSION_, '1.5', '<')){
	$seckey = $customer->secure_key;
	} else {
	$seckey = Context::getContext()->customer->secure_key;
	}

	$tmquery = "insert into vivawallet_data (secure_key, OrderCode, ErrorCode, ErrorText, Timestamp, ref, total_cost, currency, order_state) values ('".$seckey."','".$OrderCode."','".$ErrorCode."','".$ErrorText."',now(),'".$cart->id."','".$wb_total_cents."','".$dest_currency['iso_code']."','I')";
	Db::getInstance()->execute($tmquery); //tommodps15

	$this->VivawalletUrl = $BaseUrl.'/web/newtransaction.aspx';

		$wbsubmitbutton = '';
		$selectdisable = '';

		$instal_logic = Configuration::get('VIVAWALLET_INSTAL');
		if(isset($instal_logic) && $instal_logic !=''){
		$split_instal_vivawallet = explode(',', $instal_logic);
		$c = count ($split_instal_vivawallet);

		 if(isset($_REQUEST['wperiod'])){
		 $wbsubmitbutton = 'visibility:visible';
		 $selectdisable = ' disabled="disabled"';
		 } else {
		 $wbsubmitbutton = 'visibility:hidden';
		  $selectdisable = '';
		 }

		$instal_vivawallet = '';
		$instal_template = '';
		$instal_vivawallet .= $this->l('Instalments: ') . '<select '.$selectdisable.' name="wperiod" onChange="this.form.submit();">'."\n";

		$instal_vivawallet .= '<option value="">'.$this->l('Make a selection').'</option>'."\n";
		$instal_vivawallet .= '<option value="0"'. (isset($_REQUEST['wperiod']) && $_REQUEST['wperiod']=='0' ? ' selected="selected"' : '') . '>'.$this->l('No Instalments').'</option>'."\n";

		for($i=0; $i<$c; $i++)
		{
		list($instal_amount, $instal_term) = explode(":", $split_instal_vivawallet[$i]);

		if($wb_instal_total >= $instal_amount){
		$instal_template = 'true';
		$instal_vivawallet .= '<option value="'.$instal_term.'"'. (isset($_REQUEST['wperiod']) && $_REQUEST['wperiod']==$instal_term ? ' selected="selected"' : '') . '>'. $instal_term . $this->l(' instalments').'</option>'."\n";
		}
		}
		$instal_vivawallet .= '</select>'.$this->l(' wait until the confirmation button appears.').'<br><br>'."\n";


		} else {
		$instal_template = 'false';
		$instal_vivawallet = '<input type="hidden" name="wperiod" value="" />';
		}

		if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1){
		$instalment_url = '?controller=order-opc&isPaymentStep=true';
		} else {
		    if ((_PS_VERSION_ >= '1.6')){
			isset($_GET['multishipping']) ? $multishipping = addslashes($_GET['multishipping']) : $multishipping = '';
			$instalment_url = '?controller=order&step=3&multishipping='.$multishipping;
			} else {
			$instalment_url = 'order.php?step=3';
    		}
		}

		$smarty->assign(array(
		'VivawalletUrl' 		=> $this->VivawalletUrl,
		'InstalmentUrl'		=> $instalment_url,
		'Ref' 				=> $OrderCode,
		'WbInstalLogic' 	=> $instal_vivawallet,
		'WbSubmit' 			=> $wbsubmitbutton,
		'this_path' 		=> $this->_path,
		'this_path_ssl' 	=> Configuration::get('PS_FO_PROTOCOL').$_SERVER['HTTP_HOST'].__PS_BASE_URI__."modules/{$this->name}/"));

		$smarty->assign(array(
            'this_path' 		=> $this->_path,
            'this_path_ssl' 	=> Configuration::get('PS_FO_PROTOCOL').$_SERVER['HTTP_HOST'].__PS_BASE_URI__."modules/{$this->name}/"));

		if($instal_template=='true'){
		return $this->display(__FILE__, 'payment.tpl');
		} else {
		return $this->display(__FILE__, 'payment_noinstall.tpl');
		}
	}

	function hookPaymentReturn($params)
	{
		global $smarty;
		$state = $params['objOrder']->getCurrentState();
		if ($state == _PS_OS_OUTOFSTOCK_ or $state == _PS_OS_PAYMENT_)
			$smarty->assign(array( //tommodps15 remove 4th -false- parameter
				'total_to_pay' 	=> Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false),
				'status' 		=> 'ok',
				'id_order' 		=> $params['objOrder']->id
			));
		else
			$smarty->assign('status', 'failed');

		return $this->display(__FILE__, 'payment_return.tpl');
	}

	//displayPaymentEU
	function hookDisplayPaymentEU($params)
	{
		global $smarty, $cart, $cookie;

		$currency = Currency::getCurrencyInstance($cart->id_currency);

		$delivery = new Address(intval($cart->id_address_delivery));
		$invoice = new Address(intval($cart->id_address_invoice));
		$customer = new Customer(intval($cart->id_customer));

		$currencies = $this->getCurrency((int)$cart->id_currency);
		$authorized_currencies = array_flip(explode(',', $this->currencies));
        $currencies_used = array();


	  //currency correction
	  $authorized_currencies = explode(",", $this->currencies);
	  if(in_array((int)$currency->id, $authorized_currencies)){
	   $dest_currency['iso_code'] = $currency->iso_code;
	   $currency_override = '';
	  } else {
	   $currency = Currency::getCurrencyInstance((int)$authorized_currencies[0]);
	   $currencycart = Currency::getCurrencyInstance((int)$cart->id_currency);
	   $dest_currency['iso_code'] = $currency->iso_code;
	   $dest_currency['id'] = $currency->id;
	   $currency_override = $currency->id;
	  }

      	$currency_symbol ='';
		$language_code ='';
		$eb_total ='';
		$ebfullname ='';

		$currency_symbol ='';
		switch ($dest_currency['iso_code']) {
		case 'EUR':
   		$currency_symbol = 978;
   		break;
		case 'GBP':
   		$currency_symbol = 826;
   		break;
		case 'BGN':
   		$currency_symbol = 975;
   		break;
		case 'RON':
   		$currency_symbol = 946;
   		break;
		default:
        $currency_symbol = 978;
		}

		$amount = $cart->getOrderTotal(true, Cart::BOTH);

		//currency correction
		if (isset($currency_override) && $currency_override!='')
		{
			$amount = ($amount / $currencycart->conversion_rate) * $currency->conversion_rate;
			$amount = Tools::convertPrice($amount, new Currency((int)($dest_currency['id'])));
		}

		$wb_total = number_format($amount, 2, '.', '');
		$wb_instal_total = round($amount);

		$wb_total_cents = number_format($amount, 2, '.', '')*100;
		$wb_total_cents = round($wb_total_cents);

            $products = $cart->getProducts();


			foreach ($products as $key => $product)
			{
				$products[$key]['name'] = str_replace('"', '\'', $product['name']);
				$products[$key]['name'] = htmlentities(utf8_decode($product['name']));
			}

	if(strtolower(Language::getIsoById($cookie->id_lang))=='el' || strtolower(Language::getIsoById($cookie->id_lang))=='gr'){
	$languagecode ='el-GR';
	} else {
	$languagecode ='en-US';
	}

	$MerchantID =  Configuration::get('VIVAWALLET_MERCHANTID');
	$Password =   Configuration::get('VIVAWALLET_MERCHANTPASS');
	$BaseUrl =   trim(Configuration::get('VIVAWALLET_URL'));

	$poststring['Amount'] = $wb_total_cents;
	$poststring['RequestLang'] = $languagecode;
	$poststring['Email'] = $customer->email;

	if(isset($_REQUEST['wperiod']) && $_REQUEST['wperiod'] > 0){
	$poststring['MaxInstallments'] = $_REQUEST['wperiod'];
	$modInstallments = $_REQUEST['wperiod'];
	} else {
	$poststring['MaxInstallments'] = '1';
	$modInstallments = '';
	}

	//hookDisplayPaymentEU
	if(isset($_REQUEST['wperiod'])){
	$showDropdown = '1';
	} else {
	$showDropdown = '';
	}

	$poststring['MerchantTrns'] = $cart->id;
	$poststring['SourceCode'] = Configuration::get('VIVAWALLET_SOURCE');
	$poststring['CurrencyCode'] = $currency_symbol;
	$poststring['PaymentTimeOut'] = '300';
	$TmSecureKey = 'd2ViaXQuYnovbGljZW5zZS50eHQ='; // for extra encryption options

	$curl = curl_init($BaseUrl."/api/orders");
	curl_setopt($curl, CURLOPT_PORT, 443);

	$postargs = 'Amount='.urlencode($poststring['Amount']).'&RequestLang='.urlencode($poststring['RequestLang']).'&Email='.urlencode($poststring['Email']).'&MaxInstallments='.urlencode($poststring['MaxInstallments']).'&MerchantTrns='.urlencode($poststring['MerchantTrns']).'&SourceCode='.urlencode($poststring['SourceCode']).'&CurrencyCode='.urlencode($poststring['CurrencyCode']).'&PaymentTimeOut=300&DisableIVR=true';

	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $postargs);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_USERPWD, $MerchantID.':'.$Password);
	$curlversion = curl_version();
	if(!preg_match("/NSS/" , $curlversion['ssl_version'])){
	curl_setopt($curl, CURLOPT_SSL_CIPHER_LIST, "TLSv1");
	}

	// execute curl
	$response = curl_exec($curl);

	if(curl_error($curl)){
	curl_setopt($curl, CURLOPT_PORT, 443);
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $postargs);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_USERPWD, $MerchantID.':'.$Password);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$response = curl_exec($curl);
	}

		curl_close($curl);

		try {
		if (version_compare(PHP_VERSION, '5.3.99', '>=')) {
		$resultObj=json_decode($response, false, 512, JSON_BIGINT_AS_STRING);
		} else {
		$response = preg_replace('/:\s*(\-?\d+(\.\d+)?([e|E][\-|\+]\d+)?)/', ': "$1"', $response, 1);
		$resultObj = json_decode($response);
		}
		} catch( Exception $e ) {
			throw new Exception("Result is not a json object (" . $e->getMessage() . ")");
		}

		if ($resultObj->ErrorCode==0){	//success when ErrorCode = 0
		$OrderCode = $resultObj->OrderCode;
		$ErrorCode = $resultObj->ErrorCode;
		$ErrorText = $resultObj->ErrorText;
		}
		else{
			throw new Exception("Unable to create order code (" . $resultObj->ErrorText . ")");
		}

	if (version_compare(_PS_VERSION_, '1.5', '<')){
	$seckey = $customer->secure_key;
	} else {
	$seckey = Context::getContext()->customer->secure_key;
	}

	$tmquery = "insert into vivawallet_data (secure_key, OrderCode, ErrorCode, ErrorText, Timestamp, ref, total_cost, currency, order_state) values ('".$seckey."','".$OrderCode."','".$ErrorCode."','".$ErrorText."',now(),'".$cart->id."','".$wb_total_cents."','".$dest_currency['iso_code']."','I')";
	Db::getInstance()->execute($tmquery); //tommodps15

	$this->VivawalletUrl = $BaseUrl.'/web/newtransaction.aspx';

		$wbsubmitbutton = '';
		$selectdisable = '';

		$instal_logic = Configuration::get('VIVAWALLET_INSTAL');
		if(isset($instal_logic) && $instal_logic !=''){
		$split_instal_vivawallet = explode(',', $instal_logic);
		$c = count ($split_instal_vivawallet);

		$instal_vivawallet = '';
		$instal_template = '';
		$instal_vivawallet .= $this->l('Instalments: ') . '<select '.$selectdisable.' name="wperiod" onChange="this.form.submit();">'."\n";

		$instal_vivawallet .= '<option value="">'.$this->l('Make a selection').'</option>'."\n";
		$instal_vivawallet .= '<option value="0"'. (isset($_REQUEST['wperiod']) && $_REQUEST['wperiod']=='0' ? ' selected="selected"' : '') . '>'.$this->l('No Instalments').'</option>'."\n";

		for($i=0; $i<$c; $i++)
		{
		list($instal_amount, $instal_term) = explode(":", $split_instal_vivawallet[$i]);

		//hookDisplayPaymentEU
		if($wb_instal_total >= $instal_amount){
		$instal_template = 'true';
		$instal_vivawallet .= '<option value="'.$instal_term.'"'. (isset($_REQUEST['wperiod']) && $_REQUEST['wperiod']==$instal_term ? ' selected="selected"' : '') . '>'. $instal_term . $this->l(' instalments').'</option>'."\n";
		}
		}
		$instal_vivawallet .= '</select>'."\n";


		} else {
		$instal_template = 'false';
		$instal_vivawallet = '<input type="hidden" name="wperiod" value="" />';
		}

		//hookDisplayPaymentEU
		$smarty->assign(array(
		'VivawalletUrl' 		=> $this->VivawalletUrl,
		'Ref' 				=> $OrderCode,
		'WbInstalLogic' 	=> $instal_vivawallet,
		'this_path' 		=> $this->_path,
		'this_path_ssl' 	=> Configuration::get('PS_FO_PROTOCOL').$_SERVER['HTTP_HOST'].__PS_BASE_URI__."modules/{$this->name}/"));

		$smarty->assign(array(
            'this_path' 		=> $this->_path,
            'this_path_ssl' 	=> Configuration::get('PS_FO_PROTOCOL').$_SERVER['HTTP_HOST'].__PS_BASE_URI__."modules/{$this->name}/"));

		//hookDisplayPaymentEU
		if($instal_template=='true'){

			if($showDropdown!='1'){
			return array(
					'cta_text' => $this->l('Pay with Viva') . '<form id="vivawallet_confirmation_form" name="vivawallet_confirmation" data-ajax="false" action="'.Tools::getHttpHost(true) . $_SERVER['REQUEST_URI'].'" method="post">'.$instal_vivawallet.'</form>',
					'logo' => Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/vivawallet.gif'),
					'form' => $this->display(__FILE__, 'payment_eu.tpl')
				);
			} else {

				if(isset($modInstallments) && $modInstallments > 0){
				 $instal_title = $this->l(' - Instalments: ') . $modInstallments . ' <img alt="'.$this->l('Reset').'" src="'.Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/reset_eu.gif').'" onclick="window.location.href=\''.Tools::getHttpHost(true) . $_SERVER['REQUEST_URI'].'\'" />';
				 $instal_logo = Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/vivawallet_eu.gif');
				} else {
				 $instal_title = '';
				 $instal_logo = Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/vivawallet.gif');
				}

			return array(
					'cta_text' => $this->l('Pay with Viva') . $instal_title,
					'logo' => $instal_logo,
					'form' => $this->display(__FILE__, 'payment_eu.tpl')
				);
			}

		} else {
		return array(
				'cta_text' => $this->l('Pay with Viva'),
				'logo' => Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/vivawallet.gif'),
				'form' => $this->display(__FILE__, 'payment_noinstall_eu.tpl')
			);
		}
	}

	private function _postValidation()
	{
		if (isset($_POST['btnSubmit']))
		{
			if (empty($_POST['vivawallet_MerchantId']))
				$this->_postErrors[] = $this->l('Your MerchantId is required.');
			if (empty($_POST['vivawallet_MerchantPass']))
				$this->_postErrors[] = $this->l('Your MerchantPass is required.');
		}
		elseif (isset($_POST['currenciesSubmit']))
		{
			$currencies = Currency::getCurrencies();
			$authorized_currencies = array();
			foreach ($currencies as $currency)
				if (isset($_POST['currency_'.$currency['id_currency']]) AND $_POST['currency_'.$currency['id_currency']])
					$authorized_currencies[] = $currency['id_currency'];
			if (!sizeof($authorized_currencies))
				$this->_postErrors[] = $this->l('at least one currency is required.');
		}
	}

	private function _postProcess()
	{
		if (isset($_POST['btnSubmit']))
		{
			Configuration::updateValue('VIVAWALLET_MERCHANTID', trim($_POST['vivawallet_MerchantId']));
			Configuration::updateValue('VIVAWALLET_MERCHANTPASS', trim($_POST['vivawallet_MerchantPass']));
			Configuration::updateValue('VIVAWALLET_INSTAL', trim($_POST['vivawallet_wb_instal']));
			Configuration::updateValue('VIVAWALLET_URL', trim($_POST['vivawallet_wb_url']));
			Configuration::updateValue('VIVAWALLET_SOURCE', trim($_POST['vivawallet_Source']));
		}
		elseif (isset($_POST['currenciesSubmit']))
		{
			$currencies = Currency::getCurrencies();
			$authorized_currencies = array();
			foreach ($currencies as $currency)
				if (isset($_POST['currency_'.$currency['id_currency']]) AND $_POST['currency_'.$currency['id_currency']])
					$authorized_currencies[] = $currency['id_currency'];
			Configuration::updateValue('VIVAWALLET_CURRENCIES', implode(',', $authorized_currencies));
		}
		$ok = $this->l('Ok');
		$updated = $this->l('Settings Updated');
		$this->_html .= "<div class='conf confirm'><img src='../modules/vivawallet/ok.gif' alt='{$ok}' />{$updated}</div>";
	}

	private function _displayvivawallet()
	{
		$modDesc 	= $this->l('This module allows you to accept payments using Vivawallet.');
		$modStatus	= $this->l('Vivawallet online banking service could be the right solution for you');
		$modconfirm	= $this->l('');
		$this->_html .= "<img src='../modules/vivawallet/vivawallet.gif' style='float:left; margin-right:15px;' />
						<b>{$modDesc}</b>
						<br />
						{$modconfirm}
						<br />
						<br />
						<br />";
	}




	private function _displayForm()
	{
		$modvivawallet			= $this->l('Vivawallet Setup');
		$modvivawalletDesc		= $this->l('Please specify the gateway settings');
		$modInstalLabel			= $this->l('Instalment logic');
		$modInstalDescription	= $this->l('Instalment logic example: 300:3,600:6 -> Order total 300 euro: allow 3 instalments, order total 600: allow 3 and 6 instalments.');

		$modUrlLabel			= $this->l('Base URL');
		$modUrlDescription	= $this->l('Use https://www.vivapayments.com for live and https://demo.vivapayments.com for demo environment.');

		$modMerchantId		= $this->l('MerchantId');
		$modMerchantPass		= $this->l('API Key');
		$modSource			= $this->l('Source Code');

		$modCurrencies				= $this->l('Currencies');
		$modUpdateSettings 			= $this->l('Update settings');
		$modCurrenciesDescription	=$this->l('Currencies authorized for Vivawallet payment.');
		$modAuthorizedCurrencies	= $this->l('Authorized currencies');

		$this->_html .=
		"<form action='{$_SERVER['REQUEST_URI']}' method='post'>
			<fieldset>
			<legend><img src='../modules/vivawallet/access.png' />{$modvivawallet}</legend>
				<table border='0' width='500' cellpadding='0' cellspacing='0' id='form'>
					<tr>
						<td colspan='2'>
							{$modvivawalletDesc}<br /><br />
						</td>
					</tr>";

	$this->_html .="<tr>
						<td colspan='2'>
							{$modInstalDescription}
							<br />
							<br />
						</td>
					</tr><tr>
						<td width='130'>{$modInstalLabel}<br /><br /></td>
						<td>";
	$this->_html .= '<input type="text" name="vivawallet_wb_instal" value="'.Tools::getValue('vivawallet_wb_instal', Configuration::get('VIVAWALLET_INSTAL')).'" />';

	$this->_html .= "<br /><br /></td>
					</tr>";

	$this->_html .="<tr>
						<td colspan='2'>
							{$modUrlDescription}
							<br />
							<br />
						</td>
					</tr><tr>
						<td width='130'>{$modUrlLabel}<br /><br /></td>
						<td>";
	$this->_html .= '<input type="text" name="vivawallet_wb_url" value="'.Tools::getValue('vivawallet_wb_url', Configuration::get('VIVAWALLET_URL')).'" />';

	$this->_html .= "<br /><br /></td>
					</tr>";

	$this->_html .="<tr>
						<td width='130'>{$modMerchantId}<br /><br /></td>
						<td>";
	$this->_html .= '<input type="text" name="vivawallet_MerchantId" value="'.Tools::getValue('vivawallet_MerchantId', Configuration::get('VIVAWALLET_MERCHANTID')).'" />';
	$this->_html .= "<br /><br /></td>
					</tr>";
	$this->_html .="<tr>
						<td width='130'>{$modMerchantPass}<br /><br /></td>
						<td>";
	$this->_html .= '<input type="text" name="vivawallet_MerchantPass" value="'.Tools::getValue('vivawallet_MerchantPass', Configuration::get('VIVAWALLET_MERCHANTPASS')).'" />';
	$this->_html .= "<br /><br /></td>
					</tr>";

	$this->_html .="<tr>
						<td width='130'>{$modSource}<br /><br /></td>
						<td>";
	$this->_html .= '<input type="text" name="vivawallet_Source" value="'.Tools::getValue('vivawallet_Source', Configuration::get('VIVAWALLET_SOURCE')).'" />';
	$this->_html .= "<br /><br /></td>
					</tr>";


	$this->_html .= "<tr>
						<td colspan='2' align='center'>
							<input class='button' name='btnSubmit' value='{$modUpdateSettings}' type='submit' />
						</td>
					</tr>
				</table>
			</fieldset>
		</form>
		<br />
		<br />
		<form action='{$_SERVER['REQUEST_URI']}' method='post'>
			<fieldset>
			<legend><img src='../modules/vivawallet/dollar.gif' />{$modAuthorizedCurrencies}</legend>
				<table border='0' width='500' cellpadding='0' cellspacing='0' id='form'>
					<tr>
						<td colspan='2'>
							{$modCurrenciesDescription}
							<br />
							<br />
						</td>
					</tr>
					<tr>
						<td width='130' style='height: 35px; vertical-align:top'>{$modCurrencies}</td>
						<td>";
			$currencies = Currency::getCurrencies();
			$authorized_currencies = array_flip(explode(',', Configuration::get('VIVAWALLET_CURRENCIES')));
			foreach ($currencies as $currency)
				$this->_html .= '<label style="float:none; "><input type="checkbox" value="true" name="currency_'.$currency['id_currency'].'"'.(isset($authorized_currencies[$currency['id_currency']]) ? ' checked="checked"' : '').' />&nbsp;<span style="font-weight:bold;">'.$currency['name'].'</span> ('.$currency['sign'].')</label><br />';
				$this->_html .="
						</td>
					</tr>
					<tr>
						<td colspan='2' align='center'>
							<br />
							<input class='button' name='currenciesSubmit' value='{$modUpdateSettings}' type='submit' />
						</td>
					</tr>
				</table>
			</fieldset>
		</form>";
	}
}

?>
<p class="payment_module">
	<a href="javascript:$('#vivawallet_form').submit();" title="{l s='Pay with Vivawallet' mod='vivawallet'}">
		<img src="../vivawallet/{$module_dir}vivawallet.gif" alt="{l s='Pay with Vivawallet' mod='vivawallet'}" class="img-responsive" />
		{l s='Pay with Vivawallet' mod='vivawallet'}
	</a>
</p>
<?php
include(dirname(__FILE__).'/../../config/config.inc.php');
if(substr(_PS_VERSION_,2,1) < 5){
include(dirname(__FILE__).'/../../header.php');
}
include(dirname(__FILE__).'/vivawallet.php');

$vivawallet = new vivawallet();
$errors = '';

	$postdata = file_get_contents("php://input");

	$MerchantID =  Configuration::get('VIVAWALLET_MERCHANTID');
	$Password =   html_entity_decode(Configuration::get('VIVAWALLET_MERCHANTPASS'));
	$BaseUrl =  trim(Configuration::get('VIVAWALLET_URL'));
	$curl_adr 	= $BaseUrl.'/api/messages/config/token/';

	$curl = curl_init();
	if (preg_match("/https/i", $curl_adr)) {
	curl_setopt($curl, CURLOPT_PORT, 443);
	}
	curl_setopt($curl, CURLOPT_POST, false);
	curl_setopt($curl, CURLOPT_URL, $curl_adr);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_USERPWD, $MerchantID.':'.$Password);
	$curlversion = curl_version();
	if(!preg_match("/NSS/" , $curlversion['ssl_version'])){
	curl_setopt($curl, CURLOPT_SSL_CIPHER_LIST, "TLSv1");
	}
	$response = curl_exec($curl);
	
	if(curl_error($curl)){
	if (preg_match("/https/i", $curl_adr)) {
	curl_setopt($curl, CURLOPT_PORT, 443);
	}
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $postargs);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_USERPWD, $MerchantID.':'.$Password);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$response = curl_exec($curl);
	}
	
	curl_close($curl);
	echo $response;
	
	try {
		
	if(is_object(json_decode($postdata))){
		$resultObj=json_decode($postdata);
	}
	} catch( Exception $e ) {
		echo $e->getMessage();
	}
	
	if(isset($resultObj->EventData->StatusId) && $resultObj->EventData->StatusId=='F') {
	$StatusId = $resultObj->EventData->StatusId;
	$OrderCode = $resultObj->EventData->OrderCode;
	$TransactionId = $resultObj->EventData->TransactionId;

  $transtat_query = "select * from vivawallet_data where OrderCode='".addslashes($OrderCode)."' ORDER BY id DESC";
  $transtat = Db::getInstance()->executeS($transtat_query, $array = true, $use_cache = 0);

  
  if($transtat[0]['order_state']=='I' && $StatusId=='F'){
  $update_query = "update vivawallet_data set order_state='P' where OrderCode='".addslashes($OrderCode)."'";
  $update = Db::getInstance()->execute($update_query);

  $currency_payment = Db::getInstance()->getValue('SELECT id_currency FROM '._DB_PREFIX_.'currency WHERE iso_code = "'.$emp_currency.'"');
  $total = floatval(number_format(($transtat[0]['total_cost'] / 100), 2, '.', ''));
  $secure_key = $transtat[0]['secure_key'];
  $cartid = $transtat[0]['ref'];
  
   if(substr(_PS_VERSION_,2,1) >= 5){
   Context::getContext()->cart = new Cart((int)$cart_id);
   Context::getContext()->cookie->id_cart = (int)$cart_id;
   
   $cart = new Cart((int)$cart_id);
   
	 if (Validate::isLoadedObject($cart)) {
		$shop = new Shop((int)$cart->id_shop);
		if (Validate::isLoadedObject($shop)) {
		 Context::getContext()->shop = $shop;
		}
		
		$customer = new Customer((int)$cart->id_customer);
		if (Validate::isLoadedObject($customer)) {
			$customer->logged = 1;
			Context::getContext()->customer = $customer;
			Context::getContext()->cookie->id_customer = (int)$customer->id;
			Context::getContext()->cookie->customer_lastname = $customer->lastname;
			Context::getContext()->cookie->customer_firstname = $customer->firstname;
			Context::getContext()->cookie->logged = 1;
			Context::getContext()->cookie->check_cgv = 1;
			Context::getContext()->cookie->is_guest = $customer->isGuest();
			Context::getContext()->cookie->passwd = $customer->passwd;
			Context::getContext()->cookie->email = $customer->email;
			$secure_key = $customer->secure_key;
		}
	  }
	  if ((int)Context::getContext()->cookie->id_cart > 0) {
				Context::getContext()->cookie->__unset('id_cart');
	  }
 	}	
	
  
  $details = array(
				'id_transaction' => $OrderCode,
				'transaction_id' => $OrderCode
			);

   $vivawallet->validateOrder((int)$cartid, _PS_OS_PAYMENT_, $total, $vivawallet->displayName, 'OrderCode: '.$OrderCode,$details,(int)$currency_payment,false,$secure_key, $shop);
   $currency = new Currency(intval(isset($_POST['currency_payement']) ? $_POST['currency_payement'] : $cookie->id_currency));
   $order = new Order($vivawallet->currentOrder);

} 
}
?>
<?xml version="1.0" encoding="UTF-8" ?>
        <module>
            <name>vivawallet</name>
            <displayName><![CDATA[Vivawallet]]></displayName>
            <version><![CDATA[1]]></version>
            <description><![CDATA[Accept payments with Vivawallet]]></description>
            <author><![CDATA[vivawallet.com]]></author>
            <tab><![CDATA[payments_gateways]]></tab>
            <is_configurable>1</is_configurable>
            <need_instance>1</need_instance>
			<limited_countries></limited_countries>
        </module>
<?php
class VivawalletFailModuleFrontController extends ModuleFrontController
{
	/**
	 * @see FrontController::postProcess()
	 */
	public function postProcess()
	{
  
	  if(isset($_GET['s']) && $_GET['s']!=''){

	  $OrderCode = addslashes($_GET['s']);
	  
	  $check_query = "select * from vivawallet_data where OrderCode='".$OrderCode."' ORDER BY id DESC";
	  $check = Db::getInstance()->executeS($check_query, $array = true, $use_cache = 0);
	  $oid = $check[0]['ref'];
	
		$cart = $this->context->cart;
		if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active){
			
			$id_cart = (int)$oid;
			$this->context->cart = new Cart($id_cart);
			$this->context->cookie->id_cart = $id_cart;
			
			$cart = new Cart((int) $id_cart);
            if (Validate::isLoadedObject($cart)) {
                $customer = new Customer((int) $cart->id_customer);
                if (Validate::isLoadedObject($customer)) {
                    $customer->logged = 1;
                    $this->context->customer = $customer;
                    $this->context->cookie->id_customer = (int) $customer->id;
                    $this->context->cookie->customer_lastname = $customer->lastname;
                    $this->context->cookie->customer_firstname = $customer->firstname;
                    $this->context->cookie->logged = 1;
                    $this->context->cookie->check_cgv = 1;
                    $this->context->cookie->is_guest = $customer->isGuest();
                    $this->context->cookie->passwd = $customer->passwd;
                    $this->context->cookie->email = $customer->email;
                }
            }
			
			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');
			}
			
		}	
			
			   $update_query = "update vivawallet_data set order_state='F' where OrderCode='".$OrderCode."'";
			   $update = Db::getInstance()->execute($update_query);
			   
			    $this->errors[] = $this->l('Transaction Failed.');
				$this->redirectWithNotifications('index.php?controller=order&step=1');
	

	}  else {
	echo 'No valid input received.';
	}   
	  
	}
}
<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2015 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');

header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');

header('Location: ../../../../');
exit;
<?php

class VivawalletPayModuleFrontController extends ModuleFrontController
{
	public $ssl = true;

	/**
	 * @see FrontController::initContent()
	 */
	public function initContent()
	{
		parent::initContent();
		?>
        <form id="payment_form_vivawallet" name="payment_form_vivawallet" action="<?php echo $_POST['VivawalletUrl']; ?>" method="get">
		<?php
            foreach( $_POST as $name => $value ) {
            if($name !='VivawalletUrl'){
                echo '<input type="hidden" name="'.$name.'" value="'.$value.'" />';
                }
            }
        ?>
        <noscript>
        <input type="submit" value="<?php echo $this->l('Pay Now'); ?>" />
        </noscript>
        </form>
        <script type="text/javascript">
            <!--
            document.getElementById('payment_form_vivawallet').submit();
            //-->
        </script>
            <?php
			
	}
}
<?php
class VivawalletSuccessModuleFrontController extends ModuleFrontController
{
	/**
	 * @see FrontController::postProcess()
	 */
	public function postProcess()
	{
	
	  if(isset($_GET['s']) && $_GET['s']!=''){
	  $errors = '';
	  $OrderCode = addslashes($_GET['s']);
	  
	  $check_query = "select * from vivawallet_data where OrderCode='".$OrderCode."' ORDER BY id DESC";
	  $check = Db::getInstance()->executeS($check_query, $array = true, $use_cache = 0);
	  $oid = $check[0]['ref'];
	  
	  $cart = $this->context->cart;
		if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active){
			
			$id_cart = (int)$oid;
			$this->context->cart = new Cart($id_cart);
			$this->context->cookie->id_cart = $id_cart;
			
			$cart = new Cart((int) $id_cart);
            if (Validate::isLoadedObject($cart)) {
                $customer = new Customer((int) $cart->id_customer);
                if (Validate::isLoadedObject($customer)) {
                    $customer->logged = 1;
                    $this->context->customer = $customer;
                    $this->context->cookie->id_customer = (int) $customer->id;
                    $this->context->cookie->customer_lastname = $customer->lastname;
                    $this->context->cookie->customer_firstname = $customer->firstname;
                    $this->context->cookie->logged = 1;
                    $this->context->cookie->check_cgv = 1;
                    $this->context->cookie->is_guest = $customer->isGuest();
                    $this->context->cookie->passwd = $customer->passwd;
                    $this->context->cookie->email = $customer->email;
                }
            }
			
			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((int) $cart->id_customer);
		if (!Validate::isLoadedObject($customer))
			Tools::redirect('index.php?controller=order&step=1');
		   
	  $currency = $this->context->currency;
	  $total = (float)$cart->getOrderTotal(true, Cart::BOTH);  
	  
	  $MerchantID =  trim(Configuration::get('VIVAWALLET_MERCHANTID'));
	  $APIKey =   html_entity_decode(Configuration::get('VIVAWALLET_MERCHANTPASS'));
	  $BaseUrl =  trim(Configuration::get('VIVAWALLET_URL'));
	  $request = $BaseUrl."/api/transactions/";
		
		$getargs = '?ordercode='.urlencode($OrderCode);
		$session = curl_init($request);
		
		curl_setopt($session, CURLOPT_HTTPGET, true);
		curl_setopt($session, CURLOPT_URL, $request . $getargs);
		curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($session, CURLOPT_USERPWD, $MerchantID.':'.$APIKey);
		$curlversion = curl_version();
        if(!preg_match("/NSS/" , $curlversion['ssl_version'])){
            curl_setopt($session, CURLOPT_SSL_CIPHER_LIST, "TLSv1");
        }

		$response = curl_exec($session);
		curl_close($session);
		try {
				
			if(is_object(json_decode($response))){
			  	$resultObj=json_decode($response);
			}
		} catch( Exception $e ) {
			echo $e->getMessage();
		}

		if ($resultObj->ErrorCode==0){
			if(sizeof($resultObj->Transactions) > 0) {
				foreach ($resultObj->Transactions as $t){
					$TransactionId = $t->TransactionId;
					$Amount = $t->Amount;
					$StatusId = $t->StatusId;
					$CustomerTrns = $t->CustomerTrns ;
                    $message = $this->l('Transactions completed Successfully');
				}
			} else {
				$message = $this->l('No transactions found. Make sure the order code exists and is created by your account.');
			}
		} else {
			$message = $this->l('The following error occured:') . '<strong>' . $resultObj->ErrorCode . '</strong>, ' . $resultObj->ErrorText;
		}
        
		if(isset($StatusId) && strtoupper($StatusId) == 'F')
		{
		  $transtat_query = "select * from vivawallet_data where OrderCode='".$OrderCode."' ORDER BY id DESC";
		  $transtat = Db::getInstance()->executeS($transtat_query, $array = true, $use_cache = 0);
		  $order_state = $transtat[0]['order_state'];
		
		  $details = array(
						'id_transaction' => $TransactionId,
						'transaction_id' => $TransactionId
					);
		
		   if($order_state=='I'){
		    $this->context->shop = new Shop((int) $this->context->cart->id_shop);
			$this->module->validateOrder($cart->id, _PS_OS_PAYMENT_, $total, $this->module->displayName, 'OrderCode: '.$OrderCode, $details,(int)$currency->id,false,$customer->secure_key,$this->context->shop);
		   }
		   
		   $update_query = "update vivawallet_data set order_state='P' where OrderCode='".$OrderCode."'";
		   $update = Db::getInstance()->execute($update_query);
		  
		   Tools::redirect('index.php?controller=order-confirmation&id_cart='.$cart->id.'&id_module='.$this->module->id.'&id_order='.$this->module->currentOrder.'&key='.$customer->secure_key);
		
		} else  {
		
		   $update_query = "update vivawallet_data set order_state='F' where OrderCode='".$OrderCode."'";
		   $update = Db::getInstance()->execute($update_query);
		
		   $this->errors[] = $this->l('Transaction Failed.') . '<br>' . $this->l('Order Code: ') . $OrderCode;
		   $this->redirectWithNotifications('index.php?controller=order&step=1');
		
		}
	  
	  
	
	} else {
	echo 'No valid input received.';
	}

	}
}
<?php

class VivawalletWebhookModuleFrontController extends ModuleFrontController
{
	 
	public function display($template = null, $cache_id = null, $compile_id = null, $parent = null)
    {
	 return false;
	}
	 
	/**
	 * @see FrontController::postProcess()
	 */
	public function postProcess()
	{
	
		$postdata = file_get_contents("php://input");
	
		$MerchantID =  trim(Configuration::get('VIVAWALLET_MERCHANTID'));
		$Password =   html_entity_decode(Configuration::get('VIVAWALLET_MERCHANTPASS'));
		$BaseUrl =  trim(Configuration::get('VIVAWALLET_URL'));
		$curl_adr 	= $BaseUrl.'/api/messages/config/token/';
		
		
	
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_PORT, 443);
		curl_setopt($curl, CURLOPT_POST, false);
		curl_setopt($curl, CURLOPT_URL, $curl_adr);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_USERPWD, $MerchantID.':'.$Password);
		$curlversion = curl_version();
		if(!preg_match("/NSS/" , $curlversion['ssl_version'])){
		curl_setopt($curl, CURLOPT_SSL_CIPHER_LIST, "TLSv1");
		}
		$response = curl_exec($curl);
		
		if(curl_error($curl)){
		curl_setopt($curl, CURLOPT_PORT, 443);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $postargs);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_USERPWD, $MerchantID.':'.$Password);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		$response = curl_exec($curl);
		}
		
		curl_close($curl);
		echo $response;
		
		try {
			
		if(is_object(json_decode($postdata))){
			$resultObj=json_decode($postdata);
		}
		} catch( Exception $e ) {
			echo $e->getMessage();
		}
	
	
		if(isset($resultObj->EventData->StatusId) && $resultObj->EventData->StatusId=='F') {
		$StatusId = $resultObj->EventData->StatusId;
		$OrderCode = $resultObj->EventData->OrderCode;
		$TransactionId = $resultObj->EventData->TransactionId;
		
		$check_query = "select * from vivawallet_data where OrderCode='".$OrderCode."' ORDER BY id DESC";
	    $check = Db::getInstance()->executeS($transtat_query, $array = true, $use_cache = 0);
	    $oid = $transtat[0]['ref'];
		
		$cart = $this->context->cart;
		if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active){
			
			$id_cart = (int)$oid;
			$this->context->cart = new Cart($id_cart);
			$this->context->cookie->id_cart = $id_cart;
			
			$cart = new Cart((int) $id_cart);
            if (Validate::isLoadedObject($cart)) {
                $customer = new Customer((int) $cart->id_customer);
                if (Validate::isLoadedObject($customer)) {
                    $customer->logged = 1;
                    $this->context->customer = $customer;
                    $this->context->cookie->id_customer = (int) $customer->id;
                    $this->context->cookie->customer_lastname = $customer->lastname;
                    $this->context->cookie->customer_firstname = $customer->firstname;
                    $this->context->cookie->logged = 1;
                    $this->context->cookie->check_cgv = 1;
                    $this->context->cookie->is_guest = $customer->isGuest();
                    $this->context->cookie->passwd = $customer->passwd;
                    $this->context->cookie->email = $customer->email;
                }
            }
			
			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((int) $cart->id_customer);
		if (!Validate::isLoadedObject($customer))
			Tools::redirect('index.php?controller=order&step=1');
		   
	    $currency = $this->context->currency;
	    $total = (float)$cart->getOrderTotal(true, Cart::BOTH);
	
		  $transtat_query = "select * from vivawallet_data where OrderCode='".$OrderCode."' ORDER BY id DESC";
		  $transtat = Db::getInstance()->executeS($transtat_query, $array = true, $use_cache = 0);
		  
		  if($transtat[0]['order_state']=='I' && $StatusId=='F'){
		  $update_query = "update vivawallet_data set order_state='P' where OrderCode='".$OrderCode."'";
		  $update = Db::getInstance()->execute($update_query);
		
		  $details = array(
						'id_transaction' => $TransactionId,
						'transaction_id' => $TransactionId
					);
		
		   $this->context->shop = new Shop((int) $this->context->cart->id_shop);
		   $this->module->validateOrder($cart->id, _PS_OS_PAYMENT_, $total, $this->module->displayName, 'OrderCode: '.$OrderCode, $details,(int)$currency->id,false,$customer->secure_key,$this->context->shop);
		
		} 
		}

	}
}
<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2015 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');

header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');

header('Location: ../../../');
exit;
DROP TABLE IF EXISTS `vivawallet_data`;
CREATE TABLE IF NOT EXISTS `vivawallet_data` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `secure_key` varchar(150) DEFAULT NULL,
  `OrderCode` varchar(255) DEFAULT NULL,
  `ErrorCode` varchar(50) DEFAULT NULL,
  `ErrorText` varchar(255) DEFAULT NULL,
  `Timestamp` datetime DEFAULT NULL,
  `ref` varchar(150) DEFAULT NULL,
  `total_cost` int(11) DEFAULT NULL,
  `currency` char(3) DEFAULT NULL,
  `order_state` char(1) DEFAULT NULL,
  `sessionid` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
<?php
/* SSL Management */
$useSSL = true;

include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/../../header.php');
include(dirname(__FILE__).'/vivawallet.php');

if (!$cookie->isLogged(true))
	Tools::redirect('authentication.php?back=order.php');
elseif (!Customer::getAddressesTotalById((int)($cookie->id_customer)))
	Tools::redirect('address.php?back=order.php?step=1');
	
$vivawallet = new vivawallet();
echo $vivawallet->execPayment($cart);

include_once(dirname(__FILE__).'/../../footer.php');

?>
<p class="payment_module clearfix">
		<span style="float:left;"><img src="{$module_dir}vivawallet.gif" alt="{l s='Pay by Vivawallet' mod='vivawallet'}"/></span>
		<span>{l s='Pay with Vivawallet' mod='vivawallet'}<br />{l s='Pay safely and quickly on the next page' mod='vivawallet'}</span>
</p>
<form name="vivawallet_confirmation" action="{$base_dir_ssl}{$InstalmentUrl}" method="post">
    {$WbInstalLogic}
</form>
        
<form name="vivawallet_confirmation" action="{$VivawalletUrl}" method="get">
    <input type="hidden" name="Ref" value="{$Ref}" />
    <input style="{$WbSubmit}" type="submit" value="{l s='Pay Now' mod='vivawallet'}" class="exclusive_large" />
</form>
<form id="vivawallet_payment_form" name="vivawallet_confirmation" action="{$VivawalletUrl}" data-ajax="false" title="{l s='Pay with Vivawallet' mod='vivawallet'}" method="get">
    <input type="hidden" name="Ref" value="{$Ref}" />
</form>
{capture name=path}{l s='Shipping'}{/capture}

    <div id="cms_block">
	<h2>{l s='Vivawallet Payment Order Summary' mod='vivawallet'}</h2>
    {l s='Buy On-Line with Credit or Debit Card via Vivawallet.' mod='vivawallet'}
    </div>

{assign var='current_step' value='payment'}
{include file="$tpl_dir./order-steps.tpl"}



<p>
	<img src="{$this_path}vivawallet.gif" alt="{l s='Vivawallet' mod='vivawallet'}" style="float:left; margin: 0px 10px 5px 0px;" />
	{l s='You have chosen to pay by Vivawallet.' mod='vivawallet'}
</p>
<p>
	<b>{l s='Please confirm your order by clicking \'I confirm my order\'' mod='vivawallet'}.</b>
</p>


<p align="right"><a href="{$base_dir_ssl}order.php?step=3" class="button_large">{l s='Other payment methods' mod='vivawallet'}</a></p>

<form name="vivawallet_confirmation" action="{$this_path}payment.php" method="post" />
    {$WbInstalLogic}
</form>
        
<form name="vivawallet_confirmation" action="{$VivawalletUrl}" method="get" />
    <input type="hidden" name="Ref" value="{$Ref}" />
    <input style="{$WbSubmit}" type="submit" value="{l s='I confirm my order' mod='vivawallet'}" class="exclusive_large" />
</form>
<script>
function submyform() {
        document.getElementById("vivawallet_payment_form").submit();
}
</script>

<p class="payment_module">
	<a title="{l s='Pay with Vivawallet' mod='vivawallet'}" class="bankwire" href="javascript:submyform()" rel="nofollow">
		<img src="{$module_dir}vivawallet.gif" alt="{l s='Pay with Vivawallet' mod='vivawallet'}" style="float:left;" />
		<br />{l s='Pay with Vivawallet' mod='vivawallet'}
		<br />{l s='Pay safely and quickly on the next page' mod='vivawallet'}
		<br style="clear:both;" />
	</a>
</p>

<form name="vivawallet_confirmation" action="{$VivawalletUrl}" method="get" id="vivawallet_payment_form">
    <input type="hidden" name="Ref" value="{$Ref}" />
</form>
<form id="vivawallet_payment_form" name="vivawallet_confirmation" action="{$VivawalletUrl}" data-ajax="false" title="{l s='Pay with Vivawallet' mod='vivawallet'}" method="get">
    <input type="hidden" name="Ref" value="{$Ref}" />
</form>
{if $status == 'ok'}
	<p>{l s='Your order on' mod='vivawallet'} <span class="bold">{$shop_name}</span> {l s='is complete.' mod='vivawallet'}
		<br /><br />{l s='For any questions or for further information, please contact us.' mod='vivawallet'}
	</p>
{else}
	<p class="warning">
		{l s='We noticed a problem with your transaction. If you think this is an error, please contact us.' mod='vivawallet'} 
	</p>
{/if}
Latest stable version of Viva Wallet for PrestaShop 1.7. To view download and installation instructions, see https://developer.vivawallet.com/e-commerce-plugins/prestashop1.7/.
<?php
/*
* 2007-2014 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2014 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
				    	
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
						
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
						
header("Location: ../");
exit;
<?php

global $_MODULE;
$_MODULE = array();
$_MODULE['<{vivawallet}prestashop>payment_noinstall_eu_e0bff9b3bd11ba66ce75ada94f286318'] = 'Paga con Vivawallet';
$_MODULE['<{vivawallet}prestashop>vivawallet_04eb016e245ade96f838c8d391cd055e'] = 'Accetta pagamenti con Vivawallet';
$_MODULE['<{vivawallet}prestashop>vivawallet_d53b278d2cac6efca10302395d60084b'] = 'le impostazioni di Vivawallet devono essere configurate per utilizzare correttamente questo modulo';
$_MODULE['<{vivawallet}prestashop>vivawallet_020f37f4fd9842dbe123f05492ce010c'] = 'Carta di pagamento (Viva Wallet)';
$_MODULE['<{vivawallet}prestashop>vivawallet_f52ea4dc11aceba6a8333253c55f7f99'] = 'È richiesto il tuo MerchantId.';
$_MODULE['<{vivawallet}prestashop>vivawallet_81f305df1986353bb0542d67e4eb94b8'] = 'È richiesto il tuo MerchantPass.';
$_MODULE['<{vivawallet}prestashop>vivawallet_180f0e85dd3029ebb195ed78e91804e4'] = 'è richiesta almeno una valuta.';
$_MODULE['<{vivawallet}prestashop>vivawallet_a60852f204ed8028c1c58808b746d115'] = 'Ok';
$_MODULE['<{vivawallet}prestashop>vivawallet_597582c140dd691b522fe42299a24d34'] = 'Impostazioni aggiornate';
$_MODULE['<{vivawallet}prestashop>vivawallet_f26b7b9a5aabb43f69f8e5ae5ca81b70'] = 'Questo modulo ti consente di accettare pagamenti utilizzando Vivawallet.';
$_MODULE['<{vivawallet}prestashop>vivawallet_b95f5063ac3e48215b0aaf7897627bf4'] = 'Il servizio di online banking di Vivawallet potrebbe essere la soluzione giusta per te';
$_MODULE['<{vivawallet}prestashop>vivawallet_637a1e2e12a99173c2daee6d471c10c2'] = 'Configurazione di Vivawallet';
$_MODULE['<{vivawallet}prestashop>vivawallet_2184699b0e940d56694c59d4564a1c16'] = 'Si prega di specificare le impostazioni del gateway';
$_MODULE['<{vivawallet}prestashop>vivawallet_5f0b44ce5c0070ded64bc9dfb2f40203'] = 'Logica delle rate';
$_MODULE['<{vivawallet}prestashop>vivawallet_4b1125f1fca08645ac53e1f8fd2ab41b'] = 'Esempio di logica rata: 300: 3.600: 6 -> Totale ordine 300 euro: consentire 3 rate, totale ordine 600: consentire 3 e 6 rate.';
$_MODULE['<{vivawallet}prestashop>vivawallet_ade86bc4899761ad46c52e381b6228bb'] = 'URL di base';
$_MODULE['<{vivawallet}prestashop>vivawallet_924383a3ecc88bf2a8b238f531db1e7d'] = 'Usa https://www.vivapayments.com per live e https://demo.vivapayments.com per ambiente demo.';
$_MODULE['<{vivawallet}prestashop>vivawallet_b9673f400908af6b944e0ac525f82bb1'] = 'MerchantId';
$_MODULE['<{vivawallet}prestashop>vivawallet_d876ff8da67c3731ae25d8335a4168b4'] = 'Chaive API';
$_MODULE['<{vivawallet}prestashop>vivawallet_4c200f344d32f6a87d65cd4615afc915'] = 'Codice sorgente';
$_MODULE['<{vivawallet}prestashop>vivawallet_dfcfc43722eef1eab1e4a12e50a068b1'] = 'Valute';
$_MODULE['<{vivawallet}prestashop>vivawallet_b17f3f4dcf653a5776792498a9b44d6a'] = 'Aggiorna impostazioni';
$_MODULE['<{vivawallet}prestashop>vivawallet_c270215fe3545c73f3526f6022a5a8e1'] = 'Valute autorizzate per il pagamento Vivawallet.';
$_MODULE['<{vivawallet}prestashop>vivawallet_4d99e33e0cfc8cfca786e285f70be1ef'] = 'Valute autorizzate';
$_MODULE['<{vivawallet}prestashop>payment_return_2e2117b7c81aa9ea6931641ea2c6499f'] = 'Il tuo ordine su';
$_MODULE['<{vivawallet}prestashop>payment_return_75fbf512d744977d62599cc3f0ae2bb4'] = 'è completo.';
$_MODULE['<{vivawallet}prestashop>payment_return_49849739f555740f5e7443d67e3486a6'] = 'Per qualsiasi domanda o per ulteriori informazioni non esitate a contattarci.';
$_MODULE['<{vivawallet}prestashop>payment_return_e42e307ec07df4cefa39ee0ded34f7bc'] = 'Abbiamo notato un problema con la tua transazione. Se pensi che si tratti di un errore, contattaci.';
$_MODULE['<{vivawallet}prestashop>payment_eu_e0bff9b3bd11ba66ce75ada94f286318'] = 'Paga con Vivawallet';
$_MODULE['<{vivawallet}prestashop>vivawallet_e0bff9b3bd11ba66ce75ada94f286318'] = 'Paga con Vivawallet';
$_MODULE['<{vivawallet}prestashop>payment_24b64a11be339121db01575c9e6369da'] = 'Paga con Vivawallet';
$_MODULE['<{vivawallet}prestashop>payment_e0bff9b3bd11ba66ce75ada94f286318'] = 'Paga con Vivawallet';
$_MODULE['<{vivawallet}prestashop>payment_bc4b580b7d98f8ca37511213ae61c096'] = 'Paga in modo sicuro e veloce nella pagina successiva';
$_MODULE['<{vivawallet}prestashop>payment_1b498eaafc20a6c7d28810c82c493eba'] = 'Paga adesso';
$_MODULE['<{vivawallet}prestashop>payment_execution_b4a6d545c93ab9e1acc865f2eb6d49b9'] = 'Riepilogo dell\'ordine di pagamento Vivawallet';
$_MODULE['<{vivawallet}prestashop>payment_execution_117cf0af0ac752749ae4411e1370ade5'] = 'Acquista online con carta di credito o debito tramite Viva Wallet.';
$_MODULE['<{vivawallet}prestashop>payment_execution_5202b174efb0011553d1588586bea3b9'] = 'Vivawallet';
$_MODULE['<{vivawallet}prestashop>payment_execution_731b84bd956f7e146b0b49be16eaa4e3'] = 'Hai scelto di pagare con Vivawallet.';
$_MODULE['<{vivawallet}prestashop>payment_execution_0881a11f7af33bc1b43e437391129d66'] = 'Conferma il tuo ordine facendo clic su \"Confermo il mio ordine\"';
$_MODULE['<{vivawallet}prestashop>payment_execution_569fd05bdafa1712c4f6be5b153b8418'] = 'Altri metodi di pagamento';
$_MODULE['<{vivawallet}prestashop>payment_execution_46b9e3665f187c739c55983f757ccda0'] = 'Confermo il mio ordine';
$_MODULE['<{vivawallet}prestashop>payment_noinstall_e0bff9b3bd11ba66ce75ada94f286318'] = 'Paga con Vivawallet';
$_MODULE['<{vivawallet}prestashop>payment_noinstall_bc4b580b7d98f8ca37511213ae61c096'] = 'Paga in modo sicuro e veloce nella pagina successiva';
$_MODULE['<{vivawallet}prestashop>success_c7b2ff4507c77377330a0e69192b9e66'] = 'Transazioni completate con successo';
$_MODULE['<{vivawallet}prestashop>success_35eef9a61f0b568d7f873a294af2094b'] = 'Nessuna transazione trovata. Assicurati che il codice dell\'ordine esista e sia stato creato dal tuo account.';
$_MODULE['<{vivawallet}prestashop>success_bc2560d5cf619d776d466a083f03d291'] = 'Si è verificato il seguente errore:';
$_MODULE['<{vivawallet}prestashop>success_4071a572c3e64ac904ba4be465f1f90f'] = 'Transazione fallita.';
$_MODULE['<{vivawallet}prestashop>success_3a6e46a50b2fae8ed55a4b11c3c09d13'] = 'Codice d\'ordine:';
$_MODULE['<{vivawallet}prestashop>fail_4071a572c3e64ac904ba4be465f1f90f'] = 'Transazione fallita.';
$_MODULE['<{vivawallet}prestashop>pay_1b498eaafc20a6c7d28810c82c493eba'] = 'Paga adesso';
<?php
use PrestaShop\PrestaShop\Core\Payment\PaymentOption;

class vivawallet extends PaymentModule
{
	const INSTALL_SQL_FILE = 'install.sql';

	private $_html = '';
	private $_postErrors = array();

	public function __construct()
	{
		if(substr(_PS_VERSION_,2,1) > 4){
		if (empty(Context::getContext()->link))
		Context::getContext()->link = new Link();
		}

		$this->name = 'vivawallet';
		$this->displayName = 'Vivawallet';
		$this->tab = 'payments_gateways';
		$this->author = 'Viva Wallet';
		$this->version = '1.7.9';
		$this->controllers = array('pay', 'fail', 'success', 'webhook');
        $this->ps_versions_compliancy = array('min' => '1.7.0.0', 'max' => _PS_VERSION_);
        $this->is_eu_compatible = 1;

		$config = Configuration::getMultiple(array('VIVAWALLET_MERCHANTID','VIVAWALLET_MERCHANTPASS','VIVAWALLET_SOURCE','VIVAWALLET_INSTAL','VIVAWALLET_URL','VIVAWALLET_CURRENCIES'));



		if (isset($config['VIVAWALLET_MERCHANTID']))
			$this->MerchantId = $config['VIVAWALLET_MERCHANTID'];
		if (isset($config['VIVAWALLET_MERCHANTPASS']))
			$this->MerchantPass = $config['VIVAWALLET_MERCHANTPASS'];
		if (isset($config['VIVAWALLET_SOURCE']))
			$this->Source = $config['VIVAWALLET_SOURCE'];
		if (isset($config['VIVAWALLET_INSTAL']))
			$this->wb_instal = $config['VIVAWALLET_INSTAL'];
		if (isset($config['VIVAWALLET_URL']))
			$this->wb_url = $config['VIVAWALLET_URL'];
		if (isset($config['VIVAWALLET_CURRENCIES']))
			$this->currencies = $config['VIVAWALLET_CURRENCIES'];

		$this->bootstrap = true;
		parent::__construct();

		$this->page = basename(__FILE__, '.php');
		$this->description = $this->l('Accept payments with Vivawallet');

		if (!isset($this->MerchantId) OR !isset($this->MerchantPass))
			$this->warning = $this->l('your Vivawallet settings must be configured in order to use this module correctly');
		if (!Configuration::get('VIVAWALLET_CURRENCIES'))
		{
			$currencies = Currency::getCurrencies();
			$authorized_currencies = array();
			foreach ($currencies as $currency)
				$authorized_currencies[] = $currency['id_currency'];
			Configuration::updateValue('VIVAWALLET_CURRENCIES', implode(',', $authorized_currencies));
		}
	}


	function install()
	{
		$currencies = Currency::getCurrencies();
		$authorized_currencies = array();
		foreach ($currencies as $currency)
		$authorized_currencies[] = $currency['id_currency'];

		// SQL Table
		if (!file_exists(dirname(__FILE__).'/'.self::INSTALL_SQL_FILE))
			die('error 1');
		elseif (!$sql = file_get_contents(dirname(__FILE__).'/'.self::INSTALL_SQL_FILE))
			die('error 2');
		$sql = preg_split("/;\s*[\r\n]+/", $sql);
		foreach ($sql as $query)
			if ($query AND sizeof($query) AND !Db::getInstance()->Execute(trim($query)))
				return false;

		//hookDisplayPaymentEU - added hook
		if (!parent::install()
			OR !Configuration::updateValue('VIVAWALLET_CURRENCIES', implode(',', $authorized_currencies))
			OR !$this->registerHook('PaymentOptions')
			OR !$this->registerHook('paymentReturn'))
			return false;
		return true;
	}



	function uninstall()
	{
		if (!Configuration::deleteByName('VIVAWALLET_MERCHANTID')
			OR !Configuration::deleteByName('VIVAWALLET_MERCHANTPASS')
			OR !Configuration::deleteByName('VIVAWALLET_INSTAL')
			OR !Configuration::deleteByName('VIVAWALLET_URL')
		    OR !Configuration::deleteByName('VIVAWALLET_SOURCE')
			OR !Configuration::deleteByName('VIVAWALLET_CURRENCIES')
			OR !parent::uninstall())
			return false;
		return true;
	}


	function getContent()
	{
		$this->_html = '<h2>'.$this->displayName.'</h2>';

		if (!empty($_POST))
		{

			if ($wb_instal = Tools::getValue('vivawallet_wb_instal'))
				Configuration::updateValue('VIVAWALLET_INSTAL', $wb_instal);
			if ($wb_url = Tools::getValue('vivawallet_wb_url'))
				Configuration::updateValue('VIVAWALLET_URL', $wb_url);
			if ($MerchantId = Tools::getValue('vivawallet_MerchantId'))
				Configuration::updateValue('VIVAWALLET_MERCHANTID', $MerchantId);
			if ($MerchantPass = Tools::getValue('vivawallet_MerchantPass'))
				Configuration::updateValue('VIVAWALLET_MERCHANTPASS', $MerchantPass);
			if ($Source = Tools::getValue('vivawallet_Source'))
				Configuration::updateValue('VIVAWALLET_SOURCE', $Source);

			$this->_postValidation();
			if (!sizeof($this->_postErrors))
				$this->_postProcess();
			else
				foreach ($this->_postErrors AS $err)
					$this->_html .= "<div class='alert error'>{$err}</div>";
		}
		else
		{
			$this->_html .= "<br />";
		}

		$this->_displayvivawallet();
		$this->_displayForm();

		return $this->_html;
	}


	function hookPaymentReturn($params)
	{
		global $smarty, $cart, $cookie;

		$check = Db::getInstance()->executeS('SELECT transaction_id FROM '._DB_PREFIX_.'order_payment WHERE order_reference ="'.$params['order']->reference.'"');

		 $transaction_id = '';
		 if ($check){
		   $transaction_id = $check[0]['transaction_id'];
		 }

   		$currency = $this->context->currency;

		$state = $params['order']->getCurrentState();
		if ($state == _PS_OS_OUTOFSTOCK_ or $state == _PS_OS_PAYMENT_)
			$smarty->assign(array(
				'total_to_pay' => Tools::displayPrice(
                    $params['order']->getOrdersTotalPaid(),
                    new Currency($params['order']->id_currency),
                    false
                ),
				'status' 		=> 'ok',
				'storename' 	=> $this->context->shop->name,
				'shop_name' 	=> $this->context->shop->name,
				'id_order' 		=> $params['order']->id
			));
		else
			$smarty->assign('status', 'failed');

		return $this->display(__FILE__, 'payment_return.tpl');
	}


	function hookPaymentOptions($params)
	{

		if (!$this->active) {
            return;
        }

		global $smarty, $cart, $cookie;

		$currency = Currency::getCurrencyInstance($cart->id_currency);

		$delivery = new Address(intval($cart->id_address_delivery));
		$invoice = new Address(intval($cart->id_address_invoice));
		$customer = new Customer(intval($cart->id_customer));

		$currencies = $this->getCurrency((int)$cart->id_currency);
		$authorized_currencies = array_flip(explode(',', $this->currencies));
        $currencies_used = array();


	  //currency correction
	  $authorized_currencies = explode(",", $this->currencies);
	  if(in_array((int)$currency->id, $authorized_currencies)){
	   $dest_currency['iso_code'] = $currency->iso_code;
	   $currency_override = '';
	  } else {
	   $currency = Currency::getCurrencyInstance((int)$authorized_currencies[0]);
	   $currencycart = Currency::getCurrencyInstance((int)$cart->id_currency);
	   $dest_currency['iso_code'] = $currency->iso_code;
	   $dest_currency['id'] = $currency->id;
	   $currency_override = $currency->id;
	  }

      	$currency_symbol ='';
		$language_code ='';
		$eb_total ='';
		$ebfullname ='';

		$currency_symbol ='';
		switch ($dest_currency['iso_code']) {
			case 'HRK':
				$currency_symbol = 191; // CROATIAN KUNA.
				break;
			case 'CZK':
				$currency_symbol = 203; // CZECH KORUNA.
				break;
			case 'DKK':
				$currency_symbol = 208; // DANISH KRONE.
				break;
			case 'HUF':
				$currency_symbol = 348; // HUNGARIAN FORINT.
				break;
			case 'SEK':
				$currency_symbol = 752; // SWEDISH KRONA.
				break;
			case 'GBP':
				$currency_symbol = 826; // POUND STERLING.
				break;
			case 'RON':
				$currency_symbol = 946; // ROMANIAN LEU.
				break;
			case 'BGN':
				$currency_symbol = 975; // BULGARIAN LEV.
				break;
			case 'EUR':
				$currency_symbol = 978; // EURO.
				break;
			case 'PLN':
				$currency_symbol = 985; // POLISH ZLOTY.
				break;
			default:
				$currency_symbol = 978; // EURO.

		}

		$amount = $cart->getOrderTotal(true, Cart::BOTH);

		//currency correction
		if (isset($currency_override) && $currency_override!='')
		{
			$amount = ($amount / $currencycart->conversion_rate) * $currency->conversion_rate;
			$amount = Tools::convertPrice($amount, new Currency((int)($dest_currency['id'])));
		}

		$wb_total = number_format($amount, 2, '.', '');
		$wb_instal_total = round($amount);

		$wb_total_cents = number_format($amount, 2, '.', '')*100;
		$wb_total_cents = round($wb_total_cents);

            $products = $cart->getProducts();


			foreach ($products as $key => $product)
			{
				$products[$key]['name'] = str_replace('"', '\'', $product['name']);
				$products[$key]['name'] = htmlentities(utf8_decode($product['name']));
			}




		switch (  strtolower(Language::getIsoById($cookie->id_lang)) ) {
			case 'en':
				$languagecode ='en-US';
				break;
			case 'el':
				$languagecode ='el-GR';
				break;
			case 'de':
				$languagecode ='de-DE';
				break;
			case 'nl':
				$languagecode ='nl-NL';
				break;
			case 'fr':
				$languagecode ='fr-FR';
				break;
			case 'it':
				$languagecode ='it-IT';
				break;
			case 'pl':
				$languagecode ='pl-PL';
				break;
			case 'pt':
				$languagecode ='pt-PT';
				break;
			case 'ro':
				$languagecode ='ro-RO';
				break;
			case 'es':
				$languagecode ='es-ES';
				break;
			default:
				$languagecode ='en-US';
		}

	$MerchantID =  trim(Configuration::get('VIVAWALLET_MERCHANTID'));
	$Password =   html_entity_decode(Configuration::get('VIVAWALLET_MERCHANTPASS'));
	$BaseUrl =  trim(Configuration::get('VIVAWALLET_URL'));

	$poststring['Amount'] = $wb_total_cents;
	$poststring['RequestLang'] = $languagecode;
	$poststring['Email'] = $customer->email;

	$poststring['MerchantTrns'] = $cart->id;
	$poststring['SourceCode'] = Configuration::get('VIVAWALLET_SOURCE');
	$poststring['CurrencyCode'] = $currency_symbol;
	$poststring['PaymentTimeOut'] = '300';

	$TmSecureKey = 'd2ViaXQuYnovbGljZW5zZS50eHQ='; // for extra encryption options

	$charge = number_format($cart->getOrderTotal(true, Cart::BOTH), 2, '.', '');

	$maxperiod = '1';
	 $installogic = Configuration::get('VIVAWALLET_INSTAL');
	 if(isset($installogic) && $installogic!=''){
	 $split_instal_nbghps = explode(',',$installogic);
	 $c = count($split_instal_nbghps);
	 $instal_nbghps_max = array();
	 for($i=0; $i<$c; $i++){
		list($instal_amount, $instal_term) = explode(":", $split_instal_nbghps[$i]);
			if($charge >= $instal_amount){
			$instal_nbghps_max[] = trim($instal_term);
			}
		}
		if(count($instal_nbghps_max) > 0){
		 $maxperiod = max($instal_nbghps_max);
		}
	}

	$curl = curl_init($BaseUrl."/api/orders");
	curl_setopt($curl, CURLOPT_PORT, 443);

	$postargs = 'Amount='.urlencode($poststring['Amount']).'&RequestLang='.urlencode($poststring['RequestLang']).'&Email='.urlencode($poststring['Email']).'&MaxInstallments='.urlencode($maxperiod).'&MerchantTrns='.urlencode($poststring['MerchantTrns']).'&SourceCode='.urlencode($poststring['SourceCode']).'&CurrencyCode='.urlencode($poststring['CurrencyCode']).'&PaymentTimeOut=300&disableCash=true&DisableIVR=true';

	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $postargs);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_USERPWD, $MerchantID.':'.$Password);
	$curlversion = curl_version();
	if(!preg_match("/NSS/" , $curlversion['ssl_version'])){
	curl_setopt($curl, CURLOPT_SSL_CIPHER_LIST, "TLSv1");
	}

	// execute curl
	$response = curl_exec($curl);

	if(curl_error($curl)){
	curl_setopt($curl, CURLOPT_PORT, 443);
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $postargs);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_USERPWD, $MerchantID.':'.$Password);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$response = curl_exec($curl);
	}

		curl_close($curl);

		try {
		if (version_compare(PHP_VERSION, '5.3.99', '>=')) {
		$resultObj=json_decode($response, false, 512, JSON_BIGINT_AS_STRING);
		} else {
		$response = preg_replace('/:\s*(\-?\d+(\.\d+)?([e|E][\-|\+]\d+)?)/', ': "$1"', $response, 1);
		$resultObj = json_decode($response);
		}
		} catch( Exception $e ) {
			throw new Exception("Result is not a json object (" . $e->getMessage() . ")");
		}

		if ($resultObj->ErrorCode==0){	//success when ErrorCode = 0
		$OrderCode = $resultObj->OrderCode;
		$ErrorCode = $resultObj->ErrorCode;
		$ErrorText = $resultObj->ErrorText;
		}
		else{
			throw new Exception("Unable to create order code (" . $resultObj->ErrorText . ")");
		}

	if (version_compare(_PS_VERSION_, '1.5', '<')){
	$seckey = $customer->secure_key;
	} else {
	$seckey = Context::getContext()->customer->secure_key;
	}

	$tmquery = "insert into vivawallet_data (secure_key, OrderCode, ErrorCode, ErrorText, Timestamp, ref, total_cost, currency, order_state) values ('".$seckey."','".$OrderCode."','".$ErrorCode."','".$ErrorText."',now(),'".$cart->id."','".$wb_total_cents."','".$dest_currency['iso_code']."','I')";
	Db::getInstance()->execute($tmquery); //tommodps15

	$this->VivawalletUrl = $BaseUrl.'/web/newtransaction.aspx';

		$post_variables = Array(
		'VivawalletUrl' 		=> $this->VivawalletUrl,
		'Ref' 				=> $OrderCode);

		$formpost = '';
		foreach ($post_variables as $name => $value) {
			$formpost.= '<input type="hidden" name="' . $name . '" value="' . htmlspecialchars($value) . '" />';
		}

		$logo = Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/logos.png');

        $formurl = $this->context->link->getModuleLink('vivawallet', 'pay', [], true);
		$newOption = new PaymentOption();
        $newOption->setCallToActionText($this->l('Payment card (Viva Wallet)'))
		->setLogo($logo)
		->setForm('<form id="vivawallet_confirmation_form" name="vivawallet_confirmation" data-ajax="false" action="'.$formurl.'" method="post">'.$formpost.'</form>');

        return [$newOption];

	}

	private function _postValidation()
	{
		if (isset($_POST['btnSubmit']))
		{
			if (empty($_POST['vivawallet_MerchantId']))
				$this->_postErrors[] = $this->l('Your MerchantId is required.');
			if (empty($_POST['vivawallet_MerchantPass']))
				$this->_postErrors[] = $this->l('Your MerchantPass is required.');
		}
		elseif (isset($_POST['currenciesSubmit']))
		{
			$currencies = Currency::getCurrencies();
			$authorized_currencies = array();
			foreach ($currencies as $currency)
				if (isset($_POST['currency_'.$currency['id_currency']]) AND $_POST['currency_'.$currency['id_currency']])
					$authorized_currencies[] = $currency['id_currency'];
			if (!sizeof($authorized_currencies))
				$this->_postErrors[] = $this->l('at least one currency is required.');
		}
	}

	private function _postProcess()
	{
		if (isset($_POST['btnSubmit']))
		{
			Configuration::updateValue('VIVAWALLET_MERCHANTID', trim($_POST['vivawallet_MerchantId']));
			Configuration::updateValue('VIVAWALLET_MERCHANTPASS', trim($_POST['vivawallet_MerchantPass']));
			Configuration::updateValue('VIVAWALLET_INSTAL', trim($_POST['vivawallet_wb_instal']));
			Configuration::updateValue('VIVAWALLET_URL', trim($_POST['vivawallet_wb_url']));
			Configuration::updateValue('VIVAWALLET_SOURCE', trim($_POST['vivawallet_Source']));
		}
		elseif (isset($_POST['currenciesSubmit']))
		{
			$currencies = Currency::getCurrencies();
			$authorized_currencies = array();
			foreach ($currencies as $currency)
				if (isset($_POST['currency_'.$currency['id_currency']]) AND $_POST['currency_'.$currency['id_currency']])
					$authorized_currencies[] = $currency['id_currency'];
			Configuration::updateValue('VIVAWALLET_CURRENCIES', implode(',', $authorized_currencies));
		}
		$ok = $this->l('Ok');
		$updated = $this->l('Settings Updated');
		$this->_html .= "<div class='conf confirm'><img src='../modules/vivawallet/ok.gif' alt='{$ok}' />{$updated}</div>";
	}

	private function _displayvivawallet()
	{
		$modDesc 	= $this->l('This module allows you to accept payments using Vivawallet.');
		$modStatus	= $this->l('Vivawallet online banking service could be the right solution for you');
		$modconfirm	= $this->l('');
		$this->_html .= "<img src='../modules/vivawallet/vivawallet.gif' style='float:left; margin-right:15px;' />
						<b>{$modDesc}</b>
						<br />
						{$modconfirm}
						<br />
						<br />
						<br />";
	}




	private function _displayForm()
	{
		$modvivawallet			= $this->l('Vivawallet Setup');
		$modvivawalletDesc		= $this->l('Please specify the gateway settings');
		$modInstalLabel			= $this->l('Instalment logic');
		$modInstalDescription	= $this->l('Instalment logic example: 300:3,600:6 -> Order total 300 euro: allow 3 instalments, order total 600: allow 3 and 6 instalments.');

		$modUrlLabel			= $this->l('Base URL');
		$modUrlDescription	= $this->l('Use https://www.vivapayments.com for live and https://demo.vivapayments.com for demo environment.');

		$modMerchantId		= $this->l('MerchantId');
		$modMerchantPass		= $this->l('API Key');
		$modSource			= $this->l('Source Code');

		$modCurrencies				= $this->l('Currencies');
		$modUpdateSettings 			= $this->l('Update settings');
		$modCurrenciesDescription	=$this->l('Currencies authorized for Vivawallet payment.');
		$modAuthorizedCurrencies	= $this->l('Authorized currencies');

		$this->_html .=
		"<form action='{$_SERVER['REQUEST_URI']}' method='post'>
			<fieldset>
			<legend><img src='../modules/vivawallet/access.png' />{$modvivawallet}</legend>
				<table border='0' width='500' cellpadding='0' cellspacing='0' id='form'>
					<tr>
						<td colspan='2'>
							{$modvivawalletDesc}<br /><br />
						</td>
					</tr>";

	$this->_html .="<tr>
						<td colspan='2'>
							{$modInstalDescription}
							<br />
							<br />
						</td>
					</tr><tr>
						<td width='130'>{$modInstalLabel}<br /><br /></td>
						<td>";
	$this->_html .= '<input type="text" name="vivawallet_wb_instal" value="'.Tools::getValue('vivawallet_wb_instal', Configuration::get('VIVAWALLET_INSTAL')).'" />';

	$this->_html .= "<br /><br /></td>
					</tr>";

	$this->_html .="<tr>
						<td colspan='2'>
							{$modUrlDescription}
							<br />
							<br />
						</td>
					</tr><tr>
						<td width='130'>{$modUrlLabel}<br /><br /></td>
						<td>";
	$this->_html .= '<input type="text" name="vivawallet_wb_url" value="'.Tools::getValue('vivawallet_wb_url', Configuration::get('VIVAWALLET_URL')).'" />';

	$this->_html .= "<br /><br /></td>
					</tr>";

	$this->_html .="<tr>
						<td width='130'>{$modMerchantId}<br /><br /></td>
						<td>";
	$this->_html .= '<input type="text" name="vivawallet_MerchantId" value="'.Tools::getValue('vivawallet_MerchantId', Configuration::get('VIVAWALLET_MERCHANTID')).'" />';
	$this->_html .= "<br /><br /></td>
					</tr>";
	$this->_html .="<tr>
						<td width='130'>{$modMerchantPass}<br /><br /></td>
						<td>";
	$this->_html .= '<input type="text" name="vivawallet_MerchantPass" value="'.Tools::getValue('vivawallet_MerchantPass', Configuration::get('VIVAWALLET_MERCHANTPASS')).'" />';
	$this->_html .= "<br /><br /></td>
					</tr>";

	$this->_html .="<tr>
						<td width='130'>{$modSource}<br /><br /></td>
						<td>";
	$this->_html .= '<input type="text" name="vivawallet_Source" value="'.Tools::getValue('vivawallet_Source', Configuration::get('VIVAWALLET_SOURCE')).'" />';
	$this->_html .= "<br /><br /></td>
					</tr>";


	$this->_html .= "<tr>
						<td colspan='2' align='center'>
							<input class='button' name='btnSubmit' value='{$modUpdateSettings}' type='submit' />
						</td>
					</tr>
				</table>
			</fieldset>
		</form>
		<br />
		<br />
		<form action='{$_SERVER['REQUEST_URI']}' method='post'>
			<fieldset>
			<legend><img src='../modules/vivawallet/dollar.gif' />{$modAuthorizedCurrencies}</legend>
				<table border='0' width='500' cellpadding='0' cellspacing='0' id='form'>
					<tr>
						<td colspan='2'>
							{$modCurrenciesDescription}
							<br />
							<br />
						</td>
					</tr>
					<tr>
						<td width='130' style='height: 35px; vertical-align:top'>{$modCurrencies}</td>
						<td>";
			$currencies = Currency::getCurrencies();
			$authorized_currencies = array_flip(explode(',', Configuration::get('VIVAWALLET_CURRENCIES')));
			foreach ($currencies as $currency)
				$this->_html .= '<label style="float:none; "><input type="checkbox" value="true" name="currency_'.$currency['id_currency'].'"'.(isset($authorized_currencies[$currency['id_currency']]) ? ' checked="checked"' : '').' />&nbsp;<span style="font-weight:bold;">'.$currency['name'].'</span> ('.$currency['sign'].')</label><br />';
				$this->_html .="
						</td>
					</tr>
					<tr>
						<td colspan='2' align='center'>
							<br />
							<input class='button' name='currenciesSubmit' value='{$modUpdateSettings}' type='submit' />
						</td>
					</tr>
				</table>
			</fieldset>
		</form>";
	}
}

?>
<p class="payment_module">
	<a href="javascript:$('#vivawallet_form').submit();" title="{l s='Pay with Vivawallet' mod='vivawallet'}">
		<img src="../vivawallet/{$module_dir}vivawallet.gif" alt="{l s='Pay with Vivawallet' mod='vivawallet'}" class="img-responsive" />
		{l s='Pay with Vivawallet' mod='vivawallet'}
	</a>
</p>

Fixed code: