@tratta/blocks
v0.6.0
Published
A JavaScript library for integrating Tratta Blocks into your web application, providing secure, iframe-based payment form components with advanced validation and real-time feedback.
Readme
Tratta Blocks
A JavaScript library for integrating Tratta Blocks into your web application, providing secure, iframe-based payment form components with advanced validation and real-time feedback.
Installation
npm install @tratta/blocksThen import the library in your JavaScript:
import Tratta from '@tratta/blocks';Quick Start
// Initialize Tratta with your public key
const tratta = Tratta('your_public_key_here');
// Create blocks instance
const blocks = tratta.blocks();
// Create a card block with pre-filled values
const cardBlock = blocks.create('card', {
hidePostalCode: false,
hideCardHolder: false,
value: {
cardholderName: 'John Doe',
postalCode: '12345'
}
});
// Mount the card block to a container
cardBlock.mount('#card-block-container');
// Listen for form completion
cardBlock.on('change', (event) => {
if (event.complete) {
// Form is complete and valid - enable submit button
submitButton.disabled = false;
}
});
// Handle form submission
submitButton.addEventListener('click', async () => {
try {
// Create token using the card block
const result = await tratta.createToken(cardBlock);
if (result.error) {
console.error('Error:', result.error);
if (result.errors) {
// Handle validation errors
console.error('Validation errors:', result.errors);
}
} else {
console.log('Token created:', result.id);
console.log('Token type:', result.type);
console.log('Card details:', result.card);
}
} catch (error) {
console.error('Error:', error);
}
});API Reference
Tratta(publicKey, options)
Creates a new Tratta instance.
Parameters:
publicKey(string, required): Your Tratta public keyoptions(object, optional): Configuration optionsenvironment(string): Environment to use ('sandbox', 'production')
Returns: Tratta instance
tratta.blocks(options)
Creates a blocks instance for creating payment blocks.
Parameters:
options(object, optional): Global options for all blocks
Returns: Blocks instance
tratta.createToken(block)
Creates a token using the provided block.
Parameters:
block(Block instance, required): The block instance to create a token from
Returns: Promise that resolves with token data containing id, type, card, and created_at properties, or error object with error property
Example:
const result = await tratta.createToken(cardBlock);
if (result.error) {
console.error('Error:', result.error);
if (result.errors) {
// Handle validation errors
console.error('Validation errors:', result.errors);
}
} else {
console.log('Token ID:', result.id);
console.log('Token type:', result.type);
console.log('Card details:', result.card);
console.log('Created at:', result.created_at);
}Response Structure:
{
id: "pm_1234567890abcdef",
type: "card",
card: {
card_holder: "John Doe", // Cardholder name (optional)
card_number: "1234", // Last 4 digits of card number
expiration_month: "12", // Expiration month
expiration_year: "25", // Expiration year (2 digits)
card_type: "visa", // Card type (visa, mastercard, etc.)
card_zip: "12345" // Postal code (if provided)
},
created_at: "2024-01-15 10:30:00"
}blocks.create(type, options)
Creates a specific block.
Parameters:
type(string, required): Block type ('card')options(object, optional): Block-specific options
Returns: Block instance
Block Methods
mount(container)
Mounts the block to a DOM container.
Parameters:
container(string|Element): CSS selector or DOM element
Returns: Block instance
unmount()
Unmounts the block from the DOM. The block can be re-mounted later.
Returns: Block instance
update(options)
Updates the block configuration.
Parameters:
options(object): New configuration options
Returns: Block instance
focus()
Focuses the block.
Returns: Block instance
blur()
Removes focus from the block.
Returns: Block instance
clear()
Clears the block values.
Returns: Block instance
destroy()
Destroys the block and removes it from the DOM. Cannot be re-mounted.
Returns: Block instance
Event Handling
on(event, handler)
Attaches an event handler to the block.
Events:
ready: Block is ready for interactionchange: Block values have changedfocus: Block has received focusblur: Block has lost focusescape: Escape key was pressed within the block
Returns: Block instance
off(event)
Removes an event handler from the block.
Returns: Block instance
onMessage(type, handler)
Attaches a custom message handler for iframe communication.
Parameters:
type(string): Message type to listen forhandler(function): Handler function
Returns: Block instance
Block Types
Card Block
The card block provides a secure way to collect card information through an iframe with advanced validation and real-time feedback.
Pre-filling Fields
You can pre-fill non-sensitive fields to improve user experience. Only the cardholder name and postal code can be pre-filled - sensitive card information (card number, CVC, and expiration date) cannot be pre-filled for security reasons.
const cardBlock = blocks.create('card', {
hidePostalCode: false,
hideCardholder: false,
value: {
cardholderName: 'John Doe', // Pre-fill cardholder name
postalCode: '12345' // Pre-fill postal code
}
});Important Notes:
- Pre-filled values are only applied when the corresponding fields are visible (not hidden)
- Values are set when the block is initialized
- Users can still modify pre-filled values
- Pre-filling does not affect validation - all validation rules still apply
const cardBlock = blocks.create('card');Features:
- Secure iframe implementation - Card data never touches your server
- Real-time validation - Instant feedback on card number, expiration, CVV, postal code, and cardholder name
- Card network detection - Automatically detects and validates supported card networks
- BIN validation - Validation of card issuer and type
- Optional cardholder name - Cardholder name field is optional for enhanced flexibility
- Dynamic height adjustment - Automatically resizes based on content
- Accessibility support - Screen reader friendly with proper ARIA attributes
- Mobile responsive - Optimized for touch devices
CardBlock Options
const cardBlock = blocks.create('card', {
hidePostalCode: true, // Hide the postal code field. Default is true.
hideCardholder: true, // Hide the cardholder name field. Default is true.
value: { // Pre-fill values for non-sensitive fields
cardholderName: 'John Doe',
postalCode: '12345'
}
});Options:
hidePostalCode(boolean): Hide the postal code field. Default istrue.hideCardholder(boolean): Hide the cardholder name field. Default istrue.value(object): Pre-filled values for non-sensitive fields. Note that sensitive card information (card number, CVC, and expiration date) cannot be pre-filled.cardholderName(string): Pre-fill the cardholder name fieldpostalCode(string): Pre-fill the postal code field
CardBlock Events
The card block emits detailed change events with comprehensive form state:
cardBlock.on('change', (event) => {
console.log('Form state:', {
empty: event.empty, // true if no fields have values
complete: event.complete, // true if all required fields are valid
error: event.error, // validation errors object or null
blockType: event.blockType // 'card'
});
});Environments
The library supports multiple environments:
- sandbox:
https://sandbox.tratta.com- For testing and development - production:
https://app.tratta.com- For live applications
// Initialize with sandbox environment
const tratta = Tratta('pk_test_key', { environment: 'sandbox' });
// Initialize with production environment
const tratta = Tratta('pk_live_key', { environment: 'production' });Demo
See the demo/index.html file for complete working examples.
Error Handling
The library provides comprehensive error handling with detailed validation feedback.
Error Types
All validation errors follow a consistent format:
const result = await tratta.createToken(cardBlock);
if (result.error) {
console.error('Error:', result.error);
if (result.errors) {
// Handle field-specific validation errors
Object.entries(result.errors).forEach(([field, messages]) => {
console.error(`${field}:`, messages);
});
}
} else {
console.log('Token ID:', result.id);
console.log('Token type:', result.type);
}Validation Messages
The library provides user-friendly validation messages for all card fields:
- Card Number: Required, invalid format, unsupported network, card type restrictions
- Expiration Date: Required, invalid format, invalid month/year
- Security Code: Required, invalid format, length validation based on card type
- Cardholder Name: Optional, invalid format (when provided)
- Postal Code: Required (when visible), invalid format
Error Format
All error objects follow a consistent format:
{
error: 'Validation failed',
errors: {
card_number: ['Your card number is invalid.'],
card_expiration: ['Your card\'s expiration date is required.'],
card_security_code: ['Your card\'s security code is invalid.'],
card_holder: ['Your cardholder name is invalid.'],
postal_code: ['Your postal code is required.']
}
}Security Features
Iframe Security
- Sandboxed execution - Restricted iframe permissions for enhanced security
- Cross-origin isolation - Card data never accessible to parent page
- Secure communication - PostMessage API with origin validation
- No sensitive data exposure - Card details never logged or stored in parent context
Validation Layers
- Client-side validation - Real-time feedback for immediate user experience
- Server-side validation - Comprehensive validation including BIN checks
- Card network validation - Automatic detection and validation of supported networks
- Type restrictions - Configurable card type and network restrictions
Styling
The card block provides a pre-styled, secure iframe that automatically adapts to your container:
#card-block {
background-color: white;
border: 1px solid #cbd5e1;
border-radius: 8px;
padding: 1rem;
width: 100%;
max-width: 800px;
}Key styling features:
- Automatic height adjustment - Dynamically resizes based on content
- Responsive design - Adapts to container width
- Consistent branding - Can be styled to match your brand colors
- Smooth transitions - Height changes are animated for better UX
Browser Support
- Chrome 105+ (2022)
- Firefox 121+ (2023)
- Safari 15.4+ (2022)
- Edge 105+ (2022)
Note: The library uses modern JavaScript features (ES6+) and CSS features. For older browsers, some styling features may not work as expected, but core functionality remains available.
License
MIT License - see the LICENSE file for details.
