Hey there, fellow Javascript dev! Ready to dive into the world of webhooks with Hotmart? Let's get you set up in no time.
Webhooks are like the cool kids of API integrations - they notify your app in real-time when something interesting happens. And with Hotmart's API, you can tap into this power effortlessly. Let's get your app talking to Hotmart like old friends at a coffee shop.
Before we jump in, make sure you've got:
First things first, let's create a simple Express server to catch those webhook notifications:
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 is up and running!'));
Boom! You've got a basic server ready to receive webhooks. Easy peasy, right?
Now, hop over to your Hotmart dashboard:
https://yourawesome.app/webhook
)When Hotmart sends a webhook, it's packed with juicy details. Let's unpack it:
app.post('/webhook', (req, res) => { const { event, data } = req.body; switch(event) { case 'PURCHASE_COMPLETE': handlePurchase(data); break; // Add more cases as needed } res.sendStatus(200); }); function handlePurchase(data) { console.log(`Cha-ching! New purchase: ${data.purchase.order_id}`); // Do your thing with the purchase data }
Security is not just for the paranoid. Let's add some signature verification:
const crypto = require('crypto'); function verifySignature(req, res, next) { const signature = req.headers['x-hotmart-signature']; const body = JSON.stringify(req.body); const expectedSignature = crypto .createHmac('sha256', process.env.HOTMART_WEBHOOK_SECRET) .update(body) .digest('hex'); if (signature === expectedSignature) { next(); } else { res.sendStatus(401); } } app.post('/webhook', verifySignature, (req, res) => { // Your webhook handling code });
Now you're Fort Knox-level secure!
Different events, different actions. Let's handle them like a pro:
function processWebhook(event, data) { switch(event) { case 'PURCHASE_COMPLETE': sendWelcomeEmail(data.customer.email); break; case 'SUBSCRIPTION_CANCELED': startWinBackCampaign(data.customer.id); break; // More cases, more fun! } }
Errors happen. Let's catch 'em all:
app.post('/webhook', (req, res) => { try { processWebhook(req.body.event, req.body.data); res.sendStatus(200); } catch (error) { console.error('Webhook processing failed:', error); res.sendStatus(500); } });
Hotmart's got your back with a webhook testing tool. Use it to simulate events and debug like a detective. Remember, console.log
is your best friend here!
And there you have it! You're now a Hotmart webhook wizard. Remember, practice makes perfect, so keep experimenting and refining your implementation.
Next steps? Maybe dive into advanced event handling or explore Hotmart's other API features. The sky's the limit!
Now go forth and webhook like a boss! 🚀