@enviaai/sdk
v1.0.1
Published
Official EnviaAI SDK for Node.js - WhatsApp API made simple
Maintainers
Readme
EnviaAI Node.js SDK
Official Node.js/TypeScript SDK for the EnviaAI WhatsApp API.
Installation
npm install @enviaai/sdk
# or
yarn add @enviaai/sdk
# or
pnpm add @enviaai/sdkQuick Start
import { EnviaAI } from '@enviaai/sdk';
// Initialize the client
const client = new EnviaAI({ apiKey: 'your-api-key' });
// Send a message
await client.messages.send({
instanceId: 'my-instance-id',
to: '5511999999999',
message: 'Hello from EnviaAI!'
});
// List your instances
const instances = await client.instances.list();
console.log(`You have ${instances.length} WhatsApp connections`);Configuration
const client = new EnviaAI({
apiKey: 'your-api-key', // Required (or use ENVIAAI_API_KEY env var)
baseUrl: 'https://api.enviaai.app', // Optional
timeout: 30000, // Optional, milliseconds
maxRetries: 2, // Optional, retry on rate limit/server errors
debug: false // Optional, enable logging
});Environment Variables
You can also configure the SDK using environment variables:
ENVIAAI_API_KEY=your-api-key
ENVIAAI_BASE_URL=https://api.enviaai.app
ENVIAAI_DEBUG=true// Will use environment variables
const client = new EnviaAI({});Messages
Send a Text Message
const result = await client.messages.send({
instanceId: 'my-instance-id',
to: '5511999999999',
message: 'Hello!'
});
console.log(`Message sent: ${result.messageId}`);Send Media
// Send an image
await client.messages.send({
instanceId: 'my-instance-id',
to: '5511999999999',
mediaUrl: 'https://example.com/image.jpg',
caption: 'Check out this image!'
});
// Send a document
await client.messages.send({
instanceId: 'my-instance-id',
to: '5511999999999',
mediaUrl: 'https://example.com/document.pdf',
mediaType: 'document',
filename: 'report.pdf'
});
// Send audio
await client.messages.send({
instanceId: 'my-instance-id',
to: '5511999999999',
mediaUrl: 'https://example.com/audio.mp3',
mediaType: 'audio'
});Get Message Status
const status = await client.messages.getStatus('msg_abc123');
console.log(status.status); // 'sent' | 'delivered' | 'read' | 'failed'List Chats
const chats = await client.messages.getChats({
instanceId: 'my-instance-id',
limit: 50,
unreadOnly: false
});
for (const chat of chats) {
console.log(`${chat.contactName}: ${chat.lastMessage?.content}`);
}Get Chat Messages
const messages = await client.messages.getChatMessages({
instanceId: 'my-instance-id',
chatId: '[email protected]',
limit: 100
});Async Iterator for Chats
for await (const chat of client.messages.getChatsIterator({ instanceId: 'my-instance' })) {
console.log(chat.contactName);
}Instances
List Instances
const instances = await client.instances.list();
for (const instance of instances) {
console.log(`${instance.name}: ${instance.status}`);
}Get Instance Status
const status = await client.instances.getStatus('my-instance-id');
if (status.status === 'connected') {
console.log(`Connected as ${status.phone}`);
} else if (status.qrCode) {
console.log('Scan the QR code to connect');
}Connect / Disconnect
// Connect (generates QR code)
const qr = await client.instances.connect('my-instance-id');
if (qr.status === 'waiting_qr') {
// Display qr.base64 as an image
}
// Disconnect
await client.instances.disconnect('my-instance-id');Webhooks
Create a Webhook
const webhook = await client.webhooks.create({
url: 'https://myapp.com/webhook',
events: ['message.received', 'message.sent'],
secret: 'my-secret-key'
});List Webhooks
const webhooks = await client.webhooks.list();Update a Webhook
await client.webhooks.update('webhook-id', {
events: ['message.received']
});Delete a Webhook
await client.webhooks.delete('webhook-id');Verify Webhook Signature
import { EnviaAI } from '@enviaai/sdk';
app.post('/webhook', (req, res) => {
const signature = req.headers['x-enviaai-signature'] as string;
const isValid = EnviaAI.webhooks.verifySignature(req.body, signature, 'my-secret');
if (!isValid) {
return res.status(401).send('Invalid signature');
}
// Process the webhook
console.log('Received event:', req.body.event);
res.send('OK');
});Error Handling
import { EnviaAI, AuthenticationError, RateLimitError, ValidationError, NotFoundError } from '@enviaai/sdk';
try {
await client.messages.send({ ... });
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof RateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter} seconds`);
} else if (error instanceof ValidationError) {
console.error('Invalid parameters:', error.details);
} else if (error instanceof NotFoundError) {
console.error('Resource not found');
} else {
throw error;
}
}Error Classes
| Class | Description |
|-------|-------------|
| EnviaAIError | Base API error |
| AuthenticationError | Invalid or missing API key |
| RateLimitError | Too many requests (includes retryAfter) |
| ValidationError | Invalid parameters |
| NotFoundError | Resource not found |
| ServerError | Internal server error |
TypeScript Support
This SDK is written in TypeScript and includes full type definitions:
import {
EnviaAI,
EnviaAIError,
AuthenticationError,
RateLimitError,
SendMessageOptions,
Message,
Chat,
Instance,
InstanceStatus,
Webhook
} from '@enviaai/sdk';License
MIT
