<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: 			*/
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 2004-2010 ARMIA INC                                    |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts VistaCart                     |
// +----------------------------------------------------------------------+
// | Authors: Jipson<jipson.thomas@armiasystems.com>             		  |
// +----------------------------------------------------------------------+
class AuthorizepaymentComponent extends Object
{
	// This is for the payment of the sale item.
	// From a previous HTML Form, pass the following fields:
	// $FirstName = Customer's First Name
	// $LastName = Customer's Last Name
	// $CardNum = Customer's Credit Card Number
	// $Month = Customer's Credit Card Expiration Month (Should be 01, 02, etc.)
	// $Year = Customer's Credit Card Expiration Year (Should be 2003, 2004, etc.)
	// $Address = Customer's Address
	// $City = Customer's City
	// $State = Customer's State (Should be 2 letter code, CA, AZ, etc.)
	// $Zip = Customer's Zip Code
	// $Email = Customer's Email Address
	// $Cost = Total Price of purchase
	// Check to make sure customer entered all relevant information
	function authpay($billadd,$txtEmail,$txtCCNumber,$txtCVV2,$txtMM,$txtYY,$txtAuthorizeLoginId,$txtAuthorizeTransKey,$txtCurrency,
	$totaltopay,$txtAuthorizeEmail,$Company,$Cust_id,$Inv_id,$stename,$txtAuthorizeTestMode){
		############# Block to get Customer Ip##################################33
		 // Get REMOTE_ADDR as the Client IP.
		$client_ip = (!empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : ((!empty($_ENV['REMOTE_ADDR'])) ? $_ENV['REMOTE_ADDR'] : $REMOTE_ADDR);
		// Check for headers used by proxy servers to send the Client IP. We should look for HTTP_CLIENT_IP before HTTP_X_FORWARDED_FOR.
		if (isset($_SERVER["HTTP_CLIENT_IP"]))
			$proxy_ip = $_SERVER["HTTP_CLIENT_IP"];
		elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
			$proxy_ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		// Proxy is used, see if the specified Client IP is valid. Sometimes it's 10.x.x.x or 127.x.x.x... Just making sure.
		if (isset($proxy_ip)) {
			if (preg_match("/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", $proxy_ip, $ip_list)) {
				$private_ip = array('/^0\./', '/^127\.0\.0\.1/', '/^192\.168\..*/', '/^172\.16\..*/', '/^10.\.*/', '/^224.\.*/', '/^240.\.*/');
				$client_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);
			}
		}
		// Return the Client IP.
		$Cust_ip	=	$client_ip;
	#################### End Block to get Customer Ip ##########################################
		$txtFirstName	=	$billadd["fname"];
		$txtLastName	=	$billadd["lname"];
		$txtAddress		=	$billadd["address"];
		$txtCity		=	$billadd["city"];
		$txtState		=	$billadd["state"];
		$txtZIP			=	$billadd["zip"];
		$ddlCountry		=	$billadd["country"];
		$Phone			=	$billadd["phone"];
		if (!$txtFirstName ||  !$txtAddress || !$txtCity || !$txtState || !$txtZIP ||
			!$txtEmail || !$ddlCountry  || !$txtCCNumber || !$txtCVV2 || !$txtMM || !$txtYY) {
			$paymentsuccessful = false;
			
			$paymenterror = "Some necessary information were found missing.  Please enter the missing information." ;
			// exit;
		}else{
			//$referrer = SECURE_SITE_URL."/payment.php";
			$referrer =  $_SERVER["HTTP_REFERER"];
			$x_customdata = "Custom";
		
			$x_Login = urlencode($txtAuthorizeLoginId); // your login
			$x_tran_key = urlencode($txtAuthorizeTransKey); // Tran Key
			//$x_Password = urlencode($txtAuthorizePassword); // your password
			$x_currency_code = urlencode($txtCurrency);
			$x_Delim_Data = urlencode("TRUE");
			$x_Delim_Char = urlencode(",");
			$x_Encap_Char = urlencode("");
			$x_Type = urlencode("AUTH_CAPTURE");
		
			$x_ADC_Relay_Response = urlencode("FALSE");
			if($txtAuthorizeTestMode == "Y"){
				$x_Test_Request = urlencode("TRUE"); // Remove this line of code when you are ready to go live
			}else{
                            $x_Test_Request = urlencode("FALSE");
                        }
			// Customer Information
			$x_Method = urlencode("CC");
			$x_Amount = urlencode($totaltopay);
			$x_First_Name = urlencode($txtFirstName);
			$x_Last_Name = urlencode($txtLastName);
			$x_Card_Num = urlencode($txtCCNumber);
			$ExpDate = ($txtMM . $txtYY);
			$x_Exp_Date = urlencode($ExpDate);
			$x_card_code = urlencode($txtCVV2);
		
			$x_Address = urlencode($txtAddress);
			$x_City = urlencode($txtCity);
			$x_State = urlencode($txtState);
			$x_Zip = urlencode($txtZIP);
			$x_country = urlencode($ddlCountry);
			$x_Email = urlencode($txtEmail);
			$x_Email_Customer = urlencode("TRUE");
			$x_Merchant_Email = urlencode($txtAuthorizeEmail); //  Replace MERCHANT_EMAIL with the merchant email address
		
			// Build fields string to post
		
			$x_cust_ip 		=	urlencode($Cust_ip);
			$x_company 		=	urlencode($Company);
			$x_phone 		=	urlencode($Phone);
			$x_cust_id 		=	urlencode($Cust_id);
			$x_invno		=	urlencode($Inv_id);
			$x_invid			=	urlencode($Inv_id);
			$x_description	=	" Item purchase with ".$stename;
		
			$fields = "x_Version=3.1&x_Login=$x_Login&x_tran_key=$x_tran_key&x_Delim_Data=$x_Delim_Data&x_Delim_Char=$x_Delim_Char&x_Encap_Char=$x_Encap_Char";
			$fields .= "&x_Type=$x_Type&x_Test_Request=$x_Test_Request&x_Method=$x_Method&x_Amount=$x_Amount&x_currency_code=$x_currency_code&x_First_Name=$x_First_Name";
			$fields .= "&x_Last_Name=$x_Last_Name&x_Card_Num=$x_Card_Num&x_Exp_Date=$x_Exp_Date&x_card_code=$x_card_code&x_Address=$x_Address&x_City=$x_City&x_State=$x_State&x_Zip=$x_Zip&x_country=$x_country&x_Email=$x_Email&x_Email_Customer=$x_Email_Customer&x_Merchant_Email=$x_Merchant_Email&x_ADC_Relay_Response=$x_ADC_Relay_Response&x_invid=$x_invid&x_cust_ip=$x_cust_ip&x_company=$x_company&x_phone=$x_phone&x_cust_id=$x_cust_id&x_invoice_num=$x_invno&x_description=$x_description";
			/*if ($x_Password != '') {
				$fields .= "&x_Password=$x_Password";
			}*/
		
			// Start CURL session
			
			$authurl="https://secure.authorize.net/gateway/transact.dll";
						
			if($txtAuthorizeTestMode == "Y")
			{
				$authurl="https://test.authorize.net/gateway/transact.dll";
			}	
			
			
			$agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";
			$ref = $referrer;
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL,$authurl);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_NOPROGRESS, 1);
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
			curl_setopt($ch, CURLOPT_TIMEOUT, 120);
			curl_setopt($ch, CURLOPT_USERAGENT, $agent);
			curl_setopt($ch, CURLOPT_REFERER, $ref);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		
			$buffer = curl_exec($ch);
			curl_close($ch);
			// This section of the code is the change from Version 1.
			// This allows this script to process all information provided by Authorize.net...
			// and not just whether if the transaction was successful or not
			// Provided in the true spirit of giving by Chuck Carpenter (Chuck@MLSphotos.com)
			// Be sure to email him and tell him how much you appreciate his efforts for PHP coders everywhere
			$return = preg_split("/[,]+/", "$buffer"); // Splits out the buffer return into an array so . . .
			$details = $return[0]; // This can grab the Transaction ID at position 1 in the array
		//print_r($buffer);exit;
			/*$carholdername=$return[14];
			$carholderlname=$return[15];
			$carholderaddress=$return[16];
			foreach($return as $key=>$value){
			  echo "key=$key and value=$value <br>";
			}
			exit;
			*/
			// Change the number to grab additional information.  Consult the AIM guidelines to see what information is provided in each position.
			// For instance, to get the Transaction ID from the returned information (in position 7)..
			// Simply add the following:
			// $x_trans_id = $return[6];
			// You may then use the switch statement (or other process) to process the information provided
			// Example below is to see if the transaction was charged successfully
			switch ($details) {
				case "1": // Credit Card Successfully Charged
					$paymentsuccessful = true;
					if(isset($return[6])) {
					$paymenterror	   = $return[6];
					$transactionid 	   = $return[6]; }
					break;
				case "2":
					$paymentsuccessful = false;
					$paymenterror = "The card has been declined";
					if(isset($return[3]))
					$paymenterror .= "<br>" . $return[3];
					break;
				case "4":
					$paymentsuccessful = false;
					$paymenterror = "The card has been held for review";
					if(isset($return[3]))
					$paymenterror .= "<br>" . $return[3];
					break;
				default: // Credit Card Not Successfully Charged
					$paymentsuccessful = false;
					$paymenterror = "Error";
					if(isset($return[3]))
					$paymenterror .= "<br>" . $return[3];
					break;
			}
			
		}
		$ret["status"]	=	$paymentsuccessful;
		$ret["msg"]		=	$paymenterror;
		return $ret;
	}
}?>