February 5, 2014

API Best Practices Part I: AJAX

Posted by Craig Christenson Category IconTechnology

In this new blog series, 2Checkout explores the developments and features of its brand new Payment API, currently in BETA. To see the new 2Checkout Payment API BETA and use it as your new checkout, apply here.

Using AJAX with the Payment API

Over the years I’ve worked with many open source shopping cart applications and most utilize AJAX throughout the entire checkout process to eliminate page refreshing and streamline the customer’s shopping experience. This same technique can be utilized when integrating our Payment API into your web application but there are some best practices that should be kept in mind. As a base for our best practices improvements, let’s start with the following HTML form and JavaScript to retrieve the token.

// Called when token created successfully.
function successCallback(data) {
var myForm = document.getElementById('myCCForm');
myForm.token.value = data.response.token.token;
myForm.submit();
}// Called when token creation fails.
function errorCallback(data) {
if (data.errorCode === 200) {
TCO.requestToken(successCallback, errorCallback, 'myCCForm');
} else {
alert(data.errorMsg);
}
}// Setup function for the token call.
function retrieveToken() {
TCO.requestToken(successCallback, errorCallback, 'myCCForm');
}

Keep your privateKey Private!

Once you have retrieved a token, it may be tempting to bypass your server entirely and make the authorization call directly using AJAX. While possible, this would expose your privateKey to the browser and put your account at risk; it’s important to only make the authorization call server side. Luckily, our developer community maintains libraries for the most popular server side programming languages allowing you to set up the authorization call on your own server with ease. Our server side PHP example snippet below will make the authorization call and echo the response.

Twocheckout::setApiCredentials('1817037', '087F9356-39A3-4CEC-AAEE-0694E4B619EE');
try {
$charge = Twocheckout_Charge::auth(array(
"sellerId" => "1817037",
"merchantOrderId" => "123",
"token" => $_POST['token'],
"currency" => 'USD',
"total" => '10.00',
"billingAddr" => array(
"name" => 'Testing Tester',
"addrLine1" => '123 Test St',
"city" => 'Columbus',
"state" => 'OH',
"zipCode" => '43123',
"country" => 'USA',
"email" => 'testingtester@2co.com',
"phoneNumber" => '555-555-5555'
)
));
if ($charge['response']['responseCode'] == 'APPROVED') {
echo "Thanks for your Order!";
}
} catch (Twocheckout_Error $e) {
echo $e->getMessage();
}

Instead instead of submitting the form and sending your buyer to this script directly, lets make an AJAX request and display the result to the user while he or she remains on your website. In the example below, we will use jQuery to set our token value, serialize the input elements, make the AJAX call and display the response in place of the credit card form.

function successCallback(data) {
myForm = $('#myCCForm');
$('#token').val(data.response.token.token);
$.post(myForm.attr('action'), myForm.serialize(), function (response) {
myForm.parent().replaceWith(response);
});
}

Lock down the UI

One of the easiest ways to prevent duplicate charges is to provide the buyer with an indication that they should wait while you attempt to charge his or her credit card. It’s also a good idea to lock down the submit button while you attempt the authorization to prevent double clicking issues. Find an example below of our modified success function, assuming that we have a hidden element that with the id `loadingIndicator` (such as a loading spinner).

function successCallback(data) {
myForm = $('#myCCForm');
$('#token').val(data.response.token.token);
$('#loadingIndicator').show(); // <-- Show the loading indicator
$('#submit').attr('disabled', 'disabled'); // <-- Disable the submit
$.post(myForm.attr('action'), myForm.serialize(), function (response) {
$('#loadingIndicator').hide(); // <-- hide loading indicator
$('#submit').removeAttr('disabled'); // <-- re-enable submit button, this wont matter since we are replacing the content below.
myForm.parent().replaceWith(response);
});
}
As mentioned, I work with many different open source carts, and the MIT licensed BlockUI jQUery plugin is my favorite tool to throw in when I need to lock down the UI and show a loading indicator.
function successCallback(data) {
myForm = $('#myCCForm');
$('#token').val(data.response.token.token);
$.blockUI(); // <-- Block UI
$.post(myForm.attr('action'), myForm.serialize(), function (response) {
$.unblockUI(); // <-- Unblock UI
myForm.parent().replaceWith(response);
});
}
Hopefully this best practices reminder was helpful. Come back to the 2Checkout Blog for more information on how to optimize your Payment API as well as learn the latest tutorials on all things e-commerce.