Hey there, fellow JavaScript dev! Ready to supercharge your Delighted integration with webhooks? Let's dive right in and get those real-time updates flowing.
Webhooks are like the cool kids of API integrations - they notify you instantly when something happens, rather than you constantly asking, "Are we there yet?" With Delighted's webhooks, you'll get pinged the moment a survey response comes in, keeping your app in perfect sync.
Before we start, make sure you've got:
First things first, let's create an endpoint in your app to receive those juicy webhook payloads.
const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { // We'll handle the webhook payload here console.log('Webhook received:', req.body); res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook server is running'));
Pro tip: Always secure your endpoint. Consider using HTTPS and implement authentication to keep those webhooks for your eyes only.
Now, let's tell Delighted where to send those webhooks. We'll use the Delighted API to set this up:
const axios = require('axios'); axios.post('https://api.delighted.com/v1/webhooks', { url: 'https://your-app.com/webhook', events: ['survey_response.created', 'survey_response.updated'] }, { auth: { username: 'YOUR_API_KEY', password: '' } }) .then(response => console.log('Webhook created:', response.data)) .catch(error => console.error('Error:', error));
When a webhook hits your endpoint, it's party time! Here's how to handle that incoming data:
app.post('/webhook', express.json(), (req, res) => { const { event, created_at, data } = req.body; switch(event) { case 'survey_response.created': console.log('New response:', data.score); // Do something awesome with the new response break; case 'survey_response.updated': console.log('Updated response:', data.score); // Handle the updated response break; } res.sendStatus(200); });
Trust, but verify! Make sure the webhook is legit:
const crypto = require('crypto'); function verifyWebhookSignature(payload, signature, secret) { const hmac = crypto.createHmac('sha256', secret); const digest = hmac.update(payload).digest('hex'); return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(digest)); } app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => { const signature = req.headers['x-delighted-signature']; if (!verifyWebhookSignature(req.body, signature, 'YOUR_WEBHOOK_SECRET')) { return res.status(401).send('Invalid signature'); } // Process the webhook... });
Now that we've got the data, let's do something cool with it:
function processWebhook(data) { const { score, comment, person } = data; if (score <= 6) { console.log(`Uh-oh! ${person.email} isn't happy. Score: ${score}`); notifyCustomerService(person.email, comment); } else if (score >= 9) { console.log(`Woohoo! ${person.email} loves us! Score: ${score}`); addToTestimonials(person.name, comment); } }
Sometimes things go wrong. No worries, we've got your back:
app.post('/webhook', async (req, res) => { try { await processWebhook(req.body); res.sendStatus(200); } catch (error) { console.error('Error processing webhook:', error); res.status(500).send('Internal Server Error'); // Implement retry logic here setTimeout(() => retryWebhook(req.body), 5000); } }); function retryWebhook(payload) { // Implement your retry logic here }
Before going live, let's make sure everything's working smoothly:
const testPayload = { event: 'survey_response.created', created_at: 1622505600, data: { score: 9, comment: "You guys rock!", person: { email: "[email protected]", name: "Happy Customer" } } }; axios.post('http://localhost:3000/webhook', testPayload) .then(response => console.log('Test successful:', response.status)) .catch(error => console.error('Test failed:', error));
Keep an eye on your webhooks:
And there you have it! You're now a Delighted webhook wizard. Remember, webhooks are powerful, so use them wisely. Keep your endpoints secure, your code clean, and your customers delighted!
Need more info? Check out the Delighted API docs for all the nitty-gritty details.
Now go forth and webhook like a pro! 🚀