Accepting Credit Card Payments with OXID eShop CE and Authorize.Net

The Swipe Age

In recent years, there has been a rapid growth in electronic payment mechanisms, particularly credit and debit cards. To illustrate, consider that at the end of 2008, Visa and MasterCard together had issued more than 2.5 billion credit and debit cards, accounting for more than $4.5 trillion of purchases worldwide (company statistics). Many of those purchases were on e-commerce web sites, which have slowly been gaining ground on traditional retail outlets on account of their ease of use, convenience and lower prices.

Now, if you’re planning to start an online store, it should be pretty clear that accepting electronic payments isn’t an option – it’s a necessity for you to compete effectively. And that’s where this article comes in. Over the next couple of pages, I’ll show you how to begin accepting credit card payments for your products using the open source OXID shopping cart and the Authorize.Net payment gateway…with, of course, a little bit of PHP to make things interesting!

Putting The Pieces Together

When it comes to selecting a shopping cart system for your online store, there’s no shortage of options, both commercial and open-source. However, for small merchants operating on a limited budget, open source shopping carts are often a better choice than their commercial counterparts, for a number of reasons:

  • They’re typically licensed under the GNU General Public License and, as such, can be used without needing to pay an annual or one-time fee
  • Their source code is readily available, making it possible to customize them to specific requirements, or to add custom functions
  • They’re supported by a community of developers and users, who can provide assistance and advice, fix bugs, and perform testing in a wide range of environments.

One such open source shopping cart system is OXID eShop CE, which provides a modular, standards-compliant framework for an online store. Developed using PHP and MySQL and maintained by OXID eSales AG of Germany, OXID eShop CE includes support for common functions such as displaying products, managing inventory and orders, collecting user reviews and searching product catalogs. Most importantly for our purposes, it’s free for both commercial and personal use under the GNU General Public License (an enterprise version that includes paid technical support is also available), and it comes with an object-oriented architecture that can be easily extended to support custom functions, including payment gateway interfaces. This article uses OXID eShop CE v4.1.2.

Installation of OXID eShop CE is fairly straightforward – download the source package, extract its contents to a directory under your Web server root, and then use the Web-based installer to verify system requirements and perform installation. System requirements and detailed installation instructions can be found in the OXID eShop CE manual as well as in the package documentation. Once you’ve got everything installed, log in to the eShop’s administration panel at http://your-oxid-domain/admin/ and begin adding products, payment details and shipping terms; the manual has detailed instructions on these tasks, and so does this tutorial. The remainder of this article assumes that you have a fully-functional OXID eShop CE installation, complete with sample products, prices and shipping details.

Of course, a shopping cart is only a part of the puzzle. In order to successfully process electronic payments, you’ll also need a payment gateway account and, possibly, a merchant account. The payment gateway takes care of receiving credit card information and processing credit card transactions; the funds received in this manner are held in the merchant account. Again, there’s no shortage of payment gateways and merchant accounts, and they differ in their features, fees and security systems; you should choose one that works for your budget and expected transaction volume.

This article uses the Authorize.Net payment gateway, which is popular with developers because it comes with a well-documented API, free sample code for many different programming languages, free developer accounts, and a “sandbox” for detailed integration testing. The remainder of this article assumes that you have developer access to this gateway; to obtain this access, drop by their Web site and request a free developer account for your store. Account credentials include an API login ID and a transaction key; you’ll need these to gain access to the payment gateway, so hold on to them tight.

While you’re there, it’s also a good idea to download Authorize.Net’s Advanced Integration Method (AIM) Implementation Guide. This guide is your roadmap to working with Authorize.Net, as it contains detailed information on available API calls, input parameters, error codes and return values, together with information on how to integrate and use the Authorize.Net API on different platforms. You’ll be referring to it frequently throughout this article.

Finally, the code examples in this article make use of the PEAR HTTP_Request2 package, to formulate and transmit HTTP requests to the Authorize.Net API. The HTTP_Request2 package is freely available and is currently maintained by Alexey Borzov. This article uses v0.4.0 (alpha) of HTTP_Request2; the easiest way to install it is with the PEAR installer, as below:

