npm package: @itispay/typescript-client
Description: A clean, idiomatic TypeScript client for the ItIsPay cryptocurrency payment gateway API
Author: ItIsPay
Latest version: 1.0.0

﻿# ItIsPay TypeScript Client

A clean, idiomatic TypeScript client for the ItIsPay cryptocurrency payment gateway API. This package provides easy-to-use methods for creating and managing cryptocurrency invoices, handling payments, and integrating with the ItIsPay platform.

## Features

-  **TypeScript First**: Built with TypeScript from the ground up with full type safety
-  **Zero Dependencies**: Uses only Node.js built-ins and fetch API
-  **Clean API**: Idiomatic TypeScript design with proper error handling
-  **Promise-based**: Full async/await support with proper error handling
-  **Type Safety**: Strongly typed requests and responses with comprehensive interfaces
-  **Comprehensive**: Supports all ItIsPay API endpoints
-  **Modern JavaScript**: ES2020+ features with proper module support

## Installation

```bash
npm install @itispay/typescript-client
```

## Quick Start

``` typescript
import { createClient } from '@itispay/typescript-client';

// Create a new client
const client = createClient({ apiKey: 'your-api-key' });

// Create an invoice
const invoice = await client.createInvoice({
  order_id: 'ORDER-12345',
  fiat_amount: 100.0,
  fiat_currency: 'EUR',
  currency: 'BTC',
  order_name: 'Premium Subscription',
  expire_min: 30,
  callback_url: 'https://your-app.com/webhook'
});

console.log('Created invoice:', invoice.invoice_id);
console.log('Payment address:', invoice.blockchain_details?.blockchainAddress);
console.log('Amount:', invoice.crypto_amount, 'BTC');
```

## API Reference

### Client Creation

```	typescript
import { createClient, ItIsPayClient } from '@itispay/typescript-client';

// Using factory function (recommended)
const client = createClient({ 
  apiKey: 'your-api-key',
  baseURL: 'https://api.itispay.com/api/v1', // optional, defaults to production
  timeout: 30000 // optional, defaults to 30 seconds
});

// Or using constructor directly
const client = new ItIsPayClient({ 
  apiKey: 'your-api-key' 
});
```

**Note**: You can obtain your API key from your ItIsPay account dashboard after registration.

### Invoice Management

#### Create Invoice

```	typescript
const fiatAmount = 50.0;
const expireMin = 30;

const invoice = await client.createInvoice({
  order_id: 'ORDER-12345',
  fiat_amount: fiatAmount,
  fiat_currency: 'EUR',
  currency: 'BTC',
  allowed_error_percent: 5,
  order_name: 'Premium Subscription',
  expire_min: expireMin,
  callback_url: 'https://your-app.com/webhook'
});
```

#### Get Invoice

```	typescript
const invoice = await client.getInvoice('invoice_7d4e8f2a-1b3c-4d5e-8f9a-2b3c4d5e6f7a');

console.log('Invoice status:', invoice.status);
console.log('Amount paid:', invoice.actual_crypto_amount_paid, invoice.currency);
```

#### List Invoices

```	typescript
// Basic listing
const invoices = await client.listInvoices();

// With filters and pagination
const invoices = await client.listInvoices({
  page: 1,
  page_size: 20,
  status: 'completed',
  currency: 'BTC',
  sort_by: 'created_at',
  sort_order: 'desc'
});

for (const invoice of invoices.items) {
  console.log(Invoice :  -  );
}
```

#### Update Invoice Status

```	typescript
const response = await client.updateInvoiceStatus('invoice_id', 'cancelled');

console.log(Invoice  updated to );
```

### Currency and Rates

#### Get Supported Currencies

```	typescript
const currencies = await client.getCurrencies();

console.log('Supported currencies:');
for (const currency of currencies.currencies) {
  if (currency.is_crypto) {
    console.log(-  (Crypto,  network));
  } else {
    console.log(-  (Fiat));
  }
}
```

#### Get Exchange Rates

```	typescript
const rates = await client.getRates();

console.log('BTC rate: $', rates.rates['BTC']);
console.log('ETH rate: $', rates.rates['ETH']);
```

### Webhook Testing

#### Simulate Webhook

```	typescript
const response = await client.simulateWebhook('invoice_id', 'completed');

console.log('Webhook simulation:', response.message);
```

## Invoice Status Values

| Status | Description |
|--------|-------------|
| StatusNew | Invoice created, awaiting payment |
| StatusPending | Payment detected but not confirmed |
| StatusCompleted | Payment confirmed and within acceptable range |
| StatusPaidPartial | Payment received but below expected amount |
| StatusExpired | Invoice expired without payment |
| StatusCancelled | Invoice manually cancelled |

## Error Handling

The client returns typed errors for better error handling:

```	typescript
try {
  const invoice = await client.getInvoice('invalid_id');
} catch (error) {
  if (error instanceof APIError) {
    switch (error.statusCode) {
      case 401:
        console.log('Authentication failed');
        break;
      case 404:
        console.log('Invoice not found');
        break;
      case 422:
        console.log('Validation failed');
        break;
      case 400:
        console.log('Bad request:', error.message);
        break;
      default:
        console.log('API error:', error.message);
    }
  } else {
    console.log('Network error:', error.message);
  }
}
```

