The Create Webhook endpoint enables you to register webhook endpoints for receiving real-time event notifications from your Devdraft application. Webhooks allow your application to receive automated notifications when specific events occur, enabling real-time integration and workflow automation.

Endpoint Details

  • URL: /api/v0/webhooks
  • Method: POST
  • Authentication: Required (API Key Authentication with Scopes)
  • Content-Type: application/json
  • Required Scope: webhook:create

Authentication

This endpoint requires API key authentication with specific scopes:

Required Headers

x-client-key: your-client-key
x-client-secret: your-client-secret

Required Scope

Your API key must have the webhook:create scope to access this endpoint.

Request Body

Required Fields

FieldTypeDescriptionValidation
namestringWebhook name for identification3-100 characters
urlstringEndpoint URL where events will be sentValid URL format

Optional Fields

FieldTypeDescriptionDefaultValidation
isActivebooleanWhether webhook is activetrueBoolean
signing_secretstringSecret for payload signature verificationAuto-generatedMin 32 chars, alphanumeric + _-
encryptedbooleanWhether payloads should be encryptedfalseBoolean

Request Schema

{
  "name": "string",
  "url": "string",
  "isActive": "boolean",
  "signing_secret": "string",
  "encrypted": "boolean"
}

Response

Success Response (201 Created)

{
  "id": "wh_123456789",
  "name": "Payment Notifications",
  "url": "https://api.example.com/webhooks/payments",
  "isActive": true,
  "encrypted": false,
  "created_at": "2024-03-20T12:00:00.000Z",
  "updated_at": "2024-03-20T12:00:00.000Z",
  "delivery_stats": {
    "total_events": 0,
    "successful_deliveries": 0,
    "failed_deliveries": 0,
    "last_delivery": null
  }
}

Error Responses

{
  "statusCode": 400,
  "message": "Invalid webhook URL format",
  "error": "Bad Request",
  "details": "URL must be a valid HTTPS endpoint"
}

Field Validation Rules

  • Required: Yes
  • Type: String
  • Length: 3-100 characters
  • Description: Human-readable name for webhook identification
  • Required: Yes
  • Type: String (URL format)
  • Protocol: Must be a valid URL (HTTPS recommended for production)
  • Description: Endpoint where webhook events will be sent
  • Required: No (auto-generated if not provided)
  • Type: String
  • Pattern: ^[a-zA-Z0-9_\-]{32,}$
  • Length: Minimum 32 characters
  • Characters: Letters, numbers, underscores, and hyphens only
  • Required: No
  • Type: Boolean
  • Default: true
  • Description: Whether webhook will receive events
  • Required: No
  • Type: Boolean
  • Default: false
  • Description: Whether webhook payloads should be encrypted

Example Requests

curl -X POST https://api.devdraft.ai/api/v0/webhooks \
  -H "Content-Type: application/json" \
  -H "x-client-key: your-client-key" \
  -H "x-client-secret: your-client-secret" \
  -d '{
    "name": "Payment Notifications",
    "url": "https://api.example.com/webhooks/payments"
  }'

Use Cases

Payment Event Notifications

Receive real-time updates about payment status changes

Invoice Lifecycle Tracking

Monitor invoice creation, updates, and payments

Customer Activity Monitoring

Track customer registration and profile updates

Transaction Processing

Monitor transaction status and settlement events

Balance Updates

Get notified when wallet balances change

Transfer Notifications

Track the status of cross-chain transfers

Integration Examples

Express.js Webhook Handler

const express = require('express');
const crypto = require('crypto');
const app = express();

// Middleware to capture raw body for signature verification
app.use('/webhooks', express.raw({type: 'application/json'}));

// Webhook endpoint to receive events
app.post('/webhooks/payments', (req, res) => {
  const signature = req.headers['x-webhook-signature'];
  const payload = req.body;
  
  // Verify signature
  if (verifySignature(payload, signature, process.env.WEBHOOK_SECRET)) {
    const event = JSON.parse(payload);
    console.log('Received webhook event:', event.type);
    
    // Process the event
    handlePaymentEvent(event);
    
    res.status(200).send('OK');
  } else {
    res.status(401).send('Invalid signature');
  }
});

function verifySignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
    
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expectedSignature}`)
  );
}

function handlePaymentEvent(event) {
  switch(event.type) {
    case 'payment.completed':
      console.log('Payment completed:', event.data.id);
      break;
    case 'payment.failed':
      console.log('Payment failed:', event.data.id);
      break;
    default:
      console.log('Unknown event type:', event.type);
  }
}

Flask Webhook Handler

from flask import Flask, request, jsonify
import hmac
import hashlib
import json

app = Flask(__name__)

@app.route('/webhooks/payments', methods=['POST'])
def handle_payment_webhook():
    signature = request.headers.get('x-webhook-signature')
    payload = request.get_data()
    
    # Verify signature
    if verify_signature(payload, signature, 'your-signing-secret'):
        event = request.get_json()
        print(f"Received event: {event['type']}")
        
        # Process the event
        process_payment_event(event)
        
        return 'OK', 200
    else:
        return 'Invalid signature', 401

def verify_signature(payload, signature, secret):
    """Verify webhook signature"""
    expected_signature = hmac.new(
        secret.encode('utf-8'),
        payload,
        hashlib.sha256
    ).hexdigest()
    
    return hmac.compare_digest(signature, f"sha256={expected_signature}")

def process_payment_event(event):
    if event['type'] == 'payment.completed':
        print(f"Payment completed: {event['data']['id']}")
    elif event['type'] == 'payment.failed':
        print(f"Payment failed: {event['data']['id']}")
    else:
        print(f"Unknown event type: {event['type']}")

if __name__ == '__main__':
    app.run(debug=True)

Security Features

  • HMAC SHA-256: Cryptographic signature for payload verification
  • Timing-safe comparison: Prevent timing attacks
  • Automatic generation: Secure secrets generated automatically
  • AES-256 encryption: Industry-standard encryption for sensitive data
  • Key rotation: Support for periodic key rotation
  • Selective encryption: Choose which webhooks need encryption
  • Scope-based permissions: webhook:create scope required
  • Application isolation: Webhooks isolated by application
  • Rate limiting: Protection against abuse

Best Practices

1

Use HTTPS Endpoints

Always use HTTPS URLs for webhook endpoints in production to ensure data security.
2

Verify Signatures

Always verify webhook signatures before processing events to ensure authenticity.
3

Handle Retries

Implement proper error handling and return appropriate HTTP status codes (200 for success).
4

Process Asynchronously

Process webhook events asynchronously to respond quickly and avoid timeouts.
5

Monitor Delivery

Set up monitoring for webhook delivery failures and implement alerting.

Rate Limiting

This endpoint is subject to the standard API rate limits:
  • Production: 1000 requests per hour per API key
  • Development: 100 requests per hour per API key

Webhook Events

Common event types that webhooks receive include:
  • payment.completed - Payment successfully processed
  • payment.failed - Payment processing failed
  • payment.pending - Payment is pending processing
  • payment.refunded - Payment has been refunded
  • GET /api/v0/webhooks - List all webhooks
  • GET /api/v0/webhooks/{id} - Fetch specific webhook
  • PATCH /api/v0/webhooks/{id} - Update webhook
  • DELETE /api/v0/webhooks/{id} - Delete webhook