<?php
//This code is copyright (c) ViciSoft SL, all rights reserved.
//The contents of this file are protected under law as the intellectual property 
//of ViciSoft SL. Any use, reproduction, disclosure or copying of any kind 
//without the express and written permission of ViciSoft SL is forbidden.
//Author: Vince Reid, vincereid@gmail.com
if(!@$GLOBALS['incfunctionsdefined']){print 'No incfunctions.php file';exit;}
global $thesessionid,$emailAddr,$sendEmail,$success,$storeurlssl,$ordGrandTotal,$ordTotal,$ordStateTax,$ordHSTTax,$ordCountryTax,$ordShipping,$ordHandling,$ordDiscount,$txn_id,$ordID,$affilID,$ordCity,$ordState,$ordCountry,$ordDiscountText,$ordEmail;
include "./vsadmin/inc/incemail.php";
if(@$_SERVER['CONTENT_LENGTH']!='' && $_SERVER['CONTENT_LENGTH'] > 10000) exit;
$success=FALSE;
$GLOBALS['errtext']=$thereference=$orderText='';
$ordGrandTotal=$ordTotal=$ordStateTax=$ordHSTTax=$ordCountryTax=$ordShipping=$ordHandling=$ordDiscount=0;
$txn_id=$ordID=$affilID=$ordCity=$ordState=$ordCountry=$ordDiscountText=$ordEmail='';
$_SESSION['couponapply']=NULL; unset($_SESSION['couponapply']);
$_SESSION['giftcerts']=NULL; unset($_SESSION['giftcerts']);
$_SESSION['cpncode']=NULL; unset($_SESSION['cpncode']);
$ordTransSession=$ordAuthNumber='';
$GLOBALS['paypalwaitipn']=$GLOBALS['showclickreload']=FALSE;
if(@$debugmode){
	print 'POST parameters<br>';
	foreach($_POST as $key => $val){
		print 'POST: ' . $key . ' : ' . $val . '<br>';
	}
	print 'GET parameters<br>';
	foreach($_GET as $key => $val){
		print 'GET: ' . $key . ' : ' . $val . '<br>';
	}
}
function wait_paypal_ipn($ppordid,$ordTransSession){
	print '<form id="ppectform" method="post">';
	foreach($_POST as $key => $val){
		print whv($key,$val);
	}
	print '</form>';
?>
<script>/* <![CDATA[ */
var totpptries=0;
var ajaxobj;
function checkipncallback(){
	if(ajaxobj.readyState==4){
		if(ajaxobj.responseText=='1'){
			document.getElementById("ppectform").submit();
		}else{
			totpptries++;
			if(totpptries<30)
				setTimeout('checkipnarrived()',1000);
			else
				document.getElementById("orderfail").innerHTML='<div style="margin:50px"><strong><?php print jsescape($GLOBALS['xxPPTOUT'])?></strong></div>';
		}
	}
}
function checkipnarrived(){
	ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
	ajaxobj.onreadystatechange=checkipncallback;
	ajaxobj.open("GET","vsadmin/ajaxservice.php?action=ipnarrived&oid=<?php print $ppordid . ($ordTransSession!=''?'&sid='.$ordTransSession:'')?>",true);
	ajaxobj.send(null);
}
checkipnarrived();
/* ]]> */</script><?php
}
function order_failed(){
	order_failed_htmldisp(TRUE);
}
function order_failed_htmldisp($dohtmldisplay){
	global $storeurl,$success,$ordID,$txn_id,$ordTransSession;
	$success=FALSE;
?>
	<div class="ectdiv">
		<div class="ectmessagescreen">
			<div id="orderfail" style="text-align:center"><?php
		print $GLOBALS['xxThkErr'];
		if($GLOBALS['errtext']!='') print '<div style="margin:50px"><strong>' . ($dohtmldisplay?htmldisplay($GLOBALS['errtext']):$GLOBALS['errtext']) . '</strong></div>';
		if($GLOBALS['paypalwaitipn']){
			wait_paypal_ipn($ordID!=''?$ordID:@$txn_id,$ordTransSession);
			print '<div style="text-align:center"><img style="margin:30px" src="images/preloader.gif" alt="Loading" class="ectpreloader"></div>';
		}elseif($GLOBALS['showclickreload'])
			print '<div style="margin:50px;text-align:center"><input type="button" class="ectbutton" value="'.$GLOBALS['xxClkRel'].'" onclick="window.location.reload()"></div>';
?>				<a class="ectlink" href="<?php print $storeurl?>"><strong><?php print $GLOBALS['xxCntShp']?></strong></a>
			</div>
		</div>
	</div>
<?php
}
$GLOBALS['alreadygotadmin']=getadminsettings();
if(getget('action')=='moneris'&&is_numeric(getget('ordid'))&&getget('check')!=''){
	if(getpayprovdetx(34,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		$ordID=getget('ordid');
		$sSQL="SELECT ordID,ordStatus FROM orders WHERE ordID='" . escape_string($ordID) . "' AND ordTransID='" . escape_string(getget('check')) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$alreadysentemail=$rs['ordStatus']>=3;
			if($alreadysentemail){
				do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
			}else{
				$sjson='{
					"store_id":' . json_encode($data1) . ',
					"api_token":' . json_encode($data2) . ',
					"checkout_id":' . json_encode($data3) . ',
					"environment":' . json_encode($demomode?'qa':'prod') . ',
					"action":"receipt",
					"ticket":' . json_encode(getget('check')) . '
				}';
				$monerisurl='https://gateway' . ($demomode?'t':'') . '.moneris.com/chktv2/request/request.php';
				//print "sjson: " . $sjson . "<hr>";
				if(callcurlfunction($monerisurl,$sjson,$jres,'',$errormsg,FALSE)){
					//print "jres: " . $jres . "<hr>";
					$jsarray=json_decode($jres);
					$response_code=(int)$jsarray->{'response'}->{'receipt'}->{'cc'}->{'response_code'};
					if($jsarray->{'response'}->{'success'}=='true'&&$response_code<50){
						$success=TRUE;
						$authcode=$jsarray->{'response'}->{'receipt'}->{'cc'}->{'approval_code'};
						$order_no=$jsarray->{'response'}->{'receipt'}->{'cc'}->{'order_no'};
						$order_no=explode('_',$order_no)[0];
						if($order_no==$ordID){
							$avsresult=$jsarray->{'response'}->{'receipt'}->{'cc'}->{'fraud'}->{'avs'}->{'status'}=='success'?1:'';
							$cvvresult=$jsarray->{'response'}->{'receipt'}->{'cc'}->{'fraud'}->{'cvd'}->{'status'}=='success'?1:'';
							$sSQL="UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'";
							ect_query($sSQL) or ect_error();
							$sSQL="UPDATE orders SET ordStatus=3,ordAuthStatus='',ordAuthNumber='" . escape_string($authcode) . "',ordAVS='" . escape_string($avsresult) . "',ordCVV='" . escape_string($cvvresult) . "' WHERE ordPayProvider=34 AND ordID='" . escape_string($ordID) . "'";
							ect_query($sSQL) or ect_error();
							do_order_success($ordID,$emailAddr,$sendEmail,TRUE,TRUE,TRUE,TRUE);
						}
					}else{
						$GLOBALS['errtext']=$GLOBALS['xxCCErro'];
						$GLOBALS['errtext'].='<button type="button" class="ectbutton" style="margin:50px auto;display:block" onclick="document.location=\'cart' . $GLOBALS['extension'] . '\'">Click here to try again</button>';
						order_failed_htmldisp(FALSE);
					}
				}
				print "errormsg: " . $errormsg . "<hr>";
			}
		}else{
			$GLOBALS['errtext']='Order Not Found.';
			order_failed();
		}
		ect_free_result($result);
	}
}elseif(getget('action')=='ppexpress'&&getpost('paymentID')!=''&&is_numeric(getpost('ordid'))){
	$ordID=getpost('ordid');
	$success=FALSE;
	$ordauthstatus='';
	if(getpayprovdetx(27,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		$sSQL="SELECT ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordCountry,ordPhone,ordZip,ordEmail,ordAuthNumber,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordTotal,ordDiscount,ordAuthNumber,ordTransID,ordStatus,ordAuthStatus FROM orders WHERE ordPayProvider=27 AND ordTransID='" . escape_string(getpost('paymentID')) ."' AND ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$success=TRUE;
			$amount=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
			$taxtotal=$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax'];
			$shippingtotal=$rs['ordShipping'];
			$handlingtotal=$rs['ordHandling'];
			$discounttotal=$rs['ordDiscount'];
			$alreadysentemail=$rs['ordStatus']>=3;
			$ordauthstatus=$rs['ordAuthStatus'];
		}else{
			$GLOBALS['errtext']='Order Not Found.';
			order_failed();
		}
		ect_free_result($result);
		if($success){
			if($alreadysentemail){
				do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
			}else{
				if($ordauthstatus=='MODWARNOPEN'){
					$GLOBALS['errtext']=$GLOBALS['xxMoWnRC'];
					order_failed_htmldisp(FALSE);
				}elseif($access_token=paypalaccesstoken($data1,$data2,$demomode,$data6,$errormsg)){
					$GLOBALS['xmlfnheaders']=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token);
					if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/checkout/orders/'.getpost('paymentID'),'',$jres,'',$errormsg,FALSE)){
						$jsarray=json_decode($jres);
						$phone_number=@$jsarray->{'payer'}->{'phone'}->{'phone_number'}->{'national_number'};
						$ppstatus=@$jsarray->{'status'};
						if($ppstatus=='APPROVED'){
							$sSQL="SELECT cartID,cartProdID,cartOrigProdID,cartProdName,cartProdPrice,cartQuantity,pWeight,pShipping,pShipping2,pExemptions,pTax,pDownload FROM cart INNER JOIN products ON cart.cartProdID=products.pID WHERE cartOrderID='" . escape_string($ordID) . "'";
							$items='"items":[';
							$itemstotal=0;
							$result=ect_query($sSQL) or ect_error();
							while($rs=ect_fetch_assoc($result)){
								$item_category='PHYSICAL_GOODS';
								if(trim_($rs['pDownload']!=''))$item_category='DIGITAL_GOODS';
								$item_name=$rs['cartProdName'];
								$cartprodprice=$rs['cartProdPrice'];
								$sSQL="SELECT coOptGroup,coCartOption,coPriceDiff FROM cartoptions WHERE coCartID='" . escape_string($rs['cartID']) . "'";
								$result2=ect_query($sSQL) or ect_error();
								while($rs2=ect_fetch_assoc($result2)){
									$cartprodprice+=$rs2['coPriceDiff'];
									if($rs2['coCartOption']!='') $item_name.=' : ' . $rs2['coCartOption'];
								}
								if(is_null($rs['pExemptions'])){
									if($rs['cartProdID']==$giftcertificateid || $rs['cartProdID']==$donationid) $rs['pExemptions']=15;
									if($rs['cartProdID']==$giftwrappingid) $rs['pExemptions']=12;
								}
								if(@$GLOBALS['showtaxinclusive']===3 && $GLOBALS['countryTaxRate']>0 && ($rs['pExemptions'] & 2)!=2){
									$taxamount=round($cartprodprice / ((100+$GLOBALS['countryTaxRate'])/$GLOBALS['countryTaxRate']),2);
									$cartprodprice-=$taxamount;
								}
								$items.='{"name":' . json_encode(substr($item_name,0,127)) . ',"unit_amount":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($cartprodprice,2,'.','') . '"},"quantity":"' . $rs['cartQuantity'] . '","category":"' . $item_category . '"},';
								$itemstotal+=$cartprodprice*$rs['cartQuantity'];
							}
							ect_free_result($result);
							$items=rtrim($items,',').']';
							$newpurchaseunit='{
							  "reference_id":"' . $ordID . '",
							  "custom_id":"' . $ordID . '",
							  "amount":{
								"currency_code":"' . $GLOBALS['countryCurrency'] . '",
								"value":"' . number_format($amount,2,'.','') . '",
								"breakdown":{
									"item_total":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($itemstotal,2,'.','') . '"},
									"tax_total":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($taxtotal,2,'.','') . '"},
									"handling":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($handlingtotal,2,'.','') . '"},
									"discount":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($discounttotal,2,'.','') . '"},
									"shipping":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($shippingtotal,2,'.','') . '"}
								}
							  },
							  ' . $items . '
							}';
							$requestxx='[{"op": "replace",
								"path":"/purchase_units/@reference_id==\'express\'",
								"value":' . $newpurchaseunit . '
							}]';
							$GLOBALS['callxmlfunctionforcemethod']='PATCH';
							$GLOBALS['xmlfnheaders']=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token);
							if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/checkout/orders/'.getpost('paymentID'),$requestxx,$jres,'',$errormsg,FALSE)){
								$requestxx='{}';
								$jsarray=json_decode($jres);
								$tname=@$jsarray->{'name'};
								if($tname=='INVALID_REQUEST'||$tname=='UNPROCESSABLE_ENTITY'){
									$tmessage=@$jsarray->{'message'};
									$GLOBALS['errtext']=$tmessage;
									order_failed();
								}else{
									$GLOBALS['xmlfnheaders']=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token);
									if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/checkout/orders/' . getpost('paymentID') . ($ppmethod==1?'/authorize':'/capture'),$requestxx,$jres,'',$errormsg,FALSE)){
										$jsarray=json_decode($jres);
										$tname=@$jsarray->{'name'};
										if($tname=='UNPROCESSABLE_ENTITY'){
											if(@$jsarray->{'details'}[0]->{'issue'}=='PAYER_ACTION_REQUIRED')
												$ppstatus='PAYER_ACTION_REQUIRED';
											else
												$ppstatus='FAILED';
										}elseif($tname=='INVALID_REQUEST'){
											$ppstatus='FAILED';
										}else{
											$tid=@$jsarray->{'id'};
											if($ppmethod==1)
												$tid=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'authorizations'}[0]->{'id'};
											else
												$tid=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'captures'}[0]->{'id'};
											if($tid!=''){
												$pendingreason=($ppmethod==1?'Pending: Capture':'');
												$sSQL="UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'";
												ect_query($sSQL) or ect_error();
												$sSQL="UPDATE orders SET ordStatus=3,ordAuthNumber='" . escape_string(substr($tid,0,48)) . "',ordAuthStatus='" . escape_string($pendingreason) . "',ordTransSession='',ordPrivateStatus='',ordPhone='" . escape_string($phone_number) . "'" . (@$GLOBALS['autobillingtoshipping']?",ordShipPhone='" . escape_string($phone_number) . "'":'') . ",ordAddInfo='" . escape_string(getpost('ordAddInfo')) . "',ordCheckoutExtra1='" . escape_string(substr(getpost('ordcheckoutextra1'),0,255)) . "',ordCheckoutExtra2='" . escape_string(substr(getpost('ordcheckoutextra2'),0,255)) . "' WHERE ordPayProvider IN (27) AND ordID='" . escape_string($ordID) . "'";
												ect_query($sSQL) or ect_error();
												do_order_success($ordID,$emailAddr,$sendEmail,TRUE,TRUE,TRUE,TRUE);
											}
										}
									}
								}
							}
						}
						if($ppstatus=='APPROVED'){
						}elseif($ppstatus=='PAYER_ACTION_REQUIRED'){
							$thelinks=@$jsarray->{'links'};
							foreach($thelinks as $alink){
								if($alink->{'rel'}=='payer-action'){
									$sSQL="UPDATE orders SET ordAddInfo='" . escape_string(getpost('ordAddInfo')) . "',
											ordCheckoutExtra1='" . escape_string(substr(getpost('ordcheckoutextra1'),0,255)) . "',
											ordCheckoutExtra2='" . escape_string(substr(getpost('ordcheckoutextra2'),0,255)) . "' WHERE ordPayProvider IN (27) AND ordID='" . escape_string($ordID) . "'";
									ect_query($sSQL) or ect_error();
									$linklocation=$alink->{'href'};
									if(ob_get_length()!==FALSE)
										header('Location: ' . $linklocation);
									else
										print '<meta http-equiv="refresh" content="0; URL=' . $linklocation . '">';
									exit();
									//print '<div id="softopaquediv" class="ectopaque" tabindex="0">';
										//print '<script>window.open("' . $linklocation . '","PayPal","menubar=no, scrollbars=yes, width=800, height=680, directories=no,location=no,resizable=yes,status=no,toolbar=no");</script>';
										//print '<div class="ectsoftwrapper"><iframe src="' . $linklocation . '" style="width:100%;border:none;height:840px"><iframe>';</div>';
									//print '</div>';
								}
							}
						}else{
							$GLOBALS['errtext']=@$jsarray->{'message'};
							if($ppstatus!='FAILED') $GLOBALS['errtext']='Unknown status: ' . $ppstatus . ' - ' . $GLOBALS['errtext'];
							order_failed();
						}
					}
				}
			}
		}
	}
}elseif(getget('action')=='termpp'&&(getget('paymentID')!=''||(getget('token')!=''&&getget('PayerID')!=''))&&(is_numeric(getget('ordid'))||getget('ordid')=='express')){
	if(getpayprovdetx(27,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		$ordID='';
		$paymentid='';
		if(getget('ordid')=='express'){
			if($access_token=paypalaccesstoken($data1,$data2,$demomode,$data6,$errormsg)){
				$GLOBALS['xmlfnheaders']=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token);
				if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/checkout/orders/'.getget('token'),'',$jres,'',$errormsg,FALSE)){
					$jsarray=json_decode($jres);
					$ordID=@$jsarray->{'purchase_units'}[0]->{'reference_id'};
					$ppstatus=@$jsarray->{'status'};
					$paymentid=getget('token');
					$phone_number=@$jsarray->{'payer'}->{'phone'}->{'phone_number'}->{'national_number'};
					$requestxx='{}';
					if($ppstatus=='APPROVED'){
						$GLOBALS['xmlfnheaders']=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token);
						if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/checkout/orders/' . $paymentid . ($ppmethod==1?'/authorize':'/capture'),$requestxx,$jres,'',$errormsg,FALSE)){
							$jsarray=json_decode($jres);
							if($ppmethod==1)
								$tid=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'authorizations'}[0]->{'id'};
							else
								$tid=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'captures'}[0]->{'id'};
							if($tid!=''){
								$pendingreason=($ppmethod==1?'Pending: Capture':'');
								$sSQL="UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'";
								ect_query($sSQL) or ect_error();
								$sSQL="UPDATE orders SET ordStatus=3,ordAuthNumber='" . escape_string(substr($tid,0,48)) . "',ordAuthStatus='" . escape_string($pendingreason) . "',ordTransSession='',ordPhone='" . escape_string($phone_number) . "'" . (@$GLOBALS['autobillingtoshipping']?",ordShipPhone='" . escape_string($phone_number) . "'":'') . " WHERE ordPayProvider=27 AND ordID='" . escape_string($ordID) . "'";
								ect_query($sSQL) or ect_error();
								do_order_success($ordID,$emailAddr,$sendEmail,FALSE,TRUE,TRUE,TRUE);
							}
						}
					}elseif($ppstatus!='COMPLETED'){
						$GLOBALS['errtext']='Invalid Status - ' . $ppstatus;
						order_failed();
						$paymentid='';
					}
				}
			}
		}else{
			$ordID=getget('ordid');
			$paymentid=getget('paymentID');
		}
		if(is_numeric($ordID)&&$paymentid!=''){
			$sSQL="SELECT ordStatus,ordPrivateStatus FROM orders WHERE ordPayProvider=27 AND ordID='" . escape_string($ordID) . "' AND ordTransID='" . escape_string($paymentid) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$ordStatus=$rs['ordStatus'];
				$GLOBALS['errtext']=$GLOBALS['xxCCErro'];
			}
			ect_free_result($result);
			if(@$ordStatus>=3)
				do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
			else
				order_failed();
		}
	}
}elseif(getget('mode')=='authorize'&&getget('method')=='29'&&getget('payment_token')!=''&&is_numeric(getget('ordernumber'))){ // NMI New!
	if(getpayprovdetx(29,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		$sSQL="SELECT ordID FROM orders WHERE ordPayProvider=29 AND ordID='" . escape_string(getget('ordernumber')) . "' AND ordTransSession='" . escape_string(getget('payment_token')) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$ordID=getget('ordernumber');
			do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
		}else{
			$GLOBALS['errtext']=$GLOBALS['xxNoCnf'];
			order_failed();
		}
	}
}elseif(getget('mode')=='authorize'&&getget('method')=='29'&&getget('token-id')!=''&&is_numeric(getget('ordernumber'))){ // NMI
	$success=FALSE;
	$ordID=getget('ordernumber');
	if(getpayprovdetx(29,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		$tsessionid='';
		$sXML='<?xml version="1.0" encoding="UTF-8"?><complete-action>' . vrxmltag('api-key',$data1) .  vrxmltag('token-id',getget('token-id')) . '</complete-action>';
		$sSQL="SELECT ordID,ordStatus,ordSessionID FROM orders WHERE ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$currstatus=$rs['ordStatus'];
			$tsessionid=$rs['ordSessionID'];
		}
		ect_free_result($result);
		if($currstatus>=3&&$tsessionid==getsessionid()){
			do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
		}else{
			$GLOBALS['xmlfnheaders']=array('Content-Type: text/xml');
			if(callcurlfunction('https://secure.networkmerchants.com/api/v2/three-step',$sXML,$xmlres,'',$GLOBALS['errtext'],FALSE)){
				$gwResponse=new SimpleXMLElement($xmlres);
				if((string)$gwResponse->result==1){
					$success=TRUE;
					$sSQL="UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'";
					ect_query($sSQL) or ect_error();
					$sSQL="UPDATE orders SET ordStatus=3,ordAuthStatus='',ordAuthNumber='" . escape_string($gwResponse->{'authorization-code'}) . "',ordTransID='" . escape_string($gwResponse->{'transaction-id'}) . "',ordAVS='" . escape_string($gwResponse->{'avs-result'}) . "',ordCVV='' WHERE ordPayProvider=29 AND ordID='" . escape_string($ordID) . "'";
					ect_query($sSQL) or ect_error();
					do_order_success($ordID,$emailAddr,$sendEmail,TRUE,TRUE,TRUE,TRUE);
				}else{
					$GLOBALS['errtext']=(string)$gwResponse->{'result-text'};
					order_failed();
				}
			}else{
				order_failed();
			}
		}
	}
}elseif(getpost('mode')=='authorize'&&getpost('method')=='28'&&is_numeric(getpost('ordernumber'))&&getpost('payment_method_nonce')!=''&&getpost('txnid')!=''){ // SquareUp
	$ordID=getpost('ordernumber');
	$btsessionid=getpost('sessionid');
	$success=TRUE;
	if(getpayprovdetx(28,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		$sSQL="SELECT ordID FROM orders WHERE ordID='" . escape_string($ordID) . "' AND ordTransID='" . escape_string(getpost('txnid')) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
		}
		ect_free_result($result);
	}
}elseif(getpost('mode')=='authorize'&&(getpost('method')=='25'||getpost('method')=='26')&&is_numeric(getpost('ordernumber'))&&getpost('payment_method_nonce')!=''){ // Braintree
	$ordID=getpost('ordernumber');
	$btsessionid=getpost('sessionid');
	$success=TRUE;
	$ordauthstatus='';
	if(getpayprovdetx(25,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		$sSQL="SELECT ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordCountry,ordPhone,ordZip,ordEmail,ordAuthNumber,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordTotal,ordDiscount,ordAuthNumber,ordTransID,ordStatus,ordAuthStatus FROM orders WHERE ordPayProvider=".getpost('method')." AND ordSessionID='" . escape_string($btsessionid) . "' AND ordID='" . escape_string(getpost('ordernumber')) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$amount=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
			$ordStatus=$rs['ordStatus'];
			$ordTransID=$rs['ordTransID'];
			$alreadyprocessed=$ordStatus>=3;
			$ordauthstatus=$rs['ordAuthStatus'];
			
			$ordName=$rs['ordName'];
			$ordLastName=$rs['ordLastName'];
			$ordAddress=$rs['ordAddress'];
			$ordAddress2=$rs['ordAddress2'];
			$ordCity=$rs['ordCity'];
			$ordState=$rs['ordState'];
			$ordCountry=$rs['ordCountry'];
			$ordZip=$rs['ordZip'];
			$ordEmail=$rs['ordEmail'];
			
			if(!@$GLOBALS['usefirstlastname']){
				$namearr=explode(' ',trim($ordName),2);
				$ordName=$namearr[0];
				$ordLastName=@$namearr[1];
			}
			$sSQL="SELECT countryCode FROM countries WHERE countryName='" . escape_string($ordCountry) . "'";
			$result2=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result2))
				$ordCountry=$rs2['countryCode'];
			ect_free_result($result2);
			if($ordCountry=='US'){
				$sSQL="SELECT stateAbbrev FROM states WHERE stateCountryID=1 AND stateName='" . escape_string($ordState) . "'";
				$result2=ect_query($sSQL) or ect_error();
				if($rs2=ect_fetch_assoc($result2))
					$ordState=$rs2['stateAbbrev'];
				ect_free_result($result2);
			}
		}else
			$success=FALSE;
		ect_free_result($result);
		if($ordauthstatus=='MODWARNOPEN'){
			$GLOBALS['errtext']=$GLOBALS['xxMoWnRC'];
			order_failed_htmldisp(FALSE);
		}else{
			$url='https://api.' . ($demomode?'sandbox.':'') . 'braintreegateway.com:443/merchants/'.$data1.'/transactions';
			$sXML='<?xml version="1.0" encoding="UTF-8"?><transaction>' .
				'<type>sale</type>' .
				'<amount>' . number_format($amount,2,'.','') . '</amount>' .
				($data5!=''?'<merchantAccountId>' . $data5 . '</merchantAccountId>':'') .
				'<payment-method-nonce>' . getpost('payment_method_nonce') . '</payment-method-nonce>' .
				'<customer>' .
					'<firstName>' . vrxmlencode($ordName) . '</firstName>' .
					'<lastName>' . vrxmlencode($ordLastName) . '</lastName>' .
					'<email>' . vrxmlencode($ordEmail) . '</email>' .
				'</customer>' .
				'<billing>' .
					'<firstName>' . vrxmlencode($ordName) . '</firstName>' .
					'<lastName>' . vrxmlencode($ordLastName) . '</lastName>' .
					'<streetAddress>' . vrxmlencode($ordAddress) . '</streetAddress>' .
					'<locality>' . vrxmlencode($ordCity) . '</locality>' .
					'<region>' . vrxmlencode($ordState) . '</region>' .
					'<postalCode>' . vrxmlencode($ordZip) . '</postalCode>' .
					'<countryCodeAlpha2>' . vrxmlencode($ordCountry) . '</countryCodeAlpha2>' .
				'</billing>' .
				'<options><submit-for-settlement type="boolean">'.($ppmethod==1?'false':'true').'</submit-for-settlement></options></transaction>';
			$GLOBALS['xmlfnheaders']=array("Accept: application/xml","Content-Type: application/xml","User-Agent: Braintree PHP Library 3.14.0","X-ApiVersion: 4");
			$GLOBALS['xmlfnuser']=$data2;
			$GLOBALS['xmlfnpassword']=$data3;
			if(!$success){
				$GLOBALS['errtext']='Braintree error: Cannot find order details';
				order_failed();
			}elseif(callcurlfunction($url,$sXML,$res,'',$GLOBALS['errtext'],FALSE)){
				$resxml=new SimpleXMLElement($res);
				$authcode=$resxml->{'processor-authorization-code'};
				$avsstreet=$resxml->{'avs-street-address-response-code'};
				$avszip=$resxml->{'avs-postal-code-response-code'};
				$cvv=$resxml->{'cvv-response-code'};
				$transid=$resxml->{'id'};
				$amount=$resxml->{'amount'};
				$status=$resxml->{'status'};
				$paypal=$resxml->{'paypal'};
				if(is_object($paypal)){
					$authid=trim_($paypal->{'authorization-id'});
					if($authid!='') $authcode=$authid;
				}
				if($status=='authorized'||$status=='submitted_for_settlement'||$status=='settling'||$status=='settled'){
					if($status=='authorized') $pendingreason='Pending: Capture'; else $pendingreason='';
					$sSQL="UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'";
					ect_query($sSQL) or ect_error();
					$sSQL="UPDATE orders SET ordStatus=3,ordAuthStatus='" . escape_string($pendingreason) . "',ordAuthNumber='" . escape_string($authcode) . "',ordTransID='" . escape_string($transid) . "',ordAVS='".escape_string($avsstreet.':'.$avszip)."',ordCVV='".escape_string($cvv)."' WHERE ordPayProvider=".getpost('method')." AND ordID='" . escape_string($ordID) . "'";
					ect_query($sSQL) or ect_error();
					do_order_success($ordID,$emailAddr,$sendEmail,TRUE,TRUE,TRUE,TRUE);
				}else{
					$GLOBALS['errtext']='';
					$errcode=@$resxml->errors->transaction->errors->error[0]->code;
					if($errcode=='91564' && $ordStatus>=3){
						do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
					}else{
						$GLOBALS['errtext']=$GLOBALS['xxCCErro'];
						order_failed();
					}
				}
			}
		}
	}
}elseif(getget('pprov')=='31'&&is_numeric(getget('ordid'))&&getget('sessionId')!=''){ // Pay360
	if(getpayprovdetails(31,$data1,$data2,$data3,$demomode,$ppmethod)){
		$sSQL="SELECT ordID,ordStatus,ordTransID,ordTransSession FROM orders WHERE ordID='" . escape_string(getget('ordid')) . "' AND ordPayProvider=31 AND ordTransSession='" . escape_string(getget('sessionId')) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$ordID=getget('ordid');
			$ordTransSession=$rs['ordTransSession'];
			$ordtransid=$rs['ordTransID'];
			$ordstatus=$rs['ordStatus'];
			$url='https://api.' . ($demomode?'mite.':'') . 'pay360.com';
			$GLOBALS['xmlfnheaders']=array('Content-Type:application/json');
			$GLOBALS['xmlfnuser']=$data2;
			$GLOBALS['xmlfnpassword']=$data3;
			if($ordstatus>=3){
				do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
			}else{
				if($ordtransid==''){
					$GLOBALS['paypalwaitipn']=TRUE;
					$GLOBALS['xxThkErr']='';
					ect_query("UPDATE cart SET cartCompleted=2 WHERE cartCompleted=0 AND cartOrderID='" . escape_string($ordID) . "'") or ect_error();
					ect_query("UPDATE orders SET ordAuthNumber='no ipn' WHERE ordAuthNumber='' AND ordPayProvider=31 AND ordID='" . escape_string($ordID) . "'") or ect_error();
					$GLOBALS['errtext']=$GLOBALS['xxPPWIPN'];
					order_failed();
				}else{
					if(callcurlfunction($url . '/acceptor/rest/transactions/' . $data1 . '/' . $ordtransid,'',$jres,'',$GLOBALS['errtext'],FALSE)){
						$jsarray=json_decode($jres);
						$transactionStatus=@$jsarray->{'processing'}->{'authResponse'}->{'status'};
						$total=$jsarray->{'transaction'}->{'amount'};
						$transactionid=$jsarray->{'transaction'}->{'transactionId'};
						$isdeferred=@$jsarray->{'transaction'}->{'deferred'};
						$ordavs=str_replace(array('FULL_MATCH','MATCHED'),array('FM','M'),@$jsarray->{'processing'}->{'authResponse'}->{'avsAddressCheck'} . ' | ' . @$jsarray->{'processing'}->{'authResponse'}->{'avsPostcodeCheck'});
						$ordcvv=str_replace(array('FULL_MATCH','MATCHED'),array('FM','M'),@$jsarray->{'processing'}->{'authResponse'}->{'cv2Check'});
						$authcode=@$jsarray->{'processing'}->{'authResponse'}->{'authCode'};
						ect_query("UPDATE orders SET ordTransID='" . escape_string($transactionid) . "' WHERE ordID='" . escape_string($ordID) . "' AND ordStatus<3") or ect_error();
						if($transactionStatus=='AUTHORISED'){
							ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
							ect_query("UPDATE orders SET ordAVS='".escape_string(trim($ordavs))."',ordCVV='".escape_string($ordcvv)."',ordStatus=3,ordAuthNumber='".escape_string($authcode)."',ordAuthStatus='" . escape_string($isdeferred?'Pending: Capture':'') . "' WHERE ordID='" . escape_string($ordID) . "' AND ordStatus<3") or ect_error();
							do_order_success($ordID,$emailAddr,$sendEmail,TRUE,TRUE,TRUE,TRUE);
						}else{
							$GLOBALS['errtext']=$GLOBALS['xxCCErro'];
							order_failed();
						}
					}
				}
			}
		}else{
			$GLOBALS['errtext']='Order Not Found.';
			order_failed();
		}
	}
}elseif(getpost('pprov')=='21'&&is_numeric(getpost('ordernumber'))){ // Amazon Pay
	function calculateStringToSignV2(){
		global $scripturl,$endpointpath,$demomode;
		return 'POST' . "\n" . $scripturl . "\n" . $endpointpath . "\n" . getParametersAsString();
	}
	function getParametersAsString(){
		global $amazonprms;
		$queryParameters = array();
		foreach ($amazonprms as $key => $value) {
			$queryParameters[] = $key . '=' . str_replace('%7E', '~', rawurlencode($value));
		}
		return implode('&', $queryParameters);
	}
	function calculateSignatureAndParametersToString(){
		global $amazonprms,$amazonstr,$data3;
		uksort($amazonprms, 'strcmp');
		$amazonstr=getParametersAsString();
	}
	function amazonparam2($nam, $val){
		global $amazonstr,$amazonprms;
		$amazonprms[$nam]=replaceaccents($val);
	}
	$ordID=getpost('ordernumber');
	if(getpayprovdetails(21,$data1,$data2,$data3,$demomode,$ppmethod)){
		$success=TRUE;
		$alreadyprocessed=FALSE;
		$scripturl='mws-eu.amazonservices.com';
		if($GLOBALS['origCountryCode']=='US') $scripturl='mws.amazonservices.com';
		if($GLOBALS['origCountryCode']=='JP') $scripturl='mws.amazonservices.jp';
		$endpointpath='/OffAmazonPayments' . ($demomode?'_Sandbox':'') . '/2013-01-01';
		$endpoint='https://' . $scripturl . $endpointpath;
		
		$data2arr=explode('&',$data2);
		$data2=$data2arr[0];
		$sellerid=@$data2arr[1];
		
		$amazonstr='';
		$amazonprms=[];
		$timestamp=gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
		
		$itemtotal=0;
		$sSQL="SELECT ordAuthNumber,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordTotal,ordDiscount,ordAuthNumber,ordTransID,ordEmail,ordStatus FROM orders WHERE ordPayProvider=21 AND ordTransID='" . escape_string(getpost('amzrefid')) . "' AND ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$email=$rs['ordEmail'];
			$itemtotal=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
			$ordStatus=$rs['ordStatus'];
			$ordTransID=$rs['ordTransID'];
			$alreadyprocessed=$ordStatus>=3;
		}else{
			$success=FALSE;
			$GLOBALS['errtext']='The Order ID could not be found.';
		}
		ect_free_result($result);
		
		if($alreadyprocessed){
			do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
		}elseif(!$success)
			order_failed();
		else{
			amazonparam2('AWSAccessKeyId',$data2);
			amazonparam2('Action','SetOrderReferenceDetails');
			amazonparam2('AmazonOrderReferenceId',getpost('amzrefid'));
			amazonparam2('OrderReferenceAttributes.OrderTotal.Amount',number_format($itemtotal,2,'.',''));
			amazonparam2('OrderReferenceAttributes.OrderTotal.CurrencyCode',$GLOBALS['countryCurrency']);
			amazonparam2('OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId',$ordID);
			amazonparam2('SellerId',$sellerid);
			amazonparam2('SignatureMethod','HmacSHA256');
			amazonparam2('SignatureVersion',2);
			amazonparam2('Timestamp',$timestamp);
			amazonparam2('Version','2013-01-01');
			calculateSignatureAndParametersToString();
			$amazonprms['Signature']=base64_encode(hash_hmac('sha256', calculateStringToSignV2($amazonprms), $data3, true));
			$amazonstr=getParametersAsString();
			if(!callcurlfunction($endpoint,$amazonstr,$res,'',$GLOBALS['errtext'],FALSE))
				$success=FALSE;
			
			if($success){
				$amazonstr='';
				$amazonprms=[];
				$timestamp=gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
				
				amazonparam2('AWSAccessKeyId',$data2);
				amazonparam2('Action','ConfirmOrderReference');
				amazonparam2('AmazonOrderReferenceId',getpost('amzrefid'));
				amazonparam2('SellerId',$sellerid);
				amazonparam2('SignatureMethod','HmacSHA256');
				amazonparam2('SignatureVersion',2);
				amazonparam2('Timestamp',$timestamp);
				amazonparam2('Version','2013-01-01');
				calculateSignatureAndParametersToString();
				$amazonprms['Signature']=base64_encode(hash_hmac('sha256', calculateStringToSignV2($amazonprms), $data3, true));
				$amazonstr=getParametersAsString();
				if(!callcurlfunction($endpoint,$amazonstr,$res,'',$GLOBALS['errtext'],FALSE))
					$success=FALSE;

				$amazonstr='';
				$amazonprms=[];
				$timestamp=gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
				
				amazonparam2('AWSAccessKeyId',$data2);
				amazonparam2('Action','GetOrderReferenceDetails');
				amazonparam2('AmazonOrderReferenceId',getpost('amzrefid'));
				amazonparam2('SellerId',$sellerid);
				amazonparam2('SignatureMethod','HmacSHA256');
				amazonparam2('SignatureVersion',2);
				amazonparam2('Timestamp',$timestamp);
				amazonparam2('Version','2013-01-01');
				calculateSignatureAndParametersToString();
				$amazonprms['Signature']=base64_encode(hash_hmac('sha256', calculateStringToSignV2($amazonprms), $data3, true));
				$amazonstr=getParametersAsString();
			}
			if($success){
				if($success=callcurlfunction($endpoint,$amazonstr,$res,'',$GLOBALS['errtext'],FALSE)){
					$ordEmail=$ordName=$ordAddress=$ordAddress2=$ordCity=$ordPhone='';
					
					$xmlDoc=new vrXMLDoc($res);
					$nodeList=$xmlDoc->nodeList->childNodes[0];
					for($i=0; $i < $nodeList->length; $i++){
						if($nodeList->nodeName[$i]=='Error'){
							$amazonpayment=$checkoutmode='';
							$e=$nodeList->childNodes[$i];
							for($j=0; $j < $e->length; $j++){
								if($e->nodeName[$j]=='Message'){
									$GLOBALS['errtext']='Amazon Error: ' . $e->nodeValue[$j];
									$success=FALSE;
								}
							}
						}elseif($nodeList->nodeName[$i]=='GetOrderReferenceDetailsResult'){
							$e=$nodeList->childNodes[$i];
							for($j=0; $j < $e->length; $j++){
								if($e->nodeName[$i]=='OrderReferenceDetails'){
									$f=$e->childNodes[$j];
									for($k=0; $k < $f->length; $k++){
										if($f->nodeName[$k]=='Constraints'){
											$g=$f->childNodes[$k];
											for($l=0; $l < $g->length; $l++){
												if($g->nodeName[$l]=='Constraint'){
													$h=$g->childNodes[$l];
													$isamountconstraint=FALSE;
													for($m=0; $m < $h->length; $m++){
														if($h->nodeName[$m]=='Description'){
															$GLOBALS['errtext']=$h->nodeValue[$m];
															$success=FALSE;
														}
													}
												}
											}
										}elseif($f->nodeName[$k]=='Destination'){
											$g=$f->childNodes[$k];
											for($l=0; $l < $g->length; $l++){
												if($g->nodeName[$l]=='PhysicalDestination'){
													$h=$g->childNodes[$l];
													for($m=0; $m < $h->length; $m++){
														if($h->nodeName[$m]=='Name'){
															$ordName=$h->nodeValue[$m];
														}elseif($h->nodeName[$m]=='AddressLine1'){
															$ordAddress=$h->nodeValue[$m];
														}elseif($h->nodeName[$m]=='AddressLine2'){
															$ordAddress2=trim($h->nodeValue[$m].' '.$ordAddress2);
														}elseif($h->nodeName[$m]=='AddressLine3'){
															$ordAddress2=trim($ordAddress2.' '.$h->nodeValue[$m]);
														}elseif($h->nodeName[$m]=='City'){
															$ordCity=$h->nodeValue[$m];
														}elseif($h->nodeName[$m]=='StateOrRegion'){
															$ordState=$h->nodeValue[$m];
														}elseif($h->nodeName[$m]=='PostalCode'){
															$ordZip=$h->nodeValue[$m];
														}elseif($h->nodeName[$m]=='Phone'){
															$ordPhone=$h->nodeValue[$m];
														}elseif($h->nodeName[$m]=='Email'){
															$ordEmail=$h->nodeValue[$m];
														}
													}
												}
											}
										}elseif($f->nodeName[$k]=='Buyer'){
											$g=$f->childNodes[$k];
											for($l=0; $l < $g->length; $l++){
												if($g->nodeName[$l]=='Email'){
													$ordEmail=$g->nodeValue[$l];
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
			$pendingreason=$authcode=$amazonstr='';
			$amazonprms=[];
			if($success){
				$success=FALSE;
				$currdatetime=date('Y-m-d H:i:s');
				$timestamp=gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
				amazonparam2('AWSAccessKeyId',$data2);
				amazonparam2('Action','Authorize');
				amazonparam2('AmazonOrderReferenceId',getpost('amzrefid'));
				amazonparam2('AuthorizationAmount.Amount',number_format($itemtotal,2,'.',''));
				amazonparam2('AuthorizationAmount.CurrencyCode',$GLOBALS['countryCurrency']);
				amazonparam2('AuthorizationReferenceId',$ordID.'_'.str_replace(array('-',':',' '),'',$currdatetime));
				amazonparam2('CaptureNow',$ppmethod==1?'false':'true');
				amazonparam2('SellerAuthorizationNote',($ppmethod==1?'Authorization: ':'Capture: ') . $currdatetime);
				amazonparam2('SellerId',$sellerid);
				amazonparam2('SignatureMethod','HmacSHA256');
				amazonparam2('SignatureVersion',2);
				amazonparam2('Timestamp',$timestamp);
				if($ppmethod!=1) amazonparam2('TransactionTimeout','0');
				amazonparam2('Version','2013-01-01');
				calculateSignatureAndParametersToString();
				$amazonprms['Signature']=base64_encode(hash_hmac('sha256', calculateStringToSignV2($amazonprms), $data3, true));
				$amazonstr=getParametersAsString();

				if($success=callcurlfunction($endpoint,$amazonstr,$res,'',$GLOBALS['errtext'],FALSE)){
					$authresponse=new SimpleXMLElement($res);
					if($authresponse->AuthorizeResult){
						$authcode=$authresponse->AuthorizeResult->AuthorizationDetails->AmazonAuthorizationId;
						$state=$authresponse->AuthorizeResult->AuthorizationDetails->AuthorizationStatus->State;
					}
					if($authresponse->Error) $GLOBALS['errtext']=$authresponse->Error->Message;
					if($GLOBALS['errtext']!=''||$authcode==''||$state=='')
						$success=FALSE;
					else{
						if(($ppmethod==1 && ($state=='Pending' || $state=='Open')) || ($ppmethod!=1 && $state=='Closed')){
							$success=TRUE;
							if($state=='Pending') $pendingreason='Capture';
						}
					}
				}
			}
			if($success){
				if(! $alreadyprocessed){
					if($pendingreason!='') $pendingreason='Pending: ' . $pendingreason;
					$sSQL="UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'";
					ect_query($sSQL) or ect_error();
					$sSQL="UPDATE orders SET ordStatus=3,ordAuthNumber='" . escape_string($authcode) . "',ordName='" . escape_string($ordName) . "',ordAddress='" . escape_string($ordAddress) . "',ordAddress2='" . escape_string($ordAddress2) . "',ordCity='" . escape_string($ordCity) . "',ordPhone='" . escape_string($ordPhone) . "',ordEmail='" . escape_string($ordEmail) . "',ordAuthStatus='" . escape_string($pendingreason) . "' WHERE ordPayProvider=21 AND ordID='" . escape_string($ordID) . "'";
					ect_query($sSQL) or ect_error();
					if(@$GLOBALS['autobillingtoshipping']) ect_query("UPDATE orders SET ordShipName=ordName,ordShipAddress=ordAddress,ordShipAddress2=ordAddress2,ordShipCity=ordCity,ordShipState=ordState,ordShipCountry=ordCountry,ordShipPhone=ordPhone,ordShipZip=ordZip WHERE ordPayProvider=21 AND ordID='" . escape_string($ordID) . "'");
				}
				do_order_success($ordID,$emailAddr,! $alreadyprocessed,TRUE,! $alreadyprocessed,! $alreadyprocessed,! $alreadyprocessed);
				$_SESSION['AmazonLogin']='';
				$_SESSION['AmazonLoginTimeout']='';
			}else
				order_failed();
		}
	}
}elseif(getpost('method')=='striperedirect'&&getpost('url')!=''){
	header('Location: '.getpost('url'));
}elseif(getget('payment_intent')!=''&&getget('payment_intent_client_secret')!=''&&is_numeric(getget('soid'))){
	$ordID=getget('soid');
	if(getpayprovdetails(23,$data1,$data2,$data3,$demomode,$ppmethod)){
		$paymentintent=getget('payment_intent');
		$sSQL="SELECT ordID,ordStatus,ordTransID FROM orders WHERE ordPayProvider=23 AND ordID='" . escape_string($ordID) . "' AND ordTransSession='" . escape_string(getget('payment_intent_client_secret')) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$success=TRUE;
			$alreadyprocessed=$rs['ordStatus']>=3;
		}else{
			$success=FALSE;
			$GLOBALS['errtext']='Could not find order.';
		}
		ect_free_result($result);
		if($success){
			$GLOBALS['xmlfnheaders']=array("User-Agent: Stripe/v1 RubyBindings/1.12.0","Authorization: Bearer ".$data1,"Content-Type: application/x-www-form-urlencoded");
			if(callcurlfunction('https://api.stripe.com/v1/payment_intents/'.$paymentintent, '', $jres, '', $GLOBALS['errtext'], FALSE)){
				$piarray=json_decode($jres);
				$paymentstatus=$piarray->{'status'};
				$stripeorderid=@$piarray->{'metadata'}->{'order_id'};
				if($stripeorderid!=$ordID){
					$GLOBALS['errtext']='Invalid order ID';
					$success=FALSE;
				}elseif(($ppmethod!=1&&$paymentstatus=='succeeded')||($ppmethod==1&&$paymentstatus=='requires_capture')||$paymentstatus=='processing'){
					if($paymentstatus=='requires_capture') $pendingreason='Pending: Capture'; else $pendingreason='';
					if($paymentstatus=='processing') $pendingreason='Pending: Processing';
					$stripeid=@$piarray->{'id'};
					$ordavs1=@$piarray->{'charges'}->{'data'}[0]->{'payment_method_details'}->{'card'}->{'checks'}->{'address_line1_check'};
					$ordavs2=@$piarray->{'charges'}->{'data'}[0]->{'payment_method_details'}->{'card'}->{'checks'}->{'address_postal_code_check'};
					$ordcvv=@$piarray->{'charges'}->{'data'}[0]->{'payment_method_details'}->{'card'}->{'checks'}->{'cvc_check'};
					ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
					ect_query("UPDATE orders SET ordAuthStatus='" . escape_string($pendingreason) . "',ordAVS='".escape_string(trim($ordavs1.':'.$ordavs2))."',ordCVV='".escape_string($ordcvv)."',ordStatus=3,ordAuthNumber='" . escape_string($stripeid) . "' WHERE ordID='" . escape_string($ordID) . "' AND ordStatus<3") or ect_error();
					if($paymentstatus=='processing'){
						print '<div style="text-align:center;font-weight:bold;margin:50px">' . $GLOBALS['xxGenPro'] . '</div>';
					}else
						do_order_success($ordID,$emailAddr,! $alreadyprocessed,TRUE,! $alreadyprocessed,! $alreadyprocessed,! $alreadyprocessed);
				}else{
					if(@$GLOBALS['debugmode']){
						print @$piarray->{'last_payment_error'}->{'message'} . '<br>';
						print @$piarray->{'status'} . '<br>';
					}
					$GLOBALS['errtext']=$GLOBALS['xxGenPEr'];
					$success=FALSE;
				}
			}else
				$success=FALSE;
		}
		if(!$success)
			order_failed();
	}else{
		$GLOBALS['errtext']='Payment method not set.';
		order_failed();
	}
}elseif(getget('method')=='stripe'&&getget('sid')!=''&&is_numeric(getget('soid'))){
	$ordID=getget('soid');
	if(getpayprovdetails(23,$data1,$data2,$data3,$demomode,$ppmethod)){
		$paymentintent='';
		$GLOBALS['xmlfnheaders']=array("User-Agent: Stripe/v1 RubyBindings/1.12.0","Authorization: Bearer ".$data1,"Content-Type: application/x-www-form-urlencoded");
		if(callcurlfunction('https://api.stripe.com/v1/checkout/sessions/'.getget('sid'), '', $jres, '', $GLOBALS['errtext'], FALSE)){
			$piarray=json_decode($jres);
			$paymentintent=$piarray->{'payment_intent'};
		}
		if($paymentintent!=''){
			$sSQL="SELECT ordID,ordStatus,ordTransSession FROM orders WHERE ordPayProvider=23 AND ordID='" . escape_string($ordID) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if($rs['ordTransSession']!=getget('sid')){
					$GLOBALS['errtext']='Stripe Session Error.';
					order_failed();
				}else{
					$success=TRUE;
					$alreadyprocessed=$rs['ordStatus']>=3;
				}
			}else{
				$success=FALSE;
				$GLOBALS['errtext']='Could not find order.';
			}
			ect_free_result($result);
		}else{
			$success=FALSE;
			$GLOBALS['errtext']='Could not get payment intent.';
		}
		if($success&&$paymentintent!=''){
			$GLOBALS['xmlfnheaders']=array("User-Agent: Stripe/v1 RubyBindings/1.12.0","Authorization: Bearer ".$data1,"Content-Type: application/x-www-form-urlencoded");
			if(callcurlfunction('https://api.stripe.com/v1/payment_intents/'.$paymentintent, '', $jres, '', $GLOBALS['errtext'], FALSE)){
				$piarray=json_decode($jres);
				$paymentstatus=$piarray->{'status'};
				if(($ppmethod!=1&&$paymentstatus=='succeeded')||($ppmethod==1&&$paymentstatus=='requires_capture')||$paymentstatus=='processing'){
					if($paymentstatus=='requires_capture') $pendingreason='Pending: Capture'; else $pendingreason='';
					if($paymentstatus=='processing') $pendingreason='Pending: Processing';
					$stripeid=@$piarray->{'id'};
					$ordavs1=@$piarray->{'charges'}->{'data'}[0]->{'payment_method_details'}->{'card'}->{'checks'}->{'address_line1_check'};
					$ordavs2=@$piarray->{'charges'}->{'data'}[0]->{'payment_method_details'}->{'card'}->{'checks'}->{'address_postal_code_check'};
					$ordcvv=@$piarray->{'charges'}->{'data'}[0]->{'payment_method_details'}->{'card'}->{'checks'}->{'cvc_check'};
					ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
					ect_query("UPDATE orders SET ordAuthStatus='" . escape_string($pendingreason) . "',ordAVS='".escape_string(trim($ordavs1.':'.$ordavs2))."',ordCVV='".escape_string($ordcvv)."',ordStatus=3,ordAuthNumber='" . escape_string($stripeid) . "' WHERE ordID='" . escape_string($ordID) . "' AND ordStatus<3") or ect_error();
					if($paymentstatus=='processing'){
						print '<div style="text-align:center;font-weight:bold;margin:50px">' . $GLOBALS['xxGenPro'] . '</div>';
					}else
						do_order_success($ordID,$emailAddr,! $alreadyprocessed,TRUE,! $alreadyprocessed,! $alreadyprocessed,! $alreadyprocessed);
				}else{
					if(@$GLOBALS['debugmode']){
						print @$piarray->{'last_payment_error'}->{'message'} . '<br>';
						print @$piarray->{'status'} . '<br>';
					}
					$GLOBALS['errtext']=$GLOBALS['xxGenPEr'];
					$success=FALSE;
				}
			}else
				$success=FALSE;
		}
		if(!$success)
			order_failed();
	}else{
		$GLOBALS['errtext']='Payment method not set.';
		order_failed();
	}
}elseif(getpost('pprov')=='23'&&getpost('stripeToken')!=''&&getpost('stripeEmail')!=''&&is_numeric(getpost('ordernumber'))){
	$ordID=getpost('ordernumber');
	if(getpayprovdetails(23,$data1,$data2,$data3,$demomode,$ppmethod)){
		$amount=0;
		$success=TRUE;
		$isstripedotcom=TRUE; // For callxmlfunction
		$ordStatus=3;
		$ordTransID='xxxxx';
		$alreadyprocessed=FALSE;
		$token=getpost('stripeToken');
		$chargeid='';

		$sSQL="SELECT ordAuthNumber,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordTotal,ordDiscount,ordAuthNumber,ordTransID,ordEmail,ordStatus FROM orders WHERE ordPayProvider=23 AND ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$email=$rs['ordEmail'];
			$amount=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
			$ordStatus=$rs['ordStatus'];
			$ordTransID=$rs['ordTransID'];
		}else{
			$success=FALSE;
			$GLOBALS['errtext']='The Order ID could not be found.';
		}
		ect_free_result($result);
		if($ordStatus>=3){
			if($ordTransID==$token)
				$alreadyprocessed=TRUE;
			else{
				$success=FALSE;
				$GLOBALS['errtext']='The Stripe.com Order Has Already Been Processed.';
			}
		}elseif($success){
			$sXML="amount=".round($amount*100)."&currency=".strtolower($GLOBALS['countryCurrency'])."&card=".$token."&capture=".($ppmethod==1?"false":"true")."&description=".$email."&metadata[order_id]=".$ordID;
			$GLOBALS['xmlfnheaders']=array("User-Agent: Stripe/v1 RubyBindings/1.12.0","Authorization: Bearer ".$data1,"Content-Type: application/x-www-form-urlencoded");
			$success=callcurlfunction('https://api.stripe.com/v1/charges',$sXML,$xmlres,"",$GLOBALS['errtext'],FALSE);
			$piarray=json_decode($xmlres);
			if($success&&$GLOBALS['http_status']=='200'){
				$chargeid=@$piarray->{'id'};
			}else{
				$success=FALSE;
				$GLOBALS['errtext']=@$piarray->{'error'}->{'message'};
			}
		}
		if($success){
			if(! $alreadyprocessed){
				$sSQL="UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'";
				ect_query($sSQL) or ect_error();
				$sSQL="UPDATE orders SET ordStatus=3,ordAuthStatus='',ordAuthNumber='" . escape_string(substr($chargeid,0,48)) . "',ordTransID='" . escape_string(substr($token,0,48)) . "' WHERE ordPayProvider=23 AND ordID='" . escape_string($ordID) . "'";
				ect_query($sSQL) or ect_error();
			}
			do_order_success($ordID,$emailAddr,! $alreadyprocessed,TRUE,! $alreadyprocessed,! $alreadyprocessed,! $alreadyprocessed);
		}else
			order_failed_htmldisp(FALSE);
	}else{
		$GLOBALS['errtext']='Payment method not set.';
		order_failed();
	}
}elseif(getget('method')=='anethosted'&&is_numeric(getget('ordid'))){
	$ordID=getget('ordid');
	if(getpayprovdetails(3,$data1,$data2,$data3,$demomode,$ppmethod)){
		$fingerprint=strtoupper(hash_hmac('sha512',$data1 . '^' . $ordID . '^' . $GLOBALS['adminSecret'] . '^' . $data2 . '^',hex2bin($data3)));
		if(getget('fp')==$fingerprint){
			$sSQL="SELECT ordID FROM orders WHERE ordPayProvider=3 AND ordStatus>=3 AND ordAuthNumber<>'' AND ordID='" . escape_string($ordID) . "'";
			$result=ect_query($sSQL) or ect_error();
			$GLOBALS['paypalwaitipn']=ect_num_rows($result)<=0;
			ect_free_result($result);
			if($GLOBALS['paypalwaitipn']){
				$GLOBALS['xxThkErr']='';
				ect_query("UPDATE cart SET cartCompleted=2 WHERE cartCompleted=0 AND cartOrderID='" . escape_string($ordID) . "'") or ect_error();
				ect_query("UPDATE orders SET ordAuthNumber='no ipn' WHERE ordAuthNumber='' AND ordPayProvider=3 AND ordID='" . escape_string($ordID) . "'") or ect_error();
				$GLOBALS['errtext']=$GLOBALS['xxPPWIPN'];
				order_failed();
			}else{
				//$GLOBALS['errtext']=$GLOBALS['xxPPTOUT'];
				do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
			}
		}else{
			$GLOBALS['errtext']='Fingerprint mismatch';
			order_failed();
		}
	}
}elseif(getget('ectprnm')=='wpconfirm'&&is_numeric(getget('ordid'))&&is_numeric(getget('pprov'))){
	if(!getpayprovdetails(getget('pprov'),$data1,$data2,$data3,$demomode,$ppmethod)){
		$GLOBALS['errtext']='Payment method not set.';
		order_failed();
	}else{
		$ordID=getget('ordid');
		$rethash=getget('rethash');
		$sSQL="SELECT ordSessionID FROM orders WHERE ordID='".escape_string($ordID)."'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result))$sessionid=$rs['ordSessionID']; else $sessionid='xxx';
		ect_free_result($result);
		$ourhash=strtoupper(md5($ordID.'WPCONFHash'.getget('pprov').$sessionid.'1234'.$adminSecret));
		if($ourhash==$rethash){
			do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
		}else{
			$GLOBALS['errtext']='Hash values do not match';
			order_failed();
		}
	}
}elseif(getget('PNREF')!='' && getget('SECURETOKEN')!='' && getget('SECURETOKENID')!=''){ // PayPal Advanced
	$txn_id=getget('PPREF');
	$ordID=getget('INVOICE');
	print '<script language="javascript">if(window!=top)top.location.href=location.href</script>';
	$success=FALSE;
	if(getget('RESULT')=='0' && is_numeric($ordID)){
		if($txn_id!=''){
			$sSQL="SELECT ordAuthNumber FROM orders WHERE ordPayProvider=22 AND ordStatus>=3 AND ordAuthNumber='" . escape_string($txn_id) . "' AND ordID='" . escape_string($ordID) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result))
				$success=(trim($rs['ordAuthNumber'])!='');
			ect_free_result($result);
		}
		if($success)
			do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
		else{
			$sSQL="SELECT ordAuthNumber,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordTotal,ordDiscount,ordAuthNumber,ordEmail FROM orders WHERE ordPayProvider=8 AND ordID='" . escape_string($ordID) . "'";
			$result=ect_query($sSQL) or ect_error();
			$ispayflowtxn=FALSE;
			if($rs=ect_fetch_assoc($result)){
				$amount=number_format(($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'],2,'.','');
				$ispayflowtxn=TRUE;
			}
			ect_free_result($result);
			if($ispayflowtxn && getpayprovdetails(8,$data1,$data2,$data3,$demomode,$ppmethod)){
				$vsdetails=explode('&', $data1);
				$vs1=@$vsdetails[0];
				$vs2=@$vsdetails[1];
				$vs3=@$vsdetails[2];
				$vs4=@$vsdetails[3];
				$sXML='TRXTYPE=I&TENDER=C&PARTNER='.$vs3.'&VENDOR='.$vs2.'&USER='.$vs1.'&PWD='.$vs4.'&SECURETOKEN='.getget('SECURETOKEN').'&SECURETOKENID='.getget('SECURETOKENID').'&VERBOSITY=HIGH';
				$success=callcurlfunction('https://' . ($demomode?'pilot-':'') . 'payflowpro.paypal.com', $sXML, $curString, '', $GLOBALS['errtext'], TRUE);
				$resparr=explode('&',$curString);
				$AUTHCODE=$RESPMSG=$AVSADDR=$AVSZIP=$CVV2MATCH=$RESULT=$TRANSTIME=$AMT='';
				foreach($resparr as $val){
					$itemarr=explode('=',$val);
					if($itemarr[0]=='AUTHCODE') $AUTHCODE=$itemarr[1];
					if($itemarr[0]=='RESPMSG') $GLOBALS['errtext']=$itemarr[1];
					if($itemarr[0]=='AVSADDR ') $AVSADDR =$itemarr[1];
					if($itemarr[0]=='AVSZIP') $AVSZIP=$itemarr[1];
					if($itemarr[0]=='CVV2MATCH') $CVV2MATCH=$itemarr[1];
					if($itemarr[0]=='RESULT') $RESULT=$itemarr[1];
					if($itemarr[0]=='TRANSTIME') $TRANSTIME=$itemarr[1];
					if($itemarr[0]=='AMT') $AMT=$itemarr[1];
				}
				if($AUTHCODE=='') $AUTHCODE=$txn_id;
				$daysago=abs(time() - strtotime($TRANSTIME)) / (60*60*24);
				if($RESULT=='0' && $AUTHCODE!='' & $daysago<=1 && abs($amount-(float)$AMT)<=0.01){
					$alreadysentemail=TRUE;
					$result=ect_query("SELECT ordStatus FROM orders WHERE ordID='" . escape_string($ordID) . "'") or ect_error();
					if($rs=ect_fetch_assoc($result)) $alreadysentemail=$rs['ordStatus']>=3;
					ect_free_result($result);
					if(!$alreadysentemail){
						ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
						ect_query("UPDATE orders SET ordStatus=3,ordAVS='".escape_string($AVSADDR.$AVSZIP)."',ordCVV='".escape_string($CVV2MATCH)."',ordAuthNumber='".escape_string($AUTHCODE)."',ordTransID='".escape_string(getget('PNREF'))."' WHERE ordPayProvider=8 AND ordID='" . escape_string($ordID) . "'") or ect_error();
					}
					do_order_success($ordID,$emailAddr,$sendEmail && ! $alreadysentemail,TRUE,! $alreadysentemail,! $alreadysentemail,! $alreadysentemail);
				}else
					order_failed();
			}else{
				ect_query("UPDATE cart SET cartCompleted=2 WHERE cartCompleted=0 AND cartOrderID='" . escape_string($ordID) . "'") or ect_error();
				ect_query("UPDATE orders SET ordAuthNumber='no ipn' WHERE ordAuthNumber='' AND ordPayProvider=22 AND ordID='" . escape_string($ordID) . "'") or ect_error();
				$GLOBALS['xxThkErr']='';
				$GLOBALS['errtext']='&nbsp;<br>&nbsp;<br>&nbsp;<br>';
				if(strtolower(getrequest('PENDINGREASON'))=='pending')
					$GLOBALS['errtext'].=$GLOBALS['xxPPPend'];
				else{
					$sSQL="SELECT ordID FROM orders WHERE ordPayProvider=22 AND ordAuthNumber='no ipn' AND ordID='" . escape_string($ordID) . "'";
					$result=ect_query($sSQL) or ect_error();
					$GLOBALS['paypalwaitipn']=ect_num_rows($result)>0;
					ect_free_result($result);
					if($GLOBALS['paypalwaitipn']) $GLOBALS['errtext']=$GLOBALS['xxPPWIPN']; else $GLOBALS['errtext']=$GLOBALS['xxPPTOUT'];
				}
				order_failed_htmldisp(FALSE);
			}
		}
	}else{
		$GLOBALS['errtext']=urldecode(getget('RESPMSG'));
		order_failed();
	}
}elseif(@$paypalhostedsolution && getget('tx')!=''){
	if(!getpayprovdetails(18,$data1,$data2,$data3,$demomode,$ppmethod)){
		$GLOBALS['errtext']='Payment method not set.';
		order_failed();
	}else{
		$data2arr=explode('&',$data2);
		$data2=urldecode(@$data2arr[0]);
		$isthreetoken=(trim(urldecode(@$data2arr[2]))=='1');
		$signature=''; $sslcertpath='';
		if($isthreetoken) $signature=urldecode(@$data2arr[1]); else $sslcertpath=urldecode(@$data2arr[1]);
		if(strpos($data1,'@AB@')!==FALSE){
			$isthreetoken=TRUE;
			$signature='AB';
		}
		$sXML='PWD=' . $data2 . '&USER=' . $data1 . ($signature!='' ? '&SIGNATURE=' . $signature : '') . '&METHOD=GetTransactionDetails&VERSION=84.0&TRANSACTIONID=' . getget('tx');
		if(callcurlfunction('https://api-3t' . ($demomode?'.sandbox':'') . '.paypal.com/nvp', $sXML, $res, $sslcertpath, $GLOBALS['errtext'], FALSE)){
			$lines=explode('&', $res);
			$payment_status='';
			$pending_reason='';
			$txn_id='';
			for ($i=1; $i<(count($lines)-1);$i++){
				list($key,$val)=explode('=', $lines[$i]);
				if($key=='ACK') $success=($val=='Success');
				if($key=='PAYMENTSTATUS') $payment_status=$val;
				if($key=='PENDINGREASON') $pending_reason=$val;
				if($key=='CUSTOM') $ordID=str_replace("'",'',$val);
				if($key=='TRANSACTIONID') $txn_id=str_replace("'",'',$val);
				if($key=='L_LONGMESSAGE0') $GLOBALS['errtext']=urldecode($val);
			}
			if($success){
				$sSQL="SELECT ordAuthNumber FROM orders WHERE ordPayProvider=1 AND ordStatus>=3 AND ordAuthNumber='" . escape_string($txn_id) . "' AND ordID='" . escape_string($ordID) . "'";
				$result=ect_query($sSQL) or ect_error();
				$success=FALSE;
				if($rs=ect_fetch_assoc($result))
					$success=(trim($rs["ordAuthNumber"])!="");
				ect_free_result($result);
				if($success)
					do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
				else{
					ect_query("UPDATE cart SET cartCompleted=2 WHERE cartCompleted=0 AND cartOrderID='" . escape_string($ordID) . "'") or ect_error();
					ect_query("UPDATE orders SET ordAuthNumber='no ipn' WHERE ordAuthNumber='' AND ordPayProvider=1 AND ordID='" . escape_string($ordID) . "'") or ect_error();
					$GLOBALS['xxThkErr']='';
					if($payment_status=='Pending')
						$GLOBALS['errtext']=$GLOBALS['xxPPPend'];
					else{
						$sSQL="SELECT ordID FROM orders WHERE ordPayProvider=1 AND ordAuthNumber='no ipn' AND ordID='" . escape_string($ordID) . "'";
						$result=ect_query($sSQL) or ect_error();
						$GLOBALS['paypalwaitipn']=ect_num_rows($result)>0;
						ect_free_result($result);
						if($GLOBALS['paypalwaitipn']) $GLOBALS['errtext']=$GLOBALS['xxPPWIPN']; else $GLOBALS['errtext']=$GLOBALS['xxPPTOUT'];
					}
					order_failed();
				}
			}else
				order_failed_htmldisp(FALSE);
		}
	}
// }elseif(getget('amt')!='' && getget('tx')!='' && getget('st')!='' && getget('cc')!='' && getget('cm')!=''){
}elseif(getget('amt')!='' && getget('tx')!='' && getget('st')!='' && getget('cc')!=''){
	$ordID='';
	if(!getpayprovdetails(1,$data1,$data2,$data3,$demomode,$ppmethod)){
		$GLOBALS['errtext']='Payment method not set.';
		order_failed();
	}elseif($data2==''){
		$GLOBALS['errtext']='Identity token for PayPal Payment Data Transfer (PDT) not set.';
		order_failed();
	}else{
		$success=TRUE;
		$req='cmd=_notify-synch';
		$req.='&tx=' . getget('tx') . '&at=' . $data2;
		if(!callcurlfunction('https://www' . ($demomode?'.sandbox':'') . '.paypal.com/cgi-bin/webscr', $req, $res, '', $GLOBALS['errtext'], 30)){
			$success=FALSE;
			order_failed();
		}
		if($success){
			$lines=explode("\n", $res);
			if(strcmp ($lines[0], "SUCCESS")==0){
				$payment_status='';
				$pending_reason='';
				$txn_id='';
				for ($i=1; $i<(count($lines)-1);$i++){
					list($key,$val)=explode("=", $lines[$i]);
					if($key=='payment_status') $payment_status=$val;
					if($key=='pending_reason') $pending_reason=$val;
					if($key=='custom') $ordID=$val;
					if($key=='txn_id') $txn_id=$val;
				}
				$sSQL="SELECT ordAuthNumber FROM orders WHERE ordPayProvider=1 AND ordStatus>=3 AND ordAuthNumber='" . escape_string($txn_id) . "' AND ordID='" . escape_string($ordID) . "'";
				$result=ect_query($sSQL) or ect_error();
				$success=FALSE;
				if($rs=ect_fetch_assoc($result))
					$success=(trim($rs["ordAuthNumber"])!="");
				ect_free_result($result);
				if($success)
					do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
				else{
					ect_query("UPDATE cart SET cartCompleted=2 WHERE cartCompleted=0 AND cartOrderID='" . escape_string($ordID) . "'") or ect_error();
					ect_query("UPDATE orders SET ordAuthNumber='no ipn' WHERE ordAuthNumber='' AND ordPayProvider=1 AND ordID='" . escape_string($ordID) . "'") or ect_error();
					$GLOBALS['xxThkErr']='';
					if($payment_status=='Pending')
						$GLOBALS['errtext'].=$GLOBALS['xxPPPend'];
					else{
						$sSQL="SELECT ordID FROM orders WHERE ordPayProvider=1 AND ordAuthNumber='no ipn' AND ordID='" . escape_string($ordID) . "'";
						$result=ect_query($sSQL) or ect_error();
						$GLOBALS['paypalwaitipn']=ect_num_rows($result)>0;
						ect_free_result($result);
						if($GLOBALS['paypalwaitipn']) $GLOBALS['errtext']=$GLOBALS['xxPPWIPN']; else $GLOBALS['errtext']=$GLOBALS['xxPPTOUT'];
					}
					order_failed();
				}
			}else{
				$GLOBALS['errtext']=$res;
				order_failed();
			}
		}
	}
}elseif(getpost('custom')!=''){ // PayPal
	$ordID=getpost('custom');
	$txn_id=getpost('txn_id');
	$sSQL="SELECT ordAuthNumber FROM orders WHERE ordPayProvider=1 AND ordStatus>=3 AND ordAuthNumber='" . escape_string($txn_id) . "' AND ordID='" . escape_string($ordID) . "'";
	$result=ect_query($sSQL) or ect_error();
	$success=FALSE;
	if($rs=ect_fetch_assoc($result))
		$success=(trim($rs["ordAuthNumber"])!="");
	ect_free_result($result);
	if($success)
		do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
	else{
		ect_query("UPDATE cart SET cartCompleted=2 WHERE cartCompleted=0 AND cartOrderID='" . escape_string($ordID) . "'") or ect_error();
		ect_query("UPDATE orders SET ordAuthNumber='no ipn' WHERE ordAuthNumber='' AND ordPayProvider=1 AND ordID='" . escape_string($ordID) . "'") or ect_error();
		$GLOBALS['xxThkErr']='';
		$GLOBALS['errtext']='&nbsp;<br>&nbsp;<br>&nbsp;<br>';
		if(getpost('payment_status')=="Pending")
			$GLOBALS['errtext'].=$GLOBALS['xxPPPend'];
		else{
			$sSQL="SELECT ordID FROM orders WHERE ordPayProvider=1 AND ordAuthNumber='no ipn' AND ordID='" . escape_string($ordID) . "'";
			$result=ect_query($sSQL) or ect_error();
			$GLOBALS['paypalwaitipn']=ect_num_rows($result)>0;
			ect_free_result($result);
			if($GLOBALS['paypalwaitipn']) $GLOBALS['errtext']=$GLOBALS['xxPPWIPN']; else $GLOBALS['errtext']=$GLOBALS['xxPPTOUT'];
		}
		order_failed();
	}
}elseif(getpost('method')=='paypalexpress' && getpost('token')!=''){ // PayPal Express
	if($success=getpayprovdetails(19,$username,$password,$data3,$demomode,$ppmethod)){
		$data2arr=explode('&',$password);
		$password=urldecode(@$data2arr[0]);
		$isthreetoken=(trim(urldecode(@$data2arr[2]))=='1');
		$signature=''; $sslcertpath='';
		if($isthreetoken){
			$signature=urldecode(@$data2arr[1]);
			if(strpos($username,'/')!==FALSE){
				$username=explode('/',$username);$username=trim($username[0]);
				$password=explode('/',$password);$password=trim($password[0]);
				$signature=explode('/',$signature);$signature=trim($signature[0]);
			}
		}else
			$sslcertpath=urldecode(@$data2arr[1]);
		if(strpos($username,'@AB@')!==FALSE){
			$isthreetoken=TRUE;
			$signature='AB';
		}
	}
	$ordID=getpost('ordernumber');
	$token=getpost('token');
	$payerid=getpost('payerid');
	$ordAuthNumber=$ordauthstatus=$txn_id=$status=$pendingreason='';
	if($demomode) $sandbox='.sandbox'; else $sandbox='';
	$sSQL="SELECT ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordTotal,ordDiscount,ordAuthNumber,ordAuthStatus,ordEmail FROM orders WHERE ordID='" . escape_string($ordID) . "'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		if($rs["ordEmail"]==getpost('email')) $ordAuthNumber=$rs["ordAuthNumber"];
		$ordauthstatus=$rs['ordAuthStatus'];
	}else
		$success=FALSE;
	ect_free_result($result);
	if($success&&@$GLOBALS['termsandconditions']){
		if(getpost('termsandconds')!='1'){
			$GLOBALS['errtext']='You must agree to our terms and conditions in order to complete your order. Please click below to go back and try again.';
			$GLOBALS['errtext'].='<br>&nbsp;<br>&nbsp;<br>&nbsp;<br><input type="button" class="ectbutton" value="'.$GLOBALS['xxGoBack'].'" onclick="history.go(-1)" /><br>&nbsp;<br>&nbsp;<br>';
			$success=FALSE;
		}
	}elseif($ordauthstatus=='MODWARNOPEN'){
		$GLOBALS['errtext']=$GLOBALS['xxMoWnRC'];
		$success=FALSE;
	}
	if($success){
		if($ordAuthNumber==''){
			$amount=number_format(($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'],2,'.','');
			$sXML=ppsoapheader($username, $password, $signature) .
				'<soap:Body>' .
				'  <DoExpressCheckoutPaymentReq xmlns="urn:ebay:api:PayPalAPI">' .
				'    <DoExpressCheckoutPaymentRequest>' .
				'      <Version xmlns="urn:ebay:apis:eBLBaseComponents">60.00</Version>' .
				'      <DoExpressCheckoutPaymentRequestDetails xmlns="urn:ebay:apis:eBLBaseComponents">' .
				'        <PaymentAction>' . ($ppmethod==1?'Authorization':'Sale') . '</PaymentAction>' .
				'        <Token>' . $token . '</Token><PayerID>' . $payerid . '</PayerID>' .
				'        <PaymentDetails>' .
				'          <OrderTotal currencyID="' . $GLOBALS['countryCurrency'] . '">' . $amount . '</OrderTotal>' .
				'          <ButtonSource>ecommercetemplates_Cart_EC_US</ButtonSource>' .
				'    <NotifyURL>' . $storeurlssl . 'vsadmin/ppconfirm.php</NotifyURL>' .
				'        </PaymentDetails>' .
				'      </DoExpressCheckoutPaymentRequestDetails>' .
				'    </DoExpressCheckoutPaymentRequest>' .
				'  </DoExpressCheckoutPaymentReq>' .
				'</soap:Body></soap:Envelope>';
			if(callcurlfunction('https://api' . ($isthreetoken ? '-3t' : '') . $sandbox . '.paypal.com/2.0/', $sXML, $res, $sslcertpath, $GLOBALS['errtext'], FALSE)){
				$xmlDoc=new vrXMLDoc($res);
				$nodeList=$xmlDoc->nodeList->childNodes[0];
				for($i=0; $i < $nodeList->length; $i++){
					if($nodeList->nodeName[$i]=='SOAP-ENV:Body'){
						$e=$nodeList->childNodes[$i];
						for($j=0; $j < $e->length; $j++){
							if($e->nodeName[$j]=='DoExpressCheckoutPaymentResponse'){
								$ee=$e->childNodes[$j];
								for($jj=0; $jj < $ee->length; $jj++){
									if($ee->nodeName[$jj]=='Token'){
										$token=$ee->nodeValue[$jj];
									}elseif($ee->nodeName[$jj]=='DoExpressCheckoutPaymentResponseDetails'){
										$ff=$ee->childNodes[$jj];
										for($kk=0; $kk < $ff->length; $kk++){
											if($ff->nodeName[$kk]=='PaymentInfo'){
												$gg=$ff->childNodes[$kk];
												for($ll=0; $ll < $gg->length; $ll++){
													if($gg->nodeName[$ll]=='PaymentStatus'){
														$status=$gg->nodeValue[$ll];
													}elseif($gg->nodeName[$ll]=='PendingReason'){
														$pendingreason=$gg->nodeValue[$ll];
													}elseif($gg->nodeName[$ll]=='TransactionID'){
														$txn_id=$gg->nodeValue[$ll];
													}
												}
											}
										}
									}elseif($ee->nodeName[$jj]=='Errors'){
										$ff=$ee->childNodes[$jj];
										for($kk=0; $kk < $ff->length; $kk++){
											if($ff->nodeName[$kk]=='ShortMessage'){
												//$GLOBALS['errtext']=$ff->nodeValue[$kk].'<br>'.$GLOBALS['errtext'];
											}elseif($ff->nodeName[$kk]=='LongMessage'){
												$GLOBALS['errtext'].=$ff->nodeValue[$kk];
											}elseif($ff->nodeName[$kk]=='ErrorCode'){
												$errcode=$ff->nodeValue[$kk];
												$GLOBALS['errtext']='(' . $errcode . ') ' . $GLOBALS['errtext'];
												if($errcode=='10486' || $errcode=='10422'){
													if(ob_get_length()===FALSE){
														print '<meta http-equiv="Refresh" content="0; URL=https://www'.$sandbox.'.paypal.com/webscr?cmd=_express-checkout&token=' . $token . '">';
													}else
														header('Location: https://www'.$sandbox.'.paypal.com/webscr?cmd=_express-checkout&token=' . $token);
													print '<p align="center">' . $GLOBALS['xxAutFo'] . '</p>';
													print '<p align="center">' . $GLOBALS['xxForAut'] . ' <a class="ectlink" href="https://www'.$sandbox.'.paypal.com/webscr?cmd=_express-checkout&token=' . $token . '">' . $GLOBALS['xxClkHere'] . '</a></p>';
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}else
				$success=FALSE;
		}else
			$status="Refresh";
		if($status=="Completed" || $status=="Pending"){
			if($pendingreason=='authorization') $pendingreason='Capture';
			if($status=='Pending' && $pendingreason!='') $pendingreason='Pending: ' . $pendingreason; else $pendingreason='';
			ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
			ect_query("UPDATE orders SET ordStatus=3,ordAuthNumber='" . $txn_id . "',ordAuthStatus='" . escape_string($pendingreason) . "',ordAddInfo='" . escape_string(getpost('ordAddInfo')) . "' WHERE ordPayProvider=19 AND ordID='" . escape_string($ordID) . "'") or ect_error();
			do_order_success($ordID,$emailAddr,$sendEmail,TRUE,TRUE,TRUE,TRUE);
		}elseif($status=='Refresh'){
			do_order_success($ordID,$emailAddr,$sendEmail,TRUE,FALSE,FALSE,FALSE);
		}else
			order_failed();
	}else
		order_failed_htmldisp(FALSE);
}elseif(getget('ncretval')!='' && getget('ncsessid')!=''){ // NOCHEX
	$ordID=getget('ncretval');
	$ncsessid=getget('ncsessid');
	$sSQL="SELECT ordAuthNumber FROM orders WHERE ordPayProvider=6 AND ordStatus>=3 AND ordSessionID='" . escape_string($ncsessid) . "' AND ordID='" . escape_string($ordID) . "'";
	$result=ect_query($sSQL) or ect_error();
	$success=FALSE;
	if($rs=ect_fetch_assoc($result))
		$success=(trim($rs["ordAuthNumber"])!="");
	ect_free_result($result);
	if($success)
		do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
	else{
		ect_query("UPDATE cart SET cartCompleted=2 WHERE cartCompleted=0 AND cartOrderID='" . escape_string($ordID) . "'") or ect_error();
		ect_query("UPDATE orders SET ordAuthNumber='no apc' WHERE ordAuthNumber='' AND ordPayProvider=6 AND ordID='" . escape_string($ordID) . "'") or ect_error();
		$GLOBALS['errtext']=$GLOBALS['xxNoCnf'];
		$GLOBALS['xxThkErr']='';
		$GLOBALS['showclickreload']=TRUE;
		order_failed();
	}
}elseif(getpost('txn_id')!='' && getpost('payer_id')!='' && getpost('payment_gross')!=''){ // PayPal (Now not returning "custom" parameter)
	$txn_id=getpost('txn_id');
	$sSQL="SELECT ordID,ordAuthNumber,ordStatus FROM orders WHERE ordDate>='" . date('Y-m-d',time()-(36*60*60)) . "' AND ordPayProvider=1 AND ordAuthNumber='" . escape_string($txn_id) . "'";
	$result=ect_query($sSQL) or ect_error();
	$success=FALSE;
	if($rs=ect_fetch_assoc($result)){
		$success=($rs['ordStatus']>=3);
		$ordID=$rs['ordID'];
	}
	ect_free_result($result);
	if($success)
		do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
	else{
		$GLOBALS['xxThkErr']='';
		$GLOBALS['errtext']='&nbsp;<br>&nbsp;<br>&nbsp;<br>';
		if(getpost('payment_status')=="Pending")
			$GLOBALS['errtext'].=$GLOBALS['xxPPPend'];
		else{
			$GLOBALS['paypalwaitipn']=TRUE;
			$GLOBALS['errtext']=$GLOBALS['xxPPWIPN'];
		}
		order_failed();
	}
}elseif(getpost('xxpreauth')!=''){
	$ordID=getpost('xxpreauth');
	$thesessionid=trim(str_replace("'",'',getpost('thesessionid')));
	$themethod=trim(str_replace("'",'',getpost('xxpreauthmethod')));
	if($success=getpayprovdetails($themethod,$data1,$data2,$data3,$demomode,$ppmethod)){
		$sSQL="SELECT ordAuthNumber FROM orders WHERE ordSessionID='" . escape_string($thesessionid) . "' AND ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		$success=FALSE;
		if($rs=ect_fetch_assoc($result))
			$success=(trim($rs['ordAuthNumber'])!='');
		ect_free_result($result);
	}
	if($success)
		do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
	else
		order_failed();
}elseif(is_numeric(getget('sid')) && is_numeric(getget('merchant_order_id')) && is_numeric(getget('total')) && getget('order_number')!=''){ // 2Checkout Transaction
	if(getget('credit_card_processed')=='Y'){
		$ordID=getget('merchant_order_id');
		$success=getpayprovdetails(2,$acctno,$md5key,$data3,$demomode,$ppmethod);
		$keysmatch=TRUE;
		if($md5key!=''){
			$theirkey=getget('key');
			$ourkey=trim(strtoupper(md5($md5key . $acctno . ($demomode ? '1' : getget('order_number')) . getget('total'))));
			if($ourkey==$theirkey) $keysmatch=TRUE; else $keysmatch=FALSE;
		}
		if($success && $keysmatch){
			$sSQL="SELECT ordAuthNumber,((ordShipping+ordStateTax+ordCountryTax+ordHSTTax+ordTotal+ordHandling)-ordDiscount) AS ordGndTot FROM orders WHERE ordID=" . $ordID;
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)) $ordGndTot=$rs['ordGndTot']; else $ordGndTot=0;
			ect_free_result($result);
			ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
			if($ordGndTot!=(float)getget('total')) $ordAuthStatus='Pending: Total Paid ' . getget('total'); else $ordAuthStatus='';
			ect_query("UPDATE orders SET ordStatus=3,ordAuthStatus='',ordAuthNumber='" . escape_string(getget('order_number')) . "',ordAuthStatus='" . $ordAuthStatus . "' WHERE ordPayProvider=2 AND ordID='" . escape_string($ordID) . "'") or ect_error();
			order_success($ordID,$emailAddr,$sendEmail);
		}else{
			order_failed();
		}
	}else
		order_failed();
}elseif(getpost('CUSTID')!='' && (getpost('AUTHCODE')!=''||getpost('PNREF')!='')){ // PayFlow Link
	$success=getpayprovdetails(8,$data1,$data2,$data3,$demomode,$ppmethod);
	if($success && getpost('RESULT')=='0'){
		$ordID=getpost('CUSTID');
		ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
		ect_query("UPDATE orders SET ordStatus=3,ordAuthStatus='',ordAVS='" . escape_string(getpost('AVSDATA')) . "',ordCVV='" . escape_string(getpost('CSCMATCH')) . "',ordAuthNumber='" . escape_string(getpost('AUTHCODE')) . "' WHERE ordPayProvider=8 AND ordID='" . escape_string($ordID) . "'") or ect_error();
		order_success($ordID,$emailAddr,$sendEmail);
	}else{
		$GLOBALS['errtext']=getpost('RESPMSG');
		order_failed();
	}
}elseif(getpost('emailorder')!='' || getpost('secondemailorder')!=''){
	$ordGndTot=1;
	$orderstatus=0;
	$ordauthstatus='';
	if(@$emailorderstatus!='') $ordStatus=$emailorderstatus; else $ordStatus=3;
	if(getpost('emailorder')!=''){
		$ordID=trim(str_replace("'",'',getpost('emailorder')));
		$ppid=4;
		$authnumber='Email Order';
	}else{
		$ordID=trim(str_replace("'",'',getpost('secondemailorder')));
		$ppid=17;
		$authnumber='Email2 Order';
	}
	$thesessionid=trim(str_replace("'",'',getpost('thesessionid')));
	$alreadysentemail=TRUE;
	$success=is_numeric($ordID);
	if($success){
		$sSQL="SELECT ordStatus,ordAuthStatus,ordAuthNumber,((ordShipping+ordStateTax+ordCountryTax+ordHSTTax+ordTotal+ordHandling)-ordDiscount) AS ordGndTot FROM orders WHERE ordSessionID='" . escape_string($thesessionid) . "' AND ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$orderstatus=$rs['ordStatus'];
			$alreadysentemail=$rs['ordStatus']>=3;
			$ordGndTot=round($rs['ordGndTot'],2);
			$ordauthstatus=$rs['ordAuthStatus'];
		}else
			$success=FALSE;
		ect_free_result($result);
	}
	if($orderstatus<2||$ordauthstatus=='MODWARNOPEN'){
		$GLOBALS['errtext']='We apologize but this order seems to have been deleted. Please try checking out again.';
		$success=FALSE;
	}
	if($success && recaptchaenabled(256)){
		$success=checkrecaptcha($GLOBALS['errtext']);
		if(! $success){ $ordID=0; $GLOBALS['errtext']='reCAPTCHA failure. If you inadvertently refreshed this page, your order has been logged in our system.<br>' . $GLOBALS['errtext']; }
	}
	if(! $alreadysentemail && $success){
		$sSQL="SELECT ordAuthNumber,((ordShipping+ordStateTax+ordCountryTax+ordHSTTax+ordTotal+ordHandling)-ordDiscount) AS ordGndTot FROM orders WHERE ordSessionID='" . escape_string($thesessionid) . "' AND ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		$success=FALSE;
		if($rs=ect_fetch_assoc($result)){
			$success=TRUE;
			$ordGndTot=round($rs['ordGndTot'],2);
		}
		ect_free_result($result);
		$sSQL="SELECT payProvShow FROM payprovider WHERE (payProvEnabled=1 OR ".$ordGndTot."=0) AND payProvID=" . $ppid;
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			if($ordGndTot==0){ // Check if it was a gift cert
				$sSQL="SELECT gcaGCID FROM giftcertsapplied WHERE gcaOrdID='" . escape_string($ordID) . "'";
				$result2=ect_query($sSQL) or ect_error();
				if(ect_num_rows($result2)>0) $authnumber=$GLOBALS['xxGifCtc'];
				ect_free_result($result2);
			}
			if($authnumber=='') $authnumber='Email';
		}else
			$success=FALSE;
		ect_free_result($result);
	}
	if($success && $alreadysentemail)
		do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
	elseif($success){
		ect_query("UPDATE cart SET cartDateAdded='" . date('Y-m-d',time()+($GLOBALS['dateadjust']*60*60)) . "',cartCompleted=1 WHERE cartCompleted<>1 AND cartOrderID='" . escape_string($ordID) . "'") or ect_error();
		ect_query("UPDATE orders SET ordStatus=" . $ordStatus . ",ordAuthStatus='',ordAuthNumber='" . escape_string(mb_substr($authnumber,0,48)) . "',ordDate='" . date('Y-m-d H:i:s',time()+($GLOBALS['dateadjust']*60*60)) . "' WHERE ordAuthNumber='' AND (ordPayProvider=" . $ppid . " OR (ordTotal-ordDiscount)<=0) AND ordID='" . escape_string($ordID) . "'") or ect_error();
		order_success($ordID,$emailAddr,$sendEmail);
	}else
		order_failed_htmldisp(FALSE);
}elseif(getget('OrderID')!='' && getget('TransRefNumber')!=''){ // PSiGate
	$sSQL='SELECT payProvID FROM payprovider WHERE payProvEnabled=1 AND payProvID=11 OR payProvID=12';
	$result=ect_query($sSQL) or ect_error();
	$success=(ect_num_rows($result) > 0);
	ect_free_result($result);
	if(getget('Approved') != 'APPROVED') $success=FALSE;
	if(getget('CustomerRefNo') != substr(md5(getget('OrderID').':'.@$secretword), 0, 24)) $success=FALSE;
	if($success){
		$ordID=getget('OrderID');
		ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
		ect_query("UPDATE orders SET ordStatus=3,ordAuthStatus='',ordAVS='" . escape_string(getget('AVSResult').'/'.getget('IPResult')) . "',ordCVV='" . escape_string(getget('CardIDResult')) . "',ordAuthNumber='" . escape_string(getget('CardAuthNumber')) . "',ordTransID='" . escape_string(getget('CardRefNumber')) . "' WHERE (ordPayProvider=11 OR ordPayProvider=12) AND ordID='" . escape_string($ordID) . "'") or ect_error();
		order_success($ordID,$emailAddr,$sendEmail);
	}else{
		$GLOBALS['errtext']=getget('ErrMsg');
		order_failed();
	}
}elseif(getpost('ponumber')!='' && (getpost('approval_code')!='' || getpost('failReason')!='')){ // Linkpoint
	$ordID=escape_string(getpost('ponumber'));
	$ordIDa=explode('.', $ordID);
	$ordID=$ordIDa[0];
	if(is_numeric($ordID) && getpayprovdetails(16,$data1,$data2,$data3,$demomode,$ppmethod)){
		$theauthcode=escape_string(getpost('approval_code'));
		$thesuccess=strtolower(getpost('status'));
		if(($thesuccess=="approved" || $thesuccess=="submitted") && $theauthcode!=''){
			$autharr=explode(':', $theauthcode);
			if($autharr[0]=='Y' && count($autharr) >= 3){
				$theauthcode=$autharr[1];
				$theavscode=$autharr[2];
				$sSQL="SELECT ordID FROM orders WHERE ordAuthNumber='" . substr($theauthcode,0,6) . "' AND ordPayProvider=16 AND ordID='" . escape_string($ordID) . "'";
				$result=ect_query($sSQL) or ect_error();
				$foundorder=(ect_num_rows($result)>0);
				ect_free_result($result);
				if($foundorder){
					do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
				}else{
					ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='$ordID'") or ect_error();
					ect_query("UPDATE orders SET ordStatus=3,ordAuthStatus='',ordAVS='" . escape_string(substr($theavscode,0,3)) . "',ordCVV='" . escape_string(substr($theavscode,3)) . "',ordAuthNumber='" . substr($theauthcode,0,6) . "',ordTransID='" . substr($theauthcode,6) . "' WHERE ordPayProvider=16 AND ordID='" . escape_string($ordID) . "'") or ect_error();
					order_success($ordID,$emailAddr,$sendEmail);
				}
			}else{
				$GLOBALS['errtext']='Invalid auth code';
				order_failed();
			}
		}else{
			$GLOBALS['errtext']=getpost('failReason');
			$errtextarr=explode(':', $GLOBALS['errtext']);
			if(@$errtextarr[1]!='') $GLOBALS['errtext']=$errtextarr[1];
			order_failed();
		}
	}else
		order_failed();
}elseif(getpost('oid')!='' && getpost('response_hash')!='' && getpost('txndate_processed')!=''){ // Linkpoint 2.0
	$ordID=getpost('oid');
	$ordIDa=explode('.', $ordID);
	$ordID=$ordIDa[0];
	$theauthcode=trim(replace(getpost('approval_code'),"'",''));
	$lphash=getpost('response_hash');
	if(is_numeric($ordID) && getpayprovdetails(16,$data1,$data2,$data3,$demomode,$ppmethod)){
		$sSQL="SELECT ordPrivateStatus FROM orders WHERE ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $txndatetime=$rs['ordPrivateStatus']; else $txndatetime='';
		ect_free_result($result);
		$str=$data3 . $theauthcode . getpost('chargetotal') . '840' . $txndatetime . $data1;
		$hex_str='';
		for($i=0; $i < strlen($str); $i++){
			$hex_str.=dechex(ord($str[$i]));
		}
		$ourhash=hash('sha256', $hex_str);
		if($ourhash!=$lphash){
			$GLOBALS['errtext']='Invalid Response Hash';
			order_failed();
		}elseif(strtoupper(getpost('status'))=='APPROVED' || strtoupper(getpost('status'))=='SUBMITTED'){
			$autharr=explode(':', $theauthcode);
			if($autharr[0]=='Y' && count($autharr) >= 3){
				$theauthcode=$autharr[1];
				$theavscode=$autharr[2];
				$sSQL="SELECT ordID FROM orders WHERE ordAuthNumber='" . substr($theauthcode,0,6) . "' AND ordPayProvider=16 AND ordID='" . $ordID . "'";
				$result=ect_query($sSQL) or ect_error();
				$foundorder=(ect_num_rows($result)>0);
				ect_free_result($result);
				if($foundorder){
					do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
				}else{
					ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='$ordID'") or ect_error();
					ect_query("UPDATE orders SET ordStatus=3,ordAuthStatus='',ordAVS='" . escape_string(substr($theavscode,0,3)) . "',ordCVV='" . escape_string(substr($theavscode,3)) . "',ordAuthNumber='" . substr($theauthcode,0,6) . "',ordTransID='" . substr($theauthcode,6) . "' WHERE ordPayProvider=16 AND ordID='" . escape_string($ordID) . "'") or ect_error();
					order_success($ordID,$emailAddr,$sendEmail);
				}
			}else{
				$GLOBALS['errtext']='Invalid auth code';
				order_failed();
			}
		}else{
			$GLOBALS['errtext']=getpost('fail_reason');
			order_failed();
		}
	}else
		order_failed();
}elseif(getget('action')=='opayoserver'&&is_numeric(getget('orderid'))&&getget('checksum')!=''){ // Opayo Server
	if(getpayprovdetails(24,$data1,$data2,$data3,$demomode,$ppmethod)){
		$ordID=getget('orderid');
		print '<script>if(top.location!=location)top.location.href = document.location.href;</script>';
		$sSQL="SELECT ordStatus,ordTransSession FROM orders WHERE ordPayProvider=24 AND ordID='" . escape_string($ordID) . "'";
		$result = ect_query($sSQL) or ect_error();
		if($rs = ect_fetch_assoc($result)){
			$currorderstat=(int)$rs['ordStatus'];
			$SecurityKey=trim($rs['ordTransSession']);
		}
		if($SecurityKey!=''){
			$computedhash=md5($SecurityKey.$GLOBALS['adminSecret'].'opayoserver');
			if($computedhash==getget('checksum')){
				do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
			}else{
				$GLOBALS['errtext']='Hash Check Failed';
				order_failed();
			}
		}
	}
}elseif(substr(getget('crypt'),0,1)=='@' && getpayprovdetails(24,$data1,$data2,$data3,$demomode,$ppmethod)){ // Opayo / SagePay
	function decryptAes($strIn, $password){
		global $StatusDetail;
		$hex = substr($strIn, 1);
		if (!preg_match('/^[0-9a-fA-F]+$/', $hex)){
			$StatusDetail='Invalid encryption string';
			return('');
		}
		$strIn=pack('H*', $hex);
		return openssl_decrypt($strIn, 'AES-128-CBC', $password, OPENSSL_PKCS1_PADDING, $password);
	}
	function getToken($thisString){
		$Tokens = array('Status','StatusDetail','VendorTxCode','VPSTxId','TxAuthNo','Amount','AVSCV2','AddressResult','GiftAid');
		$output = array();
		$resultArray = array();
		for ($i = count($Tokens)-1; $i >= 0 ; $i--){
			$start = strpos($thisString, $Tokens[$i]);
			if ($start !== false){
				$resultArray[$i]=new stdClass();
				$resultArray[$i]->start = $start;
				$resultArray[$i]->token = $Tokens[$i];
			}
		}
		sort($resultArray);
		for ($i = 0; $i<count($resultArray); $i++){
			$valueStart = $resultArray[$i]->start + strlen($resultArray[$i]->token) + 1;
			if ($i==(count($resultArray)-1)) {
				$output[$resultArray[$i]->token] = substr($thisString, $valueStart);
			}else{
				$valueLength = $resultArray[$i+1]->start - $resultArray[$i]->start - strlen($resultArray[$i]->token) - 2;
				$output[$resultArray[$i]->token] = substr($thisString, $valueStart, $valueLength);
			}
		}
		return $output;
	}
	function randomise() {
		list($usec, $sec) = explode(' ', microtime());
		return (float) $sec + ((float) $usec * 100000);
	}
	if(($Decoded=decryptAes(getget('crypt'),$data2))!=''){
		$values = getToken($Decoded);

		$ordID = @$values['VendorTxCode'];
		$Status = @$values['Status'];
		$StatusDetail = @$values['StatusDetail'];
		$VPSTxId = @$values['VPSTxId'];
		$TxAuthNo = @$values['TxAuthNo'];
		$Amount = @$values['Amount'];
		$AVSCV2 = @$values['AVSCV2'];
		$currorderstat=0;
		if($AVSCV2=='ALL DATA MATCHED' || $AVSCV2=='ALL DATA MATCH' || $AVSCV2=='ALL MATCH'){
			$ordAVS='Y';
			$ordCVV='Y';
		}elseif($AVSCV2=='SECURITY CODE MATCH ONLY'){
			$ordAVS='N';
			$ordCVV='Y';
		}elseif($AVSCV2=='ADDRESS MATCH ONLY'){
			$ordAVS='Y';
			$ordCVV='N';
		}elseif($AVSCV2=='NO DATA MATCHES'){
			$ordAVS='N';
			$ordCVV='N';
		}elseif($AVSCV2=='DATA NOT CHECKED'){
			$ordAVS='X';
			$ordCVV='X';
		}else{
			$ordAVS='E';
			$ordCVV='E';
		}
	}
	if($ordID!='' && ($TxAuthNo!=''||$Status=='AUTHENTICATED') && ($Status=='OK'||$Status=='AUTHENTICATED')){
		$theorderarray = explode('-', $ordID);
		$ordID = $theorderarray[0];
		$sSQL="SELECT ordStatus FROM orders WHERE ordPayProvider=24 AND ordID='" . escape_string($ordID) . "'";
		$result = ect_query($sSQL) or ect_error();
		if($rs = ect_fetch_assoc($result))
			$currorderstat=(int)$rs['ordStatus'];
		if($currorderstat==2){
			$ordAuthStatus='';
			$sSQL="UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'";
			ect_query($sSQL) or ect_error();
			if($TxAuthNo==''){
				$ordAuthStatus='Pending: Settlement';
				$TxAuthNo='UNSETTLED';
			}
			$sSQL="UPDATE orders SET ordStatus=3,ordAVS='".$ordAVS."',ordCVV='".$ordCVV."',ordTransID='" . escape_string($VPSTxId) . "',ordAuthNumber='" . escape_string($TxAuthNo) . "',ordAuthStatus='" . escape_string($ordAuthStatus) . "' WHERE ordPayProvider=24 AND ordID='" . escape_string($ordID) . "'";
			ect_query($sSQL) or ect_error();
			order_success($ordID,$emailAddr,$sendEmail);
		}else
			do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
	}else{
		$GLOBALS['errtext']=$StatusDetail;
		order_failed();
	}
}elseif(getget('AccessCode')!='' && getpayprovdetails(30,$data1,$data2,$data3,$demomode,$ppmethod)){ // eWay
	$GLOBALS['xmlfnheaders']=array('Content-Type: application/json');
	$GLOBALS['xmlfnuser']=$data1;
	$GLOBALS['xmlfnpassword']=$data2;
	if(callcurlfunction('https://api.' . ($demomode?'sandbox.':'') . 'ewaypayments.com/AccessCode/'.getget('AccessCode'), '', $jres, '', $GLOBALS['errtext'], 12)){
		$jsarray=json_decode((string)$jres);
		$authcode=@$jsarray->{'AuthorisationCode'};
		$ordID=@$jsarray->{'InvoiceReference'};
		$transid=@$jsarray->{'TransactionID'};
		$ordAVS=@$jsarray->{'Verification'}->{'Address'};
		$ordCVV=@$jsarray->{'Verification'}->{'CVN'};
		$transstatus=@$jsarray->{'TransactionStatus'};
		$respmessage=@$jsarray->{'ResponseMessage'};
		if(is_numeric($ordID)&&$transstatus){
			$alreadysentemail=TRUE;
			$sSQL="SELECT ordStatus FROM orders WHERE ordID='" . escape_string($ordID) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result))
				$alreadysentemail=$rs['ordStatus']>=3;
			ect_free_result($result);
			if(!$alreadysentemail){
				$sSQL="UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'";
				ect_query($sSQL) or ect_error();
				$sSQL="UPDATE orders SET ordStatus=3,ordAVS='" . escape_string($ordAVS) . "',ordCVV='" . escape_string($ordCVV) . "',ordTransID='" . escape_string($transid) . "',ordAuthNumber='" . escape_string($authcode) . "',ordAuthStatus='' WHERE ordPayProvider=30 AND ordID='" . escape_string($ordID) . "'";
				ect_query($sSQL) or ect_error();
			}
			order_success($ordID,$emailAddr,$sendEmail);
		}else{
			$GLOBALS['errtext']=$GLOBALS['xxCCErro'];
			order_failed();
		}
	}else
		order_failed();
}elseif(getget('OrdNo')!='' && getget('ErrMsg')!=''){ // PSiGate Error Reporting
	$GLOBALS['errtext']=getget('ErrMsg');
	order_failed();
}elseif(getget('method')=='globalpayments'){ // Global Payments
	$GLOBALS['errtext']='';
	if(getpayprovdetx(32,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		// timestamp.merchantid.orderid.result.message.pasref.authcode
		$ordID=getget('ORDER_ID');
		$AUTHCODE=getget('AUTHCODE');
		$RESULT=getget('RESULT');
		$hashstring=getget('TIMESTAMP').'.'.$data1.'.'.$ordID.'.'.$RESULT.'.'.getget('MESSAGE').'.'.getget('PASREF').'.'.$AUTHCODE;
		$hashstring=sha1(sha1($hashstring).'.'.$data2);
		$ordID=explode('-',$ordID);
		$ordID=$ordID[0];
		if(!is_numeric($ordID)){
			$GLOBALS['errtext']='Invalid Order ID';
			order_failed();
		}elseif($hashstring!=getget('SHA1HASH')){
			$GLOBALS['errtext']='Invalid Hash Value';
			order_failed();
		}else{
			$isauthorized=TRUE;
			$result=ect_query("SELECT ordStatus FROM orders WHERE ordID='" . escape_string($ordID) . "'") or ect_error();
			if($rs=ect_fetch_assoc($result)) $isauthorized=$rs['ordStatus']>=3;
			ect_free_result($result);
			if($isauthorized){
				do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
			}
		}
	}else{
		$GLOBALS['errtext']='Global Payments Not Enabled';
		order_failed();
	}
}elseif(getget('cko-session-id')!=''&&is_numeric(getget('ordid'))){ // Checkout.com
	$ordID=getget('ordid');
	if(getpayprovdetx(33,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		$GLOBALS['callcurlfunctionhttperrors']=TRUE;
		$GLOBALS['xmlfnheaders']=array("Authorization: ".$data2,'Content-Type: application/json');
		callcurlfunction('https://api.' . ($demomode?'sandbox.':'') . 'checkout.com/payments/' . getget('cko-session-id'),'',$jres,'',$errormsg,FALSE);
		if($jres!=''){
			$jsarray=json_decode((string)$jres);
			if(property_exists(@$jsarray,'approved')){
				if($jsarray->{'approved'}===TRUE){
					$alreadysentemail=TRUE;
					$sSQL="SELECT ordStatus FROM orders WHERE ordID='" . escape_string($ordID) . "'";
					$result=ect_query($sSQL) or ect_error();
					if($rs=ect_fetch_assoc($result))
						$alreadysentemail=$rs['ordStatus']>=3;
					ect_free_result($result);
					if(!$alreadysentemail){
						$transid=$jsarray->{'id'};
						$ordAVS=$jsarray->{'source'}->{'avs_check'};
						$ordCVV=$jsarray->{'source'}->{'cvv_check'};
						$authcode=$jsarray->{'status'};
						if($authcode=='Pending') $pendingreason='Pending: Capture'; else $pendingreason='';
						$sSQL="UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'";
						ect_query($sSQL) or ect_error();
						$sSQL="UPDATE orders SET ordStatus=3,ordAVS='" . escape_string($ordAVS) . "',ordCVV='" . escape_string($ordCVV) . "',ordTransID='" . escape_string($transid) . "',ordAuthNumber='" . escape_string($authcode) . "',ordAuthStatus='" . escape_string($pendingreason) . "' WHERE ordPayProvider=33 AND ordID='" . escape_string($ordID) . "'";
						ect_query($sSQL) or ect_error();
					}
					order_success($ordID,$emailAddr,$sendEmail);
				}else
					$success=FALSE;
			}else
				$success=FALSE;
			if(!$success){
				$success=FALSE;
				$GLOBALS['errtext']=$GLOBALS['xxCCErro'];
				if(property_exists(@$jsarray,'error_codes'))
					$GLOBALS['errtext']=$jsarray->{'error_codes'}[0];
				order_failed();
			}
		}else{
			$GLOBALS['errtext']=$errormsg;
			order_failed();
		}
	}else{
		$GLOBALS['errtext']='Checkout.com Not Enabled';
		order_failed();
	}
}else{
	if(@$GLOBALS['mobilebrowser'] && count(@$_POST)==0 && count(@$_GET)==0 && getpayprovdetails(1,$data1,$data2,$data3,$demomode,$ppmethod)){
		print '<div class="ppmobilereturn0" style="text-align:center;margin:30px"><img src="images/paypalacceptmark.gif" alt="PayPal" /></div><div class="ppmobilereturn1" style="text-align:center;margin:30px">Your PayPal order details have now been received.</div>';
		print '<div class="ppmobilereturn2" style="text-align:center;margin:30px">For those that have paid by PayPal, please check your email inbox for your receipt and order details.</div>';
	}else{
		if(getpayprovdetails(14,$data1,$data2,$data3,$demomode,$ppmethod)){
			@include './vsadmin/inc/customppreturn.php';
		}else{
			$GLOBALS['errtext']='No matching payment system';
			order_failed();
		}
	}
}
if($success && @$GLOBALS['googletagid']!='' && is_numeric($ordID) && $ordID!=0){
	$sSQL="SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity,sectionName,pSKU,pManufacturer FROM cart INNER JOIN products ON cart.cartProdID=products.pID INNER JOIN sections ON products.pSection=sections.sectionID WHERE cartOrderID='".escape_string($ordID)."' ORDER BY cartID";
	$result=ect_query($sSQL) or ect_error();
	$ao='';
	$index=1;
	while($rs=ect_fetch_assoc($result)){
		$sSQL='SELECT SUM(coPriceDiff) AS coPrDff FROM cartoptions WHERE coCartID='. $rs['cartID'];
		$result2=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result2)) $coPriceDiff=$rs2['coPrDff']; else $coPriceDiff=0;
		if(is_null($coPriceDiff)) $coPriceDiff=0;
		$itemtotal=$rs['cartProdPrice']+$coPriceDiff;
		ect_free_result($result2);
		$sSQL='SELECT scName FROM searchcriteria WHERE scID=' . $rs['pManufacturer'];
		$result2=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result2)) $brand=$rs2['scName']; else $brand='';
		if($ao!='') $ao.=',';
		$ao.="{item_id:'" . jsescapel($rs['cartProdID']) . "'," .
			"item_name:'" . jsescapel($rs['cartProdName']) . "'," .
			'index:' . $index++ . ',';
		if($brand!='') $ao.="item_brand:'" . jsescapel($brand) . "',";
			$ao.="item_category:'" . jsescapel($rs['sectionName']) . "',";
			$ao.='price:' . jsescapel($itemtotal) . ',quantity:' . $rs['cartQuantity'] . '}';
	}
	ect_free_result($result);
	print '<script>gtag("event","purchase",{ currency:"' . $GLOBALS['countryCurrency'] . '",value:' . $ordTotal . ',shipping:'.$ordShipping.',tax:'.($ordStateTax+$ordHSTTax+$ordCountryTax).',items:[' . $ao . ']});</script>'."\n";
}
if($success && (@$googleanalyticsinfo==TRUE||@$usegoogleuniversal) && is_numeric($ordID) && $ordID!=0){
	// Order ID, Affiliation, Total, Tax, Shipping, City, State, Country
	$GLOBALS['googleanalyticstrackorderinfo']="ga('ecommerce:addTransaction',{'id':'".$ordID."','affiliation':'".$affilID."','revenue':'".$ordTotal."','shipping':'".$ordShipping."','tax':'".($ordStateTax+$ordHSTTax+$ordCountryTax)."'});\r\n";
	$sSQL='SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity,'.getlangid('sectionName',256).",pSKU FROM cart INNER JOIN products ON cart.cartProdID=products.pID INNER JOIN sections ON products.pSection=sections.sectionID WHERE cartOrderID='".escape_string($ordID)."' ORDER BY cartID";
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$sSQL='SELECT SUM(coPriceDiff) AS coPrDff FROM cartoptions WHERE coCartID='. $rs['cartID'];
		$result2=ect_query($sSQL) or ect_error();
		$coPriceDiff=0;
		if($rs2=ect_fetch_assoc($result2)) $coPriceDiff=$rs2['coPrDff'];
		ect_free_result($result2);
		$GLOBALS['googleanalyticstrackorderinfo'].="ga('ecommerce:addItem',{'id':'".$ordID."','name':'".jsescape($rs['cartProdName'])."','sku':'".jsescape($rs['cartProdID'])."','category':'".jsescape($rs[getlangid('sectionName',256)])."','price':'".($rs['cartProdPrice']+$coPriceDiff)."','quantity':'".$rs['cartQuantity']."'});\r\n";
	}
	ect_free_result($result);
	$GLOBALS['googleanalyticstrackorderinfo'].="ga('ecommerce:send');" . "\r\n";
}
?>