Webhooks API
The Webhooks API allows you to configure webhook endpoints that receive real-time notifications about events in your VesuvioPay store. Set up webhooks to keep your systems synchronized, trigger automated workflows, and build event-driven integrations.
Overview​
The Webhooks API enables you to:
- Create Webhook Endpoints: Register URLs to receive event notifications
- Manage Subscriptions: Subscribe to specific event types
- Update Configuration: Modify endpoint URLs and event subscriptions
- Test Webhooks: Send test events to verify endpoint configuration
- Security Management: Rotate webhook secrets for enhanced security
- Monitor Deliveries: Track webhook delivery status and troubleshoot issues
Webhooks provide a push-based model for real-time updates, eliminating the need for polling and ensuring immediate notification of important events.
Use Cases​
Real-Time Order Notifications​
Receive immediate notifications when orders are placed or updated:
// Create webhook for order events
await vesuvioPay.webhooks.create(storeId, {
url: 'https://your-domain.com/webhooks/vesuviopay',
eventTypes: [
'order.created',
'order.status_updated',
'order.shipped',
'order.delivered'
],
description: 'Order fulfillment webhook'
});
Inventory Synchronization​
Keep your inventory management system synchronized:
// Subscribe to product inventory events
await vesuvioPay.webhooks.create(storeId, {
url: 'https://your-domain.com/webhooks/inventory',
eventTypes: [
'product.inventory_updated',
'product.variant_created',
'product.variant_updated'
],
description: 'Inventory sync webhook'
});
Customer Analytics​
Track customer behavior for analytics and marketing:
// Monitor cart and customer events
await vesuvioPay.webhooks.create(storeId, {
url: 'https://your-domain.com/webhooks/analytics',
eventTypes: [
'cart.item_added',
'cart.abandoned',
'cart.checkout_started',
'customer.created'
],
description: 'Customer analytics webhook'
});
Multi-System Integration​
Forward events to multiple systems or message queues:
// Create multiple webhooks for different systems
const webhooks = [
{
url: 'https://erp.example.com/webhook',
eventTypes: ['order.created', 'order.cancelled'],
description: 'ERP system integration'
},
{
url: 'https://crm.example.com/webhook',
eventTypes: ['customer.created', 'customer.updated'],
description: 'CRM system integration'
},
{
url: 'https://analytics.example.com/webhook',
eventTypes: ['cart.abandoned', 'order.created'],
description: 'Analytics platform'
}
];
for (const config of webhooks) {
await vesuvioPay.webhooks.create(storeId, config);
}
Authentication​
All Webhooks API endpoints require authentication using a Private API Key. Webhook configuration affects your store's integrations and must be protected.
Include your private API key in the request header:
X-API-Key: your_private_api_key_here
Available Event Types​
Cart Events​
Track shopping cart activities:
cart.created: New cart initialized for a customercart.item_added: Item added to cartcart.item_updated: Cart item quantity or details changedcart.item_removed: Item removed from cartcart.abandoned: Cart inactive for threshold periodcart.recovered: Customer returned to abandoned cartcart.cleared: All items removed from cartcart.checkout_started: Customer began checkout process
Order Events​
Monitor order lifecycle:
order.created: New order placedorder.status_updated: Order status changedorder.confirmed: Payment confirmedorder.shipped: Order dispatched to customerorder.delivered: Order received by customerorder.cancelled: Order cancelledorder.refunded: Refund processedorder.partially_shipped: Some items shippedorder.partially_delivered: Some items delivered
Customer Events​
Track customer account changes:
customer.created: New customer registeredcustomer.updated: Customer information changedcustomer.deleted: Customer account removed
Product Events​
Monitor catalog changes:
product.created: New product addedproduct.updated: Product details changedproduct.deleted: Product removedproduct.inventory_updated: Stock level changedproduct.variant_created: New product variant addedproduct.variant_updated: Variant details changedproduct.variant_deleted: Variant removed
System Events​
Webhook management events:
webhook.test: Test event for endpoint verificationwebhook.endpoint_created: Webhook endpoint createdwebhook.endpoint_updated: Webhook configuration updatedwebhook.endpoint_deleted: Webhook endpoint removed
The following events are currently being sent by the system:
- Cart events: created, item_added, item_updated, item_removed, cleared
- Order events: created, status_updated, shipped, delivered
Other event types are supported for future use as features are rolled out.
Key Concepts​
Webhook Endpoints​
A webhook endpoint is:
- URL: HTTPS endpoint that receives POST requests
- Event Subscriptions: List of event types to receive
- Secret: Signing key for request verification
- Status: Enabled/disabled state
- Metadata: Custom information for tracking
Event Payload​
Webhook events are delivered as POST requests with JSON payloads:
{
"id": "evt_123456",
"type": "order.created",
"createdAt": "2024-01-15T10:30:00Z",
"storeId": "store_guid",
"data": {
"orderId": "order_guid",
"orderNumber": "ORD-001234",
"customerId": "customer_guid",
"total": 99.99,
"status": "pending",
// ... full order object
}
}
Webhook Signatures​
All webhook requests include a signature header for verification:
X-VesuvioPay-Signature: sha256=abc123...
The signature is an HMAC-SHA256 hash of the request body using your webhook secret. Always verify signatures to ensure requests are from VesuvioPay.
Delivery Guarantees​
VesuvioPay webhooks provide:
- At-least-once delivery: Events may be delivered multiple times
- Ordered delivery: Events for the same resource are delivered in order
- Retry logic: Failed deliveries are retried with exponential backoff
- Timeout: 30-second timeout for endpoint responses
Endpoint Requirements​
Your webhook endpoint must:
- Use HTTPS (HTTP not supported)
- Respond within 30 seconds
- Return 2xx status code for success
- Be publicly accessible (no localhost)
- Handle idempotent processing (duplicate events)
Retry Behavior​
Failed webhook deliveries are retried:
- Initial retry after 1 minute
- Subsequent retries with exponential backoff
- Maximum of 10 retry attempts
- Webhook disabled after repeated failures
Response Format​
Webhook creation returns the endpoint details:
{
"success": true,
"data": {
"id": "webhook_guid",
"storeId": "store_guid",
"url": "https://your-domain.com/webhooks/vesuviopay",
"eventTypes": [
"order.created",
"order.status_updated"
],
"secret": "whsec_abc123...",
"isEnabled": true,
"description": "Order fulfillment webhook",
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:30:00Z"
}
}
Webhook test results include delivery information:
{
"success": true,
"data": {
"webhookId": "webhook_guid",
"eventType": "webhook.test",
"deliveryStatus": "success",
"responseCode": 200,
"responseTime": 145,
"sentAt": "2024-01-15T10:30:00Z"
}
}
Webhook Security​
Verifying Signatures​
Always verify webhook signatures to ensure authenticity:
const crypto = require('crypto');
function verifyWebhookSignature(payload, signature, secret) {
// Extract signature from header
const expectedSignature = signature.replace('sha256=', '');
// Calculate HMAC
const hmac = crypto.createHmac('sha256', secret);
hmac.update(payload);
const calculatedSignature = hmac.digest('hex');
// Compare signatures
return crypto.timingSafeEqual(
Buffer.from(expectedSignature),
Buffer.from(calculatedSignature)
);
}
// In your webhook handler
app.post('/webhooks/vesuviopay', (req, res) => {
const signature = req.headers['x-vesuviopay-signature'];
const payload = JSON.stringify(req.body);
if (!verifyWebhookSignature(payload, signature, WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}
// Process webhook event
processWebhookEvent(req.body);
res.status(200).send('OK');
});
Secret Rotation​
Rotate webhook secrets periodically for security:
// Rotate webhook secret
const result = await vesuvioPay.webhooks.rotateSecret(storeId, webhookId);
// Update your application with new secret
updateWebhookSecret(result.secret);
IP Allowlisting​
For additional security, allowlist VesuvioPay webhook IP addresses in your firewall. Contact support for current IP ranges.
Error Handling​
Common error scenarios:
- 404 Not Found: Webhook endpoint doesn't exist
- 400 Bad Request: Invalid URL or event types
- 401 Unauthorized: Missing or invalid API key
- 403 Forbidden: API key doesn't have access to store
- 409 Conflict: Webhook URL already registered
Webhook delivery errors:
- Connection Refused: Endpoint not accessible
- Timeout: Endpoint didn't respond within 30 seconds
- 5xx Errors: Endpoint returned server error
- Invalid Response: Non-2xx status code
See the Error Handling guide for detailed error response formats.
Best Practices​
Idempotent Processing​
Handle duplicate events gracefully:
const processedEvents = new Set();
async function handleWebhook(event) {
// Check if already processed
if (processedEvents.has(event.id)) {
console.log(`Event ${event.id} already processed`);
return;
}
// Process event
await processEvent(event);
// Mark as processed
processedEvents.add(event.id);
}
Fast Response Times​
Respond quickly and process asynchronously:
app.post('/webhooks/vesuviopay', async (req, res) => {
// Verify signature
if (!verifySignature(req)) {
return res.status(401).send('Invalid signature');
}
// Respond immediately
res.status(200).send('OK');
// Process asynchronously
setImmediate(async () => {
try {
await processWebhookEvent(req.body);
} catch (error) {
console.error('Webhook processing error:', error);
// Log for retry or manual review
}
});
});
Error Handling and Logging​
Log webhook events for troubleshooting:
async function processWebhook(event) {
console.log(`Received webhook: ${event.type} (${event.id})`);
try {
await handleEvent(event);
console.log(`Successfully processed: ${event.id}`);
} catch (error) {
console.error(`Failed to process ${event.id}:`, error);
// Store for retry or manual processing
await logFailedWebhook(event, error);
throw error; // Re-throw for VesuvioPay to retry
}
}
Testing Webhooks​
Use the test endpoint during development:
// Send test event to your endpoint
const testResult = await vesuvioPay.webhooks.test(storeId, webhookId, 'order.created');
if (testResult.deliveryStatus === 'success') {
console.log('Webhook endpoint configured correctly');
} else {
console.error('Webhook test failed:', testResult);
}
Event Type Filtering​
Subscribe only to needed events:
// Good: Specific events
await vesuvioPay.webhooks.create(storeId, {
url: 'https://your-domain.com/webhooks',
eventTypes: ['order.created', 'order.shipped'] // Only what you need
});
// Avoid: All events if not needed
await vesuvioPay.webhooks.create(storeId, {
url: 'https://your-domain.com/webhooks',
eventTypes: ['*'] // Generates unnecessary traffic
});
Rate Limiting​
Webhook management operations are subject to rate limiting:
- Endpoint creation/updates: Limited to prevent abuse
- Test endpoint: Rate limited per webhook
- Secret rotation: Limited frequency to prevent lockouts
See the Rate Limiting documentation for details.
Monitoring and Debugging​
Webhook Logs​
Monitor webhook delivery through the merchant dashboard:
- View delivery attempts and responses
- Check error messages and status codes
- Review retry schedules
- Analyze webhook performance
Local Development​
For local testing, use tools like:
- ngrok: Expose localhost to the internet
- webhook.site: Test endpoint for debugging
- RequestBin: Capture and inspect webhook requests
# Expose local server with ngrok
ngrok http 3000
# Use the ngrok URL in webhook configuration
https://abc123.ngrok.io/webhooks/vesuviopay
Next Steps​
- Review specific endpoint documentation in the API reference below
- Set up webhook handlers for critical events
- Implement signature verification for security
- Monitor webhook delivery in the merchant dashboard
- Integrate webhooks with other APIs for complete automation
Interactive API Reference​
Detailed endpoint documentation is auto-generated from our OpenAPI specification. See the interactive API reference below for complete request/response schemas, event payload structures, and the ability to test endpoints directly.