Payment Gateway Plugin API
This page is outdate and will be updated with current information as soon as possible.
CartThrob has a payment gateway interface and helper functions that help to simplify the creation of payment gateways. Review the first-party gateways that come with CartThrob for examples located in the cartthrob/payment_gateways folder. The file Cartthrob_dev_template.php contains detailed notes and documentation within the file itself to get you started and should serve as a guide for building additional gateways.
It's important to note that the most critical element of building a gateway is understanding your credit card processor's system. You'll need to have an account with your processor to test with and you'll need their developer documentation and code samples as well, if available.
There are several functions that exist to simplify integration with off-site gateways, but some gateways are just complex to deal with, and there's no getting around it. Rather than make the process of building a custom integrated gateway even more complicated we've tried to simplify the process as much as possible through the use of helper functions that simplify integration with many different types of gateways. Review the cartthrob/libraries/Cartthrob_payments.php file to see the full list of payment gateway helper functions.
There are several types of gateways that we've discovered over the years. CartThrob can integrate with each type, but some are more difficult than others. Gateways are classified in the following groups:
- Direct – All payment details are taken on your site, the customer never leaves your site. Authorization is immediate.
- Hosted/Redirect – The customer is taken off of your site to the processor's site. All payment details are taken on the processor's site. When the transaction is complete, the customer is redirected back to your site. (see gatewayOrderUpdate())
- Hosted/Cul-de-sac – The customer is taken off site. All payment details are taken on the processor's site, and the authorization is immediate. At the end of the process, the customer is left at the processor's site, but the processor dynamically pulls in a page from your website (see getNotifyUrl() and relaunchSession() below).
- Hosted/Dead End – The customer is taken off site, and makes the payment at the processor's site. At the end of the process, the customer is not directed back to your site, no pages are pulled from your site, and your site is not notified of the success or failure of a transaction. At best, they may allow you to upload a plain HTML template to display when a transaction is successful or fails. We do not recommend any company that only offers this limited service.
- Hosted/Delayed-Response – PayPal and Google Checkout are the most well-known of this type. The customer is taken offsite. All payment details are taken on the processor's site. Authorization may take as long as a week. At the end of the process the customer may or may not be redirected back to your site. The transaction is not completed in real-time, and your site may not be notified of a successful completion for days. It's like taking an IOU that will probably be paid in a few days. These types of merchant accounts are generally inexpensive to set up and maintain, but integration is much more time consuming, and the process is inefficient and confusing. Many times if customers purchase items or software, they expect shipping or downloads to be immediate. Using one of these methods, you need to wait until the funding is authorized. Integrating these gateways is difficult because you need to set up the system to relaunch orders securely. PayPal standard is a fairly typical example of this type of gateway (see relaunchSession() function).
When you begin, follow the following requirements.
- All gateways should be named Cartthrob_your_gateway_name.php and should be stored in the cartthrob/third_party/payment_gateways folder. If you store your custom gateway alongside CartThrob's first-party gateways, they will not be loaded.
- You may also want to create a language file to go with your gateway. You can refer to existing language files (cartthrob/language/english) for structure, but at a minimum, language files need to be named cartthrob_your_gateway_name_lang.php, and should be added to the appropriate language folder.
- The classname of your gateway needs to match the filename. A file called Cartthrob_my_gateway.php will have a classname like so: "Cartthrob_my_gateway extends Cartthrob_payment_gateway"
- public $title is the descriptive name of your gateway
- public $overview is the overview or special instructions for this gateway
- public $settings is an array of settings
- public $fields is an array containing fields that will be output as part of the gateway_fields variable in the checkout form. Adding fields here handles nearly all of the formatting and basic form generation. Please see cartthrob/libraries/API/API_cartthrob_payment_gateways gateway_fields function for a list of acceptable field names. Only fields listed in the API should be used, all other field names are ignored. If it is absolutely impossible to integrate with your gateway without additional field names, please contact us.
- public $required_fields is an array containing form fields that are required. Any field set in this array will cause the checkout process to fail if that field is empty.
- public $hidden states which fields should be hidden fields not editable by the user. When a user checks out hidden fields are filled automatically if appropriate data is found in the user's session.
- public $card_types is an array containing the gateway's acceptable credit card types. If this is not set, visa => Visa, mc => MasterCard, amex => American Express, and discover => Discover are used. Your particular processor might also take additional cards like Laser and Solo, or might use different key names like MC, Master, MasterCard, in which case you'll need to provide an array of credit card types containing the required gateway code as the key, and the descriptive name the customer will see as the value.
- There is only ONE required method: charge(). This method is required of all gateways to do the bare minimum of processing.
Plugin settings are shown in the payment gateway configuration page. Generally they're used to store merchant ids and passwords, and other information required to integrate with your gateway. You'll find an example of the different types of settings below.
'settings' => array( array( 'name' => 'Settings Example', // descriptive name 'short_name' => 'settings_example', // you will use this to access this setting your code. 'type' => 'text', // or textarea 'default' => 'Default Text', // optional ), array( 'name' => 'Settings Example 2', 'short_name' => 'settings_example_2', 'type' => 'radio', 'default' => 'no', // will auto-select "no" as the default 'options' => array( 'yes' => 'Yes', 'no' => 'No', ), ), array( 'name' => 'Settings Example 3', 'short_name' => 'settings_example3', 'type' => 'matrix', 'settings' => array( array( 'name' => 'Matrix Settings', 'short_name' => 'matrix_settings', 'type' => 'checkbox', 'options' => array( 'option1' => 'Option1' ) ) array( 'name' => 'Other Setting', 'short_name' => 'other_setting', 'type' => 'text', 'default' => "More default text" ) ), ), )
Using the "settings" array, you can create multiple setting fields that will display in the gateways settings when it is selected. Name, short_name, and type are required for each settings group. You may optionally provide a default value. The available types include "text", "textarea", "radio", "checkbox" and "matrix".
By the time
$this->order() data makes it to your gateway, the data has already been cleaned and formatted. Any data will have already been
saved as an order, so all you need to do is pass the data off to your gateway in their required format. Though it's really dependent on your
processor's requirements, our typical methodology is this:
- create an array containing the processor's required variable names as array keys (eg. z_firstName) and CartThrob data (eg.
$this->order('first_name')) as array values. (see $post_array in our example below)
- convert that array into a query string (if needed)
- curl the data to the gateway for direct integration, or use completePaymentOffsite() to send the customer to the hosted processing page.
- handle the response, either by reading the curl data, or in a function that will be called by the processor (see getNotifyUrl())
Order Data Variables
You can access all order data using
$this->order('variable') You do not need to test whether or not the particular variable is set. If it's
not set NULL will be returned.
'first_name', 'last_name', 'address', 'address2', 'city', 'state', 'zip', 'description', 'company', 'phone', 'email_address', 'shipping_first_name', 'shipping_last_name', 'shipping_address', 'shipping_address2', 'shipping_city', 'shipping_state', 'shipping_zip', 'expiration_month', 'expiration_year', 'begin_month', 'begin_year', 'bday_month', 'bday_day', 'bday_year', 'CVV2', 'card_code', 'issue_number', 'card_type', 'currency_code', 'country_code', 'shipping_option', 'credit_card_number' 'entry_id' 'total'
The charge function is the only required function in your payment gateway. The $creditCardNumber is the only parameter, and
can be set to NULL. Any other information can be accessed using
In the very end of the process you should generally return a TransactionState object:
$state->isAuthorized($msg)->setTransactionId($txnId); $state->isFailed($msg); $state->isDeclined($msg);
This returned data is also used in the templates to evaluate conditionals and output authorization and error messages.
You can add other functions as necessary, however, they will not be used by CartThrob in anyway. You may call them from outside the system however (see getNotifyUrl())
curlTransaction($url, $data, $header, $mode, $suppressErrors, $options)
Uses cURL to send and receive data to another server. Pass in the curl server address as a string, and send additional data as an array or query string as required by your processor. Most of the processor documentation does not specify whether a query string is required or not, some trial and error may be needed.
completePaymentOffsite($url, $offsiteData, $formSubmission)
If you are going to be sending the user off-site for handling the rest of the transaction, add this function at the bottom of your charge() function.
The payment gateway URL in which to send the visitor.
An array of all data that should be passed to the payment gateway. The data will be encoded based on the setting of
Determines whether to send the visitor to the next page via a 302 redirect (default) or a form submission.
gatewayOrderUpdate($state, $orderId, $emailData)
This function is useful for completing an order, after being returned from a hosted gateway. Use this regardless of whether your transaction
was successful or not, as it updates the status of transactions based on the
$state TransactionState object . The $state object and order id
are required. If the
$returnUrl is empty the customer will not be redirected.
This function does the following:
- Updates the transaction data for an order (adds transaction numbers, or error messages to the order data)
- Updates order status. This will set the complete, failed, declined, processing status as dictated by the contents of the
- Updates purchased items status
- Executes the on_fail, on_authorize, and on_decline extension hooks.
- Sends notification emails
This function will generate something like this:
Many hosted payment processing systems will return your customers to a different URL for success, failed, declined transactions. You can usually use the same notification url for each of these statuses… if the gateway also posts transaction data you will be able to parse this information and update cartthrob using the gatewayOrderUpdate() method. The dynamic URLs generated by this function makes it possible to update CartThrob with order data, transaction information and status. If you use a hard-coded URL, you will not get the benefit of this additional order processing.
NOTE: Some payment processors WILL NOT use URLs containing a query string (?ACT=etc). IF that's the case with your processor, please contact us for some sample methodology and code.
This will relaunch a dead session and allow you to access order data from the session using
$this->order('key') This is only needed when a gateway needs to communicate with your site in the background or after your customer is no longer present. Generally, you will have to get the session from a
$_POST variable or other method. This is best used when you can dynamically validate that the message is coming from your payment processor.
Convert a three character country code to its two character representionation (ex: USA → US)
Splits a URL encoded string into an array, (ex:
Convert a year to its two character representation (ex: 2004 → 04)
Convert a year to its four character representation (ex: 04 → 2004)
Fetches the contents of an existing template.
Will parse ExpressionEngine template code. You can optionally send an array of variables to parse as well.