Using Webhooks
Learn how to set up and manage webhooks for real-time notifications
What are Webhooks?
Webhooks allow IriSync to send real-time notifications to your application when specific events occur. Rather than requiring your application to constantly poll the API for changes, webhooks provide push-based updates delivered directly to your specified endpoint.
When an event happens in IriSync (such as content being published or a user subscribing), a webhook sends an HTTP POST request to your configured URL with information about the event. Your application can then react to these events in real-time.
Getting Started with Webhooks
1. Creating a Webhook Endpoint
First, create an endpoint in your application that can receive POST requests. This endpoint should:
- Be publicly accessible
IriSync needs to reach your server to deliver events
- Use HTTPS
Webhooks contain sensitive data and should be sent securely
- Validate webhook signatures
Confirm that events are actually coming from IriSync
- Process events idempotently
Handle potential duplicate events gracefully
2. Registering Your Webhook
Once your endpoint is ready, register it with IriSync:
Option 1: Via Dashboard
- Go to Settings > Webhooks
- Click 'Create Webhook'
- Enter your endpoint URL
- Select events to subscribe to
- Click 'Save'
Option 2: Via API
- Use the Webhooks API endpoint
- Send a POST request with endpoint details
- Include event types to subscribe to
- Store the returned webhook ID and secret
Example code for registering a webhook via the API:
// Register a new webhook programmatically
async function registerWebhook() {
const response = await fetch('https://api.irisync.com/api/webhooks', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: 'https://your-domain.com/webhooks/irisync',
events: ['content.published', 'user.subscribed', 'platform.connected'],
description: 'Production webhook for content updates',
active: true,
secret: 'your_webhook_secret' // Optional: If not provided, IriSync will generate one
})
});
const data = await response.json();
return data;
}3. Testing Your Webhook
After registering your webhook, you can test it:
- Use the 'Test Webhook' button in the dashboard
Sends a test event to your endpoint
- Check logs for incoming test events
Verify your endpoint is receiving and processing events correctly
- Trigger real events in your IriSync account
For example, publish a piece of content
Webhook Event Types
IriSync webhooks can notify you about various events. Here are the main event categories:
Content Events
- content.created
- content.published
- content.updated
- content.deleted
User Events
- user.created
- user.updated
- user.subscribed
- user.unsubscribed
Platform Events
- platform.connected
- platform.disconnected
- platform.post.success
- platform.post.failed
content.published
Triggered when content is published
Example Payload
{
"id": "evt_123abc",
"type": "content.published",
"created": "2023-06-15T14:30:00Z",
"data": {
"content_id": "cnt_456def",
"title": "New Blog Post",
"status": "published",
"published_at": "2023-06-15T14:30:00Z",
"author_id": "usr_789ghi",
"platforms": [
"twitter",
"linkedin"
]
}
}content.updated
Triggered when content is modified
Example Payload
{
"id": "evt_234bcd",
"type": "content.updated",
"created": "2023-06-16T09:15:00Z",
"data": {
"content_id": "cnt_456def",
"title": "Updated Blog Post",
"status": "published",
"updated_at": "2023-06-16T09:15:00Z",
"author_id": "usr_789ghi"
}
}user.subscribed
Triggered when a user subscribes to a plan
Example Payload
{
"id": "evt_345cde",
"type": "user.subscribed",
"created": "2023-06-17T11:00:00Z",
"data": {
"user_id": "usr_890jkl",
"plan_id": "pln_123abc",
"subscription_id": "sub_456def",
"status": "active",
"trial_end": "2023-07-17T11:00:00Z",
"billing_interval": "month"
}
}platform.connected
Triggered when a platform is connected
Example Payload
{
"id": "evt_456def",
"type": "platform.connected",
"created": "2023-06-18T13:45:00Z",
"data": {
"user_id": "usr_901lmn",
"platform_id": "twitter",
"connected_at": "2023-06-18T13:45:00Z",
"status": "active",
"scopes": [
"read",
"write"
]
}
}Webhook Security
Signature Verification
Every webhook request from IriSync includes a signature in the X-IriSync-Signature header. This allows you to verify that the request came from IriSync and not a third party.
To verify the signature:
- Get the signature from the X-IriSync-Signature header
- Get the timestamp from the X-IriSync-Timestamp header
- Create an HMAC SHA-256 hash of [timestamp].[payload] using your webhook secret
- Compare this hash to the signature in the header
Best Security Practices
- Always verify the signature
Don't process webhooks without verifying
- Keep your webhook secret secure
Never commit it to public repositories
- Use HTTPS endpoints
Protect data in transit
- Rotate webhook secrets periodically
In the Settings > Webhooks section
Webhook Implementation Example
Here's a complete example of a Node.js webhook handler using Express:
// Example Express.js webhook handler
const express = require('express');
const crypto = require('crypto');
const app = express();
// Parse JSON requests
app.use(express.json({
verify: (req, res, buf) => {
// Store the raw body for webhook signature verification
req.rawBody = buf;
}
}));
app.post('/webhooks/irisync', async (req, res) => {
try {
// Verify webhook signature
const signature = req.headers['x-irisync-signature'];
const timestamp = req.headers['x-irisync-timestamp'];
const webhookSecret = process.env.IRISYNC_WEBHOOK_SECRET;
const payload = req.rawBody.toString();
const expectedSignature = crypto
.createHmac('sha256', webhookSecret)
.update(`${timestamp}.${payload}`)
.digest('hex');
// Compare signatures
if (signature !== expectedSignature) {
console.error('Invalid webhook signature');
return res.status(401).send('Invalid signature');
}
// Process the webhook event
const event = req.body;
switch (event.type) {
case 'content.published':
await handleContentPublished(event.data);
break;
case 'user.subscribed':
await handleUserSubscribed(event.data);
break;
default:
console.log(`Unhandled event type: ${event.type}`);
}
// Always respond with 200 to acknowledge receipt
res.status(200).send('Webhook received');
} catch (error) {
console.error('Webhook error:', error);
res.status(500).send('Webhook processing failed');
}
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});Webhook Reliability
Handling Retries
If your endpoint returns a non-2xx response code or times out, IriSync will retry the webhook delivery on the following schedule:
- 1st retry: 5 minutes after initial failure
- 2nd retry: 30 minutes after initial failure
- 3rd retry: 2 hours after initial failure
- 4th retry: 5 hours after initial failure
- 5th retry: 10 hours after initial failure
After the 5th retry, the webhook will be marked as failed and will not be retried again.
Idempotency
Since webhooks might be delivered more than once, ensure your webhook handler is idempotent – it should produce the same result even if the same event is processed multiple times.
Example of handling webhook idempotency:
// Handling webhook retries and idempotency
function isIdempotentlyProcessed(eventId) {
// Check if this event has already been processed
// This could be a database check, Redis, etc.
return db.webhookEvents.exists(eventId);
}
function markEventProcessed(eventId) {
// Mark this event as processed to prevent duplicate processing
return db.webhookEvents.create({ eventId, processedAt: new Date() });
}
app.post('/webhooks/irisync', async (req, res) => {
try {
// Verification code...
const event = req.body;
const eventId = event.id;
// Check if already processed to ensure idempotency
if (await isIdempotentlyProcessed(eventId)) {
console.log(`Event ${eventId} already processed`);
return res.status(200).send('Event already processed');
}
// Process the event...
// Mark as processed after successful processing
await markEventProcessed(eventId);
res.status(200).send('Webhook processed');
} catch (error) {
console.error('Webhook error:', error);
res.status(500).send('Webhook processing failed');
}
});Monitoring and Debugging
IriSync provides tools to help you monitor and debug your webhooks:
Webhook Logs
View detailed logs for each webhook delivery:
- Go to Settings > Webhooks
- Click on a webhook
- View the 'Recent Deliveries' section
Logs include request details, response codes, and timestamps for each attempt.
Webhook Testing
Test webhooks without triggering real events:
- Go to Settings > Webhooks
- Select a webhook
- Click 'Send Test Event'
- Select an event type
Test events are clearly marked with a test flag in the payload.
Next Steps
Now that you understand webhooks, explore these related resources: