Skip to main content

Hosted Fields Integration Guide

What are Hosted Fields?

DNA Payments Hosted Fields solution allows merchants to be eligible for the simpliest level of PCI compliance (SAQ A) whilst maintaining control over the look and feel of the checkout process. The sensitive data fields, such as PAN, CSC etc. are hosted on the DNA Payments platform but located and styled on the page by the merchant.

Getting Started

To utilise the Hosted Fields integration method, there are four main tasks that need to be completed:

  1. Include the DNA Payments hosted fields SDK
  2. Obtain the authorization token
  3. Create Hosted Fields UI markup
  4. Use Hosted Fields API to process the transaction

To assist the development process DNA Payments have created the following page. On this page it is possible to see the solution in action, make changes to formats and styles and even perform test transactions.

Include the DNA Payments Hosted Fields SDK

Add the following code in the head part of your webpage (this URL is subject to change). The URL is a script for creating Hosted Fields on your webpage.

<script type="text/javascript" src="https://cdn.dnapayments.com/js/hosted-fields/hosted-fields.js"></script>

Obtain the Authorization Token

Authentication follows the same process for all our online tools. Details of this process can be found in our Checkout Integration Guide

You should use the scope payment integration_seamless for this request.

This is not added by default, so please ensure we're aware you will be working with Hosted Fields when you request any credentials.

Ensure that you have the endpoint for obtaining the authorization token. The authentication must take place before calling any of the Hosted Fields functions. The object returned will be in the following format:

interface AuthToken {
access_token: string
expires_in?: string
refresh_token?: string
scope?: string
token_type?: string
}

The key field in this object is the access_token. The access_token is used in the transaction request.

Add the Hosted Fields UI Markup

The look and feel of the Payment Form will need to be set to fit best with the website that it is located on. In this form you provide HTML container elements for payment fields and Three D secure form. In these container elements, the Hosted Fields iFrame will be rendered.

In the test example in codepen site, we use boostrap to style the form. Here is an example code snippet for the cardholderName payment field:

<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<div id="hf-name" class="form-control"></div>
</div>

The following snippet code shows how we set container HTML elements in variables to use in Hosted Fields API in the codepen example.

const cardholderName = document.querySelector('#hf-name')
const cardNumber = document.querySelector('#hf-number')
const cardDate = document.querySelector('#hf-date')
const cardCvv = document.querySelector('#hf-cvv')

const threeDSecureModalContent = document.querySelector('#threeDSecureModalContent')
const $threeDSecureModal = $('#threeDSecureModal')

Hosted Fields API

After the including DNA Payments hosted fields SDK, access is available to the global object window.dnaPayments.hostedFields. It has an asynchronous create method which return Hosted Fields instance. The create method accepts an object as argument with the following fields:

Field NameStateData TypeDescription
isTestOptionalBooleanDefault: false. Governs which endpoints (test or live) are used to process.
accessTokenMandatoryStringThe access_token field returned during the authentication process.
stylesOptionalObjectThe styles you want to give payment field inputs which will be rendered in Iframes.
threeDSecureMandatoryObjectAn object with container property, whose value must be HTML element in which the 3D Secure iFrame will be rendered.
sendCallbackEveryFailedAttemptOptionalIntegerAllows you to specify when to receive callbacks for failed or rejected payments, as well as the number of attempts the callback is triggered after.
ValueCallback behaviour
0Will not be sent
1Will be sent after every unsuccessful attempt
2Will be sent after every 2nd unsuccessful attempt
3Will be sent after every 3rd unsuccessful attempt
You can set higher values, but too large may be impractical.
fontNamesOptionalArrayAn array of custom font names.

By default we support web safe fonts. If you want to use a custom font for credit card inputs in iframe, please contact support.
fieldsMandatoryObjectObject containing the below payment fields:
  • cardholderName
  • cardNumber
  • expirationDate
  • cvv
The value of the above will be an object with the following fields:
  • container A HTML element in which iFrame of field will be rendered.
  • placeholder A placeholder for the payment field input in iFrame

The following code snippet shows how to use create method:

let hf;

window.dnaPayments.hostedFields.create({
isTest: true,
accessToken: ACCESS_TOKEN,
styles: {
input: {
'font-size': '14px',
'font-family': 'Roboto'
},
'.valid': {
'color': 'green'
},
'.invalid': {
'color': 'red'
}
},
threeDSecure: {
container: threeDSecureModalContent
},
sendCallbackEveryFailedAttempt,
fontNames: ['Roboto'],
fields: {
cardholderName: {
container: cardholderName,
placeholder: 'Cardholder name'
},
cardNumber: {
container: cardNumber,
placeholder: 'Card number'
},
expirationDate: {
container: cardDate,
placeholder: 'Expiry date'
},
cvv: {
container: cardCvv,
placeholder: 'CSC/CVV'
}
}
}).then((res) => {
hf = res

hf.on('dna-payments-three-d-secure-show', () => {
$threeDSecureModal.modal('show')
})

hf.on('dna-payments-three-d-secure-hide', () => {
$threeDSecureModal.modal('hide')
})
}).catch((err) => {
// errors that can occur are described in detail at the last chapter of this documentation
})

As mentioned previously, the create method returns Hosted fields instance. This is an object containing the following methods:

Method NameDescription
on(event, handler)Subscribes a handler function to a named event. The following events are available:
  • dna-payments-three-d-secure-show Triggered when you need to set visible 3D Secure container HTML element
  • dna-payments-three-d-secure-hide Triggered when you need to set invisible 3D Secure container HTML element
  • focus Triggered when payment field input focused
  • blur Triggered when payment field input loses focus
  • validityChange Triggered when payment field input validity changed
For the last 3 events (focus, blur, validityChange), you get an object as parameter for handler function with the following fields:The properties of fieldsState are payment fields (cardholderName, cardNumber, cvv, expirationDate. The values of these fields are a state object of each payment field.
The properties of state object are:
NameTypeDescription
isFocusedBooleanConfirms whether the payment field input is focused.
isTouchedBooleanShows the payment field input has set value. Will be true after changing the value of input to empty.
isValidatingBooleanConfirms whether the payment field input is validating currently.
isValidBooleanConfirms if the payment field input is valid.
isEmptyBooleanConfirms if the payment field input is empty.
errorObjectConfirmation of any payment field errors. If there is no error, then the value will be NULL. Additional information on the error object is shown below.
PARAMETERS:
NameTypeDescription
eventStringThe name of the event to which you are subscribing.
handlerFunctionA callback to handle the event.
submit(data)Submits payment data to trigger payment. Below shows an example using submit method. You can read about Payment Data in detail at this link: https://developer.dnapayments.com/docs/ecommerce/checkout/direct-integration/send-payment-request
clear()Clears all payment field input values and their current states.
destroy()Removes all inserted Hosted Fields iFrames and unsubscribes all event handlers.
getState()Returns the current state object with the following properties:
hf.submit({
paymentData: {
currency: 'GBP',
description: 'Car Service',
paymentSettings: {
terminalId: TERMINAL,
returnUrl: 'https://test-pay.dnapayments.com/checkout/success.html',
failureReturnUrl: 'https://test-pay.dnapayments.com/checkout/failure.html',
callbackUrl: 'https://pay.dnapayments.com/checkout',
failureCallbackUrl: 'https://testmerchant/order/1123/fail'
},
customerDetails: {
accountDetails: {
accountId: 'uuid000001'
},
billingAddress: {
firstName: 'John',
lastName: 'Doe',
addressLine1: 'Fulham Rd',
postalCode: 'SW6 1HS',
city: 'London',
country: 'GB'
},
deliveryDetails: {
deliveryAddress: {
firstName: 'John',
lastName: 'Doe',
addressLine1: 'Fulham Rd',
addressLine2: 'Fulham',
postalCode: 'SW6 1HS',
city: 'London',
phone: '0475662834',
region: 'UKI',
country: 'GB'
}
},
email: 'demo@dnapayments.com'
},
deliveryType: 'service',
invoiceId: INVOICE_ID,
amount: AMOUNT,
}
})
.then((res) => {
hf.clear()
})
.catch((err) => {
if (err.code === 'INVALID_CARD_DATA') {
// do something
} else if (err.code === 'THREE_D_SECURE_ERROR') {
// do something
} else {
// do something
}
})

Hosted Fields Token Wallet

If you want to use token wallet in hosted fields, you must send an extra field tokenizedCardCvv. In order to conduct a payment, it's required to call the same submit method that is described above after calling the method selectCard method by passing tokenizedCardData as an argument.

window.dnaPayments.hostedFields.create({
......
fields: {
......
tokenizedCardCvv: {
container: document.querySelector('#hf-cvv-token'),
placeholder: 'CVV'
}
}
})

hf.selectCard({
merchantTokenId: 'FK6seAm/RfjBXYnGIBH4emfHKcDakqjyVWYyXTOqKmIfMQ==',
panStar: '***************0000',
cardSchemeId: '11',
cardSchemeName: 'VISA',
cardName: 'Test Card',
expiryDate: '01/25',
isCSCRequired: true,
cscState: 'required',
})

hf.submit({
paymentData: {
......
},
})

When you use token wallet in hosted fields the follwing methods will be available for displaying saved cards and making payment.

Method NameReturn TypeDescription
getCreditCardTypeIcon(tokenizedCard)StringReturns a link of the card type icon. E.g. https://test-pay.dnapayments.com/ checkout/img/visa.svg
Parameter: tokenizedCard
getTokenizedCardCvvState(tokenizedCard)Required, Optional, HiddenReturns the state of the selected card's cvv.
Parameter: tokenizedCard
selectCard(tokenizedCard)N/ASelects tokenzied card data.
Parameter: tokenizedCard
info

You can read about tokenizedCard (Tokenized card data) in detail at this link:

https://developer.dnapayments.com/docs/ecommerce/checkout/direct-integration/configuration#configurationcards

Here is an example of how to use token wallet in hosted fields.

Errors in detail

CodeMessage
Errors that can occur when creating the Hosted Fields.
HOSTED_FIELDS_TIMEOUTHosted Fields timed out when attempting to set up.
THREE_D_SECURE_TIMEOUTThreeDSecure timed out.
DUPLICATE_FIELDfieldKey field is already initialized.
NOT_ALLOWED_FIELDfieldKey field is NOT an allowed hosted field.
MISSING_REQUIRED_FIELDfieldKey required field is NOT provided.
CLIENT_INITIALIZE_ERRORCould not initialize the Client object. Please check accessToken.
Errors that can occur when submitting the Payment Data.
INVALID_CARD_DATAInvalid card data.
THREE_D_SECURE_ERROR3D Secure error.