All done? Let’s get started.

A Simple Request

To perform a credit card transaction with Authorize.Net, you need to submit a POST request to the payment gateway URL containing. This POST request must contain all the information relevant to the transaction, including the merchant’s account credentials, the credit card number and the transaction amount. Here’s an example of one such POST request:

Here’s a quick explanation of these fields (for details, refer to the AIM Implementation Guide):

  • The ‘x_login’ and ‘x_tran_key’ fields hold the merchant’s account credentials for Authorize.Net. These fields must be included with every transaction request.
  • The ‘x_type’ field indicates the type of transaction being requested. Authorization and capture (AUTH_CAPTURE) is the most common one for online stores, but Authorize.Net also supports Authorization Only (AUTH_ONLY), Capture Only (CAPTURE_ONLY), Credit (CREDIT) and Void (VOID) transactions.
  • The ‘x_method’ field specifies the payment method. While credit card (CC) is the default, Authorize.Net also supports electronic checks (ECHECK).
  • The ‘x_card_num’, ‘x_exp_date’, ‘x_card_code’ and ‘x_amount’ fields contain the credit card number, credit card expiry date, CCV key and transaction amount respectively. As you’ll see shortly, this information can easily be retrieved from OXID’s order object and interpolated into the POST request.
  • The ‘x_invoice_num’ and ‘x_description’ fields are optional fields that can be used to specify an order number and description. This information will typically appear on the customer’s credit card statement and, although optional, it’s a good idea to include it.
  • The ‘x_first_name’, ‘x_last_name’, ‘x_address’, ‘x_city’, ‘x_zip’, ‘x_country’ and ‘x_email’ fields contain billing information for the user placing the order. While these fields are optional, the ‘x_address’ and ‘x_zip’ fields in particular are good to include, as they can be used to perform further address-related verification and thereby reduce the risk of fraud.
  • The ‘x_test_request’ field tells the payment gateway whether this is a test transaction. Test transactions are useful in the first phase of integration testing, to verify that the HTTP request and response data is being successfully transmitted. Test transactions don’t make it out of the Authorize.Net sandbox into the main payment clearing system.
  • The ‘x_version’, ‘x_delim_data’, ‘x_delim_char’ and ‘x_relay_response’ fields control how the response data is formatted and relayed back to the requesting client.

It’s important to note that Authorize.Net assumes that transactions are expressed in United States Dollars (USD) only.

Authorize.Net responds to a POST request like the one above by checking the input data, attempting to perform the specified transaction, and returning an ‘Accepted’ or ‘Declined’ status. Here’s an example of the response packet returned after an accepted transaction:

And here’s an example of the response packet returned after a declined transaction:

An Authorize.Net response packet contains 40 fields. Of these, the following are of particular importance (you can read about the rest in the AIM Implementation Guide):

  • Field #1 returns the status of the transaction. This status value will be in the range 1-4, where 1 indicates an accepted transaction, 2 indicates a declined transaction, 3 indicates a processing error, and 4 indicates an “on hold” transaction.
  • If the transaction was not accepted, Field #3 returns a numeric code that provides more information on the reason, and Field #4 returns a string description of the error. A complete list of the possible reason codes can be found in the AIM Implementation Guide.
  • If the transaction was accepted, Field #5 returns a 6-character authorization or approval code.

Object Lesson

As the previous explanation should illustrate, processing credit card transactions with Authorize.Net isn’t particularly difficult. To integrate it with OXID (or any other shopping card), all you need to do is splice some code into the appropriate stage of the order process to formulate a POST request, read the response, and use that response to decide whether or not to continue processing the order.

Now, if you play with OXID eShop CE a little, you’ll realize that the process of creating and processing a customer order can broadly be broken into four stages, each making use of a different core object.

Stage 1: Finalize shopping basket

