@natyapp/meta
v1.6.7
Published
A TypeScript SDK for integrating with Meta's WhatsApp Business API, providing a simple and elegant way to send messages, handle webhooks, and manage WhatsApp business communications.
Downloads
339
Keywords
Readme
@natyapp/meta
A TypeScript SDK for integrating with Meta's WhatsApp Business API, providing a simple and elegant way to send messages, handle webhooks, and manage WhatsApp business communications.
Features
- 🚀 Easy Integration - Simple setup with your Meta app token
- 📱 Rich Messaging - Send text, images, documents, buttons, lists, and more
- 🎯 Interactive Elements - Support for buttons, menus, and quick replies
- 📍 Location & Contacts - Send location and contact information
- 🔔 Webhook Support - Handle incoming messages and events
- 📊 Logging & Monitoring - Built-in logging capabilities
- 🛡️ Type Safety - Full TypeScript support with type definitions
- ⚡ Modern Architecture - Built with async/await and promises
Installation
npm install @natyapp/metayarn add @natyapp/metapnpm add @natyapp/metaQuick Start
1. Import the SDK
import NatyMeta, { WhatsappResponse } from '@natyapp/meta';2. Environment Configuration
Set the API URL in your environment variables:
API_META=https://api.meta.naty.app3. Initialize the SDK
// Initialize without token
const sdk = new NatyMeta();
// Or initialize with token directly
const sdk = new NatyMeta('YOUR_APP_TOKEN');4. Connect to the API
const connectResult = await sdk.connect({
appToken: 'YOUR_APP_TOKEN'
});
if (connectResult.isError) {
throw new Error(connectResult.isError.message);
}
console.log('Connected successfully:', connectResult.isSuccess);Usage Examples
Sending Messages
Text Message
import { Message } from '@natyapp/meta';
const message = new Message('PHONE_NUMBER', 'MESSAGE_ID', 'ACCESS_TOKEN');
// Send a simple text message
const response = await message.send_text_message('Hello, World!');Button Message
import { Button } from '@natyapp/meta';
const button = new Button({
type: 'button',
body: 'Choose an option:',
buttons: [
{
id: 'option1',
title: 'Option 1'
},
{
id: 'option2',
title: 'Option 2'
}
]
});
const response = await message.send_button(button);List Message
import { List } from '@natyapp/meta';
const list = new List({
header: 'Our Services',
body: 'Please select a service:',
footer: 'Thank you for choosing us!',
button: 'View Services',
sections: [
{
title: 'Main Services',
rows: [
{
id: 'service1',
title: 'Web Development',
description: 'Custom web applications'
},
{
id: 'service2',
title: 'Mobile Apps',
description: 'iOS and Android applications'
}
]
}
]
});
const response = await message.send_list(list);Document Message
// Send document from URL
const response = await message.send_document(
'https://example.com/document.pdf',
'application/pdf',
{
fileName: 'report.pdf',
description: 'Monthly report'
}
);
// Send document from base64
const response = await message.send_document(
'base64EncodedString',
'application/pdf',
{
fileName: 'document.pdf',
description: 'Important document'
}
);Image Message
// Send image from URL
const response = await message.send_image('https://example.com/image.jpg');
// Send image from base64
const response = await message.send_image('base64EncodedString');Location Message
const response = await message.send_location({
lat: -23.5505,
long: -46.6333,
name: 'São Paulo',
address: 'São Paulo, Brazil'
});Contact Message
const contacts = [
{
name: {
first_name: 'John',
last_name: 'Doe'
},
phones: [
{
phone: '+1234567890',
type: 'WORK'
}
],
emails: [
{
email: '[email protected]',
type: 'WORK'
}
]
}
];
const response = await message.send_contacts(contacts);Message Reactions and Status
React to Message
// Send thumbs up reaction
const response = await message.send_reaction('👍');
// Send custom emoji
const response = await message.send_reaction('😊');Mark as Read
const success = await message.mark_as_read();Reply to Message
// Reply with text
const response = await message.reply({
type: 'text',
toReply: 'This is a reply message',
messageToReply: 'ORIGINAL_MESSAGE_ID'
});
// Reply with interactive element
const response = await message.reply({
type: 'interactive',
toReply: buttonObject,
messageToReply: 'ORIGINAL_MESSAGE_ID'
});Webhook Handling
import { Webhook } from '@natyapp/meta';
// Initialize webhook handler
const webhook = new Webhook();
// Listen for incoming messages
sdk.on('message', (response: WhatsappResponse) => {
console.log('Received message:', response);
// Send automatic reply
response.send_text_message('Thank you for your message!');
});
// Setup webhook endpoint (if using Express)
import express from 'express';
const app = express();
app.use('/webhook', webhook.getRouter());Media Handling
// Get media URL from media ID
const mediaData = await message.get_media_url('MEDIA_ID');
console.log('Media URL:', mediaData.url);
// Create media from file
const mediaId = await message.createMedia(
'base64EncodedContent',
'image/jpeg'
);Connection Management
import { Connection } from '@natyapp/meta';
// Create new connection
const connection = new Connection();
// Check connection status
const status = await connection.getStatus();
// Update connection settings
const updated = await connection.updateSettings({
webhookUrl: 'https://your-domain.com/webhook',
verifyToken: 'your-verify-token'
});Logging
import { Log } from '@natyapp/meta';
const logger = new Log();
// Log message activity
await logger.logMessage({
messageId: 'MESSAGE_ID',
phoneNumber: 'PHONE_NUMBER',
content: 'Message content',
type: 'outbound'
});
// Get message logs
const logs = await logger.getMessageLogs({
phoneNumber: 'PHONE_NUMBER',
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31')
});Error Handling
The SDK uses a consistent error handling pattern:
const result = await sdk.someMethod();
if (result.isError) {
console.error('Error occurred:', result.isError.message);
// Handle error appropriately
return;
}
// Success case
console.log('Success:', result.isSuccess);TypeScript Support
The SDK is written in TypeScript and provides full type definitions:
import {
WhatsappResponse,
ISendMessageReturn,
ConnectProps,
Button,
List
} from '@natyapp/meta';
// All types are available for importConfiguration
Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| API_META | Meta API base URL | https://api.meta.naty.app |
Initialization Options
interface ConnectProps {
appToken: string;
pathname?: string; // Custom webhook path
app?: Express; // Express app instance
}API Reference
Classes
- NatyMeta - Main SDK class
- Message - Handle message operations
- Webhook - Webhook management
- Connection - Connection management
- Log - Logging functionality
- WhatsappResponse - Response handler
Elements
- Button - Interactive buttons
- List - List messages
- Text - Text messages
- Image - Image messages
Requirements
- Node.js >= 14
- TypeScript >= 4.9 (for development)
Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
ISC License - see LICENSE file for details.
Support
- 📧 Email: [email protected]
- 🐛 Issues: GitHub Issues
- 📚 Documentation: Full Documentation
Authors
- IkiraDev - Initial work
Made with ❤️ by the Naty team
