Hey there, fellow JavaScript ninja! Ready to level up your Simpro integration game? Let's dive into the world of webhooks and make your app dance to Simpro's real-time tune.
Before we jump in, make sure you've got:
axios
and express
)First things first, let's create a simple Express server to catch 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'));
Boom! You've got a basic webhook endpoint ready to rock.
Now, let's tell Simpro where to send those sweet, sweet events:
const axios = require('axios'); async function registerWebhook() { try { const response = await axios.post('https://api.simpro.co/v1/webhooks', { url: 'https://your-domain.com/webhook', events: ['job.created', 'invoice.paid'] }, { headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' } }); console.log('Webhook registered:', response.data); } catch (error) { console.error('Error registering webhook:', error.response.data); } } registerWebhook();
Replace YOUR_API_TOKEN
with your actual token, and you're golden!
Time to do something useful with those incoming events:
app.post('/webhook', (req, res) => { const event = req.body; switch(event.type) { case 'job.created': handleNewJob(event.data); break; case 'invoice.paid': celebratePayment(event.data); break; default: console.log('Unhandled event type:', event.type); } res.sendStatus(200); }); function handleNewJob(jobData) { console.log('New job created:', jobData.id); // Do something awesome with the new job } function celebratePayment(invoiceData) { console.log('Cha-ching! Invoice paid:', invoiceData.id); // Pop the champagne! 🍾 }
Ready to see your creation in action? Fire up ngrok to expose your local server:
ngrok http 3000
Copy that fancy ngrok URL and update your webhook registration. Then, head over to Simpro and trigger some test events. Watch your console light up like a Christmas tree!
Webhook not firing? Check these common culprits:
And there you have it! You're now a Simpro webhook wizard. Remember, with great power comes great responsibility (and awesome integrations). Keep experimenting, and don't forget to check out the Simpro API docs for more magical possibilities.
Now go forth and webhook all the things! 🚀