npm package: @loyaltyhq/sdk
Description: Official JavaScript/TypeScript SDK for the LoyaltyHQ API
Author: LoyaltyHQ
Latest version: 0.1.2
Deprecated: Package is private — not ready for public use

# @loyaltyhq/sdk

Official JavaScript/TypeScript SDK for the LoyaltyHQ API.

## Installation

```bash
npm install @loyaltyhq/sdk
```

## Quick Start

```typescript
import { LoyaltyHQ } from '@loyaltyhq/sdk';

const client = new LoyaltyHQ('lhq_live_your_api_key_here');

// List partners
const partners = await client.partners.list({ limit: 10 });

// Create a referral
const referral = await client.referrals.create({
  partner_id: 'partner_123',
  referral_name: 'John Doe',
  referral_email: 'john@example.com',
});

// Award points
const transaction = await client.points.award({
  partner_id: 'partner_123',
  points: 100,
  transaction_type: 'bonus',
  description: 'Welcome bonus',
});
```

## Configuration

```typescript
const client = new LoyaltyHQ('lhq_live_your_api_key_here', {
  baseUrl: 'https://api.loyaltyhq.io/v1', // Default
  timeout: 30000, // 30 seconds (default)
  maxRetries: 3, // Number of retries (default)
});
```

## Resources

### Partners

```typescript
// List partners with filters
const partners = await client.partners.list({
  status: 'active',
  tier: 'gold',
  limit: 50,
});

// Get a specific partner
const partner = await client.partners.get('partner_123');

// Create a new partner
const newPartner = await client.partners.create({
  email: 'partner@example.com',
  name: 'Jane Doe',
  company: 'Acme Inc',
});

// Update a partner
const updated = await client.partners.update('partner_123', {
  tier: 'platinum',
});
```

### Referrals

```typescript
// List referrals
const referrals = await client.referrals.list({
  partner_id: 'partner_123',
  status: 'pending',
});

// Create a referral
const referral = await client.referrals.create({
  partner_id: 'partner_123',
  referral_name: 'John Smith',
  referral_email: 'john@example.com',
  notes: 'Met at conference',
});

// Update referral (mark as converted)
const converted = await client.referrals.update('referral_123', {
  status: 'converted',
  revenue: 5000,
});
```

### Points

```typescript
// List transactions
const transactions = await client.points.list({
  partner_id: 'partner_123',
  transaction_type: 'bonus',
});

// Award points
const award = await client.points.award({
  partner_id: 'partner_123',
  points: 500,
  transaction_type: 'bonus',
  description: 'Q1 performance bonus',
});

// Deduct points
const deduction = await client.points.deduct({
  partner_id: 'partner_123',
  points: 100,
  transaction_type: 'adjustment',
  description: 'Correction for duplicate award',
});
```

### Rewards

```typescript
// List available rewards
const rewards = await client.rewards.list({
  type: 'gift_card',
  is_active: true,
  max_points: 1000,
});

// Get a specific reward
const reward = await client.rewards.get('reward_123');
```

### Redemptions

```typescript
// List redemptions
const redemptions = await client.redemptions.list({
  partner_id: 'partner_123',
  status: 'pending',
});

// Create a redemption
const redemption = await client.redemptions.create({
  partner_id: 'partner_123',
  reward_id: 'reward_456',
  notes: 'Please ship to office address',
});

// Update redemption (mark as completed)
const completed = await client.redemptions.update('redemption_123', {
  status: 'completed',
  redemption_code: 'GIFT-CODE-123',
});
```

### Campaigns

```typescript
// List campaigns
const campaigns = await client.campaigns.list({ is_active: true });

// Create a campaign
const campaign = await client.campaigns.create({
  name: 'Q2 Double Points',
  bonus_type: 'multiplier',
  bonus_multiplier: 2,
  starts_at: '2026-04-01T00:00:00Z',
  ends_at: '2026-06-30T23:59:59Z',
});

// Update a campaign
const updated = await client.campaigns.update('campaign_123', {
  is_active: false,
});

// Delete a campaign
await client.campaigns.delete('campaign_123');
```

### Tags

```typescript
// List all partner tags
const tags = await client.tags.list();
```

### Training

