npm package: @retakeapi/js
Description: Official JavaScript SDK for Retake API - Abandoned Cart Recovery
Author: Retake
Latest version: 1.0.0

# @retakeapi/js

Official JavaScript SDK for **Retake** — Revenue Recovery Infrastructure for SaaS & E-commerce.

[![npm version](https://img.shields.io/npm/v/@retakeapi/js.svg)](https://www.npmjs.com/package/@retakeapi/js)
[![npm downloads](https://img.shields.io/npm/dm/@retakeapi/js.svg)](https://www.npmjs.com/package/@retakeapi/js)
[![license](https://img.shields.io/npm/l/@retakeapi/js.svg)](https://github.com/retakeapi/js/blob/main/LICENSE)

> ⚠️ **Server-side only** — This SDK is designed for Node.js environments. For browser usage, you **must** use a server-side proxy to protect your API keys. For Next.js applications, use [`@retakeapi/nextjs`](https://www.npmjs.com/package/@retakeapi/nextjs) which handles this automatically.

## Installation

```bash
npm install @retakeapi/js
# or
pnpm add @retakeapi/js
# or
yarn add @retakeapi/js
```

## Quick Start

### SaaS Applications

```typescript
import { Retake } from '@retakeapi/js';

const retake = new Retake({
  apiKey: process.env.RETAKE_API_KEY!
});

// Track a pricing page visit
await retake.track({
  type: 'pricing',
  userId: 'user_123',
  email: 'user@example.com',
  value: 49,
  metadata: { plan: 'pro', billingCycle: 'annual' }
});

// Track a conversion (subscription started)
await retake.trackConversion({
  userId: 'user_123',
  transactionId: 'sub_stripe_abc',
  value: 49
});

// Identify a user
await retake.identify({
  userId: 'user_123',
  email: 'user@example.com',
  name: 'John Doe',
  traits: { plan: 'starter', company: 'Acme Inc' }
});
```

### E-commerce Applications

```typescript
import { Retake } from '@retakeapi/js';

const retake = new Retake({
  apiKey: process.env.RETAKE_API_KEY!
});

// Track cart abandonment
await retake.track({
  type: 'cart',
  userId: 'sess_abc123',
  email: 'customer@example.com',
  value: 149.99,
  items: [
    { id: 'sku_1', name: 'Running Shoes', price: 149.99, quantity: 1 }
  ]
});

// Track order completion
await retake.trackConversion({
  userId: 'sess_abc123',
  transactionId: 'order_456',
  value: 149.99
});
```

## API Reference

### `new Retake(config)`

Create a new Retake client.

```typescript
interface RetakeConfig {
  apiKey: string;      // Your Retake API key (starts with rtk_)
  baseUrl?: string;    // Custom API base URL
  timeout?: number;    // Request timeout in ms (default: 10000)
}
```

### `retake.track(options)`

Track a revenue intent. This is the primary method for all tracking.

```typescript
type IntentType = 
  | 'cart'            // Cart abandonment
  | 'checkout'        // Checkout abandonment
  | 'pricing'         // Pricing page visit
  | 'trial_expiring'  // Trial about to expire
  | 'upgrade'         // Upgrade page visit
  | 'payment_failed'  // Failed payment
  | 'custom';         // Custom intent

interface TrackIntentOptions {
  type: IntentType;
  userId: string;
  value?: number;
  currency?: string;  // Default: "USD"
  email?: string;     // Required for recovery emails
  name?: string;
  metadata?: Record<string, unknown>;
  items?: CartItem[]; // For cart/checkout
}
```

### `retake.trackConversion(options)`

Track a successful conversion.

```typescript
interface TrackConversionOptions {
  userId: string;
  transactionId?: string;
  value: number;
  currency?: string;
  metadata?: Record<string, unknown>;
}
```

### `retake.identify(options)`

Identify a user for personalized recovery.

```typescript
interface IdentifyOptions {
  userId: string;
  email?: string;
  name?: string;
  traits?: Record<string, unknown>;
}
```

### `retake.verifyWebhook(payload, signature, secret)`

Verify a webhook signature.

```typescript
const isValid = retake.verifyWebhook(
  rawBody,
  request.headers['x-webhook-signature'],
  process.env.WEBHOOK_SECRET
);
```

## Use Cases

### Trial Expiration Recovery

```typescript
await retake.track({
  type: 'trial_expiring',
  userId: user.id,
  email: user.email,
  value: 49,
  metadata: {
    plan: 'pro',
    daysRemaining: 3
  }
});
```

### Failed Payment Recovery

```typescript
await retake.track({
  type: 'payment_failed',
  userId: subscription.userId,
  email: subscription.email,
  value: subscription.amount,
  metadata: {
    reason: 'card_declined',
    retryable: true
  }
});
```

### Upgrade Page Drop-off

```typescript
await retake.track({
  type: 'upgrade',
  userId: user.id,
  email: user.email,
  value: 99,
  metadata: {
    currentPlan: 'starter',
    targetPlan: 'pro'
  }
});
```

## Webhook Events

| Event | Description |
|-------|-------------|
| `intent.tracked` | New intent tracked |
| `intent.converted` | Intent converted to sale |
| `intent.expired` | Intent expired without conversion |
| `email.sent` | Recovery email sent |
| `email.opened` | Recovery email opened |
| `email.clicked` | Link in email clicked |
| `payment.failed` | Payment failure detected |
| `payment.recovered` | Failed payment recovered |

## Utilities

```typescript
import { generateSessionId, verifyWebhookSignature } from '@retakeapi/js';

const sessionId = generateSessionId();
const isValid = verifyWebhookSignature(payload, signature, secret);
```

## Security

This SDK is intended for **server-side usage only**.

```
❌ Browser (WRONG)           ✅ Server (CORRECT)
─────────────────────────    ─────────────────────────
Your frontend code           Your backend/API route
      ↓                            ↓
Retake API (blocked)         Retake API (allowed)
                                   ↑
                             API key is here
```

**Why?**
1. CORS policy blocks direct browser requests
2. API keys would be exposed in client code

**Solution:** Always proxy through your backend. For Next.js, use [`@retakeapi/nextjs`](https://www.npmjs.com/package/@retakeapi/nextjs).

## TypeScript

Full TypeScript support with exported types:

```typescript
import type {
  RetakeConfig,
  IntentType,
  CartItem,
  TrackIntentOptions,
  TrackConversionOptions,
  WebhookPayload
} from '@retakeapi/js';
```

## Links

- [Documentation](https://retakeapi.com/docs)
- [Dashboard](https://retakeapi.com/dashboard)
- [@retakeapi/nextjs](https://www.npmjs.com/package/@retakeapi/nextjs)

## License

MIT © [Retake](https://retakeapi.com)