Hey there, fellow JavaScript dev! Ready to supercharge your Campaign Monitor integration with webhooks? Let's dive right in and get those real-time updates flowing.
Webhooks are like the cool kids of the API world – they notify you instantly when something happens, rather than you constantly asking, "Are we there yet?" With Campaign Monitor, webhooks keep you in the loop about subscriber activities, campaign events, and more. Let's set 'em up!
Before we start, make sure you've got:
First things first, let's create a simple Express server to catch those webhook events:
const express = require('express'); const app = express(); app.use(express.json()); app.post('/webhook', (req, res) => { console.log('Webhook received:', req.body); res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook server running on port 3000'));
Now, let's tell Campaign Monitor where to send those juicy events. We'll use the API for this:
const axios = require('axios'); const createWebhook = async () => { try { const response = await axios.post('https://api.createsend.com/api/v3.2/webhooks.json', { Events: ['Subscribe', 'Deactivate'], Url: 'https://your-server.com/webhook', PayloadFormat: 'json' }, { auth: { username: 'your-api-key', password: 'x' } }); console.log('Webhook created:', response.data); } catch (error) { console.error('Error creating webhook:', error); } }; createWebhook();
Trust, but verify! Let's make sure these webhooks are legit:
const crypto = require('crypto'); const verifyWebhook = (payload, signature) => { const hash = crypto.createHmac('sha256', 'your-secret-key') .update(payload) .digest('base64'); return hash === signature; }; app.post('/webhook', (req, res) => { if (verifyWebhook(JSON.stringify(req.body), req.headers['x-campaign-monitor-signature'])) { // Process the webhook } else { res.sendStatus(401); } });
Time to handle those events like a pro:
app.post('/webhook', (req, res) => { const { Type, Data } = req.body; switch (Type) { case 'Subscribe': console.log(`New subscriber: ${Data.EmailAddress}`); break; case 'Deactivate': console.log(`Subscriber deactivated: ${Data.EmailAddress}`); break; // Handle other event types default: console.log(`Unhandled event type: ${Type}`); } res.sendStatus(200); });
Sometimes things go wrong. No worries, we've got your back:
const handleWebhook = async (req, res) => { let retries = 3; while (retries > 0) { try { // Process webhook return res.sendStatus(200); } catch (error) { console.error('Error processing webhook:', error); retries--; await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second before retry } } res.sendStatus(500); }; app.post('/webhook', handleWebhook);
Campaign Monitor's got a nifty test feature in their UI. Use it! It's like a fire drill for your webhook handler.
Or, be a rebel and create your own test events:
const testWebhook = { Type: 'Subscribe', Data: { EmailAddress: '[email protected]', Name: 'Test User' } }; axios.post('http://localhost:3000/webhook', testWebhook) .then(response => console.log('Test webhook sent')) .catch(error => console.error('Error sending test webhook:', error));
If you're expecting a tsunami of webhooks, consider using a queue like Redis or RabbitMQ. It's like having a bouncer for your webhook events – keeps things orderly!
And there you have it! You're now a Campaign Monitor webhook wizard. Remember, with great power comes great responsibility – use these webhooks wisely and keep your integrations snappy and responsive.
Happy coding, and may your events always find their way home!