Docs

11. REST API and Webhooks

This comprehensive guide covers the complete REST API surface and webhook integration capabilities of Order Daemon. It serves as the primary reference for developers building external tools, custom integrations, and automated workflows.

Overview

Order Daemon exposes a comprehensive REST API that enables:

  • Rule Management: Create, read, update, and delete automation rules
  • Component Discovery: Retrieve available triggers, conditions, and actions
  • Audit Timeline Access: Query execution logs and debug information
  • Webhook Processing: Receive events from external systems
  • Administrative Operations: Bulk operations, testing, and diagnostics

All endpoints follow WordPress REST API conventions and integrate with WordPress authentication and capability systems.

Authentication & Security

Authentication Methods

1. Cookie Authentication (Recommended for Admin UI)

// WordPress nonce-based authentication
fetch('/wp-json/odcm/v1/rules', {
    method: 'GET',
    headers: {
        'X-WP-Nonce': wpApiSettings.nonce
    }
})

2. Application Passwords

# Basic Auth with Application Password
curl -u "username:app-password" \
     "https://yoursite.com/wp-json/odcm/v1/rules"

3. OAuth (Third-party integrations)

  • Use WordPress OAuth plugins for secure token-based access
  • Required for headless integrations and mobile applications

Permission Model

All administrative endpoints require appropriate WordPress capabilities:

  • Rule Management: manage_woocommerce or manage_options
  • Audit Access: manage_woocommerce or manage_options
  • Webhook Processing: Public endpoints with adapter-level security
  • Administrative Functions: manage_options (admin-only)

Security Best Practices

  • Always use HTTPS in production
  • Implement proper CORS policies for browser-based integrations
  • Use least-privilege principles when creating application passwords
  • Validate and sanitize all input data
  • Implement rate limiting at the infrastructure level

API Architecture

Base URL Structure

https://yoursite.com/wp-json/odcm/v1/

Common Response Format

{
  "success": true,
  "data": { /* response data */ },
  "meta": {
    "timestamp": "2025-11-15T12:34:56Z",
    "request_id": "req_abc123",
    "version": "1.0.0"
  }
}

Error Response Format

{
  "code": "error_code",
  "message": "Human-readable error message",
  "data": {
    "status": 400,
    "details": { /* additional error context */ }
  }
}

Pagination

List endpoints support WordPress-standard pagination:

GET /wp-json/odcm/v1/audit?page=2&per_page=50

Response headers include:

  • X-WP-Total: Total number of items
  • X-WP-TotalPages: Total number of pages
  • Link: Next/previous page links

Rule Builder API

Component Discovery

Get Available Components

GET /wp-json/odcm/v1/rules/components

Returns triggers, conditions, and actions available to the current user based on entitlements:

{
  "triggers": [
    {
      "id": "order_processing",
      "label": "Order Processing",
      "description": "Triggers when order status changes to Processing",
      "capability": "core",
      "settings_schema": { /* JSON schema */ }
    }
  ],
  "conditions": [ /* ... */ ],
  "actions": [ /* ... */ ]
}

Dynamic Search for Pickers

GET /wp-json/odcm/v1/search?type=products&query=shirt&limit=10

Supports various search types for UI components:

  • products: WooCommerce products
  • categories: Product categories
  • tags: Product tags
  • users: WordPress users
  • coupons: WooCommerce coupons

Rule CRUD Operations

Create Rule

POST /wp-json/odcm/v1/rules
Content-Type: application/json

{
  "title": "Auto-complete Digital Products",
  "description": "Automatically complete orders containing only digital products",
  "enabled": true,
  "trigger": {
    "id": "order_processing",
    "settings": {}
  },
  "conditions": [
    {
      "id": "product_type",
      "settings": {
        "types": ["virtual", "downloadable"],
        "match_all": false
      }
    }
  ],
  "actions": [
    {
      "id": "complete_order",
      "settings": {
        "send_emails": true,
        "update_stock": false
      }
    }
  ]
}

Get Rule

GET /wp-json/odcm/v1/rules/{rule_id}

Update Rule

PUT /wp-json/odcm/v1/rules/{rule_id}
Content-Type: application/json

Delete Rule

DELETE /wp-json/odcm/v1/rules/{rule_id}

