Merchant Account Services

Integrate the Authorize.Net Payment Gateway with PHP

Integrate the Authorize.Net payment gateway seamlessly into your ecommerce website

 

Author: Jim Conners

Rating: 10.0

Pages: 1|2|3|4|5|6|7|8|9|10

Methods

Now that we have established what the properties for our class will be we will need to create some methods that will allow us to interact with them as well as to do the work our class is designed for.

public function transaction($cardnum, $expiration, $amount, $cvv = "", $invoice = "", $tax = "") { $this->params['x_card_num'] = trim($cardnum); $this->params['x_exp_date'] = trim($expiration); $this->params['x_amount'] = trim($amount); $this->params['x_po_num'] = trim($invoice); $this->params['x_tax'] = trim($tax); $this->params['x_card_code'] = trim($cvv); }

The transaction() method assigns values to some of the properties that we did not have values for when we first created our object. These properties contain the necessary information to process the customer's credit card. This includes the credit card number, expiration date, and amount of the transaction.

We also have three optional parameters that are not required to process our transaction but under certain circumstances will be good to have. Certain types of credit cards require additional parameters to be sent to the processing bank during a transaction. For example, business cards require an invoice number (also called a purchase order number) and the tax amount for the sale to be submitted with each transaction. If they are not, that sale will downgrade to a much higher processing rate for the merchant.

Tip: There is no way to check to see if a credit card is a business card without physically viewing the card (even then you cannot always tell). If keeping merchant accounts fees to a minimum is important to the merchant, always submit an invoice number and tax amount with every transaction. It will never hurt the transactions that do not require this information and will prevent the ones that do from downgrading to a higher rate.

The CVV2 number is a security measure designed to help reduce fraud in card not present transactions. Some credit card issuing banks will decline a transaction if the CVV2 number is incorrect. Authorize.Net can even be set to automatically decline any transaction that fails a CVV2 check. Even though this field is optional in our class, there is no reason not to send this information with every transaction.

public function process($retries = 3) { $this->prepareParameters(); $ch = curl_init($this->url); $count = 0; while ($count < $retries) { curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($this->fields, "& ")); $this->response = curl_exec($ch); $this->parseResults(); if ($this->getResultResponseFull() == "Approved") { $this->approved = true; $this->declined = false; $this->error = false; break; } else if ($this->getResultResponseFull() == "Declined") { $this->approved = false; $this->declined = true; $this->error = false; break; } $count++; } curl_close($ch); }

This method is the meat and potatoes of our class. It sends the transaction information and receives the response from the Authorize.Net API. It takes one parameter, $retries which has a default value of 3. This is the number of attempts that we will make to contact Authorize.Net and process a transaction. Earlier we had mentioned that this was one possible solution to dealing with errors when communicating with the Authorize.Net API. Here we have decided that three attempts are enough. If it does not connect after three attempts, it probably isn't going to work in a reasonable amount of time and we should fall back to another solution (like inviting the customer to call in their order).

Our next line of code: $this->prepareParameters() calls a private method that as the name would suggest prepares our parameters to be sent to the Authorize.Net API. We'll cover this method shortly.

To connect to the Authorize.Net API we have chosen to the built in CURL library. It makes interacting with remote servers easy. This line $ch = curl_init($this->url) initializes a new session and return a CURL handle for use with the other CURL functions.

Before we contact the Authorize.Net API we need to keep track of how many attempts we make before we give up. We do this by with this line: $count = 0.

curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($this->fields, "& ")); $this->response = curl_exec($ch);

These four lines of code do the hard work for communicating with the Authorize.Net API. The first line tells CURL to include header information in its output. The second line tells CURL to store the response as a string instead of outputting it to the browser. The third line provides CURL with the string to send to the Authorize.Net API which for us is our parameter string created by $this->prepareParameters(). The fourth line sends the request to the API and receives and stores the response.

To know whether our transaction was successful or not, and more, we need to parse the results. Our private method parseResults() does this for us. We will cover this method below.

if ($this->getResultResponseFull() == "Approved") { $this->approved = true; $this->declined = false; $this->error = false; break; } else if ($this->getResultResponseFull() == "Declined") { $this->approved = false; $this->declined = true; $this->error = false; break; } $count++;

