Back

Quick Guide to Implementing Webhooks in SafetyCulture

Aug 17, 2024 • 7 minute read

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!

Introduction

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.

Prerequisites

Before we start, make sure you've got:

  • A SafetyCulture API key (you're probably way ahead of me on this one)
  • Node.js installed (because, let's face it, who doesn't these days?)
  • A basic grasp of Express.js (we'll use it for our webhook endpoint)

Got all that? Great! Let's code.

Setting Up the Webhook

Creating a Webhook Endpoint

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.

Registering the Webhook with SafetyCulture API

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.

Handling Webhook Events

Verifying Webhook Signatures

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... });

Processing Different Event Types

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); });

Error Handling and Retry Mechanism

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 }

Testing Your Webhook

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!

Scaling Considerations

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.

Security Best Practices

  • Always use HTTPS for your webhook endpoint
  • Consider IP whitelisting to only accept requests from SafetyCulture's servers
  • Rotate your webhook secrets regularly (you're already verifying signatures, right?)

Conclusion

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!