List Rules

GET /wp-json/odcm/v1/rules?status=active&search=digital

Query parameters:

  • status: active, inactive, all
  • search: Text search in title/description
  • page: Page number
  • per_page: Items per page (default: 20, max: 100)

Rule Validation

All rule payloads are validated against component schemas:

{
  "code": "invalid_rule",
  "message": "Rule validation failed",
  "data": {
    "errors": [
      {
        "field": "conditions.0.settings.types",
        "code": "invalid_option",
        "message": "Invalid product type: 'subscription'"
      }
    ]
  }
}

Audit & Insight API

Timeline Query

List Audit Entries

GET /wp-json/odcm/v1/audit?search=order&level=info&source=rule_engine

Query parameters:

  • search: Text search in messages/metadata
  • level: debug, info, warning, error
  • source: Event source (e.g., rule_engine, webhook, manual)
  • start_date: Filter from date (ISO 8601)
  • end_date: Filter to date (ISO 8601)
  • process_id: Filter by process/correlation ID
  • order_id: Filter by WooCommerce order ID

Response Format

{
  "entries": [
    {
      "id": 12345,
      "timestamp": "2025-11-15T12:34:56Z",
      "level": "info",
      "message": "Rule evaluation completed",
      "source": "rule_engine",
      "process_id": "proc_abc123",
      "order_id": 5678,
      "metadata": {
        "rule_id": 42,
        "execution_time_ms": 156,
        "matched_conditions": 2
      }
    }
  ],
  "total": 1024,
  "pages": 21
}

Get Process Timeline

GET /wp-json/odcm/v1/audit/by-process/{process_id}

Returns all entries correlated by process ID, useful for tracing complete workflows.

Component Rendering

Render Audit Components

POST /wp-json/odcm/v1/audit/render
Content-Type: application/json

{
  "entries": [12345, 12346, 12347]
}

Returns server-rendered HTML components for display in dashboards.

Administrative Operations

Bulk Delete

DELETE /wp-json/odcm/v1/audit?ids=1,2,3,4,5

Export Timeline

GET /wp-json/odcm/v1/audit/export?format=json&start_date=2025-01-01

Supports json, csv formats (Pro may include additional formats).

Webhook Integration

Webhook Receiver

Universal Webhook Endpoint

POST /wp-json/odcm/v1/webhooks/{gateway}
Content-Type: application/json
X-Webhook-Signature: sha256=abc123...

{
  "event_type": "payment.completed",
  "order_id": "order_123",
  "amount": 29.99,
  "currency": "USD",
  "timestamp": "2025-11-15T12:34:56Z"
}

The {gateway} parameter identifies which adapter should process the payload:

  • stripe: Stripe webhook events
  • paypal: PayPal webhook events
  • generic: Generic webhook adapter
  • custom: Your custom adapter

Webhook Security

Signature Verification

// Example signature validation
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'];
$expected = 'sha256=' . hash_hmac('sha256', $payload, $webhook_secret);

if (!hash_equals($signature, $expected)) {
    http_response_code(401);
    exit('Invalid signature');
}

Headers to Include

  • X-Webhook-Signature: HMAC signature of payload
  • X-Event-Type: Event type identifier
  • X-Event-ID: Unique event ID (for deduplication)
  • X-Timestamp: Unix timestamp (for replay protection)

Health Check

Webhook Health Endpoint

GET /wp-json/odcm/v1/webhooks/health

Returns basic connectivity confirmation:

{
  "status": "ok",
  "timestamp": "2025-11-15T12:34:56Z",
  "version": "1.0.0"
}

Gateway Discovery

List Available Gateways

GET /wp-json/odcm/v1/webhooks/gateways

Returns registered webhook adapters:

{
  "gateways": [
    {
      "id": "stripe",
      "name": "Stripe",
      "description": "Stripe payment gateway webhooks",
      "supported_events": ["payment.completed", "payment.failed"]
    }
  ]
}

Test Tools

Test Webhook Processing

POST /wp-json/odcm/v1/webhooks/test
Content-Type: application/json

{
  "gateway": "stripe",
  "event_type": "payment.completed",
  "test_payload": { /* custom test data */ }
}

