Webhooks API

Webhooks allow your application to receive real-time notifications about events happening in the OSUS.AI platform, enabling you to build responsive integrations and keep your systems synchronized.

Base URL: https://api.osus.ai/v1/webhooks

What are Webhooks?

Webhooks are HTTP POST requests that OSUS.AI sends to your application when specific events occur. Instead of repeatedly polling our API for updates, webhooks allow you to receive notifications immediately when something important happens.

Available Events

Order Events
Payment Events
User Events
Product Events
Service Events
Security First

All webhook payloads are signed with HMAC-SHA256 to ensure authenticity and integrity. Always verify the signature before processing webhook data.

Getting Started

Follow these steps to set up webhooks for your application.

1Create Endpoint

Create an HTTPS endpoint in your application that can receive POST requests.

2Register Webhook

Use the API to register your endpoint and subscribe to specific events.

3Verify Signatures

Implement signature verification to ensure webhook authenticity.

4Process Events

Handle different event types and update your application accordingly.

Webhook Management Endpoints

Manage your webhook subscriptions using these API endpoints.

POST /webhooks

Create a new webhook subscription

GET /webhooks

List all webhook subscriptions

GET /webhooks/{webhookId}

Get specific webhook details

PUT /webhooks/{webhookId}

Update webhook configuration

DELETE /webhooks/{webhookId}

Delete webhook subscription

POST /webhooks/{webhookId}/test

Send test webhook event

Create Webhook Subscription

Parameter Type Required Description
url string Yes HTTPS endpoint URL to receive webhooks
events array Yes List of event types to subscribe to
description string No Description of the webhook purpose
secret string No Secret key for signature verification
headers object No Custom headers to include in requests
isActive boolean No Enable/disable webhook (default: true)

Example Request

curl -X POST https://api.osus.ai/v1/webhooks \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-app.com/webhooks/osus",
    "events": [
      "order.created",
      "order.status_changed",
      "payment.completed",
      "user.registered"
    ],
    "description": "Main application webhook",
    "secret": "your-webhook-secret-key",
    "headers": {
      "X-App-Version": "1.0"
    },
    "isActive": true
  }'

Response

{
  "success": true,
  "data": {
    "webhook": {
      "id": "wh-123456",
      "url": "https://your-app.com/webhooks/osus",
      "events": [
        "order.created",
        "order.status_changed",
        "payment.completed",
        "user.registered"
      ],
      "description": "Main application webhook",
      "secret": "your-webhook-secret-key",
      "headers": {
        "X-App-Version": "1.0"
      },
      "isActive": true,
      "statistics": {
        "totalSent": 0,
        "successfulDeliveries": 0,
        "failedDeliveries": 0,
        "lastDeliveryAt": null
      },
      "createdAt": "2025-01-15T10:30:00Z",
      "updatedAt": "2025-01-15T10:30:00Z"
    }
  },
  "timestamp": "2025-01-15T10:30:00Z",
  "requestId": "req_123456"
}

Event Types

Complete list of available webhook events and their descriptions.

Event Type Category Description Frequency
order.created Order New order has been created High
order.status_changed Order Order status has been updated High
order.cancelled Order Order has been cancelled Medium
payment.completed Payment Payment has been successfully processed High
payment.failed Payment Payment processing failed Medium
payment.refunded Payment Payment has been refunded Low
user.registered User New user account created Medium
user.email_verified User User email address verified Medium
service.booking_created Service New service booking created Medium
service.booking_completed Service Service booking completed Medium
product.stock_low Product Product stock below threshold Low
product.back_in_stock Product Out-of-stock product restocked Low

Order Events

Detailed structure for order-related webhook events.

Order Created Event

