Search by

citation-media / wp-webhook-framework

JUVOJustin

Entity-level webhook framework for WordPress using Action Scheduler.

Package info

github.com/JUVOJustin/wp-webhook-framework

pkg:composer/citation-media/wp-webhook-framework

Statistics

Installs: 541

Dependents: 0

Suggesters: 0

Stars: 2

Open Issues: 9


README

title WP Webhook Framework
description Entity-level webhooks for WordPress with scheduled and immediate delivery modes, retries, and failure monitoring.

WP Webhook Framework

Quality Check Integration Tests

Entity-level webhooks for WordPress using Action Scheduler with optional immediate delivery mode. Sends POSTs for create/update/delete of posts, terms, and users. Meta changes trigger the entity update. ACF updates include field context. Features intelligent failure monitoring with email notifications, automatic blocking, and comprehensive filtering options.

Features

  • Delivery mode control - Choose scheduled async delivery (default) or immediate synchronous first attempt
  • Action Scheduler dispatch - 60s windows for stacked updates; 5s initial delay for other queued webhooks
  • Update stacking - Aggregate scheduled updates in fixed 60-second windows, retaining every accepted payload and a stable delivery ID; opt out to retain legacy pending deduplication.
  • Entity-aware delivery payloads - Derives post_type, taxonomy, and roles at acceptance for stacks, or at send time for legacy delivery
  • Send-time enrichment - Adds REST URLs when available
  • ACF integration - Adds field key/name context to meta changes
  • Registry pattern - Extensible webhook system with custom configurations
  • Notification system - Opt-in email alerts for failures, extensible notification handlers
  • Failure monitoring - Automatic blocking after consecutive failures
  • Comprehensive filtering - Control payloads, URLs, headers, and meta keys

Quick Start

Installation

composer require citation-media/wp-webhook-framework

Requirements

Requirement Version
WordPress 6.7 or newer
PHP 8.1 or newer
Action Scheduler 3.x from 3.7, or 4.x from 4.2 (Composer dependency)

Action Scheduler 4.2 requires WordPress 6.9 or newer. On WordPress 6.7–6.8, consumers must constrain woocommerce/action-scheduler to ^3.7; Composer cannot infer the installed WordPress version. Future major scheduler versions require a separate compatibility review.

WordPress 6.7 is a hard requirement: the dispatcher signals every delivery and configuration failure by throwing WP_Exception, which was added to core in 6.7.0. On older releases those throw sites raise an uncatchable Error: Class "WP_Exception" not found instead.

Action Scheduler comes bundled and is loaded by Service_Provider::register() — no separate plugin activation needed. If other plugins ship their own copy, Action Scheduler's version manager initialises the newest one.

:::caution Call Service_Provider::register() while your plugin file loads, not from inside plugins_loaded. Action Scheduler registers itself on plugins_loaded at priority 0, so registering later loads it too late to initialise. :::

Basic Setup

// Initialize the framework
\juvo\WP_Webhook_Framework\Service_Provider::register();

Service_Provider::register() is idempotent, so separate plugins can call it independently while sharing the same library checkout.

:::tip If you are using a prefixer make sure to exclude this library. Due the strong typings used it will break plugins :::

See Configuration for detailed configuration options.

Usage Examples

Register Built-in Webhooks

No webhooks are active by default. Register what you need via the action:

use juvo\WP_Webhook_Framework\Webhooks\Post_Webhook;

add_action('wpwf_register_webhooks', function ($registry) {
    $post = new Post_Webhook();
    $post->webhook_url('https://api.example.com/posts')
         ->max_retries(3)
         ->timeout(60);
    $registry->register($post);
});

See Configuration for registry configuration and Custom Webhooks for creating your own webhooks.

Immediate Delivery Mode

use juvo\WP_Webhook_Framework\Delivery_Mode;
use juvo\WP_Webhook_Framework\Webhooks\Post_Webhook;

add_action('wpwf_register_webhooks', function ($registry) {
    $post = new Post_Webhook();
    $post->webhook_url('https://api.example.com/posts')
         ->delivery_mode(Delivery_Mode::IMMEDIATE)
         ->max_retries(2);
    $registry->register($post);
});

