Solved

Where is the "accepted" field on the is authorize.net page?

Posted on 2010-11-19
9
421 Views
Last Modified: 2012-05-10
I'm looking at the authorize.net sample code and while I'm understanding to a degree, I'm trying to figure out where the "approved" value is coming from as that will determine how I route my user on my shopping cart.

I have the code attached and you can see it in action at http://www.snowdogservertest.com/authorize.php

First off, I want to understand cURL. From what I can gather, cURL is magic in that you're submitting a form without the user having to hit a "submit" button. The moment you access the page, if you're using a cURL dynamic, you're submitting data and rarther than having to proceed to another page to see the results of your query, it's all happening right there on the spot. Is that an accurate understanding of cURL?

Second, and here's my main question: The code that I have attached appears to be taking the variables identified at the top of the page, submitting them to authorize.net and the results of the query are posted in the HTML section of the bottom of the page. The first field (1) is the "approved code." If it's "1" then the transaction has been approved. But here's my dilemma: How do I write an if statement that says something to the effect of

if(approval_code ==1){
proceed with sale etc...

I don't see how I can look from a coding standpoint at the status of the transaction. The info is there, I just don't know how to grab it and see what it says so I can redirect my customer to either a "success" page or a "sorry, do it again" page.

Thoughts?
<!--

This sample code is designed to connect to Authorize.net using the AIM method.

For API documentation or additional sample code, please visit:

http://developer.authorize.net

-->



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 

  "http://www.w3.org/TR/html4/loose.dtd">

<HTML lang='en'>

<HEAD>

<TITLE> Sample AIM Implementation </TITLE>

</HEAD>

<BODY>

<P> This sample code is designed to generate a post using Authorize.net's

Advanced Integration Method (AIM) and display the results of this post to

the screen. </P>

<P> For details on how this is accomplished, please review the readme file,

the comments in the sample code, and the Authorize.net AIM API documentation

found at http://developer.authorize.net </P>

<HR />



<?PHP



// By default, this sample code is designed to post to our test server for

// developer accounts: https://test.authorize.net/gateway/transact.dll

// for real accounts (even in test mode), please make sure that you are

// posting to: https://secure.authorize.net/gateway/transact.dll

$post_url = "https://secure.authorize.net/gateway/transact.dll";



$post_values = array(

	

	// the API Login ID and Transaction Key must be replaced with valid values

	"x_login"			=> "9Fmyc39Yy ",

	"x_tran_key"		=> "93YayQq39FC95kqx",



	"x_version"			=> "3.1",

	"x_delim_data"		=> "TRUE",

	"x_delim_char"		=> "|",

	"x_relay_response"	=> "FALSE",



	"x_type"			=> "AUTH_CAPTURE",

	"x_method"			=> "CC",

	"x_card_num"		=> "4111111111111111",

	"x_exp_date"		=> "0115",



	"x_amount"			=> "19.99",

	"x_description"		=> "Sample Transaction",



	"x_first_name"		=> "John",

	"x_last_name"		=> "Doe",

	"x_address"			=> "1234 Street",

	"x_state"			=> "WA",

	"x_zip"				=> "98004"

	// Additional fields can be added here as outlined in the AIM integration

	// guide at: http://developer.authorize.net

);



// This section takes the input fields and converts them to the proper format

// for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"

$post_string = "";

foreach( $post_values as $key => $value )

	{ $post_string .= "$key=" . urlencode( $value ) . "&"; }

$post_string = rtrim( $post_string, "& " );



// The following section provides an example of how to add line item details to

// the post string.  Because line items may consist of multiple values with the

// same key/name, they cannot be simply added into the above array.

//

// This section is commented out by default.

/*

$line_items = array(

	"item1<|>golf balls<|><|>2<|>18.95<|>Y",

	"item2<|>golf bag<|>Wilson golf carry bag, red<|>1<|>39.99<|>Y",

	"item3<|>book<|>Golf for Dummies<|>1<|>21.99<|>Y");

	

foreach( $line_items as $value )

	{ $post_string .= "&x_line_item=" . urlencode( $value ); }

*/



// This sample code uses the CURL library for php to establish a connection,

// submit the post, and record the response.

// If you receive an error, you may want to ensure that you have the curl

// library enabled in your php configuration

$request = curl_init($post_url); // initiate curl object

	curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response

	curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)

	curl_setopt($request, CURLOPT_POSTFIELDS, $post_string); // use HTTP POST to send form data

	curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.

	$post_response = curl_exec($request); // execute curl post and store results in $post_response

	// additional options may be required depending upon your server configuration

	// you can find documentation on curl options at http://www.php.net/curl_setopt

