Realex Redirect with PHP


Recently, we’ve been working with Realex and the Redirect method for simple once off payments which also require custom data (such as name, email address and a dynamic amount value) taken from user input.

This can be awkward when using the Redirect method as you must first handle the user input before sending the user to pay. Usually, you would need to display a new page showing a form with hidden fields for the data which needs to be passed to Realex and a button such as ‘Proceed to Secure Server’. This two step process seems a bit cumbersome so we’ve tried to make it easier for people to go from our custom form straight to payment at the Realex server.

In an effort to cut down on the amount of code, we’ve put together a small library of PHP code to do just that and help speed up the development process in future. You can buy our library for €25 excluding VAT.

The library requires PHP version 5.1.4 and includes the following files:

documentaion.html
example.html
library
    Studioforty9
        HtmlPage.php
        Realex
            Redirect
                Form.php
                Response.php
                Request.php

Buy Now

Here is an example of how you can create a HTML page dynamically, pass your Request variables to a Realex Form class and submit the form automatically.

<?php
$formIsValid = FALSE;

function __autoload($class)
{
	$classfile = str_replace('_', '/', $class).'.php';
	$path_to_library = '/path/to/library/';
	require_once $path_to_library.$classfile;
}

# Validate User Input Here
if (isset($_POST['amount']) {
	$amount = clean($_POST['amount']);
	$formIsValid = TRUE;
}

# Check that all the initial User Input data is valid
if (TRUE === $formIsValid) {

	# You can now store the user input or email it to an administrator

	# Create Request
	$Request = new Studioforty9_Realex_Redirect_Request;
	$Request->setMerchant_ID('merchant_id');
	$Request->setSecret('secret');
	$Request->setAccount('internet');
	$Request->setOrder_ID('123');
	$Request->setCurrency('EUR');
	$Request->setTimestamp(strftime("%Y%m%d%H%M%S"));
	$Request->setCust_num('123');
	$Request->setProd_ID('012345');
	$Request->setVar_Ref('0123456789');
	$Request->setAmount($amount * 100);
	$Request->setSha1Hash($Request->generateHash());
	
	# Create Form
	$Form = new Studioforty9_Realex_Redirect_Form;
	$Form->setRequest($Request);
	$Form->setAttributes(array('id' => 'realex', 'name' => 'secureserver'));
	
	# Create Page
	$Page = new Studioforty9_HtmlPage();
	$Page->html();
	$Page->head(); // Must be called to allow for title, meta, styles and scripts to be added, render() method will not run without it
	$Page->title('Realex Redirect Payment');
	$Page->addMeta(array('http-equiv' => 'content-type', 'content' => 'text/html; charset=UTF-8'));
	$Page->addMeta(array('name' => 'robots', 'content' => 'nofollow,noindex'));
	$Page->addStyleToHead(array('href' => '/css/realex.css'));
	$Page->addScriptToHead(array('src' => '/js/realex.js'));
	
	# Attach Loading paragraph, 
	$loading = '<p class="loading">Please wait while we redirect you to our secure server.</p>';
	$Page->body(
		array('onload' => 'document.secureserver.submit();'),
		$loading.$Form->render()
	);
	
	echo $Page->render();
} else {
	# Redirect the user back the initial form and show errors
}

?>

Lets break this down

Firstly, we’re automatically loading the needed classes on demand with our __autoload() function, if you decide to use our library make sure you set the correct path to the library folder. If you are on a windows server be sure to change forward slashes to backslashes.

Next, you should validate the user input from the initial form, once we know the user input is valid, we can then store the data to a file or database or just send it out to an administrator.

The Request Class

Here’s where it gets interesting, we know the data is valid, we’ve stored it and now we want to send our eager customer to Realex to relieve them of some of their hard-earned cash. Using the Studioforty9_Relex_Redirect library we can create a new Request object like so:

<?php

$Request = new Studioforty9_Realex_Redirect_Request;

?>

We can pass in any variables to this object using the setVariable_Name methods. These method names map to request variables provided by Realex. Notice the underscores in the variables are also present in the method names. (e.g. $Request->setAuto_Settle_Flag(TRUE);)

merchant_id
secret
account
order_id
currency
timestamp
cust_num
prod_id
var_ref
amount
sha1hash
shipping_code
shipping_co
billing_code
billing_co
return_tss
auto_settle_flag
<?php

$Request->setMerchant_ID('your_merchant_id');
$Request->setSecret('your_shared_secret');
$Request->setAccount('internet');
$Request->setOrder_ID('123');
$Request->setCurrency('EUR');
$Request->setTimestamp(strftime("%Y%m%d%H%M%S"));
$Request->setCust_num('123');
$Request->setProd_ID('012345');
$Request->setVar_Ref('0123456789');
$Request->setAmount($amount * 100);

?>

The last thing you need to do with the Studioforty9_Realex_Redirect_Request object is generate the Realex sha1 hash, our Request class provides an easy method for this so that all you need to do is call:

<?php

$Request->setSha1Hash($Request->generateHash());

?>

The Form Class

Once we have passed all our variables to the Request, we can then create a new Form object to dynamically build the form that will send the customer to Realex.

<?php

$Form = new Studioforty9_Realex_Redirect_Form;
$Form->setRequest($Request);
$Form->setAttributes(array('id' => 'realex', 'name' => 'secureserver'));

?>

All we need to do is create a new instance of Studioforty9_Realex_Redirect_Form and pass the Request object with the setRequest() method. Then I’ve added two attributes, and id for styling purposes and a name so that I can submit the form automatically when the page loads. The Form object also has a render() method which we will use later.

The HtmlPage Class

The Studioforty9_HtmlPage class provides a simple interface to create a HTML page without writing a single line of HTML. It uses the built in DOMDocument class to programatically create and render a valid HTML page. We will use it to build a page for our Realex form on the fly and pass attributes to our <body> tag to send the form automatically.

<?php

$Page = new Studioforty9_HtmlPage();
$Page->html();
$Page->head(); // Must be called to allow for title, meta, styles and scripts to be added, render() method will not run without it
$Page->title('Realex Redirect Payment');
$Page->addMeta(array('http-equiv' => 'content-type', 'content' => 'text/html; charset=UTF-8'));
$Page->addMeta(array('name' => 'robots', 'content' => 'nofollow,noindex'));
$Page->addStyleToHead(array('href' => '/css/realex.css'));
$Page->addScriptToHead(array('src' => '/js/realex.js'));
$loading = '&lt;p class="loading">Please wait while we redirect you to our secure server.</p>';
$Page->body(
	array('onload' => 'document.secureserver.submit();'),
	$loading.$Form->render()
);
?>

This class is fairly straight forward, we create an instance of Studioforty9_HtmlPage and call its constructor method, which automatically creates a new XHTML Strict Document, we call the html method to create the root HTML node, we must also call the head so we have a parent node for title, meta, style and script

You set the title of the document using the title method, the addMeta meta simply takes an array of attributes, the addStyleToHead and addScriptToHead methods will figure out whether to link to a resource or embed the code based on the attributes you provide, so for example, if you don’t pass an src attribute to addScriptToHead it will assume you wish to embed javascript in the head which you can do like so $Page->addScriptToHead(array(), "var greeting = 'Hello World!';");.

Next, we need to create a loading message to show the customer while the browser attempts to automatically submit your form, if you want to show a spinner/animated gif, you can either add to image in directly here or add a CSS class hook to allow for more control. Lastly you need to pass some variables to the body method, the onload attribute needs some simple javascript code to submit the form and we also need to pass in our loading content as well as our Studioforty9_Realex_Redirect_Form object’s render method

Finally, we run echo $Page->render(); which sends everything to the browser for display. You should now have a simple, re-usable, programmatic approach to using the Realex Redirect method.

Ted Robinson
Ted Robinson |