{
  "id": "evt_123456",
  "type": "order.created",
  "created": "2025-01-15T10:30:00Z",
  "data": {
    "object": {
      "id": "ord-123456",
      "orderNumber": "OSUS-2025-000001",
      "status": "pending",
      "customer": {
        "id": "user-001",
        "email": "ahmed@example.com",
        "name": "Ahmed Mohamed"
      },
      "items": [
        {
          "productId": "550e8400-e29b-41d4-a716-446655440000",
          "productName": "Modern 3-Seat Sofa",
          "quantity": 1,
          "unitPrice": 2500,
          "totalPrice": 2500
        }
      ],
      "pricing": {
        "subtotal": 2500,
        "taxAmount": 375,
        "shippingAmount": 50,
        "totalAmount": 2925,
        "currency": "EGP"
      },
      "shipping": {
        "method": "standard",
        "estimatedDelivery": "2025-01-20T10:00:00Z",
        "address": {
          "line1": "123 Tahrir Square",
          "city": "Cairo",
          "governorate": "Cairo",
          "postalCode": "11511"
        }
      },
      "createdAt": "2025-01-15T10:30:00Z"
    }
  },
  "livemode": true,
  "pending_webhooks": 1,
  "request": {
    "id": "req_123456",
    "idempotency_key": null
  }
}

Order Status Changed Event

{
  "id": "evt_123457",
  "type": "order.status_changed",
  "created": "2025-01-16T08:00:00Z",
  "data": {
    "object": {
      "id": "ord-123456",
      "orderNumber": "OSUS-2025-000001",
      "status": "confirmed",
      "previousStatus": "pending",
      "statusChangedAt": "2025-01-16T08:00:00Z",
      "statusChangedBy": "system",
      "tracking": {
        "trackingNumber": "TRK-789012345",
        "carrier": "OSUS Logistics",
        "estimatedDelivery": "2025-01-20T10:00:00Z"
      }
    }
  },
  "livemode": true
}

Payment Events

Payment-related webhook events for transaction processing.

Payment Completed Event

{
  "id": "evt_123458",
  "type": "payment.completed",
  "created": "2025-01-15T10:35:00Z",
  "data": {
    "object": {
      "id": "pay_123456",
      "orderId": "ord-123456",
      "amount": 2925,
      "currency": "EGP",
      "method": "credit_card",
      "status": "succeeded",
      "paymentMethodDetails": {
        "type": "card",
        "card": {
          "brand": "visa",
          "last4": "4242",
          "expMonth": 12,
          "expYear": 2026,
          "country": "EG"
        }
      },
      "receiptUrl": "https://cdn.osus.ai/receipts/pay_123456.pdf",
      "transactionId": "txn_789012345",
      "processedAt": "2025-01-15T10:35:00Z",
      "fees": {
        "processing": 87.75,
        "currency": "EGP"
      }
    }
  },
  "livemode": true
}

User Events

User account and authentication related events.

User Registered Event

{
  "id": "evt_123459",
  "type": "user.registered",
  "created": "2025-01-15T09:00:00Z",
  "data": {
    "object": {
      "id": "user-002",
      "email": "fatima@example.com",
      "firstName": "Fatima",
      "lastName": "Ali",
      "accountType": "individual",
      "emailVerified": false,
      "phoneVerified": false,
      "loyaltyTier": "bronze",
      "referralCode": "FATIMA2025",
      "referredBy": "user-001",
      "registrationSource": "website",
      "marketingConsent": true,
      "createdAt": "2025-01-15T09:00:00Z"
    }
  },
  "livemode": true
}

Service Events

Service booking and installation related events.

Service Booking Created Event

{
  "id": "evt_123460",
  "type": "service.booking_created",
  "created": "2025-01-15T11:00:00Z",
  "data": {
    "object": {
      "id": "booking-001",
      "bookingNumber": "SRV-2025-000001",
      "serviceType": "installation",
      "customer": {
        "id": "user-001",
        "name": "Ahmed Mohamed",
        "phone": "+201234567890"
      },
      "service": {
        "id": "service-001",
        "name": "Furniture Installation",
        "category": "furniture"
      },
      "scheduledDate": "2025-01-18T14:00:00Z",
      "timeSlot": "afternoon",
      "estimatedDuration": 120,
      "address": {
        "line1": "123 Tahrir Square",
        "city": "Cairo",
        "governorate": "Cairo"
      },
      "relatedOrderId": "ord-123456",
      "totalAmount": 200,
      "currency": "EGP",
      "status": "confirmed",
      "createdAt": "2025-01-15T11:00:00Z"
    }
  },
  "livemode": true
}

Security & Verification

Ensure webhook authenticity by verifying signatures.

Signature Verification

Each webhook request includes a X-OSUS-Signature header containing an HMAC-SHA256 signature of the request body using your webhook secret.

