Hey there, fellow JavaScript dev! Ready to supercharge your SafetyCulture 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, no constant polling required. In SafetyCulture, they're your ticket to building responsive, user-facing integrations that stay in sync with the latest data.
Before we start, make sure you've got:
Got all that? Great! Let's code.
First things first, let's set up a simple Express server to receive those juicy 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'));
Easy peasy, right? This sets up a basic endpoint at /webhook
that'll log incoming events and send a 200 OK response.
Now, let's tell SafetyCulture where to send those events:
const axios = require('axios'); async function registerWebhook() { try { const response = await axios.post('https://api.safetyculture.io/webhooks/v1', { url: 'https://your-server.com/webhook', events: ['audit.completed', 'audit.updated'], name: 'My Awesome Webhook' }, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } }); console.log('Webhook registered:', response.data); } catch (error) { console.error('Error registering webhook:', error.response.data); } } registerWebhook();
Replace 'https://your-server.com/webhook'
with your actual endpoint URL and YOUR_API_KEY
with your SafetyCulture API key.
Safety first! Let's make sure those incoming webhooks are legit:
const crypto = require('crypto'); function verifySignature(payload, signature, secret) { const hmac = crypto.createHmac('sha256', secret); const calculatedSignature = hmac.update(payload).digest('hex'); return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature)); } app.post('/webhook', (req, res) => { const signature = req.headers['x-iauditor-signature']; const isValid = verifySignature(JSON.stringify(req.body), signature, 'YOUR_WEBHOOK_SECRET'); if (!isValid) { return res.status(401).send('Invalid signature'); } // Process the webhook... });
Now, let's handle those events like a pro:
app.post('/webhook', (req, res) => { // ... signature verification ... const { event_type, payload } = req.body; switch (event_type) { case 'audit.completed': console.log('Audit completed:', payload.audit_id); // Do something cool with the completed audit break; case 'audit.updated': console.log('Audit updated:', payload.audit_id); // Update your local data or trigger a notification break; default: console.log('Unhandled event type:', event_type); } res.sendStatus(200); });
Sometimes things go wrong. No worries, we've got your back:
app.post('/webhook', async (req, res) => { try { // ... process webhook ... res.sendStatus(200); } catch (error) { console.error('Error processing webhook:', error); res.status(500).send('Internal Server Error'); // Simple retry mechanism setTimeout(() => processWebhook(req.body), 5000); } }); async function processWebhook(data) { // Your webhook processing logic here }
Time to put on your detective hat:
app.post('/webhook', (req, res) => { console.log('Received webhook:', JSON.stringify(req.body, null, 2)); // ... rest of your webhook handling code ... });
Use SafetyCulture's webhook testing tools to send test events and watch your console light up!
As your integration grows, consider using a message queue like RabbitMQ or Redis to handle high volumes of webhook events. This'll help keep your server responsive even during traffic spikes.
And there you have it! You're now ready to build some seriously cool, real-time integrations with SafetyCulture. Remember, webhooks are powerful, so use them wisely and have fun building!
For more details, check out the SafetyCulture API documentation. Happy coding!