Webhook System
Overview
Zafira's webhook system provides real-time notifications for all wallet activities, enabling seamless integration with external services and applications. This powerful feature allows you to stay informed about wallet events instantly.
What are Webhooks?
Webhooks are HTTP callbacks that send real-time notifications when specific events occur in your Zafira wallet. Instead of polling the API repeatedly, webhooks push data to your application immediately when events happen.
Benefits of Webhooks
- Real-time Updates: Instant notifications when events occur
- Efficient Integration: No need to poll APIs constantly
- Reduced Latency: Immediate response to wallet activities
- Better User Experience: Faster updates in your applications
Webhook Types
Charge Events
Monitor payment charge lifecycle:
charge.created- When a new payment charge is createdcharge.paid- When a charge payment is confirmedcharge.expired- When a charge expires without paymentcharge.failed- When a charge payment fails
Transaction Events
Track wallet transactions:
transaction.created- When a new transaction is initiatedtransaction.confirmed- When a transaction is confirmed on blockchaintransaction.failed- When a transaction fails or is reverted
Balance Events
Monitor balance changes:
balance.updated- When wallet balance changes for any token
Token Events
Track token management:
token.added- When a new token is added to wallettoken.removed- When a token is removed from wallet
Wallet Events
Monitor wallet management:
wallet.created- When a new wallet is createdwallet.updated- When wallet information is updated
Setting Up Webhooks
Creating a Webhook
- Access Webhook Management: Navigate to the Webhooks section in the sidebar menu
- Create New Webhook: Click "Create" to add a new webhook
- Configure Settings:
- Webhook URL: Enter your endpoint URL
- Webhook Type: Select the type of events to monitor
- Events: Choose specific events to listen for
- Status: Set to active or inactive
- Secret: Optional signature for verification
Webhook Configuration Options
Basic Configuration
- URL: The endpoint where notifications will be sent
- Type: The category of events to monitor
- Events: Specific events within the selected type
- Status: Enable or disable the webhook
Advanced Configuration
- Signature: Optional HMAC-SHA256 signature for verification
- Custom Headers: Additional headers for authentication
- Timeout Settings: Custom timeout for webhook delivery
- Retry Configuration: Custom retry logic for failed deliveries
Webhook Payload Structure
Standard Payload Format
json
{
"event": "event.name",
"data": {
"event_id": "unique-event-id",
"wallet_id": 1,
"timestamp": "2024-01-01T00:00:00Z",
"event_data": {
// Event-specific data
}
}
}Charge Event Payloads
Charge Created
json
{
"event": "charge.created",
"data": {
"charge_id": 1,
"wallet_id": 1,
"amount": "0.100000000000000000",
"token": "ETH",
"uuid": "550e8400-e29b-41d4-a716-446655440000",
"status": "pending",
"expires": 300,
"created_at": "2024-01-01T00:00:00Z"
}
}Charge Paid
json
{
"event": "charge.paid",
"data": {
"charge_id": 1,
"wallet_id": 1,
"amount": "0.100000000000000000",
"token": "ETH",
"uuid": "550e8400-e29b-41d4-a716-446655440000",
"status": "confirmed",
"payment_tx_hash": "0x1234567890abcdef...",
"paid_at": "2024-01-01T00:05:00Z"
}
}Transaction Event Payloads
Transaction Confirmed
json
{
"event": "transaction.confirmed",
"data": {
"transaction_id": 1,
"wallet_id": 1,
"amount": "0.050000000000000000",
"token": "ETH",
"tx_hash": "0x1234567890abcdef...",
"block_number": 12345678,
"status": "confirmed",
"confirmed_at": "2024-01-01T00:03:00Z"
}
}Balance Event Payloads
Balance Updated
json
{
"event": "balance.updated",
"data": {
"wallet_id": 1,
"token": "ETH",
"old_balance": "1.000000000000000000",
"new_balance": "1.100000000000000000",
"change": "0.100000000000000000",
"updated_at": "2024-01-01T00:05:00Z"
}
}Webhook Security
Signature Verification
Zafira uses HMAC-SHA256 signatures to verify webhook authenticity. When you provide a secret key, each webhook request includes a signature header.
Signature Header
http
X-Webhook-Signature: sha256=hash_of_payloadVerification Process
- Extract the signature from the
X-Webhook-Signatureheader - Generate the expected signature using your secret key
- Compare the signatures to verify authenticity
Implementation Examples
Node.js Verification
javascript
const crypto = require('crypto');
function verifyWebhookSignature(payload, signature, secret) {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return `sha256=${expectedSignature}` === signature;
}
// Usage
app.post('/webhook', (req, res) => {
const signature = req.headers['x-webhook-signature'];
const payload = JSON.stringify(req.body);
const secret = 'your-webhook-secret';
if (!verifyWebhookSignature(payload, signature, secret)) {
return res.status(401).json({ error: 'Invalid signature' });
}
// Process webhook
res.status(200).json({ received: true });
});PHP Verification
php
function verifyWebhookSignature($payload, $signature, $secret) {
$expectedSignature = 'sha256=' . hash_hmac('sha256', $payload, $secret);
return hash_equals($expectedSignature, $signature);
}
// Usage
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$payload = file_get_contents('php://input');
$secret = 'your-webhook-secret';
if (!verifyWebhookSignature($payload, $signature, $secret)) {
http_response_code(401);
exit('Invalid signature');
}
// Process webhook
http_response_code(200);
echo json_encode(['received' => true]);Webhook Delivery
Delivery Process
- Event Trigger: An event occurs in the system
- Webhook Selection: System selects relevant webhooks
- Payload Generation: Creates the webhook payload
- HTTP Request: Sends POST request to webhook URL
- Response Handling: Processes the response from your endpoint
Delivery Guarantees
- At Least Once: Webhooks are delivered at least once
- Retry Logic: Failed deliveries are retried automatically
- Timeout Handling: Requests timeout after 30 seconds
- Error Handling: Failed webhooks are logged and tracked
Retry Logic
- Retry Attempts: Up to 3 retry attempts for failed deliveries
- Retry Intervals: 1 minute, 5 minutes, 15 minutes
- Exponential Backoff: Increasing delays between retries
- Final Failure: Webhooks that fail after all retries are marked as failed
Webhook Management
Monitoring Webhook Health
- Delivery Status: Track delivery success and failure rates
- Response Times: Monitor response times for your endpoints
- Error Logs: View detailed error logs for failed deliveries
- Performance Metrics: Analyze webhook performance over time
Webhook Lifecycle
- Created: Webhook is created and configured
- Active: Webhook is active and receiving events
- Paused: Webhook is temporarily disabled
- Deleted: Webhook is removed from the system
Bulk Operations
- Bulk Creation: Create multiple webhooks at once
- Bulk Updates: Update multiple webhooks simultaneously
- Bulk Deletion: Remove multiple webhooks at once
- Bulk Testing: Test multiple webhooks simultaneously
Best Practices
Webhook Implementation
- Idempotency: Make your webhook handlers idempotent
- Fast Response: Respond to webhooks within 5 seconds
- Error Handling: Implement proper error handling
- Logging: Log all webhook activities for debugging
Security Best Practices
- HTTPS Only: Always use HTTPS for webhook endpoints
- Signature Verification: Always verify webhook signatures
- Input Validation: Validate all incoming webhook data
- Rate Limiting: Implement rate limiting on your endpoints
Performance Optimization
- Async Processing: Process webhook data asynchronously
- Queue Management: Use queues for webhook processing
- Resource Management: Manage resources efficiently
- Monitoring: Monitor webhook endpoint performance
Common Use Cases
Payment Processing
- Payment Notifications: Notify users when payments are received
- Payment Confirmations: Confirm payment processing
- Failed Payment Handling: Handle failed payment scenarios
- Refund Processing: Process refund notifications
Trading Applications
- Balance Updates: Update trading balances in real-time
- Transaction Monitoring: Monitor trading transactions
- Portfolio Updates: Update portfolio values
- Risk Management: Implement risk management based on balance changes
Accounting Integration
- Transaction Recording: Record transactions in accounting systems
- Balance Reconciliation: Reconcile balances with accounting records
- Tax Reporting: Generate tax reports from transaction data
- Audit Trails: Maintain audit trails for compliance
User Notifications
- Push Notifications: Send push notifications to mobile apps
- Email Notifications: Send email notifications for important events
- SMS Alerts: Send SMS alerts for critical events
- In-app Notifications: Display notifications within applications
Troubleshooting
Common Issues
- Webhook Not Receiving Events: Check webhook configuration and URL
- Signature Verification Failures: Verify secret key and signature generation
- Timeout Errors: Optimize webhook endpoint response time
- Duplicate Events: Implement idempotency in webhook handlers
Debugging Tools
- Webhook Logs: View detailed webhook delivery logs
- Event History: Track event history and delivery attempts
- Response Analysis: Analyze webhook response codes and content
- Performance Metrics: Monitor webhook performance metrics
Support Resources
- Documentation: Comprehensive webhook documentation
- Code Examples: Ready-to-use code examples
- Community Support: Community forums and support
- Technical Support: Direct technical support for issues
Next Steps
- API Integration - API usage and integration
- Payment System - Payment and charge features
- Security Features - Security and compliance
- API Examples - Practical webhook implementation examples