> ## Documentation Index
> Fetch the complete documentation index at: https://docs.finkare.io/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK TypeScript

> Installation, configuration et utilisation du SDK TypeScript officiel Finkare avec retry automatique et pagination.

## Installation

```bash theme={null}
npm install @finkare/api-sdk
# ou
pnpm add @finkare/api-sdk
# ou
yarn add @finkare/api-sdk
```

## Configuration

```typescript theme={null}
import { FinkareClient } from '@finkare/api-sdk';

// Production
const finkare = new FinkareClient('fk_live_xxx');

// Sandbox
const finkareSandbox = new FinkareClient('fk_test_xxx', {
  baseUrl: 'https://api-sandbox.finkare.io',
});

// Options avancées
const finkareAdvanced = new FinkareClient('fk_live_xxx', {
  baseUrl: 'https://api.finkare.io',  // défaut
  timeout: 30000,                       // 30s (défaut)
  maxRetries: 3,                        // retry sur 429 (défaut)
});
```

## Ressources disponibles

Le client expose les ressources suivantes :

| Ressource | Propriété          | Description                          |
| --------- | ------------------ | ------------------------------------ |
| Factures  | `finkare.invoices` | CRUD, import en masse, annulation    |
| Débiteurs | `finkare.debtors`  | Liste et détails                     |
| Paiements | `finkare.payments` | Consultation                         |
| Webhooks  | `finkare.webhooks` | CRUD, rotation de secret, deliveries |
| Workflow  | `finkare.workflow` | Statut et déclenchement d'actions    |
| API Keys  | `finkare.apiKeys`  | Gestion des clés                     |

## Factures

### Lister

```typescript theme={null}
const invoices = await finkare.invoices.list({
  status: 'in_recovery',
  page: '1',
  limit: '50',
});

console.log(invoices.data); // Invoice[]
```

### Pagination automatique

```typescript theme={null}
// Itère automatiquement sur toutes les pages
for await (const invoice of finkare.invoices.listAll(50)) {
  console.log(`${invoice.invoiceNumber} — ${invoice.amountCents / 100} EUR`);
}
```

### Créer

```typescript theme={null}
const invoice = await finkare.invoices.create({
  invoiceNumber: 'FAC-2026-042',
  amount: 285000,
  issueDate: '2026-02-15',
  dueDate: '2026-03-15',
  debtor: {
    name: 'Martin Consulting SAS',
    email: 'direction@martin-consulting.fr',
    phone: '+33678901234',
    siret: '83965478200012',
  },
});

console.log(invoice.data.id); // UUID
```

### Import en masse

```typescript theme={null}
const result = await finkare.invoices.bulkImport({
  invoices: [
    {
      invoiceNumber: 'FAC-2026-100',
      amount: 75000,
      issueDate: '2026-03-01',
      dueDate: '2026-04-01',
      debtor: { name: 'Lefebvre SARL', email: 'compta@lefebvre.fr' },
    },
    {
      invoiceNumber: 'FAC-2026-101',
      amount: 320000,
      issueDate: '2026-03-15',
      dueDate: '2026-04-15',
      debtor: { name: 'Moreau Industries SA', email: 'finance@moreau.fr' },
    },
  ],
  autoStartWorkflow: true,
});

console.log(`${result.data.imported} factures importées`);
```

### Annuler

```typescript theme={null}
await finkare.invoices.cancel(
  'c3d4e5f6-a1b2-7890-cdef-1234567890ab',
  'Paiement reçu directement'
);
```

## Webhooks

### Configurer

```typescript theme={null}
const webhook = await finkare.webhooks.create({
  url: 'https://api.votre-entreprise.fr/webhooks/finkare',
  events: ['payment.received', 'invoice.status_changed'],
  description: 'Production webhook',
});

// Sauvegardez le secret !
console.log(webhook.data.secret); // whsec_...
```

### Rotation de secret

```typescript theme={null}
const rotated = await finkare.webhooks.rotateSecret(
  'e5f6a7b8-c1d2-9012-ef01-345678901bcd'
);
console.log(rotated.data.secret); // Nouveau secret
```

### Historique des deliveries

```typescript theme={null}
const deliveries = await finkare.webhooks.getDeliveries(
  'e5f6a7b8-c1d2-9012-ef01-345678901bcd'
);

for (const d of deliveries.data) {
  console.log(`${d.eventType} — ${d.status} (${d.attempts} tentatives)`);
}
```

## Workflow

```typescript theme={null}
// Statut du workflow
const status = await finkare.workflow.getStatus(
  'c3d4e5f6-a1b2-7890-cdef-1234567890ab'
);
console.log(status.data.currentStep); // ex: "relance_email_2"

// Déclencher une action
await finkare.workflow.trigger(
  'c3d4e5f6-a1b2-7890-cdef-1234567890ab'
);
```

## Gestion des clés API

```typescript theme={null}
// Créer une nouvelle clé
const key = await finkare.apiKeys.create({
  name: 'Integration ERP',
  scopes: ['invoices:read', 'invoices:write', 'payments:read'],
  tier: 'pro',
});
console.log(key.data.apiKey); // Affiché une seule fois

// Rotation
const rotated = await finkare.apiKeys.rotate('key-uuid');
console.log(rotated.data.apiKey);

// Révocation
await finkare.apiKeys.revoke('key-uuid');
```

## Gestion des erreurs

Le SDK distingue deux types d'erreurs :

```typescript theme={null}
import { FinkareApiError, FinkareNetworkError } from '@finkare/api-sdk';

try {
  await finkare.invoices.get('invalid-uuid');
} catch (error) {
  if (error instanceof FinkareApiError) {
    // Erreur API (4xx/5xx avec body structuré)
    console.error(`Code: ${error.code}`);     // ex: "RES_001"
    console.error(`Message: ${error.message}`); // ex: "Resource not found"
    console.error(`Status: ${error.status}`);   // ex: 404
  } else if (error instanceof FinkareNetworkError) {
    // Erreur réseau (timeout, DNS, etc.)
    console.error(`Network error: ${error.message}`);
    console.error(`Cause: ${error.cause}`);
  }
}
```

## Retry automatique

Le SDK retente automatiquement les requêtes en cas de rate limiting (HTTP 429) avec un backoff exponentiel :

| Tentative | Délai                         |
| --------- | ----------------------------- |
| 1         | Valeur de `Retry-After` ou 1s |
| 2         | Valeur de `Retry-After` ou 2s |
| 3         | Valeur de `Retry-After` ou 4s |

Le nombre maximum de retries est configurable via `maxRetries` (défaut : 3).

## TypeScript — Types exportés

```typescript theme={null}
import type {
  Invoice,
  CreateInvoiceDto,
  UpdateInvoiceDto,
  BulkImportDto,
  Debtor,
  Payment,
  Webhook,
  CreateWebhookDto,
  WorkflowStatus,
  ApiKeyInfo,
  ApiResponse,
  Pagination,
} from '@finkare/api-sdk';
```
