@zapyapi/sdk
v1.0.0-beta.13
Published
Official TypeScript SDK for ZapyAPI - WhatsApp API
Downloads
1,345
Maintainers
Readme
@zapyapi/sdk
Official TypeScript SDK for ZapyAPI - REST API for WhatsApp integration.
Send messages, manage instances, and receive webhooks with a simple API. No infrastructure to manage.
Installation
npm install @zapyapi/sdk
# or
yarn add @zapyapi/sdk
# or
pnpm add @zapyapi/sdkQuick Start
import { ZapyClient } from '@zapyapi/sdk';
// Initialize the client
const client = new ZapyClient({
apiKey: 'your-api-key', // Get yours at https://app.zapyapi.com/
});
// Send a text message
const response = await client.messages.sendText('my-instance', {
to: '5511999999999',
text: 'Hello from ZapyAPI SDK!',
});
console.log(`Message sent with ID: ${response.messageId}`);Features
- Type-safe - Full TypeScript support with comprehensive types
- Dual Format - ESM and CommonJS support out of the box
- Modern - Works with Node.js 18+
- Simple - Intuitive API design for great developer experience
- Complete - Covers all ZapyAPI endpoints (instances, messages, webhooks)
API Reference
Client Initialization
import { ZapyClient, createClient } from '@zapyapi/sdk';
// Using constructor
const client = new ZapyClient({
apiKey: 'your-api-key',
baseUrl: 'https://api.zapyapi.com/api', // optional
timeout: 30000, // optional, in milliseconds
});
// Using factory function
const client = createClient({ apiKey: 'your-api-key' });Instances
// List all instances
const instances = await client.instances.list({ page: 1, limit: 10 });
console.log(`Total: ${instances.total} instances`);
// Create a new instance (Partner only)
const instance = await client.instances.create({
name: 'My Instance',
metadata: { department: 'sales' },
});
// Get QR code for connection
const qr = await client.instances.getQRCode('my-instance');
// qr.qrCode is a base64 encoded image
// Restart an instance
await client.instances.restart('my-instance');
// Logout from WhatsApp
await client.instances.logout('my-instance');Messages
Send Text Message
const response = await client.messages.sendText('my-instance', {
to: '5511999999999',
text: 'Hello, World!',
quotedMessageId: 'ABC123...', // optional, for replies
});Send Image
// Using URL
await client.messages.sendImage('my-instance', {
to: '5511999999999',
url: 'https://example.com/image.jpg',
caption: 'Check this out!', // optional
});
// Using Base64
await client.messages.sendImage('my-instance', {
to: '5511999999999',
base64: 'data:image/jpeg;base64,...',
caption: 'Check this out!',
});Send Video
await client.messages.sendVideo('my-instance', {
to: '5511999999999',
url: 'https://example.com/video.mp4',
caption: 'Watch this!',
});Send Audio Note (Voice Message)
await client.messages.sendAudioNote('my-instance', {
to: '5511999999999',
url: 'https://example.com/audio.ogg',
});Send Document
await client.messages.sendDocument('my-instance', {
to: '5511999999999',
url: 'https://example.com/document.pdf',
filename: 'report.pdf',
caption: 'Here is the report',
});Other Message Operations
// Forward a message
await client.messages.forward('my-instance', {
to: '5511888888888',
messageId: 'ABC123...',
});
// Edit a message
await client.messages.edit('my-instance', {
messageId: 'ABC123...',
text: 'Updated message text',
});
// Mark as read
await client.messages.markAsRead('my-instance', 'ABC123...');
// Delete a message
await client.messages.delete('my-instance', 'ABC123...');
// Get media download link
const media = await client.messages.getMediaDownloadLink('my-instance', 'ABC123...');
console.log(media.url);Webhooks
// Configure webhook
await client.webhooks.configure({
url: 'https://your-server.com/webhook',
secret: 'your-secret-min-16-chars', // for HMAC-SHA256 verification
isActive: true,
});
// Get current configuration
const config = await client.webhooks.getConfig();
// Check queue status
const status = await client.webhooks.getQueueStatus();
console.log(`Pending: ${status.pendingCount}, Failed: ${status.failedCount}`);
// Resume paused/failed webhooks
const result = await client.webhooks.resume();
console.log(`Resumed ${result.resumedCount} webhooks`);
// Delete webhook configuration
await client.webhooks.deleteConfig();Error Handling
The SDK provides detailed error classes for different failure scenarios:
import {
ZapyClient,
ZapyApiError,
AuthenticationError,
RateLimitError,
NetworkError,
TimeoutError,
ValidationError,
} from '@zapyapi/sdk';
try {
await client.messages.sendText('my-instance', {
to: '5511999999999',
text: 'Hello!',
});
} catch (error) {
if (error instanceof TimeoutError) {
// Request timed out
console.error(`Request timed out after ${error.timeout}ms`);
console.error(`Request: ${error.method} ${error.url}`);
} else if (error instanceof NetworkError) {
// Network failure (no response received)
console.error(`Network error: ${error.message}`);
console.error(`Error code: ${error.code}`); // e.g., ECONNREFUSED
} else if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof RateLimitError) {
console.error(`Rate limited. Retry after: ${error.retryAfter}ms`);
console.error(`Retry at: ${error.getRetryAfterDate()}`);
} else if (error instanceof ZapyApiError) {
console.error(`API Error [${error.code}]: ${error.message}`);
console.error(`Status: ${error.statusCode}`);
console.error(`Request ID: ${error.requestId}`);
console.error(`Request: ${error.method} ${error.url}`);
// For debugging/logging
console.error(error.toDetailedString());
// Or serialize to JSON
console.error(JSON.stringify(error.toJSON(), null, 2));
}
}Error Classes
| Error Class | Description |
|-------------|-------------|
| ZapyError | Base error class for all SDK errors |
| ZapyApiError | API returned an error response (4xx, 5xx) |
| AuthenticationError | Invalid or missing API key (401) |
| RateLimitError | Rate limit exceeded (429) |
| NetworkError | Network failure, no response received |
| TimeoutError | Request timed out |
| ValidationError | Input validation failed |
| InstanceNotFoundError | Instance not found (404) |
Utilities
import { normalizePhone, isValidPhone, isGroup, extractPhone } from '@zapyapi/sdk';
// Normalize phone numbers
normalizePhone('11999999999'); // '5511999999999'
normalizePhone('+5511999999999'); // '5511999999999'
// Validate phone numbers
isValidPhone('5511999999999'); // true
isValidPhone('[email protected]'); // true
// Check if JID is a group
isGroup('[email protected]'); // true
isGroup('[email protected]'); // false
// Extract phone from JID
extractPhone('[email protected]'); // '5511999999999'Webhook Event Types
The SDK provides fully typed webhook events with discriminated unions for each message type:
import {
ZapyWebhookPayload,
ZapyEventTypes,
isTextMessage,
isImageMessage,
isVideoMessage,
isAudioMessage,
} from '@zapyapi/sdk';
function handleWebhook(payload: ZapyWebhookPayload) {
console.log(`Event from instance: ${payload.instanceId}`);
switch (payload.event) {
case ZapyEventTypes.MESSAGE:
// payload.data is ZapyMessage (discriminated union)
const message = payload.data;
if (isTextMessage(message)) {
console.log(`Text: ${message.text}`);
} else if (isImageMessage(message)) {
console.log(`Image: ${message.url}, caption: ${message.caption}`);
} else if (isVideoMessage(message)) {
console.log(`Video: ${message.url}`);
} else if (isAudioMessage(message)) {
console.log(`Audio: ${message.url}, duration: ${message.duration}s`);
}
break;
case ZapyEventTypes.MESSAGE_STATUS:
console.log(`Message ${payload.data.messageId} status: ${payload.data.status}`);
break;
case ZapyEventTypes.QR_CODE:
console.log(`QR Code received, attempt: ${payload.data.attempt}`);
break;
case ZapyEventTypes.INSTANCE_STATUS:
console.log(`Instance status: ${payload.data.status}`);
break;
}
}Available Message Type Guards
import {
isTextMessage,
isImageMessage,
isVideoMessage,
isAudioMessage,
isDocumentMessage,
isStickerMessage,
isLocationMessage,
isContactMessage,
isReactionMessage,
isPollMessage,
isMediaMessage, // matches any media type
} from '@zapyapi/sdk';Requirements
- Node.js 18 or higher
- TypeScript 5.0+ (for TypeScript users)
CommonJS Usage
The SDK also works with CommonJS:
const { ZapyClient } = require('@zapyapi/sdk');
const client = new ZapyClient({ apiKey: 'your-api-key' });Low-Level REST API Client
For advanced use cases, the SDK also exports an auto-generated REST client with full type definitions from the OpenAPI spec:
import { ZapyRestApi } from '@zapyapi/sdk';
const api = new ZapyRestApi({
baseURL: 'https://api.zapyapi.com',
headers: {
'x-api-key': 'your-api-key',
},
});
// Direct REST calls with full type safety
const response = await api.instances.managerInstancesControllerListInstances({
page: 1,
limit: 10,
});
// Send a message
await api.sendMessage.sendMessageControllerSendTextMessage(
'my-instance',
{ to: '5511999999999', text: 'Hello!' }
);License
MIT
Links
Support
- Email: [email protected]
Made with :heart: by ZapyAPI
