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

# JavaScript SDK

> Integrate Zeplo's WhatsApp Business API into your JavaScript or TypeScript application using the official @zeplo/sdk package.

# JavaScript SDK

The official Zeplo JavaScript SDK provides a typed, promise-based interface for the WhatsApp Business API. It works in Node.js, Deno, Bun, and modern browsers.

> [!NOTE]
>
> The SDK is fully written in TypeScript and ships with built-in type definitions. No additional `@types` package is needed.

## Installation

**1. Install the package**

```bash npm theme={null}
npm install @zeplo/sdk
```

```bash yarn theme={null}
yarn add @zeplo/sdk
```

```bash pnpm theme={null}
pnpm add @zeplo/sdk
```

**2. Verify installation**

```typescript theme={null}
import { ZeploClient } from "@zeplo/sdk";

console.log("Zeplo SDK loaded successfully");
```

## Initialization

Create a new `ZeploClient` instance with your configuration:

```typescript theme={null}
import { ZeploClient } from "@zeplo/sdk";

const client = new ZeploClient({
  apiKey: "zp_live_abc123...",       // Required — your Zeplo API key
  apiSecret: "zp_live_secret_abc123...", // Required — your Zeplo API secret key
  channelId: "ch_whatsapp_01...",    // Required — your WhatsApp channel ID
  baseURL: "https://zeplo.ai/api/v1" // Optional — defaults to Zeplo cloud
});
```

> [!NOTE]
>
> Store your API key in an environment variable such as `ZEPLO_API_KEY`. Never commit secrets to source control.

### Environment Variables

```typescript theme={null}
const client = new ZeploClient({
  apiKey: process.env.ZEPLO_API_KEY!,
  apiSecret: process.env.ZEPLO_API_SECRET!,
  channelId: process.env.ZEPLO_CHANNEL_ID!,
});
```

## Operations

### Messaging

**JavaScript/TypeScript**

```typescript theme={null}
// Send a template message
const templateMessage = await client.messaging.sendTemplate({
  to: "+1234567890",
  templateName: "welcome_message",
  language: "en",
  parameters: ["John", "Order #1234"],
});

console.log(templateMessage.messageId);

// Send a reply to an existing conversation
const reply = await client.messaging.sendReply({
  conversationId: "conv_abc123",
  text: "Thank you for reaching out! We will get back to you shortly.",
  attachments: [
    {
      type: "image",
      url: "https://example.com/photo.jpg",
      caption: "Product photo",
    },
  ],
});
```

**Python**

```python theme={null}
# Send a template message
template_message = client.messaging.send_template(
    to="+1234567890",
    template_name="welcome_message",
    language="en",
    parameters=["John", "Order #1234"],
)

print(template_message.message_id)

# Send a reply to an existing conversation
reply = client.messaging.send_reply(
    conversation_id="conv_abc123",
    text="Thank you for reaching out! We will get back to you shortly.",
    attachments=[
        {
            "type": "image",
            "url": "https://example.com/photo.jpg",
            "caption": "Product photo",
        }
    ],
)
```

### Contacts

**JavaScript/TypeScript**

```typescript theme={null}
// Create a new contact
const contact = await client.contacts.create({
  phone: "+1234567890",
  name: "Jane Smith",
  tags: ["vip", "enterprise"],
  customFields: {
    company: "Acme Corp",
    plan: "pro",
  },
});

// List contacts with filters
const contacts = await client.contacts.list({
  limit: 50,
  tags: ["vip"],
  search: "Jane",
});

// Update a contact
const updated = await client.contacts.update(contact.id, {
  tags: ["vip", "enterprise", "upsell"],
  customFields: {
    plan: "enterprise",
  },
});
```

**Python**

```python theme={null}
# Create a new contact
contact = client.contacts.create(
    phone="+1234567890",
    name="Jane Smith",
    tags=["vip", "enterprise"],
    custom_fields={
        "company": "Acme Corp",
        "plan": "pro",
    },
)

# List contacts with filters
contacts = client.contacts.list(
    limit=50,
    tags=["vip"],
    search="Jane",
)

# Update a contact
updated = client.contacts.update(
    contact.id,
    tags=["vip", "enterprise", "upsell"],
    custom_fields={
        "plan": "enterprise",
    },
)
```

### Campaigns

**JavaScript/TypeScript**

```typescript theme={null}
// Create a campaign
const campaign = await client.campaigns.create({
  name: "Summer Sale 2026",
  templateName: "summer_promo",
  segmentIds: ["seg_abc123", "seg_def456"],
  scheduledAt: "2026-06-01T09:00:00Z",
  language: "en",
});

// Launch the campaign immediately
await client.campaigns.launch(campaign.id);

// Get campaign analytics
const stats = await client.campaigns.getStats(campaign.id);
console.log(`Sent: ${stats.sent}, Delivered: ${stats.delivered}`);
```

**Python**

```python theme={null}
# Create a campaign
campaign = client.campaigns.create(
    name="Summer Sale 2026",
    template_name="summer_promo",
    segment_ids=["seg_abc123", "seg_def456"],
    scheduled_at="2026-06-01T09:00:00Z",
    language="en",
)

# Launch the campaign immediately
client.campaigns.launch(campaign.id)

# Get campaign analytics
stats = client.campaigns.get_stats(campaign.id)
print(f"Sent: {stats.sent}, Delivered: {stats.delivered}")
```

