<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: SecurepayModel.php, v 1.0 2011/06/14 20:52:11
//
class SecurepayModel extends PaymentModel
{
    //FUNCTION TO PROCESS ORDERS
    public function process($order = '', $orderItems = '')
    {
		$ObjCurrency		= new CurrencyModel();
        parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);
        $paymentCurrency                        = $this->settingsVars["payment_currency"];
        $merchantID                             = urlencode($this->settingsVars["payment_login"]);
        $merchantPassword                       = urlencode($this->settingsVars["payment_login_password"]);
        $postURL                                = trim($this->settingsVars["payment_gateway_url"]) == "" ?
		"http://test.securepay.com.au/securepay/payments/process2.asp" : trim($this->settingsVars["payment_gateway_url"]);
		$payAmount    = $order['orderTotalAmount'];
        $taxAmount    = $order["orderTaxAmount"];
        $currencyArr  = '';
		if ($paymentCurrency != '')
		{
			$paymentCurrency = str_replace(", ", ",", $paymentCurrency);
			$currencyArr     = explode(",", $paymentCurrency);
		}
		if(count($currencyArr)<1)
		{
			$this->isError 		= true;
			$this->errorMessage	= "Currency not configured , Please contact the site admin";
			return false;
		}
		else
		{
			$currencyFlag = false;
			$purchasedCurrencyDetails 	= $ObjCurrency->getCurrencyByCurrencyID($order["purchasedCurrency"]);
			$currencyCode				= $purchasedCurrencyDetails['currencyCode'];
			$systemCurrencies 			=	$ObjCurrency->listCurrencyCodes();
			if(!in_array($purchasedCurrencyDetails['currencyCode'],$currencyArr))
			{
				foreach ($systemCurrencies as $key => $currency)
				{
					if(in_array($currency['currencyCode'],$currencyArr))
					{
						$currencyFlag = true;
						$supportedCurrencyCode 	= $currency['currencyCode'];	
						$supportedCurrencyID 	= $currency['currencyID'];
						break;
					}
				}
				if($currencyFlag==true)
				{
					$payAmount = $ObjCurrency->convertValueCustom($payAmount,$order["purchasedCurrency"],$supportedCurrencyID);
					$taxAmount = $ObjCurrency->convertValueCustom($taxAmount,$order["purchasedCurrency"],$supportedCurrencyID);
					$currencyCode		=	$supportedCurrencyCode;
				}
				else
				{
					$this->isError 		= true;
					$this->errorMessage	= "Currency not configured , Please contact the site admin";
					return false;
				}
				
			}
		}
		
		
		if ($order['authValue'] == 'Authorization')
        {
            $authOnly = 10;
        }
        else
        {
            $authOnly = 0;
        }
        $authOnly              = 0;
        $totalAmnt             = $payAmount;
		$messageId             = $order['masterOrderID'] . date("his") . current(explode(' ', microtime()));
		$totalAmnt_new         = (number_format(ceil($totalAmnt), 2)) * 100;
        $_SESSION['MessageId'] = $messageId;
        $requestMessage                     = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . 
		"<SecurePayMessage>" . "<MessageInfo>" . "<messageID>" . $messageId . "</messageID>" . 
		"<messageTimestamp>" . $this->getGMTTimeStamp() . "</messageTimestamp>" . "<timeoutValue>60</timeoutValue>" . 
		"<apiVersion>xml-4.2</apiVersion>" . "</MessageInfo>" . "<MerchantInfo>" . "<merchantID>" . $merchantID . 
		"</merchantID>" . "<password>" . $merchantPassword . "</password>" . "</MerchantInfo>" . "<RequestType>Payment
		</RequestType>" . "<Payment>" . "<TxnList count=\"1\">" . "<Txn ID=\"1\">" . "<txnType>".$authOnly."</txnType>" . 
		"<txnSource>23</txnSource>" . "<currency>" . $currencyCode . "</currency>" . "<amount>" . $totalAmnt_new . "</amount>" . 
		"<purchaseOrderNo>" . $order['masterOrderID'] . "</purchaseOrderNo>" . "<CreditCardInfo>" . "<cardNumber>"
		. $order['postData']['creditCardNumber'] . "</cardNumber>";
        if (trim($order['postData']['securityCode']) <> "")
        {
            $requestMessage .= "<cvv>" . $order['postData']['securityCode'] . "</cvv>";
        }
        $requestMessage .= "<expiryDate>" . sprintf("%02d", $order['postData']['expMonth']) . "/" . 
		substr($order['postData']['expYear'], 2) . "</expiryDate>" . "</CreditCardInfo>" . "</Txn>" . "</TxnList>" . 
		"</Payment>" . "</SecurePayMessage>";
		