```typescript
// List training modules
const modules = await client.training.list({ category: 'product', active_only: true });

// Create a training module
const module = await client.training.create({
  module_key: 'product-overview-v1',
  title: 'Product Overview',
  content: '# Introduction\n\nWelcome to our product...',
  category: 'product',
  points_reward: 100,
});

// Update a training module
const updated = await client.training.update('module_123', {
  is_active: true,
  points_reward: 150,
});

// Generate module content via AI (enterprise only)
const draft = await client.training.generate({
  topic: 'Cloud security best practices',
  context: 'Target audience: enterprise IT managers',
});
```

### Dashboard

```typescript
// Get programme statistics
const stats = await client.dashboard.stats();
console.log(stats.total_partners);
console.log(stats.active_referrals);
console.log(stats.pending_redemptions);
console.log(stats.points_in_circulation);
```

### Tenant

```typescript
// Get tenant configuration
const tenant = await client.tenant.get();

// Update branding and points config
const updated = await client.tenant.update({
  branding: {
    primary_color: '#1a73e8',
    program_name: 'Partner Rewards',
    company_name: 'Acme Inc',
  },
  points_config: {
    confirmed_referral: 200,
    closed_won_base: 500,
  },
});
```

### Webhooks

```typescript
// List registered webhooks
const webhooks = await client.webhooks.list();

// Register a new webhook (signing secret returned once)
const result = await client.webhooks.create({
  name: 'CRM Sync',
  url: 'https://example.com/webhooks/loyaltyhq',
  events: ['partner.created', 'referral.status_changed', 'points.awarded'],
});
console.log(result.webhook);
console.log(result.signing_secret); // store securely — shown only once

// Delete a webhook
await client.webhooks.delete('webhook_123');

// Send a test payload to verify the endpoint
const testResult = await client.webhooks.test('webhook_123');
console.log(testResult.success, testResult.status_code, testResult.response_time_ms);
```

### Credits

```typescript
// Get current credit balance
const credits = await client.credits.balance();
console.log(credits.balance);
console.log(credits.used_this_period);
```

## Pagination

All list methods return paginated responses:

```typescript
const page1 = await client.partners.list({ limit: 20 });
console.log(page1.data); // Array of partners
console.log(page1.has_more); // true if more pages exist
console.log(page1.next_cursor); // Cursor for next page

if (page1.has_more && page1.next_cursor) {
  const page2 = await client.partners.list({
    limit: 20,
    cursor: page1.next_cursor,
  });
}
```

## Error Handling

The SDK provides typed error classes for different error scenarios:

```typescript
import {
  LoyaltyHQ,
  LoyaltyHQError,
  AuthenticationError,
  ValidationError,
  NotFoundError,
  RateLimitError,
} from '@loyaltyhq/sdk';

try {
  await client.partners.create({ email: 'invalid' });
} catch (error) {
  if (error instanceof AuthenticationError) {
    // Invalid or expired API key (401)
    console.error('Check your API key');
  } else if (error instanceof ValidationError) {
    // Invalid request data (400)
    console.error('Validation errors:', error.errors);
  } else if (error instanceof NotFoundError) {
    // Resource not found (404)
    console.error('Partner not found');
  } else if (error instanceof RateLimitError) {
    // Rate limit exceeded (429)
    console.error(`Retry after ${error.retryAfter} seconds`);
  } else if (error instanceof LoyaltyHQError) {
    // Other API errors
    console.error(error.message, error.status, error.requestId);
  }
}
```

### Error Types

| Error Class | HTTP Status | Description |
|-------------|-------------|-------------|
| `AuthenticationError` | 401 | Invalid or expired API key |
| `PermissionError` | 403 | Insufficient permissions |
| `NotFoundError` | 404 | Resource not found |
| `ValidationError` | 400 | Invalid request parameters |
| `RateLimitError` | 429 | Rate limit exceeded |
| `ConflictError` | 409 | Resource conflict (e.g., duplicate) |
| `ServerError` | 5xx | Server-side error |
| `TimeoutError` | - | Request timed out |
| `NetworkError` | - | Network connectivity issue |

## TypeScript

The SDK is written in TypeScript and exports all types:

```typescript
import type {
  Partner,
  PartnerCreateParams,
  Referral,
  ReferralStatus,
  PointsTransaction,
  Reward,
  Redemption,
  PaginatedResponse,
} from '@loyaltyhq/sdk';
```

## API Key Format

API keys follow the format:
- Live keys: `lhq_live_` followed by 32 characters
- Test keys: `lhq_test_` followed by 32 characters

Get your API key from the [LoyaltyHQ Dashboard](https://app.loyaltyhq.io/settings/api).

## License

MIT