Admin-only endpoint for testing webhook processing without external triggers.

Gateway Adapters

Creating Custom Adapters

Implement the AbstractGatewayAdapter interface:

use OrderDaemon\CompletionManager\Core\Events\Adapters\AbstractGatewayAdapter;

class CustomGatewayAdapter extends AbstractGatewayAdapter {
    public function get_slug(): string {
        return 'my-gateway';
    }

    public function get_supported_events(): array {
        return ['payment.completed', 'subscription.created'];
    }

    public function process_payload(array $payload): array {
        // Validate signature
        if (!$this->validate_signature($payload)) {
            return ['status' => 'invalid_signature'];
        }

        // Transform to universal event
        return [
            'event_type' => $payload['type'],
            'order_id' => $payload['order_reference'],
            'metadata' => $payload['data']
        ];
    }

    private function validate_signature(array $payload): bool {
        // Implement your signature validation
        return true;
    }
}

Registering Adapters

add_action('odcm_register_gateway_adapters', function($router) {
    $router->register_adapter('my-gateway', new CustomGatewayAdapter());
});

Error Handling

Common Error Codes

  • rest_invalid_param: Invalid request parameter
  • rest_missing_callback_param: Required parameter missing
  • rest_forbidden: Insufficient permissions
  • odcm_premium_blocked: Premium feature without entitlement
  • odcm_invalid_rule: Rule validation failed
  • odcm_component_not_found: Referenced component doesn’t exist
  • odcm_webhook_invalid: Webhook payload invalid
  • odcm_process_timeout: Operation timed out

Error Response Examples

Validation Error

{
  "code": "rest_invalid_param",
  "message": "Invalid parameter(s): trigger",
  "data": {
    "status": 400,
    "params": {
      "trigger": "Missing required trigger configuration"
    }
  }
}

Permission Error

{
  "code": "rest_forbidden",
  "message": "You do not have permission to access this resource",
  "data": {
    "status": 403,
    "required_capability": "manage_woocommerce"
  }
}

Rate Limiting & Performance

Recommended Limits

  • Rule Operations: 60 requests/minute per user
  • Audit Queries: 100 requests/minute per user
  • Webhook Processing: 1000 requests/minute globally
  • Search Operations: 30 requests/minute per user

Performance Optimization

Pagination Best Practices

// Efficient pagination
const fetchAuditEntries = async (page = 1, perPage = 50) => {
    const response = await fetch(`/wp-json/odcm/v1/audit?page=${page}&per_page=${perPage}`);
    return response.json();
};

Caching Strategies

  • Cache component discovery results (rarely changes)
  • Use ETags for conditional requests
  • Implement client-side caching for frequently accessed data

Batch Operations

// Batch rule updates
const updateMultipleRules = async (rules) => {
    const promises = rules.map(rule => 
        fetch(`/wp-json/odcm/v1/rules/${rule.id}`, {
            method: 'PUT',
            body: JSON.stringify(rule)
        })
    );
    return Promise.all(promises);
};

Core vs Pro Considerations

Feature Detection

// Check if Pro features are available
const checkProFeatures = async () => {
    const components = await fetch('/wp-json/odcm/v1/rules/components')
        .then(r => r.json());

    const proComponents = components.triggers.filter(t => 
        t.capability === 'premium'
    );

    return proComponents.length > 0;
};

Graceful Degradation

// Handle Pro-only features gracefully
const createRule = async (ruleData) => {
    try {
        const response = await fetch('/wp-json/odcm/v1/rules', {
            method: 'POST',
            body: JSON.stringify(ruleData)
        });

        if (!response.ok) {
            const error = await response.json();
            if (error.code === 'odcm_premium_blocked') {
                // Show upgrade prompt or remove Pro components
                return handlePremiumRequired(ruleData);
            }
            throw new Error(error.message);
        }

        return response.json();
    } catch (error) {
        console.error('Failed to create rule:', error);
        throw error;
    }
};

Integration Examples

External Dashboard Integration

# Python example: External monitoring dashboard
import requests