### Webhooks

**JavaScript/TypeScript**

```typescript theme={null}
// Register a webhook endpoint
const webhook = await client.webhooks.create({
  url: "https://yourapp.com/webhooks/zeplo",
  events: ["message.received", "message.delivered", "conversation.opened"],
  secret: "whsec_abc123...",
});

// List existing webhooks
const webhooks = await client.webhooks.list();

// Verify a webhook signature (for your endpoint handler)
import { verifyWebhookSignature } from "@zeplo/sdk";

const isValid = verifyWebhookSignature(
  request.body,
  request.headers["x-zeplo-signature"],
  "whsec_abc123..."
);
```

**Python**

```python theme={null}
# Register a webhook endpoint
webhook = client.webhooks.create(
    url="https://yourapp.com/webhooks/zeplo",
    events=["message.received", "message.delivered", "conversation.opened"],
    secret="whsec_abc123...",
)

# List existing webhooks
webhooks = client.webhooks.list()

# Verify a webhook signature (for your endpoint handler)
from zeplo import verify_webhook_signature

is_valid = verify_webhook_signature(
    request.body,
    request.headers["x-zeplo-signature"],
    "whsec_abc123...",
)
```

## Error Handling

All SDK errors inherit from the base `ZeploError` class. Wrap calls in try/catch blocks to handle specific failure cases:

```typescript theme={null}
import {
  ZeploError,
  ZeploAuthenticationError,
  ZeploRateLimitError,
  ZeploValidationError,
  ZeploNotFoundError,
} from "@zeplo/sdk";

try {
  const message = await client.messaging.sendTemplate({
    to: "+1234567890",
    templateName: "welcome_message",
    language: "en",
  });
} catch (error) {
  if (error instanceof ZeploAuthenticationError) {
    console.error("Invalid API key:", error.message);
  } else if (error instanceof ZeploRateLimitError) {
    console.error("Rate limited. Retry after:", error.retryAfter, "seconds");
  } else if (error instanceof ZeploValidationError) {
    console.error("Validation failed:", error.details);
  } else if (error instanceof ZeploNotFoundError) {
    console.error("Resource not found:", error.resourceId);
  } else if (error instanceof ZeploError) {
    console.error("Zeplo error:", error.message, error.code);
  } else {
    throw error;
  }
}
```

> [!WARNING]
>
> `ZeploRateLimitError` includes a `retryAfter` property (in seconds). Implement exponential backoff rather than retrying immediately.

## TypeScript Types

The SDK exports all request and response types so you can type your own functions:

```typescript theme={null}
import type {
  // Request types
  SendTemplateRequest,
  SendReplyRequest,
  CreateContactRequest,
  CreateCampaignRequest,

  // Response types
  MessageResponse,
  ContactResponse,
  CampaignResponse,
  PaginatedResponse,

  // Configuration
  ZeploConfig,

  // Enums
  MessageStatus,
  ConversationStatus,
} from "@zeplo/sdk";

async function sendMessage(
  client: ZeploClient,
  payload: SendTemplateRequest
): Promise<MessageResponse> {
  return client.messaging.sendTemplate(payload);
}
```

## FAQ

> **Does the SDK support tree-shaking?**
>
> Yes. The `@zeplo/sdk` package is published as ES modules with per-module entry points. If you only import the specific sub-modules you need, your bundler can eliminate unused code from the final build.

> **Can I use the SDK in the browser?**
>
> The SDK works in all modern browsers (Chrome, Firefox, Safari, Edge). However, webhook signature verification requires Node.js APIs (`crypto`). For browser-only usage, use the REST-based operations and perform webhook verification on your server.

> **How does rate limiting work?**
>
> The SDK does not automatically retry on rate-limit errors. When you receive a `ZeploRateLimitError`, inspect the `retryAfter` property and wait that many seconds before retrying. For high-throughput scenarios, consider implementing a queue with concurrency control.

> **Are requests retried automatically?**
>
> By default, the SDK retries failed requests up to 3 times with exponential backoff. You can customize this behavior through the client configuration:
>
> ```typescript theme={null}
> const client = new ZeploClient({
>   apiKey: process.env.ZEPLO_API_KEY!,
>   apiSecret: process.env.ZEPLO_API_SECRET!,
>   channelId: process.env.ZEPLO_CHANNEL_ID!,
>   maxRetries: 5,
>   retryDelay: 1000, // base delay in ms
> });
> ```

> **Does the SDK support WebSocket connections?**
>
> The REST SDK (`@zeplo/sdk`) handles HTTP-based operations only. For real-time WebSocket communication, use Socket.IO directly or the dedicated `@zeplo/ws` package. See the [WebSocket API](https://docs.zeplo.ai/websocket-api/introduction) documentation for details.

## Next Steps

> **API Reference**
>
> Browse the full REST API endpoints, parameters, and response schemas.

> **Python SDK**
>
> Use the official Python SDK for server-side and data pipeline integrations.

> **Webhooks**
>
> Set up real-time event notifications for incoming messages and status updates.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.