Hướng dẫn Tích hợp Webhook
Nhận thông báo thời gian thực khi tác vụ hoàn thành
Tổng quan
Webhooks allow your application to receive real-time notifications when events occur in Toolify. Instead of polling the API to check task status, webhooks will send you an HTTP POST request whenever a task status changes.
This enables you to build reactive applications that respond immediately to task completion, failure, or progress updates.
Webhooks là gì?
Webhooks are automated messages sent from apps when something happens. They're also known as reverse APIs or push APIs. Instead of constantly checking the API for updates, webhooks push updates to you when they occur.
Key benefits:
- Real-time notifications instead of polling
- Reduced server load and network traffic
- Faster response to task completion
- Automatic retry on failure
- Signed payloads for security verification
Thiết lập Webhooks
- Log in to your Toolify account and navigate to the API Dashboard
- Go to the Webhooks section
- Enter your webhook URL (must be HTTPS)
- Save your webhook configuration
- Test your webhook by creating a task
Requirements:
- Webhook URL must be publicly accessible
- Must use HTTPS (HTTP is not supported)
- Must respond with HTTP 200 status within 30 seconds
- Should handle retries gracefully
Sự kiện Webhook
Toolify sends webhooks for the following task events:
Processing Event
Sent when a task starts processing. This indicates that your task has been queued and is about to begin processing.
{
"event": "processing",
"timestamp": "2025-01-15T10:28:00Z",
"task": {
"id": 123,
"service": "domain_check_availability",
"platform": "domain",
"status": "processing",
"total_items": 2,
"completed_items": 0,
"failed_items": 0,
"cost": 60,
"created_at": "2025-01-15T10:28:00Z",
"started_at": "2025-01-15T10:28:00Z"
}
}
Completed Event
Sent when a task completes successfully. Includes all results from the task processing.
{
"event": "completed",
"timestamp": "2025-01-15T10:30:00Z",
"task": {
"id": 123,
"service": "domain_check_availability",
"platform": "domain",
"status": "completed",
"total_items": 2,
"completed_items": 2,
"failed_items": 0,
"cost": 60,
"created_at": "2025-01-15T10:28:00Z",
"completed_at": "2025-01-15T10:30:00Z"
}
}
Failed Event
Sent when a task fails or encounters an error. Includes error information for debugging.
{
"event": "failed",
"timestamp": "2025-01-15T10:29:30Z",
"task": {
"id": 123,
"service": "domain_check_availability",
"platform": "domain",
"status": "failed",
"total_items": 2,
"completed_items": 1,
"failed_items": 1,
"cost": 60,
"error_message": "Network timeout while checking domain availability",
"created_at": "2025-01-15T10:28:00Z",
"failed_at": "2025-01-15T10:29:30Z"
}
}
Bảo mật & Xác minh
All webhook requests include an X-Webhook-Signature header that contains your API key. You should verify this signature to ensure the webhook came from Toolify.
Request Headers
POST /your-webhook-url HTTP/1.1
Content-Type: application/json
X-Webhook-Signature: your_api_key_here
User-Agent: Toolify-Webhook/1.0
Security Best Practices
- Always verify the signature by comparing the X-Webhook-Signature header with your API key
- Use HTTPS only to ensure webhook payload encryption
- Validate the timestamp to prevent replay attacks (optional)
- Respond quickly - your endpoint should respond within 30 seconds
- Log all webhooks for debugging and auditing purposes
- Handle retries gracefully - Toolify will retry failed deliveries
Xử lý Webhooks
const express = require('express');
const app = express();
app.use(express.json());
// Your API key from Toolify dashboard
const API_KEY = process.env.TOOLIFY_API_KEY;
app.post('/webhook', (req, res) => {
// Verify the signature
const signature = req.headers['x-webhook-signature'];
if (signature !== API_KEY) {
return res.status(401).json({ error: 'Invalid signature' });
}
const { event, task } = req.body;
// Handle different events
switch (event) {
case 'processing':
console.log(`Task ${task.id} is processing`);
break;
case 'completed':
console.log(`Task ${task.id} completed with ${task.completed_items} items`);
// Process results
break;
case 'failed':
console.log(`Task ${task.id} failed: ${task.error_message}`);
// Handle failure
break;
}
// Respond immediately
res.json({ received: true });
});
app.listen(3000, () => {
console.log('Webhook server listening on port 3000');
});
from flask import Flask, request, jsonify
import os
app = Flask(__name__)
# Your API key from Toolify dashboard
API_KEY = os.environ.get('TOOLIFY_API_KEY')
@app.route('/webhook', methods=['POST'])
def webhook():
# Verify the signature
signature = request.headers.get('X-Webhook-Signature')
if signature != API_KEY:
return jsonify({'error': 'Invalid signature'}), 401
data = request.json
event = data['event']
task = data['task']
# Handle different events
if event == 'processing':
print(f"Task {task['id']} is processing")
elif event == 'completed':
print(f"Task {task['id']} completed with {task['completed_items']} items")
# Process results
elif event == 'failed':
print(f"Task {task['id']} failed: {task['error_message']}")
# Handle failure
# Respond immediately
return jsonify({'received': True}), 200
if __name__ == '__main__':
app.run(port=3000)
'Invalid signature']);
exit;
}
// Get the webhook payload
$payload = json_decode(file_get_contents('php://input'), true);
$event = $payload['event'];
$task = $payload['task'];
// Handle different events
switch ($event) {
case 'processing':
error_log("Task {$task['id']} is processing");
break;
case 'completed':
error_log("Task {$task['id']} completed with {$task['completed_items']} items");
// Process results
break;
case 'failed':
error_log("Task {$task['id']} failed: {$task['error_message']}");
// Handle failure
break;
}
// Respond immediately
header('Content-Type: application/json');
echo json_encode(['received' => true]);
?>
Chính sách Thử lại
Toolify automatically retries failed webhook deliveries with exponential backoff. If your endpoint doesn't respond with HTTP 200 within 30 seconds, the request is considered failed and will be retried.
Retry schedule:
- Attempt 1: Immediate
- Attempt 2: 5 seconds later
- Attempt 3: 30 seconds later
- Attempt 4: 2 minutes later
- Attempt 5: 5 minutes later
- Attempt 6: 10 minutes later
After 6 failed attempts (over approximately 18 minutes), the webhook delivery is abandoned and logged as failed.
Thử nghiệm Webhooks
You can test your webhook implementation by:
- Using a webhook testing service like webhook.site or requestbin.com
- Creating a task in your Toolify account
- Observing the webhook delivery in your test service
You can also view all webhook deliveries in your API Dashboard, including:
- Delivery timestamps
- HTTP status codes
- Response times
- Payloads
- Retry history
Khắc phục sự cố
Webhook Not Being Delivered
- Check that your webhook URL is correct and publicly accessible
- Verify your endpoint is using HTTPS
- Check your server logs for errors
- Ensure your endpoint responds with HTTP 200
- Check webhook delivery history in your dashboard
Invalid Signature Error
- Verify you're using the correct API key
- Check that you're reading the X-Webhook-Signature header correctly
- Ensure there are no extra spaces or characters in the signature comparison
Slow Response Times
- Process webhook payload asynchronously when possible
- Don't perform heavy operations directly in webhook handler
- Use message queues (RabbitMQ, Redis, etc.) for async processing
- Respond immediately with HTTP 200, then process in background
Ready to Start?
Set up webhooks in your API Dashboard and start receiving real-time notifications for your tasks.
Back to API Guide →