        $this->responseArray["raw-XML-request"] = htmlentities($requestMessage);
        $ch                                     = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $requestMessage);
        $result             = curl_exec($ch);
        $debugoutput        = curl_getinfo($ch);
        $curl_error_message = curl_error($ch); // must retrieve an error message (if any) before closing the curl object
        curl_close($ch);
        $xml_array = $this->XML2Array($result);
        $messageID = (isset($xml_array['MessageInfo']['messageID'])?$xml_array['MessageInfo']['messageID']:0);
        $response  = (isset($xml_array['Payment']['TxnList']['Txn']['approved'])?$xml_array['Payment']['TxnList']['Txn']['approved']:'');
        if (strtolower($response) == 'yes' && trim($xml_array['Payment']['TxnList']['Txn']['responseText']) == 'Approved')
        {
            $response = true;
        }
        else
        {
            $response = false;
        }
        if ($result === false)
        {
            $this->isError     = true;
            $this->errorString = 'CURL failed and reported the following error : ' . $curl_error_message;
            return "Failure";
        }
        if ($response === false)
        {
            $error_status_code  = $xml_array['Status']['statusDescription'];
            $this->isError      = true;
            $this->errorMessage = "A general response error was detected :" . (isset($xml_array['Payment']['TxnList']['Txn']['responseText'])?$xml_array['Payment']['TxnList']['Txn']['responseText']:'') . ' ' . $error_status_code;
            return "Failure";
        }
        if ($response)
        {
            if ($_SESSION['MessageId'] == $messageID)
            {
                $authOnly      = 'AUTH_ONLY';
                $transactionID = $xml_array['Payment']['TxnList']['Txn']['txnID'];
                $amnt          = trim($xml_array['Payment']['TxnList']['Txn']['amount']) / 100;
                $httpResponse  = "Message id:" . trim($xml_array['MessageInfo']['messageID']) . "~" . "\n";
                $httpResponse .= "messageTimestamp:" . trim($xml_array['MessageInfo']['messageTimestamp']) . "~" . "\n";
                $httpResponse .= "API Version:" . trim($xml_array['MessageInfo']['apiVersion']) . "~" . "\n";
                $httpResponse .= "RequestType:" . trim($xml_array['RequestType']) . "~" . "\n";
                $httpResponse .= "MerchantID:" . trim($xml_array['MerchantInfo']['merchantID']) . "~" . "\n";
                $httpResponse .= "TxnType:" . trim($xml_array['Payment']['TxnList']['Txn']['txnType']) . "~" . "\n";
                $httpResponse .= "TxnSource:" . trim($xml_array['Payment']['TxnList']['Txn']['txnSource']) . "~" . "\n";
                $httpResponse .= "Amount:" . $amnt . "~" . "\n";
                $httpResponse .= "Currency:" . $xml_array['Payment']['TxnList']['Txn']['currency'] . "~" . "\n";
                $httpResponse .= "Approved:" . trim($xml_array['Payment']['TxnList']['Txn']['approved']) . "~" . "\n";
                $httpResponse .= "Response Code:" . trim($xml_array['Payment']['TxnList']['Txn']['responseCode']) . "~" . "\n";
                $httpResponse .= "Response Text:" . trim($xml_array['Payment']['TxnList']['Txn']['responseText']) . "~" . "\n";
                $httpResponse .= "Bank txnID:" . trim($xml_array['Payment']['TxnList']['Txn']['txnID']) . "~" . "\n";
                $httpResponse .= "API Version:" . trim($xml_array['Periodic']['PeriodicList']['PeriodicItem']['CreditCardInfo']['pan']) . "~" . "\n";
                $httpResponse .= "Pre Auth ID:" . trim($xml_array['Payment']['TxnList']['Txn']['preauthID']) . "~" . "\n";
                $httpResponse .= "ExpiryDate:" . trim($xml_array['Payment']['TxnList']['Txn']['CreditCardInfo']['expiryDate']);
                $paymentMethodName    = $this->settingsVars["payment_method_name"];
				if($order['authValue']=='Authorization') 
				{
					$authOnly	=	'AUTH_ONLY';	
				} 
				else 
				{				
					$authOnly	=	'AUTH_CAPTURE';		
				}
                parent::createTransaction($order, $transactionID, $httpResponse, "", $authOnly, 0, $paymentMethodName,$supportedCurrencyID,$payAmount);
                if ($order['store_cc_info'] == 'Yes')
                {
                    parent::saveCCdata($order['postData'], $order["userID"]);
                }
                $this->isError      = false;
                $this->errorMessage = "";
                return "Pending";
            }
        }
    }
    //END OF FUNCTION		
    //FUNCTION TO GET RESULT BY KEY NAME
    public function getResultByKeyName($keyName)
    {
        if (array_key_exists($keyName, $this->responseArray) === true)
        {
            return $this->responseArray[$keyName];
        }
        else
            return false;
    }
    //END OF FUNCTION	
    //FUNCTION TO PROCESS TRANSACTION RESPONSE	
    private function processTransactionResponseMessageIntoResponseArray($responseMessage)
    {
        $xmlres = array();
        $xmlres = $this->convertXMLToNestedArray($responseMessage);
        if ($xmlres === false)
        {
            if (strlen($this->errorString) == 0)
            {
                $this->errorString = "An unspecified error was found in the response message (missing field?)";
            }
            return false;
        }
        $responseArray["raw-XML-response"]  = htmlentities($responseMessage);
        $statusCode                         = trim($xmlres['SecurePayMessage']['Status']['statusCode']);
        $statusDescription                  = trim($xmlres['SecurePayMessage']['Status']['statusDescription']);
        $responseArray["statusCode"]        = $statusCode;
        $responseArray["statusDescription"] = $statusDescription;
        // Three digit codes indicate a repsonse from the Securepay gateway (error detected by gateway) 
        if (strcmp($statusCode, '000') != 0)
        {
            $this->errorString = "The remote Gateway reported the following status error: " . $statusCode . " " . $statusDescription;
            return false;
        }
        $responseArray["messageID"]        = trim($xmlres['SecurePayMessage']['MessageInfo']['messageID']);
        $responseArray["messageTimestamp"] = trim($xmlres['SecurePayMessage']['MessageInfo']['messageTimestamp']);
        $responseArray["apiVersion"]       = trim($xmlres['SecurePayMessage']['MessageInfo']['apiVersion']);
        $responseArray["RequestType"]      = trim($xmlres['SecurePayMessage']['RequestType']);
        $responseArray["merchantID"]       = trim($xmlres['SecurePayMessage']['MerchantInfo']['merchantID']);
        $responseArray["txnType"]          = trim($xmlres['SecurePayMessage']['Payment']['TxnList']['Txn']['txnType']);
        $responseArray["txnSource"]        = trim($xmlres['SecurePayMessage']['Payment']['TxnList']['Txn']['txnSource']);
        $responseArray["amount"]           = (trim($xmlres['SecurePayMessage']['Payment']['TxnList']['Txn']['amount'])) / 100;
        $responseArray["approved"]         = trim($xmlres['SecurePayMessage']['Payment']['TxnList']['Txn']['approved']);
        $responseArray["responseCode"]     = trim($xmlres['SecurePayMessage']['Payment']['TxnList']['Txn']['responseCode']);
        $responseArray["responseText"]     = trim($xmlres['SecurePayMessage']['Payment']['TxnList']['Txn']['responseText']);
        $responseArray["banktxnID"]        = trim($xmlres['SecurePayMessage']['Payment']['TxnList']['Txn']['txnID']);
        $responseArray["creditCardPAN"]    = trim($xmlres['SecurePayMessage']['Periodic']['PeriodicList']['PeriodicItem']['CreditCardInfo']['pan']);
        $responseArray["expiryDate"]       = trim($xmlres['SecurePayMessage']['Payment']['TxnList']['Txn']['CreditCardInfo']['expiryDate']);
        $this->responseArray               = $responseArray;
        // field "successful" = "Yes" means "triggered transaction successfully registered", anything else is failure
        // responseCode "00" indicates approved, "08" is Honor with ID (approved) and "77" is Approved (ANZ only). Any other 2 digit code is a decline or error from the bank.
        if ((strcasecmp($responseArray["approved"], "Yes") == 0) && (strcmp($responseArray["responseCode"], "00") === 0 || strcmp($responseArray["responseCode"], "08") === 0 || strcmp($responseArray["responseCode"], "77") === 0))
        {
            return true;
        }
        else
        {
            $this->errorString = "Transaction Declined: " . $responseArray["responseCode"] . " " . $responseArray["responseText"];
            return false;
        }
    }
    //FUNCTION TO CONVERT XML TO NEST ARRAY
    private function convertXMLToNestedArray($XMLDocument)
    {
        $output = array();
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        $parse_result = xml_parse_into_struct($parser, $XMLDocument, $values);
        if ($parse_result === 0)
        {
            $this->errorString = "A unspecified error was detected in the response content : " . xml_get_error_code($parser) . " " . xml_error_string(xml_get_error_code($parser));
            xml_parser_free($parser);
            return false;
        }
        xml_parser_free($parser);
        $hash_stack = array();
        foreach ($values as $val)
        {
            switch ($val['type'])
            {
                case 'open':
                    array_push($hash_stack, $val['tag']);
                    break;
                case 'close':
                    array_pop($hash_stack);
                    break;
                case 'complete':
                    array_push($hash_stack, $val['tag']);
                    if (array_key_exists('value', $val))
                        eval("\$output['" . implode($hash_stack, "']['") . "'] = \"{$val['value']}\";");
                    else // to handle empty self closing tags i.e. <paymentInterval/>
                        eval("\$output['" . implode($hash_stack, "']['") . "'] = null;");
                    array_pop($hash_stack);
                    break;
            }
        }
        return $output;
    }
    //END OF FUNCTION
    //FUNCTION TO CREATE XML TRANSACTION REQUEST
    function createXMLTransactionRequestString($postForm, $order, $paymentCurrency = '', $merchantID, $merchantPassword)
    {
        $payAmount    = $order['masterOrderTotalAmount'];
        $taxAmount    = $order["orderTaxAmount"];
        $currencyArr  = '';
        $currencyCode = $postForm['currencyCode'];
        if ($paymentCurrency != '')
        {
            $paymentCurrency = str_replace(", ", ",", $paymentCurrency);
            $currencyArr     = explode(",", $paymentCurrency);
        }
        if (!empty($currencyArr) && !in_array($postForm['currencyCode'], $currencyArr))
        {
            $payAmount    = $payAmount * $postForm['USDValue'];
            $taxAmount    = $taxAmount * $postForm['USDValue'];
            $currencyCode = 'USD';
        }
        if ($postForm['authValue'] == 'Authorization')
        {
            $authOnly = 10;
        }
        else
        {
            $authOnly = 0;
        }
        $authOnly              = 0;
        $totalAmnt             = $payAmount;
        $messageId             = $order['masterOrderID'] . date("his") . current(split(' ', microtime()));
		$totalAmnt_new         = (number_format(ceil($totalAmnt), 2)) * 100;
        $_SESSION['MessageId'] = $messageId;
        $x                     = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "<SecurePayMessage>" . "<MessageInfo>" . "<messageID>" . $messageId . "</messageID>" . "<messageTimestamp>" . $this->getGMTTimeStamp() . "</messageTimestamp>" . "<timeoutValue>60</timeoutValue>" . "<apiVersion>xml-4.2</apiVersion>" . "</MessageInfo>" . "<MerchantInfo>" . "<merchantID>" . $merchantID . "</merchantID>" . "<password>" . $merchantPassword . "</password>" . "</MerchantInfo>" . "<RequestType>Payment</RequestType>" . "<Payment>" . "<TxnList count=\"1\">" . "<Txn ID=\"1\">" . "<txnType>".$authOnly."</txnType>" . "<txnSource>23</txnSource>" . "<currency>" . $currencyCode . "</currency>" . "<amount>" . $totalAmnt_new . "</amount>" . "<purchaseOrderNo>" . $order['masterOrderID'] . "</purchaseOrderNo>" . "<CreditCardInfo>" . "<cardNumber>" . $postForm['creditCardNumber'] . "</cardNumber>";
        if (trim($postForm['securityCode']) <> "")
        {
            $x .= "<cvv>" . $postForm['securityCode'] . "</cvv>";
        }
        $x .= "<expiryDate>" . sprintf("%02d", $postForm['expMonth']) . "/" . substr($postForm['expYear'], 2) . "</expiryDate>" . "</CreditCardInfo>" . "</Txn>" . "</TxnList>" . "</Payment>" . "</SecurePayMessage>";
        return $x;
    }
    //END OF FUNCTION
    //FUNCTION TO GET GMT TIME STAMP
    private function getGMTTimeStamp()
    {
        $val = date("Z") / 60;
        if ($val >= 0)
        {
            $val = "+" . strval($val);
        }
        $stamp = date("YdmGis000000") . $val;
        return $stamp;
    }
    //END OF FUNCTION
    //FUNCTION TO CREATE XML TRANSACTION REQUEST STRING FOR COMPLETE
    function createXMLTransactionRequestStringForComplete($getPaymentTransactionDetails, $order, $merchantID, $merchantPassword)
    {
        $paymentResponse      = $getPaymentTransactionDetails['paymentResponse'];
        $preAuthDetails_array = explode('~', $paymentResponse);
        $messageId_array      = explode(':', trim($preAuthDetails_array[0]));
        $messageId            = trim($messageId_array[1]);
        $timeStamp_array      = explode(':', trim($preAuthDetails_array[1]));
        $timeStamp            = trim($timeStamp_array[1]);
        $currencyCode_array   = explode(':', trim($preAuthDetails_array[8]));
        $currencyCode         = trim($currencyCode_array[1]);
        $amount_array         = explode(':', trim($preAuthDetails_array[7]));
        $amount               = trim($amount_array[1]);
        $totalAmnt_new        = $amount * 100;
        $transactionID_array  = explode(':', trim($preAuthDetails_array[12]));
        $transactionID        = trim($transactionID_array[1]);
        $preauthID_array      = explode(':', trim($preAuthDetails_array[14]));
        $preauthID            = trim($preauthID_array[1]);
        $expirydate_array     = explode(':', trim($preAuthDetails_array[15]));
        $expirydate           = trim($expirydate_array[1]);
        $x                    = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "<SecurePayMessage>" . "<MessageInfo>" . "<messageID>" . $messageId . "</messageID>" . "<messageTimestamp>" . $timeStamp . "</messageTimestamp>" . "<timeoutValue>60</timeoutValue>" . "<apiVersion>xml-4.2</apiVersion>" . "</MessageInfo>" . "<MerchantInfo>" . "<merchantID>" . $merchantID . "</merchantID>" . "<password>" . $merchantPassword . "</password>" . "</MerchantInfo>" . "<RequestType>Payment</RequestType>" . "<Payment>" . "<TxnList count=\"1\">" . "<Txn ID=\"1\">" . "<txnType>11</txnType>" . "<txnSource>23</txnSource>" . "<currency>" . $currencyCode . "</currency>" . "<amount>" . ceil($totalAmnt_new) . "</amount>" . "<purchaseOrderNo>" . $order['masterOrderID'] . "</purchaseOrderNo>" . "<txnID>" . $transactionID . "</txnID>" . "<preauthID>" . $preauthID . "</preauthID>" . "<CreditCardInfo>" . "<expiryDate>" . $expirydate . "</expiryDate>" . "</CreditCardInfo>" . "</Txn>" . "</TxnList>" . "</Payment>" . "</SecurePayMessage>";
        return $x;
    }
    //END OF FUNCTION
    //FUNCTION TO PROCESS CUSTOM
    public function processCustom($order = '', $postForm = '')
    {
		$ObjCurrency			= new CurrencyModel();
        parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);
        $getPaymentTransactionDetails = $this->getPaymentTransactionDetails($order["masterOrderID"]);
        $merchantID                   = urlencode($this->settingsVars["payment_login"]);
        $merchantPassword             = urlencode($this->settingsVars["payment_login_password"]);
        $postURL                      = trim($this->settingsVars["payment_gateway_url"]) == "" ? "http://test.securepay.com.au/securepay/payments/process2.asp" : trim($this->settingsVars["payment_gateway_url"]);
        $transactionID                = $order["transactionID"];
        $this->isError                = false;
        //check is transaction completed
        if ($order["paymentType"] != "AUTH_ONLY" || $order["paymentStatus"] == 'Received')
        {
            $this->isError      = true;
            $this->errorMessage = "Transaction already completed";
            return false;
        }
		$getPaymentTransactionDetails =  parent::getPaymentTransactionDetails(0,$order["masterOrderID"]);
        //get captured total amount & x_trans_id
        $requestMessage                         = $this->createXMLTransactionRequestStringForComplete($getPaymentTransactionDetails,
		$order, $merchantID, $merchantPassword);
        $this->responseArray["raw-XML-request"] = htmlentities($requestMessage);
        $ch                                     = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $requestMessage);
        $result             = curl_exec($ch);
        $debugoutput        = curl_getinfo($ch);
        $curl_error_message = curl_error($ch); // must retrieve an error message (if any) before closing the curl object 
        curl_close($ch);
        $xml_array = $this->XML2Array($result);
        $response  = $xml_array['Payment']['TxnList']['Txn']['approved'];
        if ($response == 'Yes' && trim($xml_array['Payment']['TxnList']['Txn']['responseText']) == 'Approved')
        {
            $transactionID = $xml_array['Payment']['TxnList']['Txn']['txnID'];
            $amnt          = trim($xml_array['Payment']['TxnList']['Txn']['amount']) / 100;
            $httpResponse  = "Message id:" . trim($xml_array['MessageInfo']['messageID']) . "~" . "\n";
            $httpResponse .= "messageTimestamp:" . trim($xml_array['MessageInfo']['messageTimestamp']) . "~" . "\n";
            $httpResponse .= "API Version:" . trim($xml_array['MessageInfo']['apiVersion']) . "~" . "\n";
            $httpResponse .= "RequestType:" . trim($xml_array['RequestType']) . "~" . "\n";
            $httpResponse .= "MerchantID:" . trim($xml_array['MerchantInfo']['merchantID']) . "~" . "\n";
            $httpResponse .= "TxnType:" . trim($xml_array['Payment']['TxnList']['Txn']['txnType']) . "~" . "\n";
            $httpResponse .= "TxnSource:" . trim($xml_array['Payment']['TxnList']['Txn']['txnSource']) . "~" . "\n";
            $httpResponse .= "Amount:" . $amnt . "~" . "\n";
            $httpResponse .= "Currency:" . $xml_array['Payment']['TxnList']['Txn']['currency'] . "~" . "\n";
            $httpResponse .= "Approved:" . trim($xml_array['Payment']['TxnList']['Txn']['approved']) . "~" . "\n";
            $httpResponse .= "Response Code:" . trim($xml_array['Payment']['TxnList']['Txn']['responseCode']) . "~" . "\n";
            $httpResponse .= "Response Text:" . trim($xml_array['Payment']['TxnList']['Txn']['responseText']) . "~" . "\n";
            $httpResponse .= "Bank txnID:" . trim($xml_array['Payment']['TxnList']['Txn']['txnID']) . "~" . "\n";
            $httpResponse .= "API Version:" . trim($xml_array['Periodic']['PeriodicList']['PeriodicItem']['CreditCardInfo']['pan']) . "~" . "\n";
            $httpResponse .= "Pre Auth ID:" . trim($xml_array['Payment']['TxnList']['Txn']['preauthID']) . "~" . "\n";
            $httpResponse .= "ExpiryDate:" . trim($xml_array['Payment']['TxnList']['Txn']['CreditCardInfo']['expiryDate']);
            $transactionID = $httpParsedResponseAr["AUTHORIZATIONID"];
            $paymentMethodName                  = $this->settingsVars["payment_method_name"];
            parent::createTransaction($order, $transactionID, "ORDER TYPE: PRIOR_AUTH_CAPTURE\n\n" . $httpResponse, "", "AUTH_CAPTURE", $paymentGatewayCharge, $paymentMethodName,$supportedCurrencyID,$payAmount);
            $this->isError      = false;
            $this->errorMessage = "";
            return "Success";
        }
        elseif ($response == 'No')
        {
            $this->isError      = true;
            $this->errorMessage = $xml_array['Payment']['TxnList']['Txn']['responseText'];
        }
        else
        {
            $this->isError      = true;
            $this->errorMessage = "Incorrect form params. Please contact site administartor.";
        }
        if ($this->isError)
        {
            $this->logStart();
            $this->log($httpResponse, $this->settingsVars["payment_processor_id"]);
            $this->logFinish();
            $this->isError = true;
        }
        return !$this->isError;
    }
    //END OF FUNCTION
    //FUNCTION TO CONVERT XML TO ARRAY
    function XML2Array($xml, $recursive = false)
    {
        if (!$recursive)
        {
            $array = simplexml_load_string($xml);
        }
        else
        {
            $array = $xml;
        }
        $newArray = array();
        $array    = ( array ) $array;
        foreach ($array as $key => $value)
        {
            $value = ( array ) $value;
            if (isset($value[0]))
            {
                $newArray[$key] = trim($value[0]);
            }
            else
            {
                $newArray[$key] = $this->XML2Array($value, true);
            }
        }
        return $newArray;
    }
    //END OF FUNCTION
    //FUNCTION TO PROCESS REFUNDS
    public function processRefund($order = '', $postValues = '')
    {
        parent::listPaymentSettingsValues($postValues['paymentSettingsGroupID']);
        $paymentCurrency                        = $this->settingsVars["payment_currency"];
        $merchantID                             = urlencode($this->settingsVars["payment_login"]);
        $merchantPassword                       = urlencode($this->settingsVars["payment_login_password"]);
        $postURL                                = trim($this->settingsVars["payment_gateway_url"]) == "" ? "http://test.securepay.com.au/securepay/payments/process2.asp" : trim($this->settingsVars["payment_gateway_url"]);
        $requestMessage                         = $this->createXMLRefundRequest($order, $postValues, $paymentCurrency, $merchantID, $merchantPassword);
        $this->responseArray["raw-XML-request"] = htmlentities($requestMessage);
        $ch                                     = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $requestMessage);
        $result 			= curl_exec($ch);
        $debugoutput        = curl_getinfo($ch);
        $curl_error_message = curl_error($ch); // must retrieve an error message (if any) before closing the curl object
        curl_close($ch);
        $xml_array 			= $this->XML2Array($result);
        $messageID 			= $xml_array['MessageInfo']['messageID'];
        $response  			= $xml_array['Payment']['TxnList']['Txn']['approved'];
        if (strtolower($response) == 'yes' && trim($xml_array['Payment']['TxnList']['Txn']['responseText']) == 'Approved')
        {
            $response = true;
        }
        else
        {
            $response = false;
        }
        if ($result === false)
        {
            $this->isError     	= true;
            $this->errorString 	= 'CURL failed and reported the following error : ' . $curl_error_message;
            return !$this->isError;
        }
        if ($response === false)
        {
            $error_status_code  = $xml_array['Status']['statusDescription'];
            $this->isError      = true;
            $this->errorMessage = "A general response error was detected :" . $xml_array['Payment']['TxnList']['Txn']['responseText'] . ' ' . $error_status_code;
            return !$this->isError;
        }
        if ($response)
        {
            $transactionID = $xml_array['Payment']['TxnList']['Txn']['txnID'];
            $refundAmount  = trim($xml_array['Payment']['TxnList']['Txn']['amount']) / 100;
            $httpResponse  = "Message id:" . trim($xml_array['MessageInfo']['messageID']) . "~" . "\n";
            $httpResponse .= "MessageTimestamp:" . trim($xml_array['MessageInfo']['messageTimestamp']) . "~" . "\n";
            $httpResponse .= "API Version:" . trim($xml_array['MessageInfo']['apiVersion']) . "~" . "\n";
            $httpResponse .= "RequestType:" . trim($xml_array['RequestType']) . "~" . "\n";
            $httpResponse .= "MerchantID:" . trim($xml_array['MerchantInfo']['merchantID']) . "~" . "\n";
            $httpResponse .= "TxnType:" . trim($xml_array['Payment']['TxnList']['Txn']['txnType']) . "~" . "\n";
            $httpResponse .= "TxnSource:" . trim($xml_array['Payment']['TxnList']['Txn']['txnSource']) . "~" . "\n";
            $httpResponse .= "Amount:" . $refundAmount . "~" . "\n";
            $httpResponse .= "Currency:" . $xml_array['Payment']['TxnList']['Txn']['currency'] . "~" . "\n";
            $httpResponse .= "Approved:" . trim($xml_array['Payment']['TxnList']['Txn']['approved']) . "~" . "\n";
            $httpResponse .= "Response Code:" . trim($xml_array['Payment']['TxnList']['Txn']['responseCode']) . "~" . "\n";
            $httpResponse .= "Response Text:" . trim($xml_array['Payment']['TxnList']['Txn']['responseText']) . "~" . "\n";
            $httpResponse .= "TxnID:" . trim($transactionID) . "~" . "\n";
            $httpResponse .= "ExpiryDate:" . trim($xml_array['Payment']['TxnList']['Txn']['CreditCardInfo']['expiryDate']);
            $masterOrderID                   = $postValues['masterOrderID'];
            $refundTransactionID             = $postValues['keyRefundTransactionID'];
            $arrXnResponse['transactionID']  = $transactionID;
            $arrXnResponse['refundResponse'] = $httpResponse;
            $arrXnResponse['refundAmount']   = $refundAmount;
            $ObjRefund                       = new RefundModel();
            $resUpdateRefund                 = $ObjRefund->updateRefundTransaction('', $refundTransactionID, $arrXnResponse, $masterOrderID);
            $this->isError                   = false;
            $this->errorMessage              = "";
            return !$this->isError;
        }
    }
    //END OF FUNCTION
    //FUNCTION TO CREATE XML TRANSACTION REQUEST
    function createXMLRefundRequest($order, $postValues, $paymentCurrency = '', $merchantID, $merchantPassword)
    {
        $transactionID = urlencode($postValues['apiPaymentTransactionID']);
        $totalAmnt     = $order['masterOrderTotalAmount'];
        $totalAmnt_new = (number_format($totalAmnt, 2)) * 100;
        $messageId     = $order['masterOrderID'] . date("his") . current(split(' ', microtime()));
        $x             = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "<SecurePayMessage>" . "<MessageInfo>" . "<messageID>" . $messageId . "</messageID>" . "<messageTimestamp>" . $this->getGMTTimeStamp() . "</messageTimestamp>" . "<timeoutValue>60</timeoutValue>" . "<apiVersion>xml-4.2</apiVersion>" . "</MessageInfo>" . "<MerchantInfo>" . "<merchantID>" . $merchantID . "</merchantID>" . "<password>" . $merchantPassword . "</password>" . "</MerchantInfo>" . "<RequestType>Payment</RequestType>" . "<Payment>" . "<TxnList count=\"1\">" . "<Txn ID=\"1\">" . "<txnType>4</txnType>" . "<txnSource>23</txnSource>" . "<amount>" . $totalAmnt_new . "</amount>" . "<purchaseOrderNo>" . $order['masterOrderID'] . "</purchaseOrderNo>" . "<txnID>" . $transactionID . "</txnID>" . "<CreditCardInfo>" . "<cardNumber>" . $postValues['creditCardNumber'] . "</cardNumber>" . "<expiryDate>" . sprintf("%02d", $postValues['expMonth']) . "/" . substr($postValues['expYear'], 2) . "</expiryDate>" . "</CreditCardInfo>" . "</Txn>" . "</TxnList>" . "</Payment>" . "</SecurePayMessage>";
        return $x;
    }
    //END OF FUNCTION
}