5 min read
ā¢Question 15 of 28mediumWhat are Webhooks?
Understanding webhooks and event-driven APIs.
What You'll Learn
- What webhooks are
- Webhooks vs polling
- Implementation example
What are Webhooks?
Webhooks are HTTP callbacks that notify your server when events occur in another system.
Webhooks vs Polling
| Aspect | Polling | Webhooks |
|---|---|---|
| Direction | Client ā Server | Server ā Client |
| Efficiency | Wastes resources | Event-driven |
| Real-time | Delayed | Immediate |
| Complexity | Simple | More setup |
How Webhooks Work
code.jsJavaScript
1. Register webhook URL with provider
2. Event occurs (e.g., payment completed)
3. Provider sends HTTP POST to your URL
4. Your server processes the eventImplementation
code.jsJavaScript
// Receiving webhooks
app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), (req, res) => {
const sig = req.headers['stripe-signature'];
try {
// Verify webhook signature
const event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
// Handle event
switch (event.type) {
case 'payment_intent.succeeded':
handlePaymentSuccess(event.data.object);
break;
case 'customer.subscription.deleted':
handleCancellation(event.data.object);
break;
}
res.json({ received: true });
} catch (err) {
res.status(400).send(`Webhook Error: ${err.message}`);
}
});
// Sending webhooks
async function sendWebhook(url, event, data) {
const payload = { event, data, timestamp: Date.now() };
const signature = createHmac('sha256', secret)
.update(JSON.stringify(payload))
.digest('hex');
await fetch(url, {
method: 'POST',
headers: { 'X-Webhook-Signature': signature },
body: JSON.stringify(payload),
});
}