Merchant Account Services

Integrate the Authorize.Net Recurring Billing API with PHP

Establish subscriptions and recurring payments for your website

 

Author: Jim Conners

Rating: 10.0

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

Methods

Now that we have the properties for our class set we will need some methods to interact with them and the ARB API.

private function process($retries = 3) { $count = 0; while ($count < $retries) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->xml); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $this->response = curl_exec($ch); $this->parseResults(); if ($this->resultCode === "Ok") { $this->success = true; $this->error = false; break; } else { $this->success = false; $this->error = true; break; } $count++; } curl_close($ch); }

This method is the workhorse of our class. It takes the parameters we have set, sends them them to Authorize.Net, receives the response, and parses the results. It takes one parameter $retries which has a default value of '3'. This is how many times it will try to connect to the ARB API if it experiences connection issues. This way if we do have a temporary connection issue it might be resolved in time for us to run a successful transaction without the user being aware of any problems.

To connect to Authorize.Net we will use the cURL PHP extension. We set the parameters for cURL with these lines of code:

$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->xml); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

Once our parameters are set we execute our transaction with one line of code: $this->response = curl_exec($ch);. It sends our transaction to Authorize.Net and receives their response. It assigns that response to our $response parameter. The data in that parameter is processed by our class when we call our parseResults() method on the very next line. The results are stored in the parameters we covered earlier in this article.

We then need to check to see if our transaction was successful. We do so with this code:

if ($this->resultCode === "Ok") { $this->success = true; $this->error = false; break; } else { $this->success = false; $this->error = true; break; }

If the result code returned by Authorize.Net is 'Ok' we know our transaction was successful. If any other value is returned we know an error occurred.

public function createAccount() { $this->xml = "<?xml version='1.0' encoding='utf-8'?> <ARBCreateSubscriptionRequest xmlns='AnetApi/xml/v1/schema/AnetApiSchema.xsd'> <merchantAuthentication> <name>" . $this->login . "</name> <transactionKey>" . $this->transkey . "</transactionKey> </merchantAuthentication> <refId>" . $this->params['refID'] ."</refId> <subscription> <name>". $this->params['subscrName'] ."</name> <paymentSchedule> <interval> <length>". $this->params['interval_length'] ."</length> <unit>". $this->params['interval_unit'] ."</unit> </interval> <startDate>" . $this->params['startDate'] . "</startDate> <totalOccurrences>". $this->params['totalOccurrences'] . "</totalOccurrences> <trialOccurrences>". $this->params['trialOccurrences'] . "</trialOccurrences> </paymentSchedule> <amount>". $this->params['amount'] ."</amount> <trialAmount>" . $this->params['trialAmount'] . "</trialAmount> <payment> <creditCard> <cardNumber>" . $this->params['cardNumber'] . "</cardNumber> <expirationDate>" . $this->params['expirationDate'] . "</expirationDate> </creditCard> </payment> <billTo> <firstName>". $this->params['firstName'] . "</firstName> <lastName>" . $this->params['lastName'] . "</lastName> <address>" . $this->params['address'] . "</address> <city>" . $this->params['city'] . "</city> <state>" . $this->params['state'] . "</state> <zip>" . $this->params['zip'] . "</zip> </billTo> </subscription> </ARBCreateSubscriptionRequest>"; $this->process(); }

This method might look complex but if you look closely it only contains two statements. The first sets the value of $xml. We populate it with the XML specified by Authorize.Net to be used for creating a recurring subscription. At the same time we take the values we have stored in our $params and place them within the XML in their appropriate homes. After doing this we call the process() method to complete our transaction.

public function setParameter($field = "", $value = null) { $field = (is_string($field)) ? trim($field) : $field; $value = (is_string($value)) ? trim($value) : $value; $this->params[$field] = $value; }

The ARB API can accept over 60 different parameters when submitting a transaction. To keep our code organized and optimized we store them in our $params array. To add new fields to the array we simply use this method and pass it two parameters. $field is the name of the field in the array we wish to set. $value is the value we wish to assign to the field in parameter number one.

Make sure your XML expects your parameters

The XML we use in our example is a subset of the complete XML you can send to Authorize.Net through their ARB API. If you add fields to the $params array but the associated XML is not present then that parameter will never be sent to Authorize.Net. For a complete list of parameters and the XML associated with each one refer to the Automatic Recurring Billing Guidepdf.

private function parseResults() { $this->resultCode = $this->parseXML('<resultCode>', '</resultCode>'); $this->code = $this->parseXML('<code>', '</code>'); $this->text = $this->parseXML('<text>', '</text>'); $this->subscrId = $this->parseXML('<subscriptionId>', '</subscriptionId>'); }

This method uses the ParseXML() method below to populate some of our class properties with the data returned by Authorize.Net. It takes two parameters: the opening and closing XML tag that contains the information we want.

private function ParseXML($start, $end) { return preg_replace('|^.*?'.$start.'(.*?)'.$end.'.*?$|i', '$1', substr($this->response, 335)); }

This method takes the response returned for Authorize.Net and looks for pieces of information inside the XML. What information it looks for depends on the parameters we pass to it. In our case we pass the XML node we wish to get information from. It takes the opening and closing tag and places it into a regular expression that extracts the information we are looking for.

public function getSubscriberID() { return $this->subscrId; }

This method is important for any application that will also be editing and/or deleting recurring billing subscriptions. You will need to provide Authorize.Net with this ID if you wish to work with existing records. If you only wish to establish records and then manage them through your Authorize.Net control panel then recording this is not necessary.

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

These two methods are very straight forward. They allow us to check to see if our transaction was successful or not. They may be redundant but by having both options available to us it will make our client code easier to read and understand which is always a good thing.

Constructor | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Using Our Class