<?php
/**
 * Library required for Authorize.Net  E-Commerce Transaction
 *
 * @package Authorize.Net Class for PremiumWebCart
 * @author A.R. ZERIN
 * @version 1.0
 * @license  Not Allowed to modify the code without Permission of Author please
 *
 */
class AuthorizeDotNet
{

	// Set these variables prior to use
	var $login; //Merchant API login ID

	var $transkey; //Merchant transaction key

	var $test = false;

	var $params = array();

	var $results = array();

	var $approved = false;

	var $declined = false;

	var $error = true;

	var $fields;

	var $response;

	var $url;

	var $emailToCustomer = FALSE;

	var $DEBUG = false;

	var $instance;
	var $responseCode = 'ABC';
	var $responseReasonCode;
	var $errorCode;
	var $errorDetails;


	function AuthorizeDotNet ()
	{
		$config = & get_config();
	}

	function initializeIt ()
	{
		if (empty($this->login) || empty($this->transkey))
		{
			die("<b>You have not configured your Authnet login credentials.</b>");
		}
		$subdomain = ($this->test) ? 'test' : 'secure';
		$this->url = "https://" . $subdomain . ".authorize.net/gateway/transact.dll";
		$this->params['x_delim_data'] = "TRUE";
		$this->params['x_delim_char'] = "|";
		$this->params['x_relay_response'] = "FALSE";
		$this->params['x_url'] = "FALSE";
		$this->params['x_version'] = "3.1";
		$this->params['x_method'] = "CC";
		$this->params['x_type'] = "AUTH_CAPTURE";
		$this->params['x_login'] = $this->login;
		$this->params['x_tran_key'] = $this->transkey;
		$this->params['x_email_customer'] = $this->emailToCustomer;
		$this->params['x_customer_ip'] = gethostbyname($_SERVER['REMOTE_ADDR']);
		$this->params['x_Customer_Organization_Type'] = 'B';
        $this->error = true;
        $this->errorDetails = '';
		#$this->params['x_Test_Request'] = 'TRUE';
		#$this->params['x_line_item'] = "item1<|>golf balls<|><|>2<|>18.95<|>Y";
	}

	function setTransaction ($cardnum, $expiration, $amount, $currency_code = "USD", $cvv = null, $invoice = null, $tax = null)
	{
		$this->params['x_card_num'] = (string) trim($cardnum);
		$this->params['x_exp_date'] = $expiration;//(int) $expiration;
		$this->params['x_amount'] = (float) $amount;
		$this->params['x_currency_code'] = (string) $currency_code;
		$this->params['x_po_num'] = (int) $invoice; // Purchase Order Number
		$this->params['x_tax'] = (float) $tax;
		if (! (is_null($cvv)))
			$this->params['x_card_code'] = (int) $cvv;
		if (empty($this->params['x_card_num']) || empty($this->params['x_exp_date']) || empty($this->params['x_amount']))
		{
			die("Required information for transaction processing omitted.");
		}
	}

	function process ($retries = 3)
	{
		$this->prepareParameters();
		//$ch = curl_init($this->url);
		$ch = curl_init();
		$count = 0;
		while ($count < $retries)
		{
			if ($this->error == true)
			{
				//curl_setopt($ch, CURLOPT_HEADER, 0);
				//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				//curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($this->fields, "& "));
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
				curl_setopt($ch, CURLOPT_URL, $this->url);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($this->fields, "& "));
				//Start ob to prevent curl_exec from displaying stuff.
				ob_start();
				curl_exec($ch);
				//Get contents of output buffer
				$info = ob_get_contents();
				curl_close($ch);
				//End ob and erase contents.
				ob_end_clean();
				$this->response = $info;
				$this->parseResults();
				if ($this->getResultResponseFull() == "Approved")
				{
					$this->approved = true;
					$this->declined = false;
					$this->error = false;
				} else if ($this->getResultResponseFull() == "Declined")
				{
					$this->approved = false;
					$this->declined = true;
					$this->error = false;
					$this->responseCode = $this->getResponseCode();
					$this->responseReasonCode = $this->getResponseReasonCode();
					$this->errorCode = $this->getErrorCode();
					$this->errorDetails = $this->getErrorDetails();
				} else if ($this->getResultResponseFull() == "Error")
				{
					$this->approved = false;
					$this->declined = true;
					$this->error = true;
					$this->responseCode = $this->getResponseCode();
					$this->responseReasonCode = $this->getResponseReasonCode();
					$this->errorCode = $this->getErrorCode();
					$this->errorDetails = $this->getErrorDetails();
				}
				$count ++;
			} else
			{
				break;
			}
		}

		if($ch)
        {
            curl_close($ch);
        }

