Hey there, fellow JavaScript dev! Ready to supercharge your WhatsApp Business integration with webhooks? Let's dive right in and get your app responding to real-time WhatsApp events in no time.
Webhooks are like your app's personal news feed for WhatsApp events. Instead of constantly asking "Any updates?", WhatsApp will ping your app whenever something interesting happens. Cool, right?
Make sure you've got:
First things first, let's create a simple Express server to handle those incoming webhooks:
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; app.use(express.json()); app.post('/webhook', (req, res) => { console.log('Webhook received!', req.body); res.sendStatus(200); }); app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Easy peasy, right? This sets up a basic endpoint at /webhook
that'll log incoming messages and send a 200 OK response.
Head over to your WhatsApp Business API dashboard and set your webhook URL (e.g., https://your-domain.com/webhook
). You'll also need to set up a verify token - think of it as a secret handshake between WhatsApp and your server.
Here's how to handle the verification:
app.get('/webhook', (req, res) => { const VERIFY_TOKEN = 'your_super_secret_verify_token'; const mode = req.query['hub.mode']; const token = req.query['hub.verify_token']; const challenge = req.query['hub.challenge']; if (mode && token === VERIFY_TOKEN) { res.status(200).send(challenge); } else { res.sendStatus(403); } });
Now for the fun part - actually doing something with those events! Let's parse and handle incoming messages:
app.post('/webhook', (req, res) => { const { body } = req; if (body.object === 'whatsapp_business_account') { body.entry.forEach(entry => { entry.changes.forEach(change => { if (change.field === 'messages') { const message = change.value.messages[0]; console.log('New message:', message); // Do something awesome with the message! } }); }); res.sendStatus(200); } else { res.sendStatus(404); } });
Got a message? Let's send one back! Here's a quick example using the axios
library:
const axios = require('axios'); async function sendWhatsAppMessage(to, message) { try { const response = await axios.post('https://graph.facebook.com/v12.0/YOUR_PHONE_NUMBER_ID/messages', { messaging_product: 'whatsapp', to: to, type: 'text', text: { body: message } }, { headers: { 'Authorization': `Bearer ${YOUR_ACCESS_TOKEN}`, 'Content-Type': 'application/json' } }); console.log('Message sent successfully'); return response.data; } catch (error) { console.error('Error sending message:', error); } }
Remember, with great power comes great responsibility. Always validate those incoming webhooks and implement rate limiting to keep the bad guys out.
Use ngrok to expose your local server to the internet for testing. It's a lifesaver during development!
And there you have it! You're now ready to build some awesome WhatsApp integrations. Remember, this is just the tip of the iceberg - there's so much more you can do with the WhatsApp Business API.
Keep experimenting, keep building, and most importantly, have fun with it! If you get stuck, the official WhatsApp Business API docs are your best friend.
Now go forth and webhook all the things! 🚀