## Webhook Integration

ItIsPay will send webhook notifications to your specified callback URL when invoice statuses change. Here's how to handle them:

### Express.js Example

```	typescript
import express from 'express';
import { StatusCompleted, StatusPaidPartial, StatusExpired, StatusCancelled } from '@itispay/typescript-client';

const app = express();
app.use(express.json());

app.post('/webhook', async (req, res) => {
  try {
    const webhook = req.body;

    // Validate required fields
    if (!webhook.invoice_id || !webhook.status) {
      return res.status(400).json({ error: 'Missing required fields' });
    }

    // Process the webhook based on status
    switch (webhook.status) {
      case StatusCompleted:
        console.log(Payment completed for invoice );
        // Update your database, send confirmation email, fulfill order, etc.
        break;
      case StatusPaidPartial:
        console.log(Partial payment received for invoice );
        // Handle partial payment (e.g., send notification)
        break;
      case StatusExpired:
        console.log(Invoice  expired);
        // Handle expired invoice (e.g., release inventory)
        break;
      case StatusCancelled:
        console.log(Invoice  was cancelled);
        // Handle cancelled invoice (e.g., cleanup)
        break;
      default:
        console.log(Invoice  status changed to: );
    }

    // Always respond with success to acknowledge receipt
    res.status(200).json({ status: 'ok' });
  } catch (error) {
    console.error('Webhook processing error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});
```

### Webhook Data Structure

The webhook payload contains the following fields:

```	typescript
interface WebhookPayload {
  invoice_id: string;
  status: string;
  order_id: string;
  currency: string;
  crypto_amount: number;
  fiat_amount: number;
  fiat_currency: string;
  actual_crypto_amount_paid: number;
  actual_crypto_amount_paid_in_units: number;
  updated_at: string; // ISO 8601 timestamp
}
```

## Complete Example

Here's a complete example showing a typical payment flow:

```	typescript
import { createClient, StatusCompleted } from '@itispay/typescript-client';

async function processPayment() {
  const client = createClient({ apiKey: 'your-api-key' });

  try {
    // 1. Create an invoice
    const fiatAmount = 25.0;
    const expireMin = 30;

    const invoice = await client.createInvoice({
      order_id: ORDER-,
      fiat_amount: fiatAmount,
      fiat_currency: 'USD',
      currency: 'BTC',
      order_name: 'Test Payment',
      expire_min: expireMin,
      callback_url: 'https://your-app.com/webhook'
    });

    console.log('Created invoice:', invoice.invoice_id);
    console.log(Pay  BTC to: );

    // 2. Simulate a payment (for testing)
    await client.simulateWebhook(invoice.invoice_id, StatusCompleted);

    // 3. Check invoice status
    await new Promise(resolve => setTimeout(resolve, 2000)); // Wait for webhook processing

    const updatedInvoice = await client.getInvoice(invoice.invoice_id);
    console.log('Invoice status:', updatedInvoice.status);
    
    if (updatedInvoice.status === StatusCompleted) {
      console.log(Payment confirmed! Received  BTC);
    }
  } catch (error) {
    console.error('Payment processing failed:', error);
  }
}

processPayment();
```

## Development Setup

### Prerequisites

- Node.js 16.0.0 or higher
- npm or yarn

### Local Development

1. **Clone the repository:**
   ```bash
   git clone <repository-url>
   cd itispay-typescript-client
   ```

2. **Install dependencies:**
   ```bash
   npm install
   ```

3. **Build the project:**
   ```bash
   npm run build
   ```

4. **Run the example:**
   ```bash
   npm run example
   ```

5. **Development mode (watch for changes):**
   ```bash
   npm run dev
   ```

### Available Scripts
- pm run build - Build the project
- pm run dev - Watch mode for development
- pm run lint - Run ESLint
- pm run format - Format code with Prettier
- pm run clean - Clean build directory
- pm run example - Run the example

## TypeScript Support

This package is built with TypeScript and provides comprehensive type definitions:

```	typescript
import type { 
  Invoice, 
  CreateInvoiceRequest, 
  ListInvoicesParams,
  APIError 
} from '@itispay/typescript-client';

// All types are fully typed and documented
const request: CreateInvoiceRequest = {
  order_id: 'ORDER-123',
  currency: 'BTC',
  // TypeScript will enforce required fields and types
};
```

## Browser Support

This client works in both Node.js and modern browsers that support:

- Fetch API
- AbortController
- ES2020+ features

For older browsers, you may need to include polyfills.

## Production Usage

```bash
npm install @itispay/typescript-client
```

```	typescript
import { createClient } from '@itispay/typescript-client';

const client = createClient({ 
  apiKey: process.env.ITISPAY_API_KEY 
});
```

## License

This project is licensed under the MIT License - see the LICENSE file for details.

## Support

For API support and integration assistance:

- **Documentation**: Review the [ItIsPay API Reference](https://api-docs.itispay.com/invoice)
- **Testing**: Use the webhook simulation endpoint for integration testing
- **Issues**: Report bugs and feature requests via GitHub issues