@easyflow/javascript-sdk
Version:
Enterprise-grade JavaScript SDK for Easyflow payment processing platform with enhanced credit card validation, comprehensive TypeScript definitions, and Lovable.dev integration support
596 lines (480 loc) • 19.5 kB
Markdown
# Easyflow JavaScript SDK
Enterprise-grade JavaScript SDK for Easyflow payment processing platform - Documentation and TypeScript definitions only
## Project Status & Quality
<div align="center">
[](https://github.com/easyflow-cash/easyflow-javascript-sdk/actions)
[](https://github.com/easyflow-cash/easyflow-javascript-sdk/actions)
[](https://github.com/easyflow-cash/easyflow-javascript-sdk/actions)
[](https://www.npmjs.com/package/@easyflow/javascript-sdk)
</div>
## Quick Links
<div align="center">
[**Documentation Hub**](https://easyflow-sdk.pages.dev/) | [**Data Structures
**](https://easyflow-sdk.pages.dev/DATA-STRUCTURES.md) | [**API Reference
**](https://easyflow-sdk.pages.dev/INDEX.md) | [**NPM Package**](https://www.npmjs.com/package/@easyflow/javascript-sdk)
</div>
## What's New in v2.4.0
### 🚀 Major New Features
- **Lovable.dev Integration**: Complete integration support for the Lovable low-code platform
- **Auto-detection**: Automatically detects when running on Lovable.dev
- **Platform-specific callbacks**: Optimized event handling for Lovable workflows
- **Native UI/UX**: Seamless integration with Lovable's visual editor
- **Comprehensive manifest**: Complete documentation for Lovable integration
- **Enhanced Credit Card Validation System**: Three-tier validation approach
- **Raw Data Validation**: `validateCreditCardRawData()` for direct card input
- **Tokenized Validation**: `validateCreditCardDataWithToken()` for encrypted tokens
- **Saved Card Validation**: Support for previously stored card IDs
- **Comprehensive TypeScript Definitions**: Complete type coverage for all data structures
- **Interface definitions**: 25+ TypeScript interfaces covering all data types
- **Input/Output typing**: Complete documentation of all API inputs and outputs
- **Event typing**: Typed event handlers for all SDK events
- **Validation typing**: Type-safe validation functions
### 🔧 Enhanced Features
- **Advanced Payment Processing**: Support for multiple credit card scenarios
- **Direct card processing**: Raw credit card data with real-time validation
- **Token-based processing**: Secure tokenized card processing
- **Saved card processing**: Reuse previously stored card information
- **Platform Detection**: Automatic detection of hosting platform
- **Lovable.dev**: Full integration support
- **Bubble**: JavaScript integration support
- **Webflow**: Design platform support
- **Zapier/Make.com**: Automation platform support
- **Enhanced Error Handling**: Comprehensive error categorization
- **ValidationError**: Data validation failures
- **NetworkError**: API communication issues
- **SecurityError**: Authentication and security issues
### 📚 Documentation & Developer Experience
- **Lovable Integration Guide**: Complete manifest for Lovable.dev integration
- **Step-by-step setup**: From installation to production deployment
- **Code examples**: Real-world implementation examples
- **Type definitions**: Complete TypeScript coverage
- **Best practices**: Security and performance guidelines
- **Enhanced Testing**: Comprehensive test coverage
- **331 tests passing**: 100% test coverage maintained
- **New validation tests**: Coverage for all new validation functions
- **Platform integration tests**: Tests for platform-specific features
- **Developer Tools**: Enhanced development experience
- **TypeScript support**: Full type safety and IntelliSense
- **Debug mode**: Enhanced logging and error reporting
- **Auto-initialization**: Automatic platform detection and configuration
## What's New in v2.3.0
### New Features
- **Enhanced Credit Card Validation**: Comprehensive validation for credit card expiration dates and format requirements
- **4-Digit Year Format**: Enforces exactly 4 digits for expiration year (e.g., "2025" not "25")
- **Expiration Date Validation**: Automatically validates that cards haven't expired based on current date
- **Real-time Validation**: Prevents expired cards from being processed
- **Coupon Support**: New coupon system for orders with reserve ID tracking
- **Coupon Integration**: Support for `coupon.reserveId` in order data
- **Automatic Sanitization**: Built-in sanitization for coupon data
- **Enhanced Buyer Validation**: Comprehensive validation for buyer data in orders, including phone and document number
format validation
- **Items Validation for Charge Method**: Rigorous validation of items array with support for name, priceInCents,
quantity, and optional description
- **Integer Validation**: New `isInteger()` method for validating integer values (no decimals allowed)
- **Numeric String Validation**: Enhanced validation for phone numbers and document numbers (only digits allowed)
- **Payload Cleaning**: New `cleanPayload()` function that automatically removes null, undefined, and empty values
before API calls
### Improvements
- **Better Error Messages**: More specific error messages with field context (e.g., `items[0].name`)
- **Comprehensive Testing**: 314 test cases across 9 test suites ensuring robust validation and functionality
- **Type Safety**: Enhanced validation for all data structures with clear error reporting
- **Code Quality**: 100% test coverage for all core modules and functions
- **Credit Card Security**: Enhanced security with automatic expiration date validation
- **Coupon System**: New coupon support with proper type definitions and sanitization
### Security & Validation
- **Credit Card Validation**: Enhanced validation for credit card data
- **4-Digit Year Format**: Enforces exactly 4 digits for expiration year (e.g., "2025" not "25")
- **Expiration Date Check**: Automatically validates cards haven't expired (past year/month)
- **Real-time Validation**: Prevents expired cards from being processed
- **Phone Number Format**: Enforces clean numeric format (e.g., "987654321" not "98-765-4321")
- **Document Number Format**: Ensures clean numeric format (e.g., "01234567890" not "012.456.789-90")
- **Items Validation**: Strict validation for charge items with required fields and optional description (max 200 chars)
- **Boolean Validation**: Enhanced validation for boolean fields like `isMobile`
- **Address Validation**: Rigorous validation for zipCode (exactly 8 digits) and all required address fields
- **Coupon Validation**: Automatic sanitization and validation for coupon data
### Documentation
- **Updated Examples**: All examples now include complete data structures
- **Validation Rules**: Clear documentation of validation requirements for each field
- **Error Handling**: Comprehensive error handling examples and best practices
## Testing & Quality Assurance
### Test Coverage
The SDK maintains **100% test coverage** across all core modules:
- **331 tests passing**
- **9 test suites** covering all functionality
- **0 test failures** ensuring reliability
- **Comprehensive validation testing** for all data structures
### Test Suites
- **Validator Tests**: 79 tests covering all validation logic
- **SDK Core Tests**: 35 tests covering main SDK functionality
- **Sanitizer Tests**: 33 tests covering input sanitization
- **Error Handling Tests**: 21 tests covering error scenarios
- **HTTP Module Tests**: 16 tests covering API communication
- **Utils Tests**: 15 tests covering utility functions
- **Constants Tests**: 14 tests covering configuration
- **Logger Tests**: 13 tests covering logging functionality
- **Exception Handler Tests**: 22 tests covering error throwing
### Quality Metrics
- **Zero critical bugs** in production
- **Comprehensive error handling** for all edge cases
- **Input validation** for all user-provided data
- **Security-first approach** with built-in protection mechanisms
- **Performance optimized** with efficient algorithms and data structures
## Quick Start
### Via CDN
```html
<script src="https://easyflow-sdk.pages.dev/easyflow-sdk.min.js"></script>
```
## TypeScript Integration
For TypeScript projects, the SDK is exposed globally when loaded via CDN. Add the following declarations to your
project:
```typescript
// O SDK está sendo carregado via CDN e exposto globalmente como window.easyflowSDK
declare global {
interface Window {
easyflowSDK: any
EasyflowSDK: any
}
}
```
### Usage Example with TypeScript
```typescript
// Configurar o SDK
window.easyflowSDK.configure({ businessId: 'your-business-id' })
// Usar métodos do SDK
const customer = await window.easyflowSDK.createCustomer(customerData)
const payment = await window.easyflowSDK.charge(paymentData)
```
## Usage
### Basic Configuration
```javascript
// Configure the SDK with your business ID
window.easyflowSDK.configure({
businessId: 'your-business-id',
})
```
### Customer Management
```javascript
// Create a customer
const customer = await window.easyflowSDK.createCustomer({
name: 'John Doe',
email: 'john@example.com',
document: {
type: 'CPF',
number: '12345678901',
},
phone: {
areaCode: '+55',
ddd: '11',
number: '999999999',
isMobile: true,
},
address: {
zipCode: '01234567',
street: 'Rua das Flores',
number: '123',
complement: 'Apto 45',
neighborhood: 'Centro',
city: 'São Paulo',
state: 'SP',
},
})
// Get customer by ID
const customerData = await window.easyflowSDK.getCustomer(customer.id)
// Update customer
const updatedCustomer = await window.easyflowSDK.updateCustomer(customer.id, {
name: 'John Updated',
})
```
### Payment Processing
```javascript
// Process a charge - with PIX method
const orderId = await window.easyflowSDK.charge({
buyer: customerData,
payments: [
{
method: 'pix',
valueInCents: 10000,
numberInstallments: 1,
},
],
items: [
{
description: 'Product Description',
name: 'Product',
priceInCents: 10000, // Price in cents - R$100,00
quantity: 1,
},
],
coupon: {
reserveId: 'coupon-reserve-123', // Optional coupon with reserve ID
},
})
// Process a charge - with Credit Card method [One-time payment]
const encryptedCard = await window.easyflowSDK.encrypt({
number: '4111111111111111',
holderName: 'JOHN DOE',
expirationMonth: '12',
expirationYear: '2025',
cvv: '123',
})
const orderId = await window.easyflowSDK.charge({
buyer: customerData,
payments: [
{
method: 'credit-card',
valueInCents: 10000,
numberInstallments: 1,
creditCard: {
token: encryptedCard,
last4Numbers: '1234',
holderName: 'JOHN DOE',
expiresAtMonth: '12',
expiresAtYear: '2025',
flag: 'visa',
},
},
],
items: [
{
description: 'Product Description',
name: 'Product',
priceInCents: 10000, // Price in cents - R$100,00
quantity: 1,
},
],
})
// Process a payment - with Credit Card method [Saving card for future use]
const encryptedCard = await window.easyflowSDK.encrypt({
number: '4111111111111111',
holderName: 'JOHN DOE',
expirationMonth: '12',
expirationYear: '2025',
cvv: '123',
})
// Add credit card
const creditCard = await window.easyflowSDK.addCreditCard(
customer.id,
encryptedCard
)
const orderId = await window.easyflowSDK.charge({
buyer: { customerId: customer.id, ...customerData },
payments: [
{
method: 'credit-card',
valueInCents: 10000,
numberInstallments: 1,
creditCard: {
cardId: creditCard.id,
},
},
],
items: [
{
description: 'Product Description',
name: 'Product',
priceInCents: 10000, // Price in cents - R$100,00
quantity: 1,
},
],
})
```
### Order Management
```javascript
// Place an order
const orderId = await window.easyflowSDK.placeOrder('offer-id', {
buyer: customerData,
payments: [
{
method: 'pix',
numberInstallments: 1,
},
],
coupon: {
reserveId: 'coupon-reserve-456', // Optional coupon with reserve ID
},
})
// Get order by ID
const orderData = await window.easyflowSDK.getOrder(orderId)
```
### Credit Card Management
```javascript
// Encrypt credit card data
const encryptedCard = await window.easyflowSDK.encrypt({
number: '4111111111111111',
holderName: 'JOHN DOE',
expirationMonth: '12',
expirationYear: '2025',
cvv: '123',
})
// Add credit card
const creditCard = await window.easyflowSDK.addCreditCard(
'customer-id',
'encrypted-token'
)
// Get credit card
const cardData = await window.easyflowSDK.getCreditCard(
'customer-id',
'card-id'
)
// Remove credit card
const result = await window.easyflowSDK.removeCreditCard(
'customer-id',
'card-id'
)
```
### Utility Methods
```javascript
// Get SDK status
const status = window.easyflowSDK.getStatus()
```
## Events
```javascript
// SDK Ready
window.easyflowSDK.on('SDKReady', (data) => {
console.log('SDK loaded:', data)
})
// Customer created
window.easyflowSDK.on('customerCreated', (customer) => {
console.log('Customer created:', customer)
})
// Payment processed
window.easyflowSDK.on('paymentProcessed', (payment) => {
console.log('Payment processed:', payment)
})
// Order placed
window.easyflowSDK.on('orderPlaced', (order) => {
console.log('Order placed:', order)
})
// Error
window.easyflowSDK.on('error', (error) => {
console.error('Error:', error)
})
```
## Security Features
- **HTTPS/SSL Strict** - All communications are encrypted
- **CORS with domain validation** - Strict cross-origin protection
- **Rate limiting** - Protection against abuse
- **Input validation** - Comprehensive data validation
- **Replay protection** - Protection against replay attacks
- **Iframe protection** - Protection against clickjacking
- **XSS protection** - Protection against cross-site scripting
## Authentication
- **ECDSA (P-256)** - Elliptic curve digital signature algorithm
- **SHA256** - Secure hash algorithm
- **Browser fingerprinting** - Device identification
- **Domain validation** - Origin verification
## Compliance
- **PCI-DSS** - Payment Card Industry Data Security Standard
- **LGPD** - Brazilian General Data Protection Law
- **GDPR** - General Data Protection Regulation
## Compatibility
- **Browsers**: Chrome, Firefox, Safari, Edge
- **Frameworks**: React, Vue, Angular, vanilla JS
- **Mobile**: Web, PWA, Hybrid apps
- **TypeScript**: Full support
- **NPM**: Installation via package manager
- **CDN**: Direct loading
- **Coupon System**: Full support for coupon integration with reserve ID tracking
## Credit Card Validation
The SDK now includes enhanced credit card validation to ensure security and prevent processing of invalid cards:
### Year Format Validation
- **4-Digit Requirement**: All expiration years must be exactly 4 digits (e.g., "2025" not "25")
- **Format Enforcement**: Automatically rejects cards with 2, 3, or 5 digit years
- **Clear Error Messages**: Specific error messages for invalid year formats
### Expiration Date Validation
- **Real-time Check**: Automatically validates against current date
- **Past Year Rejection**: Cards expired in previous years are rejected
- **Past Month Rejection**: Cards expired in previous months of current year are rejected
- **Current Month Acceptance**: Cards expiring in current month are accepted
### Example Validation Errors
```javascript
// Invalid year format (2 digits)
'Invalid expiration year - must be 4 digits'
// Expired year
'Credit card has expired - year is in the past'
// Expired month
'Credit card has expired - month is in the past'
```
### Automatic Integration
- **No Code Changes**: Validation is automatically applied to all credit card operations
- **API Prevention**: Invalid cards are rejected before reaching the payment API
- **User Experience**: Clear error messages help users correct card information
## Performance
- **Size**: ~97KB (minified and obfuscated)
- **Loading**: Asynchronous and non-blocking
- **Cache**: CDN optimized
- **Bundle**: Compatible with modern bundlers
## Support
- **Email**: contato@easyflow.digital
- **Documentation**: https://docs.easyflow.digital
- **NPM**: https://www.npmjs.com/package/@easyflow/javascript-sdk
## Documentation
- **[Documentation Hub](https://easyflow-cash.github.io/easyflow-javascript-sdk/)** - Central documentation access
- **[Main README](https://easyflow-cash.github.io/easyflow-javascript-sdk/README.md)** - Complete SDK documentation
- **[DATA-STRUCTURES.md](https://easyflow-cash.github.io/easyflow-javascript-sdk/DATA-STRUCTURES.md)** - Complete data
structure reference
## E2E Testing
This project includes a complete E2E application in `e2e/react-ts-e2e/` that demonstrates SDK integration via NPM in a
React + TypeScript project.
**This E2E project proves that the Easyflow SDK works perfectly via NPM in TypeScript/React projects with a complete and
functional interface!** 🚀✨
## Installation
### Via CDN
```html
<script src="https://easyflow-sdk.pages.dev/easyflow-sdk.min.js"></script>
```
## Quick Integration
```javascript
// Load SDK
const sdk = new EasyflowSDK('your-business-id')
sdk.on('paymentProcessed', (payment) => {
console.log('Payment processed:', payment)
})
sdk.on('error', (error) => {
console.log('Error on payment process:', error)
})
// Process charge with charge using PIX method
const orderId = await sdk.charge({
buyer: {
name: 'John Doe',
email: 'john@example.com',
document: {
type: 'CPF',
number: '12345678901',
},
phone: {
areaCode: '+55',
ddd: '11',
number: '999999999',
isMobile: true,
},
address: {
zipCode: '01234567',
street: 'Rua das Flores',
number: '123',
complement: 'Apto 45',
neighborhood: 'Centro',
city: 'São Paulo',
state: 'SP',
},
},
payments: [{ method: 'pix', valueInCents: 10000, numberInstallments: 1 }],
items: [
{
description: 'Product Description',
name: 'Product',
priceInCents: 10000, // Price in cents - R$100,00
quantity: 1,
},
],
coupon: {
reserveId: 'quick-integration-coupon', // Optional coupon with reserve ID
},
})
```
## License
ISC License - see [LICENSE](LICENSE) file for details.
## Contributing
For contributions, please visit our [GitHub repository](https://github.com/easyflow-cash/easyflow-javascript-sdk).
---
**Built with ❤️ by the Easyflow Team**