As the user browses the online store, he or she can directly add products to a session-based shopping basket. This cart, represented by an oxBasket object, includes methods to return the current contents of the basket, add or remove items to and from the basket, set shipping and delivery prices, and add or remove gift vouchers. When the user heads for checkout, the system renders a Basket view that takes care of retrieving the oxBasket object, getting a list of the items in it, and generating a summary listing that also includes controls to edit quantities or remove items, as below:

Stage 2: Enter billing and shipping addresses

Once the user has finalized his or her shopping basket, the next step is to instantiate a new oxUser object, representing the currently logged-in user, and use this object’s getter methods to retrieve the user’s previous shipping and billing addresses, if available. These details are used to create and pre-fill a User view, as below:

Stage 3: Select payment and shipment method

Once the billing and shipping addresses are known, the next step is to render a view that allows the user to choose from a list of payment and shipping methods. This isn’t as simple as it sounds, because OXID eShop allows merchants to define payment and shipping rules on a per-location basis, allowing for a wide variety of possible combinations. Working through these combinations, loading delivery sets and corresponding payment methods, and offering these choices to the user is the task of the oxPayment and oxPaymentList objects. These objects are used by the Payment view, which also takes care of requesting the appropriate input for each payment method (number and expiry date for credit cards, routing and account numbers for bank transfers), calculating the cost or discount associated with each payment method, validating credit card numbers, and handling redirects in case of payment errors in the next stage.

Stage 4: Confirm and submit order

The final stage uses information from the previous three stages to create a new oxOrder object. This object represents the customer’s final order, and it includes methods to calculate the total order price, apply discounts, check inventory status, write order information to the database and process payment. When the user submits the order, the Order view calls these methods and then, depending on the results, either displays a success notification or redirects the client back to the Payment view for re-entry of payment information.

Most of the heavy lifting in the final stage is done by the oxOrder::finalizeOrder() method, which is the main order checking and processing method. Internally, this method invokes the oxOrder::_executePayment() method and passes it two objects: an oxBasket object, which represents the user’s shopping basket, and an oxUserPayment object, which represents the user’s payment information. The oxOrder::_executePayment()in turn initializes an new oxPaymentGateway object with these parameters and then calls oxPaymentGateway::executePayment() to actually perform the payment transaction.

  • If oxPaymentGateway::executePayment() returns false, it implies that the payment transaction failed. The order is then deleted from the database and control passes back to the Order view, which returns an error.
  • If oxPaymentGateway::executePayment() returns true, it implies that the payment transaction succeeded. The order status is then updated in the database, appropriate inventory is subtracted, and an email confirmation is sent to the shop owner and customer. Control returns to the Order view, which shows a success notification.

Here’s a quick flow chart of how this works:

Back To Class

It should be clear from the above discussion that extending the base oxPaymentGateway object and overriding its executePayment() method is the simplest and most efficient way to add support for the Authorize.Net payment gateway (this is also the method recommended by the OXID development team).

The first step is to extend the base payment gateway class, oxPaymentGateway, and override the parent class’ executePayment() method, as in the following empty class definition:

OXID eShop expects custom classes and modules to be stored in subdirectories of the $OXID/modules directory, where $OXID refers to the main OXID installation directory. With this in mind, save the above class definition to $OXID/modules/extpaymentgateway/extarticle.php.

Now, you’d expect the above authorizenetPaymentGateway class to extend the base oxPaymentGateway class. However, from the listing, it’s clear that it actually extends something called authorizenetPaymentGateway_parent. This isn’t a typo – it’s the recommended method to extend OXID’s core classes. When OXID encounters a class definition like the one above, it automatically creates the *_parent class and then creates your custom class as a child of that parent class. This “dynamic chaining” of one class to another makes it possible for multiple modules to use the same class.

One question remains: how do you link your custom class to the base oxPaymentGateway class? To do this, log in to the OXID eShop administration panel, navigate your way to Master Settings -> Core Settings -> System -> Modules and add the following entry to it:

Here’s what it looks like:

This line tells OXID that instead of creating instances of the oxPaymentGateway class, it should create instances of the child authorizenetPaymentGateway class.

The next step is to update the authorizenetPaymentGateway::executePayment() method with the code necessary to communicate with the Authorize.Net payment gateway. Begin by adding some properties to the class definition, as below:

Remember that you’ll need to update these properties to reflect your own account with Authorize.Net.

Next, check that this order uses a credit card as the payment method. Retrieve the payment information from the oxUserPayment object and store it in an array:

You should also retrieve the current oxUser object, and read user information such as name, address and zip code from it into an array:

Create an array of data that matches the input expected by the Authorize.Net transaction gateway:

Then, use the PEAR HTTP_Request2 class to generate and send this data as a POST request to the transaction gateway:

Check the first field of the response and, depending on its value, return either true or false to the caller. In case the request was unsuccessful, you can also set the authorizenetPaymentGateway::_sLastError property to the error string returned by the payment gateway. This error string will then be forwarded and displayed in the Payment view:

Here’s the complete class definition for your reference:

Before trying it out, pop back in to the eShop administration panel, navigate to the Master Settings -> Core Settings -> Settings -> Other Settings -> Add or Remove Shop Currencies form, and update it to set USD as the shop currency. This step is necessary because the Authorize.Net payment gateway assumes that all transaction amounts are expressed in USD, and doesn’t support payments in other currencies.

In case your shop’s prices are expressed in a currency other than USD, you can specify a conversion rate to have them automatically converted as well.

To try it out, add some items to your shopping cart and head for checkout. When asked for credit card information, use one of the test credit card numbers provided to you by Authorize.Net. Once you submit your order, OXID will create an authorizenetPaymentGateway instance and then call authorizenetPaymentGateway::executePayment() to process the transaction. Assuming all goes well, you should see an order confirmation page, as below:

In the event of an error, you’ll be redirected back to the Payment view and the error string returned by authorizenetPaymentGateway::executePayment() will be displayed in this view, as below:

Room With A View

OXID’s extensible module API doesn’t just allow you to extend core classes – you can just as easily extend and customize views to alter the information users see when browsing through your store. This is possible because all OXID views are derived from the oxUBase class, which in turn is derived from the base oxView class.

Let’s see how this works with an example. You’ll remember, from a few pages back, that Authorize.Net returns an approval code if the transaction is accepted. However, by default, OXID doesn’t include any mechanism to display this code on the final order confirmation template – so let’s add it in!

Begin by extending the Thankyou view, which is responsible for displaying the final order confirmation template, as below:

Save this class file as $OXID/modules/extpaymentgateway/authorizenetthankyou.php.

Head back to the eShop administration panel and let OXID know about your new class, by adding the following definition to the module list:

Next, edit the authorizenetPaymentGateway class, and save the approval code and transaction ID as session variables:

Then, update your new authorizenetThankyou class with methods to retrieve these values from the session, as below:

To display this information in the order confirmation template, all that’s left is to invoke these methods at the appropriate place in the HTML code. Pop open the template file at $OXID/out/basic/tpl/thankyou.tpl, and update it to include the code in bold:

The OXID eShop framework already includes support for localization so, if you’d like to support languages other than English, you can replace the English-language strings in the above template with resource identifiers, as below:

Translated strings for each language should then be placed in the corresponding language file, at $OXID/out/basic/lang/cust_lang.php. Here’s an example of setting up the English language file for the resource identifiers used above:

Here’s an example of what the revised order confirmation page looks like, complete with approval code and transaction ID:

And that’s about it. As this article illustrates, the open source OXID shopping cart is built on an extensible, object-oriented architecture that makes it easy to “plug in” new modules and functions. By facilitating integration with third-party payment gateways and making it simple to alter the default user views, OXID eShop CE provides a flexible and economical foundation for build highly-customized online stores. Try it out for yourself sometime…and happy coding!

Copyright OXID eSales AG, 2009. All rights reserved.