curl_close ($request); // close curl object



// This line takes the response and breaks it into an array using the specified delimiting character

$response_array = explode($post_values["x_delim_char"],$post_response);



// The results are output to the screen in the form of an html numbered list.

echo "<OL>\n";

foreach ($response_array as $value)

{

	echo "<LI>" . $value . "&nbsp;</LI>\n";

	$i++;

}

echo "</OL>\n";

// individual elements of the array could be accessed to read certain response

// fields.  For example, response_array[0] would return the Response Code,

// response_array[2] would return the Response Reason Code.

// for a list of response fields, please review the AIM Implementation Guide

?>

</BODY>

</HTML>

Open in new window

0
Comment
Question by:brucegust
  • 4
  • 3
  • 2
9 Comments
 
LVL 18

Accepted Solution

by:
Sudaraka Wijesinghe earned 300 total points
ID: 34174873
Hi,

cUrl, is a piece of software that allows us to send all sort of HTTP (and HTTPS) requests and receive the response. In this case we are using the the cUrl php module. Therefor it runs on the web server, your HTTPS request originated from the web server and sent to Authorize.Net API interface. There's no involvement of the client (browser) in this other than invoking the php page to execute.

Authorize.Net return the primary approval/failure status of the transaction in the first elements of the response array (once you split the response string in to an array). This has an integer with the following meaning:

1 = Approved, indicates that the credit card number is valid, card is not expired and the specified amount can be charged to the card.
2 = Declined, indicates that credit card failed pass one of the conditions mentioned above. (More details provided on 4th element of the response array)
3 = Error, indicate the failure of the process due to technical failure.

First parameter MUST return 1 in order to consider the transaction as valid.

Other than this there are couple of other parameters (AVS and CVV) that you might want to validate .

CVV (Card Verification Value) is indicated by the 39th elements of the Authorize.Net response array. It's a single character should be something other than S or N (please refer the Authorize.Net documentation for more and latest details).

AVS (Address Verification Service) is only available in certain countries and it's status indicated by the 6th parameter, and it should something other than N and E (again, please refer the Authorize.Net documentation).

Card can be charged even if the AVS and/or CVV is failed, they are only additional security measures.

I have attached a PHP class written to access Authorize.Net API. Maybe it can help you.
AuthnetAPI.php
0
 

Author Comment

by:brucegust
ID: 34174986
sudaraka! This looks great!

I know just enough about Object Oriented Programming to be frustrated, so some of your syntax is a little confusing, so if you don't mind, let me ask you some questions and rest assured, you have the points for your effort.

I can trace the logic of what's going on, but I'm looking at the sample code provided by a.net and comparing that to what you've built. I can see where you're looking at the "approved" variable here:

if($this->APPROVED)

How is authorize.net defining "approved?" In the sample code that they provide, you see the variables that are being submitted, but the results of the query are listed as an array on line 97. Your code is sweet because I can see the "approved" variable on line 52. How can I isolate that "approved" variable as it's coming from authorize.net? Does that make sense?

If everything on the sample code is being funneled into the page as an array, that's great, but I need to do what you're doing by grabbing on to that one piece of information and building a "success" path for my customer that includes inserting their order and contact info into the database.

How is authorize.net delivering the "approved" value?
0
 
LVL 18

Expert Comment

by:Sudaraka Wijesinghe
ID: 34175311
The php class I posted is actually a part of a large application, what it basically does is take the response from Authorize.Net API and assign the values to class members to support a common interface. So some parts may look confusing to you and even unnecessary.