		if ($this->DEBUG == true)
		{
			echo $this->debugOutput();
		}
	}

	function prepareParameters ()
	{
		foreach ($this->params as $key => $value)
		{
			$this->fields .= "$key=" . urlencode($value) . "&";
		}
	}

	function parseResults ()
	{
		$this->results = explode("|", $this->response);
	}

	function getResultResponseFull ()
	{
		$response = array("" , "Approved" , "Declined" , "Error");
		return $response[$this->results[0]];
	}

	/*  New */
	function getResponseCode ()
	{
		return $this->results[0];
	}

	function getResponseReasonCode ()
	{
		return $this->results[1];
	}

	function getErrorCode ()
	{
		return $this->results[2];
	}

	function getErrorDetails ()
	{
		return $this->results[3];
	}

	/*  New */
	function debugOutput ()
	{
		if (! $this->params)
		{
			return (string) $this;
		}
		$output = "";
		$output .= '<table summary="Authnet Results" id="authnet">' . "\n";
		$output .= '<tr>' . "\n\t\t" . '<th colspan="2"><b>Outgoing Parameters</b></th>' . "\n" . '</tr>' . "\n";
		foreach ($this->params as $key => $value)
		{
			$output .= "\t" . '<tr>' . "\n\t\t" . '<td><b>' . $key . '</b></td>';
			$output .= '<td>' . $value . '</td>' . "\n" . '</tr>' . "\n";
		}
		if ($this->results)
		{
			$output .= '<tr>' . "\n\t\t" . '<th colspan="2"><b>Incomming Parameters</b></th>' . "\n" . '</tr>' . "\n";
			$response = array("Response Code" , "Response Subcode" , "Response Reason Code" , "Response Reason Text" , "Approval Code" , "AVS Result Code" , "Transaction ID" , "Invoice Number" , "Description" , "Amount" , "Method" , "Transaction Type" , "Customer ID" , "Cardholder First Name" , "Cardholder Last Name" , "Company" , "Billing Address" , "City" , "State" , "Zip" , "Country" , "Phone" , "Fax" , "Email" , "Ship to First Name" , "Ship to Last Name" , "Ship to Company" , "Ship to Address" , "Ship to City" , "Ship to State" , "Ship to Zip" , "Ship to Country" , "Tax Amount" , "Duty Amount" , "Freight Amount" , "Tax Exempt Flag" , "PO Number" , "MD5 Hash" , "Card Code (CVV2/CVC2/CID) Response Code" , "Cardholder Authentication Verification Value (CAVV) Response Code");
			foreach ($this->results as $key => $value)
			{
				if ($key > 40)
					break;
				$output .= "\t" . '<tr>' . "\n\t\t" . '<td><b>' . $response[$key] . '</b></td>';
				$output .= '<td>' . $value . '</td>' . "\n" . '</tr>' . "\n";
			}
		}
		$output .= '</table>' . "\n";
		return $output;
	}

	function setParameter ($field = "", $value = null)
	{
		$field = (is_string($field)) ? trim($field) : $field;
		$value = (is_string($value)) ? trim($value) : $value;
		if (! is_string($field))
		{
			die("setParameter() arg 1 must be a string or integer: " . gettype($field) . " given.");
		}
		if (! is_string($value) && ! is_numeric($value) && ! is_bool($value))
		{
			die("setParameter() arg 2 must be a string, integer, or boolean value: " . gettype($value) . " given.");
		}
		if (empty($field))
		{
			die("setParameter() requires a parameter field to be named.");
		}
		if ($value === "")
		{
			die("setParameter() requires a parameter value to be assigned: $field");
		}
		$this->params[$field] = $value;
	}

	function setTransactionType ($type = "")
	{
		$type = strtoupper(trim($type));
		$typeArray = array("AUTH_CAPTURE" , "AUTH_ONLY" , "PRIOR_AUTH_CAPTURE" , "CREDIT" , "CAPTURE_ONLY" , "VOID");
		if (! in_array($type, $typeArray))
		{
			die("No Valid Transaction Type assigned.");
		}
		$this->params['x_type'] = $type;
	}

	function setCustomer ($customer_first_name = "", $customer_last_name = "", $customer_email = "")
	{
		$this->params['x_first_name'] = $customer_first_name;
		$this->params['x_last_name'] = $customer_last_name;
		$this->params['x_email'] = $customer_email;
	}

	function setCustomerIP ($customer_ip = "")
	{
		if (! empty($customer_ip))
		{
			$this->params['x_customer_ip'] = $customer_ip;
		}
		else
		{
			$this->params['x_customer_ip'] = GetHostByName($REMOTE_ADDR);
		}
	}

	function getCustomerIP()
	{
		return $this->params['x_customer_ip'];
	}

	function setMerchantEmail ($merchant_email = "")
	{
		$this->params['x_merchant_email'] = $merchant_email;
	}

	/* New */
	function setCustomerId ($customer_id = "")
	{
		$this->params['x_cust_id'] = $customer_id;
	}

	function setReceipt ($header_text = "", $footer_text = "")
	{
		$this->params['x_header_email_receipt'] = $header_text;
		$this->params['x_footer_email_receipt'] = $footer_text;
	}

	function setCustomerBillAddress ($billing_address = "", $company_name = "", $city_name = "", $state_name = "", $zip_code = "", $country_name = "", $phone_number = "", $fax_number = "")
	{
		$this->params['x_address'] = $billing_address;
		$this->params['x_company'] = $company_name;
		$this->params['x_city'] = $city_name;
		$this->params['x_state'] = $state_name;
		$this->params['x_zip'] = $zip_code;
		$this->params['x_country'] = $country_name;
		$this->params['x_phone'] = $phone_number;
		$this->params['x_fax'] = $fax_number;
	}

	function setCustomerShippingAddress ($customer_first_name = "", $customer_last_name = "", $company_name = "", $shipping_address = "", $city_name = "", $state_name = "", $zip_code = "", $country_name = "")
	{
		$this->params['x_ship_to_first_name'] = $customer_first_name;
		$this->params['x_ship_to_last_name'] = $customer_last_name;
		$this->params['x_ship_to_company'] = $company_name;
		$this->params['x_ship_to_address'] = $shipping_address;
		$this->params['x_ship_to_city'] = $city_name;
		$this->params['x_ship_to_state'] = $state_name;
		$this->params['x_ship_to_zip'] = $zip_code;
		$this->params['x_ship_to_country'] = $country_name;
	}

	function setInvoiceNumber ($invoice_number = "")
	{
		$this->params['x_invoice_num'] = $invoice_number;
	}

	function setPaymentDetails ($bill_details = "")
	{
		$this->params['x_description'] = $bill_details;
	}

	function setItems ($item_details = "")
	{
		$this->params['x_line_item'] = $item_details;
	}

	function getResultResponse ()
	{
		return $this->results[0];
	}

	function isApproved ()
	{
		return $this->approved;
	}

	function isDeclined ()
	{
		return $this->declined;
	}

	function isError ()
	{
		return $this->error;
	}

	function getResponseSubcode ()
	{
		return $this->results[1];
	}

	function getResponseText ()
	{
		return $this->results[3];
	}

	function getAuthCode ()
	{
		return $this->results[4]; // Position In Response Value = 5
	}

	function getAVSResponse ()
	{
		return $this->results[5];
	}

	function getTransactionID ()
	{
		return $this->results[6]; // Position In Response Value = 7
	}

	function getInvoiceNumber ()
	{
		return $this->results[7]; // Position In Response Value = 8
	}

	function getDescription ()
	{
		return is_null($this->results[8]) ? '' : $this->results[8];
	}

	function getAmount ()
	{
		return $this->results[9];
	}

	function getPaymentMethod ()
	{
		return $this->results[10];
	}

	function getTransactionType ()
	{
		return $this->results[11];
	}

	function getCustomerID ()
	{
		return $this->results[12];
	}

	function getCHFirstName ()
	{
		return $this->results[13];
	}

	function getCHLastName ()
	{
		return $this->results[14];
	}

	function getCompany ()
	{
		return $this->results[15];
	}

	function getBillingAddress ()
	{
		return $this->results[16];
	}

	function getBillingCity ()
	{
		return $this->results[17];
	}

	function getBillingState ()
	{
		return $this->results[18];
	}

	function getBillingZip ()
	{
		return $this->results[19];
	}

	function getBillingCountry ()
	{
		return $this->results[20];
	}

	function getPhone ()
	{
		return $this->results[21];
	}

	function getFax ()
	{
		return $this->results[22];
	}

	function getEmail ()
	{
		return $this->results[23];
	}

	function getShippingFirstName ()
	{
		return $this->results[24];
	}

	function getShippingLastName ()
	{
		return $this->results[25];
	}

	function getShippingCompany ()
	{
		return $this->results[26];
	}

	function getShippingAddress ()
	{
		return $this->results[27];
	}

	function getShippingCity ()
	{
		return $this->results[28];
	}

	function getShippingState ()
	{
		return $this->results[29];
	}

	function getShippingZip ()
	{
		return $this->results[30];
	}

	function getShippingCountry ()
	{
		return $this->results[31];
	}

	function getTaxAmount ()
	{
		return $this->results[32];
	}

	function getDutyAmount ()
	{
		return $this->results[33];
	}

	function getFreightAmount ()
	{
		return $this->results[34];
	}

	function getTaxExemptFlag ()
	{
		return $this->results[35];
	}

	function getPONumber ()
	{
		return $this->results[36];
	}

	function getMD5Hash ()
	{
		return $this->results[37];
	}

	function getCVVResponse ()
	{
		return $this->results[38];
	}

	function getCAVVResponse ()
	{
		return $this->results[39];
	}
}
?>