Now that we have our results we need to determine whether our transaction was successful, declined, or experienced an error. Using the getResultResponseFull() method (covered later) we can find the status of our transaction. If the transaction is "Approved" or "Declined" we set our status properies approriately. We will use the break statement to end our while loop since we do not need to connect to the API any longer. If the transaction is neither "Approved" nor "Declined" we can assume an error occurred. In this case we will increment our counter and try again.

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

Before we can send our transaction information to Authorize.Net we need to make sure that information is in a format they are expecting. prepareParameters() takes the values in this array and separates each key/value pair with a pipe. It then spearates each set of parameters with an ampersand (&). We store the results in $this->fields to be sent when we process the transaction.

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

When we receive the response from the Authorize.Net API we will need to convert it into a format that we find easy to use (just like we had to format our parameters to their specifications). Fortunately this is as easy as splitting a pipe-delimited string. In our constructor we told the Authorize.Net API that we will be using a pipe ("|") as our delimiting character ($this->params['x_delim_char'] = "|") so we know we need to split the values by looking for it. We store the results in the $this->results array for later accessing.

public function setParameter($param, $value) { $param = trim($param); $value = trim($value); $this->params[$param] = $value; }

The Authorize.Net API can accept over 80 parameters when submitting a transaction. Only a few are required but many are handy to use for various reasons ranging from enhanced security to better record keeping. Our array $this->params stores these fields for us. We can add fields to this array using the setParameter() method. The first parameter of this function is the name of the parameter you wish to send. You can refer to the Advanced Integration Method Integration GuidePDF to see what parameters are available for use. The second parameter to our method is the value you wish to set.

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

When a transaction is processed and Authorize.Net returns the results of that transaction, it sends 73 fields back containing various pieces of information about the transaction. These 73 fields are all contained in the $this->results array created by the parseResults() method. The first field contains a numerical indicator of the results of our transaction. Our method getResultResponse() returns that number directly to our script. If you choose to use this method you will receive one of the following numbers:

  • 1 - Indicates an Approval
  • 2 - Indicates a Decline
  • 3 - Indicates an Error

To make displaying this easier, and also making our script possibly easier to read, we can use getResultResponseFull() to output a human-readable result of our transaction. We simply put the human-readable results into an array and use the response code as our array key.

public function isApproved() { return $this->approved; }
public function isDeclined() { return $this->declined; }
public function isError() { return $this->error; }

These three methods are just accessor methods that allow our scripts to access private properties of our class. In these three cases they allow a script do determine the status of a transaction. The names of the methods will make it very clear in your script what you are trying to accomplish (checking the status of the transaction) and will promote readability which makes maintaining your script much easier.

public function getResponseText() { return $this->results[3]; }
public function getAuthCode() { return $this->results[4]; }
public function getAVSResponse() { return $this->results[5]; }
public function getTransactionID() { return $this->results[6]; }

Just like we have created accessor methods for the results of the transaction, we can create accessor methods to access the other 72 fields returned by the Authorize.Net API. The four chosen for this article are important enough to be listed here are:

  • getResponseText()

    If an error occurs or a transaction is declined, this field will contain text explaining what happened. If it is approved it will simply say, "This transaction has been approved.".

  • getAuthCode()

    This is the six-digit approval code provided by the processing bak for the transaction. This is good to have for any transaction and vital for AUTH_ONLY transactions.

  • getAVSResponse()

    This is a one character response indicating the results of AVS. The results of AVS can be very useful in determining whether a transaction may be fraudulant or not. Here are the important AVS codes to know:

    • X or Y - Both the numeric address and the Zip code match the card issuing bank’s database.
    • A - Address matches but the Zip code does not.
    • W or Z - Zip code matches but numeric address does not.
    • N - Neither the zip code or street address matches.
    • U - The issuing bank doesn’t support AVS.
    • G - An international credit card. AVS is not supported.


  • getTransactionID()

    This is the transaction ID assigned to this transaction by Authorize.Net. When researching this transaction on their server this will be handy to have.

Constructor | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Validating Our Data