# Easyflow JavaScript SDK

Enterprise-grade JavaScript SDK for Easyflow payment processing platform - Documentation and TypeScript definitions only

## Project Status & Quality

<div align="center">

[![Tests](https://img.shields.io/badge/Tests-533%20passing-brightgreen?style=for-the-badge&logo=jest)](https://github.com/easyflow-cash/easyflow-javascript-sdk/actions)
[![Test Suites](https://img.shields.io/badge/Test%20Suites-11%20suites-blue?style=for-the-badge&logo=jest)](https://github.com/easyflow-cash/easyflow-javascript-sdk/actions)
[![Coverage](https://img.shields.io/badge/Coverage-100%25-brightgreen?style=for-the-badge&logo=codecov)](https://github.com/easyflow-cash/easyflow-javascript-sdk/actions)
[![Version](https://img.shields.io/badge/Version-2.4.6-blue?style=for-the-badge&logo=npm)](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.6

### Major New Features

- **Coupon Management**: New `reserveCoupon()` method for reserving coupons
    - **Coupon Reservation**: Reserve coupons for offers with specific items
    - **Multiple Items Support**: Reserve coupons for multiple offer items
    - **Full Validation**: Comprehensive validation for coupon code, offer ID, and items
    - **Rate Limiting**: Built-in rate limiting for coupon operations
- **Installments Management**: New `getInstallments()` method for retrieving available installment options
    - **Multiple Target Types**: Support for offers, payment links, and charges
    - **Flexible Configuration**: Get installment options for any target type with amount
    - **Full Validation**: Comprehensive validation for target ID, type, and amount
    - **Rate Limiting**: Built-in rate limiting for installment queries
- **Invoice Charging**: New `chargeInvoice()` method for processing invoice payments
    - **Invoice Support**: Charge invoices directly with payment information
    - **Event Emission**: Emits `invoiceCharged` event on successful charge
    - **Full Validation**: Comprehensive validation for invoice data and payments
    - **Rate Limiting**: Built-in rate limiting for invoice operations
- **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
- **Enhanced Error Handling**: Comprehensive error categorization
    - **ValidationError**: Data validation failures
    - **NetworkError**: API communication issues
    - **SecurityError**: Authentication and security issues
- **Code Quality Improvements**: Refactored and optimized codebase
    - **Removed deprecated modules**: Cleaned up unused integration wrappers
    - **Improved code organization**: Better separation of concerns
    - **Enhanced maintainability**: Cleaner, more maintainable codebase

### Documentation & Developer Experience

- **Enhanced Testing**: Comprehensive test coverage
    - **533 tests passing**: 100% test coverage maintained
    - **11 test suites**: Complete coverage across all modules
    - **New coupon tests**: Full test coverage for coupon reservation
    - **New installments tests**: Full test coverage for installments management
    - **New invoice tests**: Full test coverage for invoice charging
- **Developer Tools**: Enhanced development experience
    - **TypeScript support**: Full type safety and IntelliSense
    - **Debug mode**: Enhanced logging and error reporting
    - **Comprehensive examples**: Updated examples for all features

## 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:

- **533 tests passing**
- **11 test suites** covering all functionality
- **0 test failures** ensuring reliability
- **Comprehensive validation testing** for all data structures

### Test Suites

- **Validator Tests**: Comprehensive validation logic coverage
- **SDK Core Tests**: Complete main SDK functionality coverage including `chargeInvoice`
- **Sanitizer Tests**: Full input sanitization coverage
- **Error Handling Tests**: Complete error scenario coverage
- **HTTP Module Tests**: Full API communication coverage
- **Utils Tests**: Complete utility functions coverage
- **Constants Tests**: Full configuration coverage
- **Logger Tests**: Complete logging functionality coverage
- **Exception Handler Tests**: Complete error throwing coverage
- **Security Tests**: Complete security features coverage
- **Fingerprint Tests**: Complete browser fingerprinting coverage

### 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)
```

### Installments Management

```javascript
// Get installments for an offer
const installments = await window.easyflowSDK.getInstallments(
    '550e8400-e29b-41d4-a716-446655440000',
    'offer',
    10000 // Amount in cents
)
console.log('Available installments:', installments)

// Get installments for a payment link
const paymentLinkInstallments = await window.easyflowSDK.getInstallments(
    '550e8400-e29b-41d4-a716-446655440000',
    'payment-link',
    50000
)

// Get installments for a charge
const chargeInstallments = await window.easyflowSDK.getInstallments(
    '550e8400-e29b-41d4-a716-446655440000',
    'charge',
    25000
)
```

### Coupon Management

```javascript
// Reserve a coupon for an offer
const reservation = await window.easyflowSDK.reserveCoupon({
    code: 'ESTRANHO40',
    offerId: '550e8400-e29b-41d4-a716-446655440000',
    offerItems: [
        {
            id: 'd661d558-b80b-47b3-903a-2ec4e2295a28',
            quantity: 1,
        },
    ],
})
console.log('Coupon reserved:', reservation)

// Reserve coupon with multiple items
const multiItemReservation = await window.easyflowSDK.reserveCoupon({
    code: 'DESCONTO50',
    offerId: '550e8400-e29b-41d4-a716-446655440000',
    offerItems: [
        {
            id: 'd661d558-b80b-47b3-903a-2ec4e2295a28',
            quantity: 2,
        },
        {
            id: 'e772e669-c91c-58c4-a014-3fd5f33a0b39',
            quantity: 1,
        },
    ],
})
```

### Invoice Management

```javascript
// Charge an invoice
const orderId = await window.easyflowSDK.chargeInvoice({
    invoiceId: '550e8400-e29b-41d4-a716-446655440000',
    payments: [
        {
            method: 'pix',
            numberInstallments: 1,
        },
    ],
    coupon: {
        reserveId: 'coupon-reserve-789', // Optional coupon with reserve ID
    },
})

// Listen for invoice charged event
window.easyflowSDK.on('invoiceCharged', (data) => {
    console.log('Invoice charged:', data.orderId)
})
```
<｜tool▁calls▁begin｜><｜tool▁call▁begin｜>
read_file

### Installments Management

```javascript
// Get installments for an offer
const installments = await window.easyflowSDK.getInstallments(
    '550e8400-e29b-41d4-a716-446655440000',
    'offer',
    10000 // Amount in cents
)
console.log('Available installments:', installments)

// Get installments for a payment link
const paymentLinkInstallments = await window.easyflowSDK.getInstallments(
    '550e8400-e29b-41d4-a716-446655440000',
    'payment-link',
    50000
)

// Get installments for a charge
const chargeInstallments = await window.easyflowSDK.getInstallments(
    '550e8400-e29b-41d4-a716-446655440000',
    'charge',
    25000
)
```

### 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)
})

// Invoice charged
window.easyflowSDK.on('invoiceCharged', (data) => {
    console.log('Invoice charged:', data.orderId)
})

// 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**: ~95KB (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**
