Hey there, fellow JavaScript dev! Ready to dive into the world of ServiceTitan webhooks? Buckle up, because we're about to turbocharge your integration game. Let's cut to the chase and get your webhooks up and running in no time.
Webhooks are like your app's personal news feed from ServiceTitan. Instead of constantly asking "What's new?", ServiceTitan will ping you when something interesting happens. Cool, right?
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'));
This little server is like a catcher's mitt for your webhook events. It'll log the event and send a thumbs-up back to ServiceTitan.
Now, let's tell ServiceTitan where to send those juicy events:
const axios = require('axios'); async function registerWebhook() { try { const response = await axios.post('https://api.servicetitan.io/webhooks/v2/register', { url: 'https://your-server.com/webhook', events: ['job.created', 'job.updated'], active: true }, { headers: { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN' } }); console.log('Webhook registered:', response.data); } catch (error) { console.error('Registration failed:', error.response.data); } } registerWebhook();
Replace 'https://your-server.com/webhook'
with your actual endpoint URL and YOUR_ACCESS_TOKEN
with your ServiceTitan API token. Choose the events you want to subscribe to - we're listening for job creations and updates in this example.
When an event hits your server, you'll want to do something useful with it:
app.post('/webhook', (req, res) => { const event = req.body; switch(event.type) { case 'job.created': console.log('New job created:', event.data.id); // Do something cool with the new job break; case 'job.updated': console.log('Job updated:', event.data.id); // Update your local data or trigger a process break; default: console.log('Unhandled event type:', event.type); } res.sendStatus(200); });
This switch statement lets you handle different event types like a pro. Add more cases as you subscribe to more events.
Let's add a simple retry mechanism for those "oops" moments:
const MAX_RETRIES = 3; async function processWebhook(event, retryCount = 0) { try { // Your event processing logic here console.log('Processing event:', event.type); } catch (error) { if (retryCount < MAX_RETRIES) { console.log(`Retry attempt ${retryCount + 1}`); await new Promise(resolve => setTimeout(resolve, 1000 * (retryCount + 1))); return processWebhook(event, retryCount + 1); } else { console.error('Max retries reached. Event processing failed:', error); } } } app.post('/webhook', async (req, res) => { res.sendStatus(200); // Acknowledge receipt immediately await processWebhook(req.body); });
This setup will retry processing up to 3 times with increasing delays. Because sometimes, it's not you, it's the network.
ServiceTitan sends a signature with each webhook. Let's verify it to make sure it's legit:
const crypto = require('crypto'); function verifySignature(payload, signature, secret) { const hmac = crypto.createHmac('sha256', secret); const digest = hmac.update(JSON.stringify(payload)).digest('hex'); return signature === digest; } app.post('/webhook', (req, res) => { const signature = req.headers['x-servicetitan-signature']; if (!verifySignature(req.body, signature, 'YOUR_WEBHOOK_SECRET')) { return res.status(401).send('Invalid signature'); } // Process the webhook... res.sendStatus(200); });
Replace 'YOUR_WEBHOOK_SECRET'
with the secret ServiceTitan provides you. Safety first!
ServiceTitan offers webhook testing tools in their developer portal. Use them to simulate events and debug your implementation. It's like a sandbox, but for grown-up devs.
Log incoming webhooks and set up alerts for failures. You don't want to miss out on important events because your server decided to take a coffee break.
app.post('/webhook', (req, res) => { console.log(`Webhook received at ${new Date().toISOString()}:`, req.body); // Your processing logic here res.sendStatus(200); });
And there you have it! You've just leveled up your ServiceTitan integration skills. Remember, this is just the beginning. As you get more comfortable, you can add more complex event handling, improve your error management, and even scale your webhook processing for high-volume scenarios.
Keep experimenting, keep building, and most importantly, keep being awesome!
Check out the ServiceTitan API docs for all the nitty-gritty details. And don't forget to join the ServiceTitan developer community - we're all in this together!
Now go forth and webhook like a champion! 🚀