Immediate mode sends the first attempt in the current request. If it fails, retries are still queued asynchronously with exponential backoff.

Filter Payloads

// Prevent delete webhooks
add_filter('wpwf_payload', function($payload, $entity, $id) {
    if ($payload['action'] === 'delete') {
        return false; // Return false to prevent webhook
    }
    return $payload;
}, 10, 3);

See Hooks and Filters for all available hooks and filters.

Architecture Overview

Core Components

  • Service_Provider - Singleton that bootstraps the framework
  • Webhook_Registry - Manages webhook instances and initialization
  • Webhook (abstract) - Base class for all webhooks
  • Dispatcher - Schedules and sends HTTP requests via Action Scheduler
  • Entity Handlers - Prepare payloads for posts, terms, users, and meta

Data Flow:

WordPress hook → Webhook → Handler::prepare_payload() → Webhook::emit() → Dispatcher
  ├─ scheduled updates: persistent 60-second stack → Action Scheduler → HTTP POST
  ├─ other scheduled actions / opt-out: pending deduplication → Action Scheduler → HTTP POST
  └─ immediate mode: send now in current request → HTTP POST

Webhook Statefulness

Webhook instances are singletons and must remain stateless. Never store per-emission data as instance properties. Configuration (URL, timeout, headers) is set during init(). Payloads and dynamic data are passed directly to emit().

See Webhook Statefulness for detailed explanation and examples.

Payload Structure

Scheduled updates keep the latest event fields at the root and add timestamp and flat aggregated_events; see the stacking format. Version 4.1.0 moves delivery metadata to headers and removes history wrappers. This changes the 4.0.0 wire format; update receivers before upgrading. The fixed 60-second window remains unchanged. Set stack_updates( false ) to keep the 2.x contract. Existing queued jobs keep their original format.

Example legacy or immediate post webhook payload:

{
  "action": "update",
  "entity": "post",
  "id": 123,
  "post_type": "post"
}

Persisted fields (event-time):

  • Meta: meta_type, meta_key
  • Meta: acf_field_key, acf_field_name (if ACF field)

Derived fields (when available at acceptance for stacks, otherwise at send time):

  • Post: post_type
  • Term: taxonomy
  • User: roles[]
  • rest_url

Failure Monitoring

  • Email notifications when a URL becomes blocked (opt-in via notifications(['blocked']))
  • Automatic blocking after 10 consecutive failures within 1 hour
  • Auto-unblock after 1 hour
  • Success resets failure count and blocked status

See Failure Handling for configuration and customization.

Code Quality

  • PHPCS Compliant - WordPress coding standards (WPCS 3.1)
  • Type Safe - PHPStan level 6 static analysis
  • i18n Ready - All user-facing strings internationalized
  • Filterable - Extensive WordPress filter integration
  • Well Documented - Comprehensive inline documentation

Commands

composer install              # Install dependencies
pnpm install                   # Install wp-env tooling
pnpm run wp-env:start          # Start WordPress test environment
pnpm run composer:install      # Install Composer dependencies inside wp-env
pnpm run test:phpunit          # Run application tests
pnpm run wp-env:stop           # Stop WordPress test environment
composer run-script phpstan   # Run static analysis
composer run-script phpcs     # Lint code
composer run-script phpcbf    # Auto-fix code style

Documentation

  • Configuration - Webhook configuration methods, registry setup, and options
  • Custom Webhooks - Creating custom webhooks, plugin integrations (WooCommerce, CF7, Gravity Forms)
  • Hooks and Filters - All available hooks and filters with examples
  • Failure Handling - Failure monitoring, retry mechanism, and blocking behavior
  • Notifications - Notification system, opt-in pattern, and custom handlers
  • Testing - wp-env application test suite, fixture plugins, and validation workflow
  • Webhook Statefulness - Webhook statelessness rules and best practices

Releases

This Composer library publishes versions through GitHub Releases with matching Semantic Versioning tags. A maintainer selects the release version after the PR is merged and its checks pass, then creates the release from that commit. There is no source version field to update: Composer derives it from the tag. Do not publish a standalone tag without the corresponding release.