Use and adapt WhatsApp-Meta-Business-API-Handler
Use and adapt WhatsApp-Meta-Business-API-Handler: A lightweight, easy-to-use TypeScript wrapper for WhatsApp Cloud API. Send messages, media, buttons, and more with full type safety.
Use the documented interfaces and source layout for WhatsApp-Meta-Business-API-Handler. The sections below retain the README’s examples and configuration details.
Configuration
Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
token | string | Required | WhatsApp API access token |
phoneNumberId | string | Required | Your WhatsApp phone number ID |
businessAccountId | string | Optional | Business account ID |
version | string | 'v21.0' | API version |
appSecret | string | Optional | App secret for signature verification |
webhookVerifyToken | string | Optional | Token for webhook verification |
apiTimeout | number | 30000 | API request timeout (ms) |
maxRetries | number | 3 | Max retry attempts for failed requests |
autoMarkRead | boolean | true | Auto-mark messages as read |
autoProcessMessages | boolean | true | Auto-process incoming messages |
queueEnabled | boolean | true | Enable message queue |
maxQueueSize | number | 1000 | Maximum queue size |
Full Configuration Example
const whatsapp = createWhatsAppHandler({
token: 'YOUR_TOKEN',
phoneNumberId: 'YOUR_PHONE_ID',
businessAccountId: 'YOUR_BUSINESS_ID',
version: 'v21.0',
appSecret: 'YOUR_APP_SECRET',
webhookVerifyToken: 'YOUR_VERIFY_TOKEN',
apiTimeout: 30000,
maxRetries: 3,
autoMarkRead: true,
autoProcessMessages: true,
queueEnabled: true,
maxQueueSize: 1000,
storage: {
type: 'memory',
autoCleanup: true,
maxMessagesPerConversation: 1000
},
webhook: {
verifyToken: 'YOUR_VERIFY_TOKEN',
appSecret: 'YOUR_APP_SECRET',
autoProcess: true,
autoMarkRead: true,
verifySignature: true,
maxBodySize: 10485760, // 10MB
timeout: 30000
}
});API Reference
Core Methods
sendMessage(to, message, options?)
Send a text message.
Parameters:
to(string): Recipient phone numbermessage(string): Message textoptions(object, optional):previewUrl(boolean): Enable URL previewreplyTo(string): Message ID to reply topriority(number): Message priorityqueueIfBusy(boolean): Queue if busy
Returns: Promise<MessageResponse>
sendVoice(to, audioIdOrUrl, options?)
Send a voice message.
Parameters:
to(string): Recipient phone numberaudioIdOrUrl(string): Media ID or URLoptions(object, optional):replyTo(string): Message ID to reply topriority(number): Message priority
Returns: Promise<MessageResponse>
markAsRead(messageId)
Mark a message as read.
Parameters:
messageId(string): WhatsApp message ID
Returns: Promise<{ success: boolean }>
processWebhook(request)
Process a webhook request (universal handler).
Parameters:
request(UniversalRequest): Request object
Returns: Promise<WebhookResult>
setWebhookHandlers(handlers)
Set webhook event handlers.
Parameters:
handlers(WebhookHandlers): Handler functions
Returns: void
getConversationHistory(conversationId, limit?, offset?)
Get conversation message history.
Parameters:
conversationId(string): Phone numberlimit(number, optional): Max messages (default: 50)offset(number, optional): Pagination offset (default: 0)
Returns: Promise<StoredMessage[]>
searchMessages(query, conversationId?)
Search messages by text.
Parameters:
query(string): Search termconversationId(string, optional): Limit to conversation
Returns: Promise<StoredMessage[]>
getConversationState(conversationId)
Get conversation state.
Parameters:
conversationId(string): Phone number
Returns: ConversationState | undefined
updateConversationContext(conversationId, context)
Update conversation context data.
Parameters:
conversationId(string): Phone numbercontext(object): Context data to merge
Returns: ConversationState
getStatistics()
Get message statistics.
Returns: Object with sent, received, failed, delivered, read counts
getQueueStats()
Get message queue statistics.
Returns: Object with size, maxSize, usagePercentage
startWebhookServer(port?, path?, callback?)
Start standalone HTTP webhook server.
Parameters:
port(number, optional): Port (default: 3000)path(string, optional): Webhook path (default: '/webhook')callback(function, optional): Success callback
Returns: http.Server
stopWebhookServer()
Stop webhook server.
Returns: Promise<void>
Troubleshooting
Common Issues
1. Webhook Verification Fails
Problem: GET webhook returns 403
Solution:
// Ensure verify token matches
const whatsapp = createWhatsAppHandler({
webhookVerifyToken: 'same_token_in_meta_dashboard'
});2. Signature Verification Fails
Problem: POST webhook returns 401
Solution:
// Add app secret and enable verification
const whatsapp = createWhatsAppHandler({
appSecret: 'your_app_secret',
webhook: {
verifySignature: true,
appSecret: 'your_app_secret'
}
});3. Messages Not Sending
Problem: Messages fail silently
Solution:
// Listen for errors
whatsapp.on('messageFailed', (data) => {
console.error('Failed:', data.error);
});
// Check API credentials
console.log('Token:', process.env.WHATSAPP_TOKEN);
console.log('Phone ID:', process.env.WHATSAPP_PHONE_NUMBER_ID);4. Webhook Not Receiving Events
Problem: No events received
Checklist:
- ✅ Webhook URL is publicly accessible
- ✅ SSL certificate is valid
- ✅ Webhook is subscribed in Meta dashboard
- ✅ Verify token matches
- ✅ Server is running and reachable
Test webhook:
# Test GET (verification)
curl "http://your-domain.com/webhook?hub.mode=subscribe&hub.verify_token=YOUR_TOKEN&hub.challenge=test"
# Test POST (message)
curl -X POST http://your-domain.com/webhook \
-H "Content-Type: application/json" \
-d '{"object":"whatsapp_business_account","entry":[]}'5. Rate Limiting
Problem: 429 Too Many Requests
Solution:
// Enable queue to handle rate limits
const whatsapp = createWhatsAppHandler({
queueEnabled: true,
maxQueueSize: 1000,
maxRetries: 3
});
// Send with queue
await whatsapp.sendMessage(to, message, { queueIfBusy: true });Debug Mode
// Enable verbose logging
whatsapp.on('messageSent', console.log);
whatsapp.on('messageFailed', console.error);
whatsapp.on('messageRead', console.log);
// Log all webhook events
whatsapp.setWebhookHandlers({
onMessage: (msg, meta) => console.log('Message:', msg, meta),
onMessageStatus: (status) => console.log('Status:', status),
onError: (error) => console.error('Error:', error),
onUnknown: (event) => console.log('Unknown:', event)
});Source and help
The catalog identifies the license as MIT. Read the repository license before redistributing source or assets.
Source captured: 2026-10-11
