@maxpantech/evolution-api-wrapper
v1.0.1
Published
TypeScript wrapper for Evolution API - WhatsApp integration made simple
Maintainers
Readme
Evolution API Wrapper
A modern, type-safe TypeScript wrapper for Evolution API, providing a simple and intuitive interface for WhatsApp integration.
✨ Features
- 🎯 Full TypeScript support with complete type definitions
- 🔒 Type-safe API with intellisense and auto-completion
- 📦 Dual package - Works with both ESM and CommonJS
- 🌳 Tree-shakeable - Only import what you need
- 🚀 Modern axios-based HTTP client
- 📝 Comprehensive documentation with examples
- ⚡ Zero dependencies (except peer dependency on axios)
📦 Installation
npm install @maxpantech/evolution-api-wrapper axiosor with yarn:
yarn add @maxpantech/evolution-api-wrapper axiosor with pnpm:
pnpm add @maxpantech/evolution-api-wrapper axios🚀 Quick Start
TypeScript
import { EvolutionAPI } from '@maxpantech/evolution-api-wrapper';
// Create client instance
const client = new EvolutionAPI({
baseUrl: 'https://your-evolution-api.com',
apiKey: 'your-api-key-here'
});
// Create an instance
const result = await client.createInstance('my-whatsapp-instance');
if (result.success) {
console.log('Instance created:', result.data);
console.log('QR Code:', result.data?.qrcode);
}
// Send a text message
await client.sendTextMessage(
'my-whatsapp-instance',
'5511999999999',
'Hello from TypeScript!'
);JavaScript (CommonJS)
const { EvolutionAPI } = require('@maxpantech/evolution-api-wrapper');
const client = new EvolutionAPI({
baseUrl: process.env.EVOLUTION_API_URL,
apiKey: process.env.EVOLUTION_API_KEY
});
// Use the client...Using the Singleton (Recommended)
The easiest way to get started is using the pre-configured singleton instance:
import { evolutionClient } from '@maxpantech/evolution-api-wrapper';
// Set environment variables first:
// EVOLUTION_API_URL=https://your-evolution-api.com
// EVOLUTION_API_KEY=your-api-key-here
// Use directly without instantiation
const result = await evolutionClient.createInstance('my-whatsapp-instance');
if (result.success) {
console.log('Instance created:', result.data);
}
// Send a text message
await evolutionClient.sendTextMessage(
'my-whatsapp-instance',
'5511999999999',
'Hello from the singleton!'
);
## 📖 API Documentation
### Configuration
```typescript
interface EvolutionAPIConfig {
baseUrl: string; // Evolution API base URL
apiKey: string; // Global API key
timeout?: number; // Request timeout in ms (default: 30000)
}Response Format
All methods return a standardized response:
interface EvolutionAPIResponse<T> {
success: boolean; // Whether the operation succeeded
data: T | null; // Response data (null on error)
error: string | null; // Error message (null on success)
}Example:
const result = await client.createInstance('my-instance');
if (result.success) {
console.log('Data:', result.data);
} else {
console.error('Error:', result.error);
}🔧 Available Methods
Instance Management
createInstance(instanceName, options?)
Creates a new WhatsApp instance.
const result = await client.createInstance('my-instance', {
qrcode: true,
integration: 'WHATSAPP-BAILEYS',
webhook: {
url: 'https://your-webhook.com/webhook',
enabled: true,
events: ['MESSAGES_UPSERT', 'CONNECTION_UPDATE']
}
});Options:
interface CreateInstanceOptions {
qrcode?: boolean; // Generate QR code (default: true)
integration?: 'WHATSAPP-BAILEYS' | 'WHATSAPP-BUSINESS';
webhook?: WebhookConfig;
}deleteInstance(instanceName)
Permanently deletes an instance.
await client.deleteInstance('my-instance');restartInstance(instanceName)
Restarts an instance.
await client.restartInstance('my-instance');fetchInstances()
Lists all instances.
const result = await client.fetchInstances();
console.log('Instances:', result.data);fetchInstanceById(instanceId)
Fetches a specific instance by UUID.
const result = await client.fetchInstanceById('93ecfcf2-f1a7-444b-baa2-83afee38413b');getInstanceStatus(instanceName)
Gets the connection status of an instance.
const result = await client.getInstanceStatus('my-instance');
// result.data.state: 'close' | 'connecting' | 'open'Status values:
close- Disconnectedconnecting- Waiting for QR code scanopen- Connected and ready
getQRCode(instanceName)
Gets the current QR code for an instance.
const result = await client.getQRCode('my-instance');
console.log('QR Code:', result.data?.base64);disconnectInstance(instanceName)
Disconnects/logs out an instance.
await client.disconnectInstance('my-instance');Message Sending
sendTextMessage(instanceName, number, text, options?)
Sends a text message.
await client.sendTextMessage(
'my-instance',
'5511999999999',
'Hello, World!',
{
delay: 1000, // Delay in ms before sending
presence: 'composing', // Show typing indicator
linkPreview: true // Enable link preview
}
);Options:
interface SendTextOptions {
delay?: number;
presence?: 'composing' | 'recording';
linkPreview?: boolean;
mentioned?: string[]; // Array of numbers to mention
}sendMediaMessage(instanceName, number, media, options?)
Sends media (image, video, audio, document).
// Send image from URL
await client.sendMediaMessage(
'my-instance',
'5511999999999',
'https://example.com/image.jpg',
{
mediatype: 'image',
mimetype: 'image/jpeg',
caption: 'Check this out!',
fileName: 'photo.jpg'
}
);
// Send base64 image
await client.sendMediaMessage(
'my-instance',
'5511999999999',
'data:image/png;base64,iVBORw0KGgo...',
{
mediatype: 'image',
caption: 'Base64 image'
}
);
// Send document
await client.sendMediaMessage(
'my-instance',
'5511999999999',
'https://example.com/document.pdf',
{
mediatype: 'document',
mimetype: 'application/pdf',
fileName: 'report.pdf'
}
);Options:
interface SendMediaOptions {
mediatype?: 'image' | 'video' | 'audio' | 'document';
mimetype?: string;
caption?: string;
fileName?: string;
delay?: number;
presence?: 'composing' | 'recording';
}sendContact(instanceName, number, contact)
Sends a contact.
await client.sendContact(
'my-instance',
'5511999999999',
{
fullName: 'John Doe',
wuid: '5511888888888', // WhatsApp ID
phoneNumber: '5511888888888',
organization: 'Company Inc.',
email: '[email protected]'
}
);Utilities
checkWhatsAppNumber(instanceName, numbers)
Checks if numbers have WhatsApp.
const result = await client.checkWhatsAppNumber(
'my-instance',
['5511999999999', '5511888888888']
);
result.data?.forEach(check => {
console.log(`${check.number}: ${check.exists ? 'Has WhatsApp' : 'No WhatsApp'}`);
});🎯 Advanced Usage
Error Handling
try {
const result = await client.sendTextMessage(
'my-instance',
'5511999999999',
'Hello!'
);
if (!result.success) {
console.error('Failed to send message:', result.error);
return;
}
console.log('Message sent:', result.data);
} catch (error) {
console.error('Unexpected error:', error);
}Creating a Singleton Instance
// api-client.ts
import { EvolutionAPI } from '@maxpantech/evolution-api-wrapper';
let instance: EvolutionAPI | null = null;
export function getEvolutionClient(): EvolutionAPI {
if (!instance) {
instance = new EvolutionAPI({
baseUrl: process.env.EVOLUTION_API_URL!,
apiKey: process.env.EVOLUTION_API_KEY!
});
}
return instance;
}
// Usage in other files
import { getEvolutionClient } from './api-client';
const client = getEvolutionClient();
await client.sendTextMessage('instance', '5511999999999', 'Hello!');TypeScript Type Imports
import type {
EvolutionAPIResponse,
CreateInstanceOptions,
SendTextOptions,
SendMediaOptions,
Contact,
InstanceStatus,
MessageSendResponse
} from '@maxpantech/evolution-api-wrapper';🔐 Environment Variables
For Singleton Usage
The singleton automatically reads these environment variables:
# Required
EVOLUTION_API_URL=https://your-evolution-api.com
EVOLUTION_API_KEY=your-global-api-key
# Optional
EVOLUTION_API_TIMEOUT=30000
## 📋 Phone Number Format
Always use international format without `+` or spaces:
- ✅ Correct: `5511999999999`
- ❌ Wrong: `+55 11 99999-9999`
- ❌ Wrong: `11999999999`
## 🛠️ Development
### Building the Library
```bash
npm run buildType Checking
npm run typecheckLinting
npm run lint
npm run lint:fixDevelopment Mode (Watch)
npm run dev📝 Publishing to NPM
- Update version in
package.json - Build the library:
npm run build - Login to NPM (if not already logged in):
npm login - Publish:
npm publish --access public
📦 Publishing to GitHub Packages
Create a
.npmrcfile in the project root:@maxpantech:registry=https://npm.pkg.github.comUpdate
package.jsonwith repository info:{ "name": "@maxpantech/evolution-api-wrapper", "repository": "https://github.com/maxpantech/evolution-api-wrapper" }Authenticate with GitHub:
npm login --registry=https://npm.pkg.github.comPublish:
npm publish
🔗 Using the Library in Other Projects
After publishing, install in your projects:
npm install @maxpantech/evolution-api-wrapper axiosFor GitHub Packages, add .npmrc to the consuming project:
@maxpantech:registry=https://npm.pkg.github.com📄 License
MIT © MaxPanTech
🔗 Links
Made with ❤️ by MaxPanTech
