REST API & Webhooks Reference

Order Daemon Docs

11. API Overview

This guide provides an overview of Order Daemon’s REST API and webhook integration capabilities. For detailed documentation of specific API endpoints, refer to the individual API documentation files.

API Architecture

Order Daemon provides a comprehensive REST API that follows WordPress REST API conventions and integrates with WordPress authentication and capability systems.

Base URL Structure

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

API Organization

The Order Daemon API is organized into several functional areas:

  1. Rule Management API – Create, read, update, and delete automation rules
  2. Audit Log API – Access automation activity logs and timelines
  3. Webhooks API – Receive and process external webhook events
  4. Pro API – Advanced features available in Order Daemon Pro

Authentication & Security

Authentication Methods

1. Cookie Authentication (Recommended for Admin UI)

// WordPress nonce-based authentication
fetch('/wp-json/odcm/v1/rule-builder/components', {
    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/rule-builder/components"

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 Documentation

Rule Management API

The Rule Management API provides endpoints for managing automation rules and discovering available components.

Key Endpoints:

  • GET /wp-json/odcm/v1/rule-builder/components – Get available triggers, conditions, and actions
  • GET /wp-json/odcm/v1/rule/{id} – Get a specific rule
  • POST /wp-json/odcm/v1/rule/{id} – Save a rule
  • GET /wp-json/odcm/v1/rule-builder/search-content – Search for dynamic content

Full Documentation →

Audit Log API

The Audit Log API provides access to automation activity logs with comprehensive filtering capabilities.

Key Endpoints:

  • GET /wp-json/odcm/v1/audit-log – List audit log entries
  • GET /wp-json/odcm/v1/audit-log/{id} – Get specific audit entry
  • GET /wp-json/odcm/v1/audit-log/timeline/{order_id} – Get order timeline
  • GET /wp-json/odcm/v1/audit-log/stats – Get activity statistics

Full Documentation →

Webhooks API

The Webhooks API enables Order Daemon to receive and process events from external services.

Key Endpoints:

  • POST /wp-json/odcm/v1/webhooks/{gateway} – Receive webhook events
  • GET /wp-json/odcm/v1/webhooks/gateways – Get available gateways
  • POST /wp-json/odcm/v1/webhooks/test/{gateway} – Test webhook processing
  • GET /wp-json/odcm/v1/webhooks/test/{gateway}/events – Get test event types

Supported Gateways:

  • stripe – Stripe payment events
  • paypal – PayPal IPN and webhook events
  • generic – Generic webhook adapter for any service

Full Documentation →

Pro API

The Pro API provides advanced features and debugging capabilities available in Order Daemon Pro.

Key Endpoints:

  • GET /wp-json/odcm-pro/v1/debug-rule/search-orders – Search orders for debugging
  • POST /wp-json/odcm-pro/v1/debug-rule/test – Test rules against specific orders

Full Documentation →

Core vs Pro Feature Comparison

Rule Components

Core Version:

  • Triggers: order_processing
  • Conditions: order_total_amount, product_category, product_type
  • Actions: change_status_to_completed

Pro Version:

  • All Core components plus:
  • Triggers: payment_complete, order_on_hold, any_status_change, order_created, subscription_renewal
  • Conditions: source_gateway, event_type, payment_date
  • Actions: change_status_to_processing, change_status_to_on_hold, add_order_note, send_email

API Features

Core Version:

  • Basic rule management (CRUD operations)
  • Component discovery and search
  • Audit log access with filtering
  • Webhook processing (Stripe, PayPal, Generic)

Pro Version:

  • All Core features plus:
  • Debug Rule API for comprehensive testing
  • Advanced rule analysis and suggestions
  • Enhanced error handling and diagnostics

Integration 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

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

Pro Feature Error Handling

// Handle Pro-only features gracefully
const createRule = async (ruleData) => {
    try {
        const response = await fetch('/wp-json/odcm/v1/rule-builder/rule', {
            method: 'POST',
            headers: {
                'X-WP-Nonce': wpApiSettings.nonce,
                'Content-Type': 'application/json'
            },
            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
                alert('This rule uses Pro features. Please upgrade to Order Daemon Pro.');
                return handlePremiumRequired(ruleData);
            }
            throw new Error(error.message);
        }

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

Getting Started

Quick Start Guide

  1. Set up authentication using WordPress application passwords
  2. Explore available components with the Rule Builder API
  3. Create your first rule using the rule management endpoints
  4. Monitor activity using the Audit Log API
  5. Set up webhooks for external integrations

Example Integration

// Complete integration example
class OrderDaemonClient {
    constructor(baseUrl, authToken) {
        this.baseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
        this.authToken = authToken;
        this.defaultHeaders = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        };
    }

    async getComponents() {
        return this.request('/wp-json/odcm/v1/rule-builder/components');
    }

    async getRule(ruleId) {
        return this.request(`/wp-json/odcm/v1/rule/${ruleId}`);
    }

    async saveRule(ruleId, ruleData) {
        return this.request(`/wp-json/odcm/v1/rule/${ruleId}`, 'POST', ruleData);
    }

    async searchContent(source, query, limit = 10) {
        return this.request(`/wp-json/odcm/v1/rule-builder/search-content?source=${source}&search=${query}&limit=${limit}`);
    }

    async request(endpoint, method = 'GET', data = null) {
        const url = `${this.baseUrl}${endpoint}`;
        const options = {
            method,
            headers: this.defaultHeaders
        };

        if (data) {
            options.body = JSON.stringify(data);
        }

        try {
            const response = await fetch(url, options);

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(`API Error: ${errorData.message || response.statusText}`);
            }

            return await response.json();
        } catch (error) {
            console.error('OrderDaemon API Error:', error.message);
            throw error;
        }
    }
}

// Usage
const client = new OrderDaemonClient(
    'https://mystore.com',
    'your-api-token-or-app-password'
);

// Get components and create a rule
const components = await client.getComponents();
const ruleData = {
    trigger: { id: 'order_processing', settings: {} },
    conditions: [{
        id: 'product_type',
        settings: { types: ['virtual'], match_all: false }
    }],
    primaryAction: { id: 'change_status_to_completed', settings: {} },
    secondaryActions: []
};

// Save the rule
await client.saveRule(123, { rule: ruleData });

Additional Resources

This guide serves as an overview of Order Daemon’s API capabilities. For implementation-specific details, refer to the individual API documentation files.

Was this article helpful?

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