Origin of $this->APPROVED is basically the first element of the Authorize.Net parameter list. This is how the value gets assigned to $this->APPROVED (line numbers in reference to the file I attached before).

Line 41:             $this->__Response = curl_exec ($ch);
HTTP Response (body) from the Authorize.Net is received and assigned to the __Response member variable.

Line 44:             $this->BuildResultArray($this->__Response);
__Response is sent to BuildResultArray member function to be processed.

Line 117:             $out=split(",", $xmlTags);
$xmlTags, (the __Response class member passed to the BuildResultArray function) is split into an array by the comma.
Note: In this case I only used comma but Authorize.Net support other delimiters. Also note that split function is deprecated as of php 5.3.x use preg_split instead

Line 120 to 126:
            switch($out[0])
            {
                  case 1: $this->ResultDetails["R_APPROVED"]="APPROVED"; break;
                  case 2: $this->ResultDetails["R_APPROVED"]="DECLINED"; break;
                  case 3: $this->ResultDetails["R_APPROVED"]="ERROR"; break;
                  default: $this->ResultDetails["R_APPROVED"]="UNKNOWN (".$out[0].")"; break;
            }

$out[0], the first elements of the result array is compared to the values specified in the Authorize.Net documentation. and element of another member array of the class (ResultDetails["R_APPROVED"]) is populated with a text accordingly.
For a successful transaction it reads APPROVED.

Other elements are parsed here and BuildResultArray returns to line 44

Line 50:             $this->APPROVED=($this->ResultDetails["R_APPROVED"]=="APPROVED");
Member array element ResultDetails["R_APPROVED"] is compared with text "APPROVED" (assigned on line 122 for successful transactions) and the result (Boolean true/false) is assigned to the member variable APPROVED.

Hope this helps you to understand the code. Please feel free to ask me if you need more details.
0
 

Author Comment

by:brucegust
ID: 34175506
Alright, let me ask you this: I've found a very straightforward and simplistic sample for an authorize.net integration on their site. The sample code looks like this:

require_once('anet_php_sdk/AuthorizeNet.php'); // Make sure this path is correct. 
$transaction = new AuthorizeNetAIM('9Fmyc39Yy', '93YayQq39FC95kqx'); 
$transaction->amount = '9.99'; 
$transaction->card_num = '4007000000027'; 
$transaction->exp_date = '10/16'; 
 
$response = $transaction->authorizeAndCapture(); 
 
