- Introduction
- How it works
- Required Credentials
- Step-By-Step Overview
- JWT Token
- Step 1: Build Payment Form
- Step 2: Client-Side Integration
- Step 2.1: Adding script reference
- Step 2.2: Initialize Hosted Fields
- HMAC Authentication
- Generate JWT Token
- Generate JWT Token with all fields
- Generate JWT Token For Card Hash
- Generate JWT Token For Create Token
- Generate JWT Token For Update Token
- Google Pay Initialization
- Apple Pay Initialization
- PayPal Initialization
- Google Pay Payment Method
- Apple Pay Payment Method
- PayPal Payment Method
- Request Format
- Final Transaction Response
- Test Cards
In this page
Useful Resources
You've chosen Hosted Fields
A flexible JavaScript-based checkout experience while preserving your design and user experience.
Introduction
The Hosted Fields SDK offers customizable, prebuilt fields that securely capture customer payment information, thereby enabling you to design tailored checkout experiences for both desktop and mobile websites.
The SDK ensures that the merchant's website does not handle sensitive card information directly. Instead, card data is securely received within an iframe provided by the SDK to process the transaction.
How it works
Hosted Fields integration involves two stages: server-side and client-side. In the client-side integration, you specify non-editable <div> elements for payment information in your checkout flow, maintaining your UI's look and feel. Our SDK then replaces these with a secure iframe that captures card data while preserving the same appearance. During client-side integration, our SDK directly reads the card data and use that for the transactions.
-
Create JWT Session
When serving the checkout, the client application requests a jwt token from the server.
-
Initialize Hosted Fields
From the client-side script, initialize WebbankJS using the JWT provided by the server. After initializing WebbankJS, configure the containers for the hosted fields.
-
Hosted Fields Iframe
The Hosted Fields SDK then takes control of the payment form elements. When the user clicks the submit/pay button, the SDK captures the card data.
-
Submit Transaction
The server submits the transaction to TNS for payment processing. The TNS server processes the transaction and generates a stored token, which is returned along with the transaction response.
-
5 & 6. Process Transaction Response
The transaction response received for the transactions, which will contain the transaction identifier that can be used for secondary transactions like void, capture and refunds. See Secondary Transactions for more information.
Required Credentials
The following credentials will be issued by TNS to you if you want to use Hosted Fields.
Step-By-Step Guide
Overview
This section offers step-by-step guidance on how to build a checkout page with a payment form, integrate Hosted Fields, and start accepting payments.
First, let's understand a few key constructs before we begin building our example.
Setting up Hosted Fields initialization parameters
1. JWT Token
JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.
To commence a Hosted Fields session, the initial step is to acquire a JWT token from the TNS server by utilizing the API Key and the secret provided by TNS. Below is a sample request for generating a JWT token. For further insights on JWT tokens, see JWT Token section of our documentation.
{
"merchantId": "102606",
"reference": "merchantReference_66327cdd6bc356.93538846",
"sessionMode": "PERFORM_TRANSACTION",
"transactionType": "PAYMENT",
"subTotal": "17.00",
"currencyCode": "USD",
"countryCode": "US",
"paymentMethods": [
"CARD",
"GOOGLE_PAY",
"APPLE_PAY",
"PAYPAL"
]
}
Field | Description | Type | Example | ||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
merchantId
|
The customer code issued by TNS uniquely identifies your account for their services. |
string | 102606 | ||||||||
reference
|
A unique ID you generate to track the transaction. |
string | ba2e0c5a-523c-460b-8dcc-0cd6b64265ca | ||||||||
sessionMode
|
Specifies the purpose of the requested session. This value is formatted as a string, and the allowed enum values are listed below.
|
string | PERFORM_TRANSACTION | ||||||||
transactionType
|
Specifies what transaction will be performed. The value is formatted as a string, and the allowed enum values are listed below.
|
string | PRE_AUTH | ||||||||
subtotal
|
The total amount of the transaction, excluding taxes and fees, in the designated currency and transmitted as a string. The amount should be in decimal format, such as “10.12” for a transaction totaling $10.12. |
string | 120.00 | ||||||||
currencyCode
|
TThis is the ISO 4217 currency code. Use "AUD" for Australian dollar, "USD" for United States dollar, "GBP" for Pound sterling. Please refer https://en.wikipedia.org/wiki/ISO_4217 for list of all currency codes. |
string | USD | ||||||||
countryCode
|
This is the ISO 3166-2 country code. Use “AU” for Australia, “US” for United States, “GB” for United Kingdom. Please refer https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes for list of all country codes. |
string | US | ||||||||
paymentMethods
|
Selected payment methods for this transaction include Card, ApplePay, and GooglePay. |
array | ["CARD", "APPLE_PAY", "GOOGLE_PAY", PAYPAL] |
2. Hosted Fields Configuration for payment fields
Hosted Fields requires you to define the appearance and feel of payment fields, then pass the list of these fields to initialize the Hosted Fields configuration. For this example we will include only Card Number, Expiry Date and CVV. The example for the fields list is as follows:
{
"fields": {
"cardNumber": {
"containerId": "hosted-card-number",
"placeholder": "Card Number",
"fieldName": "Card Number"
},
"expiryDate": {
"containerId": "hosted-expiry-date",
"placeholder": "MM/YY",
"format": "MM/YY",
"fieldName": "Expiry Date"
},
"cvv": {
"containerId": "hosted-cvv",
"placeholder": "CVV",
"fieldName": "Card Verification Value",
"mask": false
}
},
"events": {},
"styles": {
"hostedFieldInvalid": {
"color": "red"
},
"hostedFieldValid": {
"color": "green"
},
"hostedFieldFocus": {
"color": "#008dca"
},
"hostedField": {
"background-color": "transparent",
"color": "black",
"padding": "8px 16px",
"font-size": "14px",
"font-family": "monospace, courier"
}
},
"language": "en",
"supportedCardTypes": "["VISA","MASTERCARD", "AMEX", "DINERS", "JCB", "DISCOVER"]"
}
Step 1
Build Payment Form
Let's begin constructing an HTML page featuring a payment form to process card information. The form should include elements for the Card Number, Expiry Date, and CVV. These three fields are the minimum required to process a payment transaction using a credit card.
Here is the sample code for the form group:
<form id="payment-form" name="payment-form" method="post" action="transaction-authorisation.php">
<div class="form-group">
<label for="hosted-card-number" class="form-label mt-4 required">Card Number</label>
<div class="input-group">
<div id="hosted-card-number" class="form-control hosted-field"></div>
</div>
<div id="hosted-card-number-error-message" for="hosted-card-number" class="invalid-feedback hosted-field-error-message-hidden"></div>
</div>
<div class="form-group">
<label for="hosted-expiry-date" class="form-label mt-4 required">Expiry Date</label>
<div id="hosted-expiry-date" class="form-control hosted-field"></div>
<div id="hosted-expiry-date-error-message" for="hosted-expiry-date" class="invalid-feedback hosted-field-error-message-hidden"></div>
</div>
<div class="form-group">
<label for="hosted-cvv" class="form-label mt-4 required">Card Verification Value</label>
<div id="hosted-cvv" class="form-control hosted-field"></div>
<div id="hosted-cvv-error-message" for="hosted-cvv" class="invalid-feedback hosted-field-error-message-hidden"></div>
</div>
<input name="signature-format" id="signature-format" type="hidden">
<input name="tokenisation-response" id="tokenisation-response" type="hidden">
<input name="paypal-response" id="paypal-response" type="hidden">
<br>
<div class="form-group">
<div class="d-grid gap-2">
<input name="hosted-fields-payment-submit" id="hosted-fields-payment-submit" type="submit" value="Pay Now" disabled="disabled" class="btn btn-primary">
<div id="alternative-payment-title" class="row" style="display: none;">
<p class="small" style="margin-top: 10px">or pay with</p>
</div>
<div id="google-pay-button" style="display: none;"></div>
<div id="paypal-button" style="display: none;"></div>
<div id="apple-pay-button" class="apple-pay-button apple-pay-button-black" style="display: none;"></div>
<button id="google-pay-not-supported-button" type="button" class="btn btn-dark disabled" style="display: none;">Google Pay is not supported on this device.</button>
<button id="apple-pay-not-supported-button" type="button" class="btn btn-dark disabled" style="display: none;">Apple Pay is not supported on this device.</button>
<button id="paypal-not-supported-button" type="button" class="btn btn-dark disabled" style="display: none;">PayPal is not supported on this device.</button>
</div>
</div>
</form>
The provided HTML forms the basis for a payment form and can be incorporated into your checkout page design. You have the option to customize the styling of the payment form fields to match your website's aesthetics. These custom styles can then be passed to the Hosted Fields SDK through the configuration settings.
Step 2
Client-Side Script Integration
For integrating the Hosted Fields SDK, you'll need to include the necessary SDK references in your HTML. If you wish to support GooglePay and ApplePay as well, you can include their respective script packages. Here’s how you can include these references:
Step 2.1
Add SDK script references in the page.
<script type="text/javascript" src="https://pay.google.com/gp/p/js/pay.js"></script>
<script type="text/javascript" src="https://developer.uat.paymentgateway.tnsi.com/static-k8s/webbank/webbank-js/js/v2/webbank.js"></script>
Step 2.2
Initialize Hosted Fields SDK
Use the signed JWT to initialize the Hosted Fields SDK. Upon initialization, verify the availability of Google Pay, Apple Pay, and PayPal for this merchant and initialize them as needed. Then, proceed to initialize the hosted fields configuration.
var webbankJs = new WebbankJs();
//Initialise Webbank JS.
webbankJs.initialise(webbankJwt).then(onWebbankJsInitialised, processFailure);
function onWebbankJsInitialised() {
// Webbank JS initialisation was successful we can now initialise Webbank JS services.
//Initialise PayPal
if (webbankJs.payPal.isEnabled()) {
initialisePayPal();
}
//Initialise ApplePay
if (webbankJs.applePay.isEnabled()) {
initialiseApplePay();
}
//Initialise GooglePay
if (webbankJs.googlePay.isEnabled()) {
initialiseGooglePay();
}
hostedFieldsConfiguration = {
fields: hostedFieldList,
events: {
onFocus: onFocus,
onBlur: onBlur,
onInput: onInput,
onCardTypeChange: onCardTypeChange
},
styles: hostedFieldStyles,
language: language,
supportedCardTypes: supportedCardTypes
};
//Initialise Hosted Fields
initialiseHostedFields(hostedFieldsConfiguration);
}
function initialisePayPal() {
var payPalConfig = {
authorisePayment: true,
onAuthorized: processPayPalPayment
};
webbankJs.payPal.initialise(payPalConfig).then(onPayPalInitialised,
function (error) {
//Display some text to the user to indicated that PayPal is not available.
});
}
function initialiseHostedFields(hostedFieldsConfig) {
webbankJs.hostedFields.initialise(hostedFieldsConfig)
.then(onHostedFieldsInitialised, processFailure);
}
function initialiseApplePay() {
var config = { applePayButtonId: "apple-pay-button" };
webbankJs.applePay.initialise(config).then(onApplePayInitialised, function (error) {
//Display some text to the user to indicated that Apple Pay is not available.
});
}
function initialiseGooglePay() {
let googlePayConfig = {
authorisePayment: true,
allowedCardNetworks: ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"],
allowedCardAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
googlePayButtonId: "google-pay-button",
buttonOptions: {
onClick: processGooglePayPayment,
buttonColor: 'default',
buttonType: 'plain',
buttonSizeMode: 'fill'
}
};
webbankJs.googlePay.initialise(googlePayConfig).then(onGooglePayInitialised,
function (error) {
//Display some text to the user to indicated that Google Pay is not available.
});
}
For more information on each payment method initialization, see our documentation.
Step 2.3
Payment Request
After the Hosted Field Configuration is initialized, you need to add an event listener for the payment submit button. In the event listener, include the billing address collected from the customer in the payment request and submit it to Hosted Fields. This will submit the transaction for processing. Sample code is provided below.
function onPayPalInitialised() {
console.log("onPayPalInitialised***");
}
function onApplePayInitialised() {
document.getElementById("apple-pay-button").onclick = processApplePayPayment;
}
function onGooglePayInitialised() {
webbankJs.googlePay.paymentDataValidation = getPaymentDataValidation;
}
function getPaymentDataValidation(paymentData) {
var validationRules = {
result: paymentData.paymentMethodData.info.cardNetwork != "INTERAC",
message: "Card not supported."
};
return validationRules;
}
function onHostedFieldsInitialised() {
var hostedFieldsPaymentSubmit = document.getElementById('hosted-fields-payment-submit');
hostedFieldsPaymentSubmit.addEventListener('click', function (event) {
event.preventDefault();
var transactionRequest = {
billing: billingAddress
};
webbankJs.hostedFields.submit(transactionRequest)
.then(onHostedFieldsSubmitSuccessful, onHostedFieldsSubmitFailed);
});
}
function onHostedFieldsSuccessful(response) {
console.log(response);
}
function onHostedFieldsSubmitFailed(err) {
console.error(err);
}
The billing address structure is as follows:
{
"firstName": "firstName",
"lastName": "lastName",
"addressLines": [
"26 Franklin Street"
],
"locality": "Adelaide",
"administrativeAreaCode": "AU-SA",
"countryCode": "AU",
"postalCode": "5000",
"mobilePhoneNumber": "61412345678",
"emailAddress": "email@tnsi.com"
}
Congratulations!
You've successfully integrated Hosted Fields with your checkout process. You’ll now receive a response that is sent via the onApprove callback method as configured in the SDK initialization above. Below is the sample transaction response.
{
"type": "APPROVE",
"data": {
"authCode": "OK1249",
"approvedAmount": "250.20",
"accountFirst6": "499977",
"accountLast4": "9004",
"hostNetwork": "1",
"expiryMonth": "12",
"expiryYear": "2034",
"cardHolderName": "Sivam K",
"avs": {
"avsResult": "Y"
},
"clientTransactionId": "88af81f2-6b37-4e6a-8105-46180b713c39",
"transactionDateUtc": "2024-07-12T06:13:51.522Z",
"tnsResponseCode": "00",
"tnsResponseText": "TRANSACTION_APPROVED",
"hostResponseCode": "00",
"hostResponseText": "APPROVAL",
"token": "6485251555209004",
"status": "00: APPROVAL",
"stan": "458045",
"transactionId": "d75f422e-ec8a-44b2-84a2-7b5a94d9a1df",
"subtotalAmount": "250",
"totalAmount": "250.00",
"requestId": "742ba5fd-679a-92d0-a275-30c3d79ba4f8",
"successful": true
}
}
Test Card
Use the following test card information to make a payment transaction.
Test Card
4111 1111 1111 1111
Card Holder | Valid Thru |
Any valid cardholder name |
Any future date in MM/YY format |
CVV - Any three digit number
Address information - Any valid address
For more test cards to use, see Test Cards.
That's It, You're Done!
You just made a payment. For more detailed information on configuration, formatting options and callbacks, see Hosted Fields.