Card Tokenization SDK - Integration Guide
A secure, PCI-compliant SDK for collecting and tokenizing card information on your website.
Installation
Include the SDK script in your HTML page:
<script src="https://your-bank-domain.com/sdk/tokenizer-sdk.js"></script>
Quick Start
The SDK supports two integration modes: Embed (inline form) and Modal (popup form).
Embed Mode
Displays the card form inline within your page:
<div id="card-container"></div>
<script>
const sdk = TokenizerSDK.create({
clientId: 'your-client-id',
authCode: '123456', // Optional TOTP code (see Security section below)
mode: 'embed',
containerId: 'card-container',
onSuccess: (data) => {
console.log('Token:', data.token);
console.log('Last 4 digits:', data.last4);
console.log('Expiry:', data.expiryDate);
// Send token to your backend
},
onError: (error) => {
console.error('Error:', error);
}
});
</script>
Modal Mode
Opens the card form in a popup modal:
<button id="pay-button">Add Card</button>
<script>
const sdk = TokenizerSDK.create({
clientId: 'your-client-id',
authCode: '123456', // Optional TOTP code (see Security section below)
mode: 'modal',
onSuccess: (data) => {
console.log('Token:', data.token);
// Send token to your backend
}
});
document.getElementById('pay-button').addEventListener('click', () => {
sdk.openModal();
});
</script>
Customization
Styling Options
Customize the appearance of the card form:
const sdk = TokenizerSDK.create({
clientId: 'your-client-id',
mode: 'embed',
containerId: 'card-container',
styles: {
primaryColor: '#667eea',
primaryHoverColor: '#5568d3',
errorColor: '#e74c3c',
successColor: '#28a745',
borderColor: '#ddd',
fontFamily: 'Inter, sans-serif',
fontSize: '14px',
borderRadius: '8px'
},
onSuccess: (data) => {
console.log('Token:', data.token);
}
});
Available Style Properties
Available Style Properties
| Property | Description | Default |
|---|---|---|
| primaryColor | Primary accent color | #667eea |
| primaryHoverColor | Hover state for primary elements | #5568d3 |
| errorColor | Error messages and borders | #e74c3c |
| successColor | Success message color | #28a745 |
| borderColor | Input border color | #ddd |
| fontFamily | Font family | System fonts |
| fontSize | Base font size | 14px |
| borderRadius | Input/button border radius | 4px |
Button Customization
Customize button appearance and text:
const sdk = TokenizerSDK.create({
clientId: 'your-client-id',
mode: 'modal',
buttons: {
submit: {
backgroundColor: '#4CAF50',
hoverColor: '#45a049',
text: 'Complete Payment'
},
cancel: {
backgroundColor: '#ff6b6b',
hoverColor: '#ee5a52',
text: 'Go Back'
}
},
onSuccess: (data) => {
console.log('Token:', data.token);
}
});
SDK Reference
Configuration Options
Required Parameters
Required Parameters
| Parameter | Type | Description |
|---|---|---|
| clientId | string | Your unique merchant identifier |
| mode | string | Integration mode: 'embed' or 'modal' |
| onSuccess | function | Callback when tokenization succeeds |
Optional Parameters
Optional Parameters
| Parameter | Type | Description |
|---|---|---|
| authCode | string | Optional TOTP authentication code (generated by your backend) |
| containerId | string | DOM element ID (required for embed mode) |
| onError | function | Callback when tokenization fails |
| onCancel | function | Callback when user cancels |
| styles | object | Style customization options |
| buttons | object | Button customization options |
Success Callback Data
The 'onSuccess' callback receives an object with:
{
token: "abc123...", // Secure token (50 characters)
last4: "4242", // Last 4 digits of card
expiryDate: "12/25", // Card expiry (MM/YY)
expiresAt: "2025-10-27T10:35:00Z" // Token expiration timestamp
}
SDK Methods
Modal Mode Methods
// Open the modal
sdk.openModal()
// Close the modal
sdk.closeModal()
Embed Mode Methods
// Manually mount the form
sdk.mount()
// Remove the form
sdk.unmount()
Complete Example with Customization
<!DOCTYPE html>
<html>
<head>
<title>Payment Page</title>
<script src="https://your-bank-domain.com/sdk/tokenizer-sdk.js"></script>
</head>
<body>
<div id="payment-form"></div>
<script>
const sdk = TokenizerSDK.create({
clientId: 'your-client-id',
mode: 'embed',
containerId: 'payment-form',
styles: {
primaryColor: '#667eea',
borderRadius: '8px',
fontFamily: 'Inter, sans-serif',
fontSize: '15px'
},
buttons: {
submit: {
backgroundColor: '#4CAF50',
hoverColor: '#45a049',
text: 'Pay Now'
}
},
onSuccess: (data) => {
// Send token to your backend
fetch('/api/process-payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: data.token,
amount: 100.00
})
})
.then(response => response.json())
.then(result => {
console.log('Payment processed:', result);
});
},
onError: (error) => {
alert('Payment failed: ' + error);
}
});
</script>
</body>
</html>
Security Features
- Iframe Isolation: Card data never touches your website's DOM
- Client-Side Validation: Real-time card validation (Luhn algorithm, expiry checks)
- Secure Tokens: Single-use tokens with 15-minute expiration
- PCI Compliance: No card data stored on your servers
- TOTP Authentication: Optional Time-based One-Time Password verification for enhanced security
TOTP Authentication (Optional)
For enhanced security, the SDK supports TOTP (Time-based One-Time Password) authentication using RFC 6238. When enabled for your client, you must provide a valid TOTP code with each tokenization request.
Important Security Requirements
⚠️ CRITICAL: Generate TOTP codes in your backend, NOT in the frontend!
TOTP codes must be generated server-side to prevent exposing your TOTP secret to the browser. Your frontend should request a fresh TOTP code from your backend API immediately before initializing the SDK.
Backend TOTP Generation Examples
Node.js Example:
// Backend API endpoint to generate TOTP code
const speakeasy = require('speakeasy');
app.get('/api/generate-totp', (req, res) => {
const totpSecret = process.env.TOTP_SECRET; // Store securely in environment variables
const token = speakeasy.totp({
secret: totpSecret,
encoding: 'base32'
});
res.json({ authCode: token });
});
Python Example:
# Backend API endpoint to generate TOTP code
import pyotp
import os
@app.route('/api/generate-totp')
def generate_totp():
totp_secret = os.environ.get('TOTP_SECRET') # Store securely in environment variables
totp = pyotp.TOTP(totp_secret)
token = totp.now()
return {'authCode': token}
Go Example:
// Backend API endpoint to generate TOTP code
import (
"github.com/pquerna/otp/totp"
"time"
)
func GenerateTOTP(w http.ResponseWriter, r *http.Request) {
totpSecret := os.Getenv("TOTP_SECRET") // Store securely in environment variables
code, err := totp.GenerateCode(totpSecret, time.Now())
if err != nil {
http.Error(w, "Failed to generate TOTP", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(map[string]string{"authCode": code})
}
Frontend Integration with TOTP
Your frontend should fetch a fresh TOTP code from your backend before initializing the SDK:
// Fetch TOTP code from your backend
async function initializeSDK() {
// Step 1: Get TOTP code from YOUR backend API
const response = await fetch('/api/generate-totp');
const { authCode } = await response.json();
// Step 2: Initialize SDK with the TOTP code
const sdk = TokenizerSDK.create({
clientId: 'your-client-id',
authCode: authCode, // Pass the backend-generated TOTP code
mode: 'embed',
containerId: 'card-container',
onSuccess: (data) => {
console.log('Token:', data.token);
},
onError: (error) => {
console.error('Error:', error);
// Handle authentication_failed errors
}
});
}
// Call when user is ready to enter card details
initializeSDK();
TOTP Error Handling
When TOTP authentication fails, you'll receive a 401 error:
onError: (error) => {
if (error.includes('authentication')) {
// TOTP code invalid or expired
// Generate new TOTP code and retry
console.error('Authentication failed. Please try again.');
}
}
Need Help?
For a complete working example, refer to the 'merchant-demo.html' file provided with the SDK.