if ($response->approved) { 
  echo "<h1>Success! The test credit card has been charged!</h1>"; 
  echo "Transaction ID: " . $response->transaction_id; 
} else { 
  echo $response->error_message; 


I've got the required directory installed, but I keep getting an error that says, "Parse error: syntax error, unexpected T_VARIABLE in /var/www/vhosts/kolcrafttesting.com/httpdocs/new_authorize.php on line 4
 which is the amount. What am I doing wrong?
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 1

Assisted Solution

by:EmmyS
EmmyS earned 200 total points
ID: 34175560
I've been using the sample code from authorize.net for several months now; I modified it to deal with various response codes. Here's what I did:

function runCreditCard($ccData){

	//first get values from database - now we don't need to comment out live/test values; just put correct values in database

			$transKeys = getTransactionKeys();			

			$post_url = $transKeys['url'];

					

			$post_values = array(

			"x_login"			=> $transKeys['api'],

			"x_tran_key"		=> $transKeys['key'],	



			"x_version"			=> "3.1",

			"x_delim_data"		=> "TRUE",

			"x_delim_char"		=> "|",

			"x_relay_response"	=> "FALSE",

                        "x_duplicate_window"  => "15",



			"x_type"			=> "AUTH_CAPTURE",

			"x_method"			=> "CC",

			"x_card_num"		=> $_POST['CCCardNum'],

			"x_card_code"	=> $_POST['CC_CVV2'],

			"x_exp_date"		=> $_POST['CCEXP_MON'] .$_POST['CCEXP_YEAR'] ,



			"x_amount"			=> $_POST['certificateBalance'],

			"x_description"		=> "ArrayCard Transaction",



			"x_first_name"		=> $_POST['CCFirstNm'],

			"x_last_name"		=> $_POST['CCLastNm'],

			"x_address"			=> $_POST['billaddress1'],

			"x_city"				=> $_POST['billcity'],

			"x_state"			=> $_POST['billstate'],

			"x_zip"				=> $_POST['billzip']

		);



		// This section takes the input fields and converts them to the proper format

		// for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"

		$post_string = "";

		foreach( $post_values as $key => $value )

			{ $post_string .= "$key=" . urlencode( $value ) . "&"; }

		$post_string = rtrim( $post_string, "& " );

		error_log("post string=".$post_string);





		$request = curl_init($post_url); // initiate curl object

			curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response

			curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)

			curl_setopt($request, CURLOPT_POSTFIELDS, $post_string); // use HTTP POST to send form data

			curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.

			$post_response = curl_exec($request); // execute curl post and store results in $post_response

		curl_close ($request); // close curl object



		// This line takes the response and breaks it into an array using the specified delimiting character

		$response_array = explode($post_values["x_delim_char"],$post_response);

		//print_r($response_array);



		// The results are output to the screen in the form of an html numbered list.

		/*

		echo "<OL>\n";

		foreach ($response_array as $value)

		{

			echo "<LI>" . $value . "&nbsp;</LI>\n";

			$i++; 

		}

		echo "</OL>\n";

		*/

		// individual elements of the array could be accessed to read certain response

		// fields.  For example, response_array[0] would return the Response Code,

		// response_array[2] would return the Response Reason Code.

		// for a list of response fields, please review the AIM Implementation Guide





		if($response_array[0] == 1) {

			//approved

			error_log("credit card approval code: ".$response_array[4]);

			return $response_array[4];

			//return strtoupper(substr(md5(uniqid()),0,6)); 

		}

		else {

			error_log("transaction errored out: ".$response_array[2] . " - ".$response_array[3]);

                       $tmp = "error:".$response_array[3];

                      return $tmp;

		}

	

		//return false;

}

Open in new window


The main thing: comment out the loop printing all values of the response array, and stick in an if/else that determines what should happen based on the actual response code sent back in response_array[0]. My code that calls this function is object-oriented, but you could use it procedurally too. The main thing is the return. If you don't care what the message is that's sent back, but only care if it's accepted or not, you can change the if/else to something like this:

if($response_array[0] == 1) {

			//approved

			error_log("credit card approval code: ".$response_array[4]);

			return true;
			//return strtoupper(substr(md5(uniqid()),0,6)); 

		}

		else {

			error_log("transaction errored out: ".$response_array[2] . " - ".$response_array[3]);

                      return false;

		}

Open in new window


You'd then call it like this:

if(runCreditCardData($yourArray)) {
              //do what you need for an accepted transaction;
          }
          else {
              //do what you need to for a declined transaction;
         }

Open in new window

0
 
LVL 18

Expert Comment

by:Sudaraka Wijesinghe
ID: 34175606
In most cases culprit of "unexpected T_VARIABLE" is a missing semicolon. Check you have any.

Also it's not a good idea to post your access keys :) (unless they are developer keys)
0
 

Author Comment

by:brucegust
ID: 34175693
Got it!

if($response_array[0] == 1)

It's amazing how obvious something can be when someone points it out.

Thank you so much!

I'm going to favor sudaraka a little bit in the way I distribute points just because he was kind enough to weigh in so quickly and so thoroughly, but EmmyS, that one little line was all that I needed. Thanks to you both for being so comprehensive in your reponses.
0
 
LVL 18

Expert Comment

by:Sudaraka Wijesinghe
ID: 34175772
Glad to help. Thanks for the points.
0
 
LVL 1

Expert Comment

by:EmmyS
ID: 34176272
You're welcome. Authorize.net's live chat tech support is usually pretty good about helping out, too - they pointed out the Response Reason Code Tool, which I never would have found on my own. It's really helpful for debugging unexpected response codes.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

These days socially coordinated efforts have turned into a critical requirement for enterprises.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now