whaple
v1.0.3
Published
Standalone WhatsApp messaging SDK with direct Baileys integration, Firebase queue system, and smart routing. Zero Baileys exposure to your app.
Downloads
18
Maintainers
Readme
Whaple
The standalone WhatsApp messaging SDK
A complete WhatsApp messaging SDK with direct Baileys integration, Firebase queue system, and smart routing. Zero Baileys exposure to your application - just a clean, simple API.
🎯 Production Ready - Standalone NPM package with TypeScript support
🔒 Security First - No sensitive data, clean for public repositories
⚡ Zero Dependencies - Your app only needs to know about Whaple's API
Features
🚀 Core Functionality
✅ Direct WhatsApp Connection - Uses Baileys under the hood, but you never see it
✅ Message Sending - Send text messages with automatic retry logic
✅ Message History - Retrieve chat history from WhatsApp
✅ Connection Management - Automatic QR code generation and authentication
✅ Queue Management - Firebase-based persistent message queuing
🎯 Smart Features
✅ Smart Routing - Auto-route between direct send and Firebase queue
✅ Zero-Downtime - Messages persist in Firebase when connection drops
✅ Rate Limit Safe - Built-in WhatsApp API rate limiting
✅ Connection Recovery - Automatic reconnection with exponential backoff
✅ Real-time Status - Live connection and queue monitoring
🛠 Developer Experience
✅ TypeScript First - Full type definitions included
✅ Edge Function Ready - Works in Vercel, Cloudflare Workers, etc.
✅ Clean API - Simple methods, no Baileys complexity exposed
✅ Multi-Platform - Use same SDK across all your applications
✅ Comprehensive Docs - Examples for all major platforms
Installation
npm install whaple🆕 Recent Updates (v1.0.0)
✅ WhatsApp Connection Issues Fixed
- Updated Baileys: Now using latest version 6.7.20 with improved WhatsApp protocol support
- Dynamic Version Fetching: Automatically fetches latest WhatsApp protocol version using
fetchLatestBaileysVersion() - Enhanced QR Code Generation: Fixed 405 "Connection Failure" errors that prevented QR code display
- Improved Connection Reliability: Better timeout handling and retry logic for stable connections
🔧 New Features
- Logout Endpoint: Added
/api/logoutfor clearing authentication sessions without server restart - Better Error Handling: Enhanced connection error recovery and automatic reconnection
- Firebase Auth Persistence: Improved authentication state management with Firebase integration
Quick Start
Direct WhatsApp Mode (Recommended)
Perfect for dedicated WhatsApp servers or standalone applications:
import { Whaple } from 'whaple';
const whaple = new Whaple({
useDirectWhatsApp: true,
firebaseConfig: {
type: 'service_account',
project_id: 'your-project-id',
private_key: '-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----\\n',
client_email: '[email protected]',
// ... rest of Firebase service account
},
debug: true
});
// Connect to WhatsApp (scan QR code)
await whaple.connectToWhatsApp();
// Send message
const result = await whaple.sendMessage('+1234567890', 'Hello from Whaple!');
console.log(result);API Mode
For applications that connect to an existing WhatsApp API server:
import { Whaple } from 'whaple';
const whaple = new Whaple({
whatsappServerUrl: 'https://your-whatsapp-server.com',
apiKey: 'your-api-key',
firebaseConfig: { /* Firebase config */ },
enableSmartRouting: true
});
// Send message with smart routing
const result = await whaple.sendMessage('+1234567890', 'Hello World!');API Reference
Core Methods
sendMessage(number, message, options?)
Send a WhatsApp message with automatic smart routing.
const result = await whaple.sendMessage('+1234567890', 'Hello!', {
priority: 'high'
});
// Result:
// {
// success: true,
// method: 'direct' | 'queued',
// messageId: 'msg-123...',
// timestamp: 1234567890
// }getMessageHistory(number, limit?)
Retrieve message history for a contact.
const history = await whaple.getMessageHistory('+1234567890', 20);getWhatsAppConnectionStatus()
Get current WhatsApp connection status.
const status = whaple.getWhatsAppConnectionStatus();
// {
// isConnected: true,
// isAuthenticated: true,
// connectionState: 'connected',
// userInfo: { ... }
// }getQueueStatus()
Get current message queue status.
const queueStatus = await whaple.getQueueStatus();
// {
// totalMessages: 5,
// pendingMessages: 3,
// processingMessages: 1,
// isProcessing: true
// }Connection Management
connectToWhatsApp()
Connect to WhatsApp (direct mode only).
await whaple.connectToWhatsApp();disconnectFromWhatsApp()
Disconnect from WhatsApp.
await whaple.disconnectFromWhatsApp();getCurrentQR()
Get current QR code for authentication.
const qrCode = whaple.getCurrentQR();Configuration
Environment Variables
# For API mode
WHATSAPP_SERVER_URL=https://your-whatsapp-server.com
WHATSAPP_API_KEY=your-api-key
# Firebase configuration (required for both modes)
FIREBASE_SERVICE_ACCOUNT='{"type":"service_account","project_id":"your-project",...}'
# Optional
WHAPLE_DEBUG=true
WHAPLE_QUEUE_THRESHOLD=5Configuration Options
interface WhapleConfig {
// Direct WhatsApp mode
useDirectWhatsApp?: boolean;
// API mode
whatsappServerUrl?: string;
apiKey?: string;
// Firebase (required)
firebaseConfig: FirebaseServiceAccount;
// Optional
debug?: boolean;
healthCheckTimeout?: number;
queueTimeout?: number;
enableSmartRouting?: boolean;
retryAttempts?: number;
retryDelay?: number;
}Usage Examples
Next.js API Route
// pages/api/send-message.ts
import { Whaple } from 'whaple';
const whaple = new Whaple({
useDirectWhatsApp: process.env.NODE_ENV === 'production',
whatsappServerUrl: process.env.WHATSAPP_SERVER_URL,
apiKey: process.env.WHATSAPP_API_KEY,
firebaseConfig: JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT || '{}'),
});
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const { number, message } = req.body;
const result = await whaple.sendMessage(number, message);
res.json({ success: true, result });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
}Vercel Edge Function
// api/send-message.js
import { Whaple } from 'whaple';
const whaple = new Whaple({
whatsappServerUrl: process.env.WHATSAPP_SERVER_URL,
apiKey: process.env.WHATSAPP_API_KEY,
firebaseConfig: JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT),
});
export default async function handler(req) {
const { number, message } = await req.json();
const result = await whaple.sendMessage(number, message);
return new Response(JSON.stringify(result), {
headers: { 'Content-Type': 'application/json' }
});
}
export const config = {
runtime: 'edge'
};Express.js Server
import express from 'express';
import { Whaple } from 'whaple';
const app = express();
const whaple = new Whaple({
useDirectWhatsApp: true,
firebaseConfig: JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT),
});
// Initialize WhatsApp connection
await whaple.connectToWhatsApp();
app.post('/send-message', async (req, res) => {
try {
const { number, message } = req.body;
const result = await whaple.sendMessage(number, message);
res.json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000);Error Handling
Whaple provides comprehensive error handling:
try {
const result = await whaple.sendMessage('+1234567890', 'Hello!');
} catch (error) {
if (error.message.includes('WhatsApp not connected')) {
// Handle connection issues
console.log('Attempting to reconnect...');
await whaple.connectToWhatsApp();
} else if (error.message.includes('Firebase')) {
// Handle Firebase issues
console.log('Firebase connection problem');
} else {
// Handle other errors
console.error('Unexpected error:', error.message);
}
}TypeScript Support
Whaple is built with TypeScript and provides full type definitions:
import { Whaple, WhapleConfig, SendMessageResult, WhatsAppConnectionStatus } from 'whaple';
const config: WhapleConfig = {
useDirectWhatsApp: true,
firebaseConfig: { /* typed Firebase config */ }
};
const whaple = new Whaple(config);
const result: SendMessageResult = await whaple.sendMessage('+1234567890', 'Hello!');
const status: WhatsAppConnectionStatus = whaple.getWhatsAppConnectionStatus();Development
Building from Source
git clone https://github.com/your-org/whaple.git
cd whaple
npm install
npm run buildRunning Tests
npm testSecurity Audit
Before publishing, run the security audit to ensure no sensitive data:
node security-audit.jsContributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT License - see LICENSE file for details.
Support
- 📚 Documentation: Full API docs
- 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
- 📧 Email: [email protected]
Made with ❤️ for developers who want WhatsApp integration without the complexity.
