Implementation example
Using vanilla html and javascript.
This self-contained example demonstrates the complete end-to-end flow.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Custom CTP UI</title>
<script src="https://sandbox-assets.comcarde.com/web/v2/js/client.js"></script>
<script src="https://sandbox-assets.comcarde.com/web/v2/js/visa-click-to-pay.js"></script>
<script src="https://sandbox-assets.comcarde.com/web/v2/js/hosted-fields.js"></script>
</head>
<body>
<!-- Only one section is visible at a time. -->
<section id="screen-identification">
<h2>Pay with Click to Pay</h2>
<input id="email" type="email" placeholder="[email protected]" />
<input id="phone" type="tel" placeholder="+44..." />
<button id="lookup">Look up my cards</button>
</section>
<section id="screen-otp" hidden>
<h2>Enter the 6-digit code</h2>
<p id="otp-target"></p>
<input id="otp" type="text" inputmode="numeric" maxlength="6" />
<button id="verify">Verify</button>
<button id="resend">Resend</button>
</section>
<section id="screen-cards" hidden>
<h2>Pick a card</h2>
<div id="card-list"></div>
<button id="pay">Pay</button>
<button id="add-new">Use a different card</button>
<button id="switch-id">Switch ID</button>
</section>
<section id="screen-add-card" hidden>
<h2>New card</h2>
<input id="cardholder-name" type="text" placeholder="Name on card" />
<input id="enrol-first-name" type="text" placeholder="First name" />
<input id="enrol-last-name" type="text" placeholder="Last name" />
<input id="enrol-phone" type="text" placeholder="Phone (+44...)" />
<input id="billing-address" type="text" placeholder="Address line 1" />
<input id="billing-city" type="text" placeholder="Town / City" />
<input id="billing-county" type="text" placeholder="County" />
<input id="billing-postcode" type="text" placeholder="Postcode" />
<select id="billing-country">
<option value="GB" selected>United Kingdom</option>
<option value="US">United States</option>
</select>
<div id="card-number"></div>
<div id="card-expiry"></div>
<div id="card-cvv"></div>
<label>
<input id="enrol" type="checkbox" checked />
Save this card to Click to Pay
</label>
<button id="pay-new" disabled>Pay</button>
</section>
<section id="screen-success" hidden>
<h2>Payment complete</h2>
<p id="success-nonce"></p>
</section>
<section id="screen-failure" hidden>
<h2>Something went wrong</h2>
<p id="failure-code"></p>
<button id="retry">Try again</button>
</section>
<script>
(async function () {
// ----- Setup ----------------------------------------------------------
const clientInstance = await comcarde.client.create({
authorization: '<merchant-client-bearer-token>'
});
const ctpClient = await comcarde.visaClickToPay.create({
client: clientInstance,
authorization: '<merchant-client-bearer-token>'
});
const cartAmount = '10.00';
const cartCurrency = 'GBP';
// Initialise CTP before the user clicks anything. See section 4.
await ctpClient.initializeClickToPay({
amount: cartAmount,
currencyCode: cartCurrency
});
// ----- Screen helpers -------------------------------------------------
const screens = [
'screen-identification', 'screen-otp', 'screen-cards',
'screen-add-card', 'screen-success', 'screen-failure'
];
function show(name) {
screens.forEach(function (s) {
document.getElementById(s).hidden = (s !== name);
});
}
function fail(err) {
document.getElementById('failure-code').textContent =
(err && err.code) || 'UNKNOWN';
show('screen-failure');
}
// ----- Identification -------------------------------------------------
document.getElementById('lookup').addEventListener('click', async function () {
const email = document.getElementById('email').value.trim();
const phone = document.getElementById('phone').value.trim();
// identityType must be 'EMAIL_ADDRESS' or 'MOBILE_PHONE_NUMBER'.
const identity = email
? { identityValue: email, identityType: 'EMAIL_ADDRESS' }
: { identityValue: phone, identityType: 'MOBILE_PHONE_NUMBER' };
try {
const result = await ctpClient.getCards(identity);
if (result.status === 'OTP_REQUIRED') {
document.getElementById('otp-target').textContent =
'We sent a code to ' + (result.maskedEmail || result.maskedPhone);
show('screen-otp');
return;
}
if (result.status === 'SUCCESS' && result.cards.length > 0) {
renderCards(result.cards);
show('screen-cards');
return;
}
// Recognised consumer but no cards, or unknown consumer.
show('screen-add-card');
await mountHostedFields();
} catch (err) {
fail(err);
}
});
// ----- OTP ------------------------------------------------------------
document.getElementById('verify').addEventListener('click', async function () {
const code = document.getElementById('otp').value.trim();
try {
const result = await ctpClient.verifyOtp({ validationData: code });
if (result.cards.length === 0) {
show('screen-add-card');
await mountHostedFields();
return;
}
renderCards(result.cards);
show('screen-cards');
} catch (err) {
fail(err);
}
});
document.getElementById('resend').addEventListener('click', function () {
ctpClient.resendOtp().catch(fail);
});
// ----- Card selection -------------------------------------------------
let selectedCardId = null;
function renderCards(cards) {
const list = document.getElementById('card-list');
list.innerHTML = '';
cards.forEach(function (card) {
const btn = document.createElement('button');
btn.type = 'button';
btn.textContent = card.displayText;
btn.addEventListener('click', function () {
selectedCardId = card.id;
});
list.appendChild(btn);
});
}
document.getElementById('pay').addEventListener('click', async function () {
if (!selectedCardId) { return; }
// chk-skip is a checkbox input type
const skipVerification = document.getElementById('chk-skip')?.checked;
const checkoutSavedCardPayload = {
action: 'CHECKOUT_SAVED_CARD',
cardId: selectedCardId,
includeAuthenticationDetails: true
};
if (skipVerification) {
checkoutSavedCardPayload.complianceSettings = {
complianceResources: [
{
complianceType: 'REMEMBER_ME',
uri: window.location.origin + '/privacy'
}
]
};
}
try {
const result = await ctpClient.processPayment(checkoutSavedCardPayload);
completePayment(result);
} catch (err) {
fail(err);
}
});
document.getElementById('add-new').addEventListener('click', async function () {
show('screen-add-card');
await mountHostedFields();
});
document.getElementById('switch-id').addEventListener('click', async function () {
try {
await ctpClient.unbindAppInstance();
document.getElementById('email').value = '';
document.getElementById('phone').value = '';
show('screen-identification');
} catch (err) {
fail(err);
}
});
// ----- Add-card with Hosted Fields -----------------------------------
let hostedFields = null;
async function mountHostedFields() {
if (hostedFields) { return; }
hostedFields = await comcarde.hostedFields.create({
client: clientInstance,
fields: {
number: { selector: '#card-number', placeholder: 'Card number' },
expirationDate: { selector: '#card-expiry', placeholder: 'MM/YY' },
cvv: { selector: '#card-cvv', placeholder: 'CVV' }
}
});
hostedFields.on('validityChange', function (state) {
const allValid =
state.fields.number && state.fields.number.isValid &&
state.fields.expirationDate && state.fields.expirationDate.isValid &&
state.fields.cvv && state.fields.cvv.isValid;
document.getElementById('pay-new').disabled = !allValid;
});
}
document.getElementById('pay-new').addEventListener('click', async function () {
const enrol = document.getElementById('enrol').checked;
const cardholderName = document.getElementById('cardholder-name').value.trim();
const billingAddress = {
address1: document.getElementById('billing-address').value.trim(),
country: document.getElementById('billing-country').value || 'GB',
county: document.getElementById('billing-county').value.trim(),
firstName: document.getElementById('enrol-first-name').value.trim() || 'Firstname',
lastName: document.getElementById('enrol-last-name').value.trim() || 'Surname',
postcode: document.getElementById('billing-postcode').value.trim(),
town: document.getElementById('billing-city').value.trim()
};
try {
if (enrol) {
// ENROLL_AND_CHECKOUT: the iframe encrypts the PAN and returns
// a JWE. The raw card number never leaves the iframe.
const encrypted = await hostedFields.encryptCard({
session: ctpClient.getSessionJwt(),
cardholderName: cardholderName,
billingAddress: billingAddress
});
const emailAddress = document.getElementById('email').value.trim();
const firstName = document.getElementById('enrol-first-name').value.trim() || 'Firstname';
const lastName = document.getElementById('enrol-last-name').value.trim() || 'Surname';
const rawPhone = (document.getElementById('enrol-phone').value || '').replace(/\s+/g, '');
const phoneDigits = rawPhone.replace(/^\+/, '');
const countryCode = phoneDigits.startsWith('44') ? '44' : '44';
const phoneNumber = phoneDigits.startsWith('44') ? phoneDigits.slice(2) : phoneDigits;
const result = await ctpClient.processPayment({
action: 'ENROLL_AND_CHECKOUT',
cardId: null,
enrol: true,
includeAuthenticationDetails: true,
encryptedCard: encrypted.encryptedCard,
complianceSettings: {
complianceResources: [
{
complianceType: 'PRIVACY_POLICY',
uri: 'https://www.visa.com/en-us/legal/global-privacy-notice'
},
{
complianceType: 'REMEMBER_ME',
uri: window.location.origin + '/privacy'
}
]
},
consumer: {
emailAddress: emailAddress,
consumerIdentity: {
identityProvider: 'SRC',
identityValue: emailAddress,
identityType: 'EMAIL_ADDRESS'
},
mobileNumber: {
countryCode: countryCode,
phoneNumber: phoneNumber
},
countryCode: 'GB',
locale: 'en',
firstName: firstName,
lastName: lastName,
fullName: firstName + ' ' + lastName
}
});
completePayment(result);
} else {
// TOKENIZE: pay once without saving the card to Click to Pay.
const tokenizePayload = await hostedFields.tokenize({
cardholderName: cardholderName
});
const result = await ctpClient.processPayment({
action: 'TOKENIZE',
hostedFieldsToken: tokenizePayload.token
});
completePayment(result);
}
} catch (err) {
fail(err);
}
});
// ----- Success -------------------------------------------------------
function completePayment(result) {
const nonce = result.paymentInstrument && result.paymentInstrument.nonce;
document.getElementById('success-nonce').textContent =
'Single-use token: ' + nonce;
show('screen-success');
// POST nonce to your server: POST /v1/payments
// see https://docs.br-dge.io/reference/createpaymentusingpost for more details
}
document.getElementById('retry').addEventListener('click', function () {
show('screen-identification');
});
// ----- Start ---------------------------------------------------------
show('screen-identification');
})();
</script>
</body>
</html>Updated about 3 hours ago
What’s Next
Did this page help you?
