@akson/chatsuite-sdk
Version:
Production-ready TypeScript SDK for ChatSuite - WhatsApp automation with built-in session management, message queuing, webhook server, and database sync
157 lines (138 loc) β’ 5.82 kB
text/typescript
import { WhatsAppClient } from '@whatsapp-baileys/sdk';
async function main() {
// Initialize client
const client = new WhatsAppClient({
apiToken: process.env.WHATSAPP_API_TOKEN || 'wa_your_token_here',
baseUrl: process.env.WHATSAPP_API_URL || 'https://whatsapp-api.akson.ch'
});
const phoneNumber = '+1234567890'; // Replace with your session number
const webhookUrl = 'https://your-webhook-url.com/webhook'; // Replace with your webhook URL
try {
console.log('=== WhatsApp SDK Webhook Example ===\n');
// 1. Create a webhook for message events
console.log('1. Creating message webhook...');
const messageWebhook = await client.webhooks.setupMessageWebhook(
phoneNumber,
webhookUrl,
'My Message Webhook'
);
console.log('β
Message webhook created:', messageWebhook.name);
console.log(' Secret:', messageWebhook.secret);
// 2. Create a webhook for session events
console.log('\n2. Creating session webhook...');
const sessionWebhook = await client.webhooks.setupSessionWebhook(
phoneNumber,
webhookUrl,
'My Session Webhook'
);
console.log('β
Session webhook created:', sessionWebhook.name);
// 3. Create a custom webhook for multiple events
console.log('\n3. Creating custom webhook...');
const customWebhook = await client.webhooks.createForEvents(
phoneNumber,
webhookUrl,
['message.received', 'session.connected', 'session.disconnected'],
{
name: 'Custom Multi-Event Webhook',
headers: {
'X-Custom-Header': 'my-value',
'Authorization': 'Bearer my-token'
},
retryConfig: {
maxAttempts: 5,
backoffMultiplier: 2,
initialDelay: 1000
}
}
);
console.log('β
Custom webhook created:', customWebhook.name);
// 4. List all webhooks for the session
console.log('\n4. Listing all webhooks...');
const webhooks = await client.webhooks.list(phoneNumber);
console.log(`π Found ${webhooks.length} webhooks:`);
webhooks.forEach((webhook, index) => {
console.log(` ${index + 1}. ${webhook.name} (${webhook.events.join(', ')})`);
console.log(` URL: ${webhook.url}`);
console.log(` Active: ${webhook.active}`);
console.log(` Calls: ${webhook.statistics.totalCalls} (${webhook.statistics.successfulCalls} successful)`);
});
// 5. Test a webhook
console.log('\n5. Testing webhook...');
const testResult = await client.webhooks.test(phoneNumber, messageWebhook._id);
console.log('π§ͺ Test result:', testResult.success ? 'PASSED' : 'FAILED');
if (testResult.success) {
console.log(` Response time: ${testResult.responseTime}ms`);
console.log(` Status: ${testResult.status} ${testResult.statusText}`);
} else {
console.log(` Error: ${testResult.error}`);
}
// 6. Update webhook settings
console.log('\n6. Updating webhook settings...');
await client.webhooks.update(phoneNumber, customWebhook._id, {
name: 'Updated Custom Webhook',
events: ['message.received', 'message.sent'] // Remove session events
});
console.log('β
Webhook updated successfully');
// 7. Get webhook logs/statistics
console.log('\n7. Getting webhook statistics...');
const logs = await client.webhooks.getLogs(phoneNumber, messageWebhook._id);
console.log(`π Statistics for "${logs.name}":`);
console.log(` Total calls: ${logs.statistics.totalCalls}`);
console.log(` Successful: ${logs.statistics.successfulCalls}`);
console.log(` Failed: ${logs.statistics.failedCalls}`);
if (logs.statistics.lastCallAt) {
console.log(` Last call: ${logs.statistics.lastCallAt}`);
}
if (logs.statistics.averageResponseTime) {
console.log(` Average response time: ${logs.statistics.averageResponseTime}ms`);
}
// 8. Rotate webhook secret
console.log('\n8. Rotating webhook secret...');
const rotateResult = await client.webhooks.rotateSecret(phoneNumber, messageWebhook._id);
console.log('π Secret rotated successfully');
console.log(' New secret:', rotateResult.secret);
// 9. Toggle webhook active status
console.log('\n9. Disabling webhook...');
await client.webhooks.toggleActive(phoneNumber, customWebhook._id, false);
console.log('βΈοΈ Webhook disabled');
console.log('\nπ― Quick webhook setup using convenience methods:');
// Using the main client convenience methods
const quickWebhook = await client.setupSessionWebhook(
phoneNumber,
'https://example.com/quick-webhook',
['message.received'],
'Quick Setup Webhook'
);
console.log(`β
Quick webhook: ${quickWebhook.name}`);
// Get all session webhooks
const allWebhooks = await client.getSessionWebhooks(phoneNumber);
console.log(`π Total webhooks for session: ${allWebhooks.length}`);
console.log('\n=== Webhook Example Complete ===');
console.log('\nπ‘ Next steps:');
console.log('1. Implement webhook endpoint at your URL');
console.log('2. Verify webhook signatures using the secret');
console.log('3. Handle different event types in your webhook');
console.log('4. Monitor webhook statistics and logs');
} catch (error) {
console.error('β Error:', error);
}
}
// Example webhook payload structure
console.log('\nπ Example webhook payload structure:');
console.log(JSON.stringify({
event: 'message.received',
timestamp: new Date().toISOString(),
session: {
tel: '+1234567890',
name: 'My Session'
},
data: {
id: 'message_id',
from: '1234567890@c.us',
body: 'Hello!',
timestamp: Date.now(),
type: 'chat'
}
}, null, 2));
// Run the example
main();