Verification Example (Node.js)

const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload, 'utf8')
    .digest('hex');
  
  const receivedSignature = signature.replace('sha256=', '');
  
  return crypto.timingSafeEqual(
    Buffer.from(expectedSignature, 'hex'),
    Buffer.from(receivedSignature, 'hex')
  );
}

// Express.js middleware example
app.post('/webhooks/osus', express.raw({type: 'application/json'}), (req, res) => {
  const signature = req.headers['x-osus-signature'];
  const payload = req.body;
  
  if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }
  
  const event = JSON.parse(payload);
  
  // Process the webhook event
  switch (event.type) {
    case 'order.created':
      handleOrderCreated(event.data.object);
      break;
    case 'payment.completed':
      handlePaymentCompleted(event.data.object);
      break;
    // ... handle other events
  }
  
  res.status(200).send('OK');
});

Verification Example (Python)

import hmac
import hashlib

def verify_webhook_signature(payload, signature, secret):
    expected_signature = hmac.new(
        secret.encode('utf-8'),
        payload.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()
    
    received_signature = signature.replace('sha256=', '')
    
    return hmac.compare_digest(expected_signature, received_signature)

# Flask example
from flask import Flask, request, abort
import json

app = Flask(__name__)

@app.route('/webhooks/osus', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-OSUS-Signature')
    payload = request.get_data(as_text=True)
    
    if not verify_webhook_signature(payload, signature, os.environ['WEBHOOK_SECRET']):
        abort(401)
    
    event = json.loads(payload)
    
    # Process the webhook event
    if event['type'] == 'order.created':
        handle_order_created(event['data']['object'])
    elif event['type'] == 'payment.completed':
        handle_payment_completed(event['data']['object'])
    
    return 'OK', 200

Testing Webhooks

Test your webhook implementation before going live.

Send Test Event

curl -X POST https://api.osus.ai/v1/webhooks/wh-123456/test \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "eventType": "order.created"
  }'

Webhook Testing Tools

ngrok

Create secure tunnels to your local development server

ngrok http 3000
Webhook.site

Test webhook endpoints online without coding

Visit

Best Practices

Do
  • Always verify webhook signatures
  • Respond with 2xx status codes quickly
  • Implement idempotency for duplicate events
  • Use HTTPS endpoints only
  • Process webhooks asynchronously
  • Log webhook events for debugging
  • Handle duplicate events gracefully
  • Set up monitoring and alerting
Don't
  • Perform long-running operations in handlers
  • Rely on webhook order for processing
  • Ignore failed webhook deliveries
  • Use HTTP (non-secure) endpoints
  • Store sensitive data in webhook URLs
  • Process webhooks without verification
  • Block webhook processing for errors
  • Assume webhooks arrive exactly once
Performance Tips
  • Respond to webhooks within 10 seconds
  • Use queues for processing webhook events
  • Implement exponential backoff for retries
  • Monitor webhook delivery success rates

Troubleshooting

Issue Possible Cause Solution
Webhooks not being received Endpoint URL unreachable or returning errors Check endpoint availability and response codes
Signature verification failing Incorrect secret or signature algorithm Verify webhook secret and HMAC-SHA256 implementation
Duplicate events received Webhook retries due to slow responses Implement idempotency using event IDs
Events arriving out of order Network delays and retries Use event timestamps for ordering
Webhook delivery failures Endpoint timeouts or errors Optimize endpoint performance and error handling

Webhook Delivery Logs

Check webhook delivery logs in the API dashboard:

curl -X GET https://api.osus.ai/v1/webhooks/wh-123456/deliveries \
  -H "Authorization: Bearer YOUR_API_KEY"

Error Codes

HTTP Status Error Code Description
400 INVALID_WEBHOOK_URL Webhook URL is invalid or not HTTPS
400 INVALID_EVENT_TYPES One or more event types are invalid
400 WEBHOOK_URL_UNREACHABLE Cannot reach the specified webhook URL
404 WEBHOOK_NOT_FOUND Webhook with specified ID not found
409 WEBHOOK_URL_EXISTS Webhook URL already registered
429 WEBHOOK_LIMIT_EXCEEDED Maximum number of webhooks reached