Hey there, fellow Javascript devs! Ready to supercharge your Hubspot Marketing Hub integration? Webhooks are your secret weapon for real-time data syncing and automation. In this guide, we'll focus on setting up webhooks for user-facing integrations, so you can keep your app in perfect harmony with Hubspot. Let's dive in!
Before we get our hands dirty, make sure you've got:
First things first, let's get you authenticated. We'll use OAuth 2.0 because, well, it's 2023 and we're not savages.
const axios = require('axios'); async function getAccessToken(clientId, clientSecret, refreshToken) { const response = await axios.post('https://api.hubapi.com/oauth/v1/token', { grant_type: 'refresh_token', client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken }); return response.data.access_token; }
Now that we're in, let's create that webhook subscription. We'll use the /webhooks/v3/subscriptions
endpoint:
async function createWebhook(accessToken, appId, eventType, targetUrl) { const response = await axios.post('https://api.hubapi.com/webhooks/v3/subscriptions', { eventType, propertyName: 'email', active: true, targetUrl }, { headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' } }); return response.data; }
Hubspot offers a smorgasbord of event types. Here are some popular ones:
contact.creation
contact.propertyChange
deal.creation
deal.propertyChange
Want to subscribe to multiple events? No problem:
const events = ['contact.creation', 'deal.creation']; events.forEach(async (event) => { await createWebhook(accessToken, appId, event, 'https://your-app.com/webhook'); });
When Hubspot sends a webhook, it's like Christmas morning. Here's what you might get:
app.post('/webhook', (req, res) => { const { eventId, subscriptionType, objectId, propertyName, propertyValue } = req.body; // Do something magical with the data console.log(`New ${subscriptionType} event: ${propertyName} changed to ${propertyValue}`); res.sendStatus(200); });
Trust, but verify. Always check that signature:
const crypto = require('crypto'); function verifyWebhookSignature(req, clientSecret) { const signature = req.headers['x-hubspot-signature']; const requestBody = JSON.stringify(req.body); const hash = crypto.createHmac('sha256', clientSecret) .update(requestBody) .digest('hex'); return signature === hash; }
Sometimes, things go sideways. Be prepared:
async function handleWebhook(payload, retries = 3) { try { await processWebhook(payload); } catch (error) { if (retries > 0) { console.log(`Retrying... ${retries} attempts left`); await new Promise(resolve => setTimeout(resolve, 1000)); await handleWebhook(payload, retries - 1); } else { console.error('Failed to process webhook after multiple attempts'); } } }
Hubspot's webhook tester is your new best friend. But for local testing, ngrok is a lifesaver:
ngrok http 3000
Then update your webhook URL in Hubspot with the ngrok URL. Voilà! Local testing made easy.
And there you have it! You're now armed and dangerous with Hubspot webhook knowledge. Remember, with great power comes great responsibility. Use these webhooks wisely, and your integrations will be smoother than a freshly waxed sports car.
Happy coding, and may your webhooks always fire true!