class OrderDaemonAPI:
    def __init__(self, base_url, username, password):
        self.base_url = base_url
        self.auth = (username, password)

    def get_active_rules(self):
        """Get all active automation rules"""
        response = requests.get(
            f"{self.base_url}/wp-json/odcm/v1/rules?status=active",
            auth=self.auth
        )
        return response.json()

    def get_recent_activity(self, hours=24):
        """Get recent audit activity"""
        from datetime import datetime, timedelta

        start_date = datetime.now() - timedelta(hours=hours)
        response = requests.get(
            f"{self.base_url}/wp-json/odcm/v1/audit",
            params={
                'start_date': start_date.isoformat(),
                'per_page': 100
            },
            auth=self.auth
        )
        return response.json()

# Usage
api = OrderDaemonAPI('https://mystore.com', 'admin', 'app-password')
rules = api.get_active_rules()
activity = api.get_recent_activity()

Zapier Integration

// Zapier webhook trigger
const performWebhookTrigger = async (bundle, z) => {
    const response = await z.request({
        url: `${bundle.authData.site_url}/wp-json/odcm/v1/audit`,
        params: {
            start_date: bundle.meta.page ? 
                bundle.cleanedRequest.start_date : new Date().toISOString(),
            per_page: 50
        },
        auth: {
            username: bundle.authData.username,
            password: bundle.authData.password
        }
    });

    return response.json.entries || [];
};

Custom Integration Middleware

// WordPress plugin: Custom integration layer
class OrderDaemonIntegration {
    private $api_base;

    public function __construct() {
        $this->api_base = rest_url('odcm/v1');
        add_action('init', [$this, 'init_api_proxy']);
    }

    public function create_rule_from_template($template_id, $params) {
        $template = $this->get_rule_template($template_id);
        $rule_data = $this->populate_template($template, $params);

        $request = new WP_REST_Request('POST', '/odcm/v1/rules');
        $request->set_body_params($rule_data);

        $response = rest_do_request($request);

        if ($response->is_error()) {
            throw new Exception($response->as_error()->get_error_message());
        }

        return $response->get_data();
    }
}

Best Practices

API Design Principles

  1. Idempotency: Implement idempotent operations where possible
  2. Versioning: Always specify API version in requests
  3. Error Handling: Implement comprehensive error handling
  4. Security: Never expose sensitive data in API responses
  5. Performance: Use pagination and appropriate filters

Integration Architecture

  1. Loose Coupling: Design integrations to be resilient to API changes
  2. Retry Logic: Implement exponential backoff for failed requests
  3. Monitoring: Log all API interactions for debugging
  4. Fallback Strategies: Have backup plans for API unavailability

Development Workflow

  1. Testing: Use the test webhook endpoints during development
  2. Staging: Test integrations on staging environments first
  3. Documentation: Document your integration patterns
  4. Monitoring: Implement health checks and monitoring

Troubleshooting

Common Issues

Authentication Failures

# Test authentication
curl -I -u "username:password" \
     "https://yoursite.com/wp-json/odcm/v1/rules"

# Should return 200 OK, not 401

Permission Errors

  • Verify user has manage_woocommerce capability
  • Check if WooCommerce is active
  • Confirm Order Daemon is properly initialized

Webhook Processing Issues

  • Verify webhook URL is accessible externally
  • Check payload format matches expected schema
  • Validate signature computation
  • Review audit logs for error details

Performance Problems

  • Implement proper pagination
  • Use appropriate query filters
  • Consider caching strategies
  • Monitor response times

Debug Techniques

API Response Logging

// Log all API responses for debugging
const apiCall = async (endpoint, options = {}) => {
    const startTime = Date.now();

    try {
        const response = await fetch(endpoint, options);
        const data = await response.json();

        console.log('API Call:', {
            endpoint,
            duration: Date.now() - startTime,
            status: response.status,
            data
        });

        return data;
    } catch (error) {
        console.error('API Error:', {
            endpoint,
            duration: Date.now() - startTime,
            error: error.message
        });
        throw error;
    }
};

Webhook Testing

# Test webhook endpoint manually
curl -X POST \
     -H "Content-Type: application/json" \
     -H "X-Event-Type: test" \
     -d '{"test": true}' \
     "https://yoursite.com/wp-json/odcm/v1/webhooks/generic"

Was this article helpful?

  • Loading...
Table of Contents
  • Loading...