Skip to content

Receive webhooks in WordPress

A small plugin that takes Rabbitflare's webhooks at a REST route of your WordPress site, checked and handled once each.

2 min read Updated

A small must-use plugin that takes Rabbitflare's webhooks at a REST route of your WordPress site: it checks each call's signature, answers at once, and hands each event to your own code once, through a WordPress action.

What you need

  • A WordPress site served over https, on a Rabbitflare server or anywhere else.
  • To add the endpoint through the API, a token with servers:read (View servers), sites:read (View sites) and webhooks:write (Manage webhooks): each event needs its group's read scope. Or add it in the panel.

1. Add the plugin

Save the plugin at the end of this page as wp-content/mu-plugins/rabbitflare-webhooks.php (make the mu-plugins folder if there isn't one), with the panel's File Manager or over SFTP. Must-use plugins load on every request, and can't be turned off by mistake from the Plugins page. Its route is then https://www.example.com/wp-json/rabbitflare/v1/webhooks.

2. Add the endpoint

In the panel ( API Webhooks , then Add endpoint), or with POST /v1/webhooks/endpoints, with your site's address and the events you want:

curl -X POST "https://api.rabbitflare.com/v1/webhooks/endpoints" \
  -H "Authorization: Bearer $RABBITFLARE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "url": "https://www.example.com/wp-json/rabbitflare/v1/webhooks",
  "description": "WordPress",
  "events": [
    "server.unreachable",
    "site.ready"
  ]
}'

Copy the signing secret from the answer's secret: it's shown this once.

3. Give the plugin the secret

In wp-config.php, above the line /* That's all, stop editing! */, define the secret. The plugin refuses every call until it's there.

wp-config.php
define('RABBITFLARE_WEBHOOK_SECRET', 'rfwhsec_…');

4. Send a test event

Send a test event from the panel or the API. The answer is the delivery: lastStatus 204 means the plugin checked the signature and took it.

curl -X POST "https://api.rabbitflare.com/v1/webhooks/endpoints/3c6f9a1e-2b4d-4e8f-9a0b-1c2d3e4f5a6b/actions/send-test" \
  -H "Authorization: Bearer $RABBITFLARE_TOKEN"

5. Do your work

The plugin hands every new event to the rabbitflare_webhook_event action, after it has answered. Hook your own code to it, in the plugin or in another of yours: its example emails the site's administrator when a server can't be reached. Skip the types you don't handle, and read the resource in $event['data']['resource'] with your API token for its full state (see what your endpoint must do).

What can go wrong

A delivery shows what the site answered (lastStatus, and the start of the answer). The usual ones:

404
The plugin isn't loaded (check its folder), or the site uses plain permalinks: then the route is https://www.example.com/?rest_route=/rabbitflare/v1/webhooks.
400
The plugin refused the signature: the secret in wp-config.php is missing or isn't this endpoint's, or the site's clock is more than 5 minutes off (see Verify signatures).
401 or 403
Something in front of WordPress answered instead, like a security plugin or a firewall that blocks requests to the REST API: let POST requests to /wp-json/rabbitflare/v1/webhooks through.
A redirect
Redirects aren't followed: use the site's final address, with or without www as it's served.

The plugin remembers the events it has taken for 3 days, longer than a delivery's retries last, so an event sent again in that time isn't handled twice.

The plugin

Save it as wp-content/mu-plugins/rabbitflare-webhooks.php.

PHP
<?php
/**
 * Plugin Name: Rabbitflare webhooks
 * Description: Receives Rabbitflare webhooks at /wp-json/rabbitflare/v1/webhooks.
 */

// Your endpoint's signing secret, in wp-config.php:
// define('RABBITFLARE_WEBHOOK_SECRET', 'rfwhsec_…');

add_action('rest_api_init', function () {
    register_rest_route('rabbitflare/v1', '/webhooks', [
        'methods' => 'POST',
        'callback' => 'rabbitflare_webhook_receive',
        // Open to anyone: the signature decides what's accepted.
        'permission_callback' => '__return_true',
    ]);
});

/**
 * Whether the Rabbitflare-Signature header was made with your secret,
 * over this raw body, in the last 5 minutes.
 */
function rabbitflare_webhook_verify(string $raw_body, string $header, string $secret): bool
{
    $timestamp = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        [$name, $value] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($name === 't' && ctype_digit($value)) {
            $timestamp = (int) $value;
        } elseif ($name === 'v1' && preg_match('/^[0-9a-f]{64}$/i', $value)) {
            $signatures[] = strtolower($value);
        }
    }
    if ($timestamp === null || abs(time() - $timestamp) > 300) {
        return false;
    }
    $expected = hash_hmac('sha256', $timestamp . '.' . $raw_body, $secret);
    foreach ($signatures as $signature) {
        // Compared in constant time. For 24 hours after a secret is rotated,
        // the header holds two v1 values (new and old secret): either may match.
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}

function rabbitflare_webhook_receive(WP_REST_Request $request)
{
    $secret = defined('RABBITFLARE_WEBHOOK_SECRET') ? RABBITFLARE_WEBHOOK_SECRET : '';
    // The raw bytes, as sent: JSON parsed and written out again isn't the same.
    $raw_body = $request->get_body();
    $signature = (string) $request->get_header('Rabbitflare-Signature');
    if ($secret === '' || !rabbitflare_webhook_verify($raw_body, $signature, $secret)) {
        $message = 'The signature is missing, wrong or too old.';
        return new WP_Error('rabbitflare_webhook_signature', $message, ['status' => 400]);
    }
    $event = json_decode($raw_body, true);
    // Each event once: the same event can be sent more than once.
    $key = 'rabbitflare_event_' . md5($event['id']);
    if (get_transient($key) === false) {
        set_transient($key, 1, 3 * DAY_IN_SECONDS);
        // The work runs in WordPress's scheduled tasks (WP-Cron), after this answer.
        wp_schedule_single_event(time(), 'rabbitflare_webhook_event', [$event]);
    }
    // Answer within 10 seconds, and do the work after answering.
    return new WP_REST_Response(null, 204);
}

// Your work here. New event types can appear: ignore those you don't handle.
add_action('rabbitflare_webhook_event', function (array $event) {
    if ($event['type'] === 'server.unreachable') {
        $subject = 'A server can\'t be reached';
        wp_mail(get_option('admin_email'), $subject, $event['data']['message']);
    }
});

Still have a question?

Our team answers support tickets about the API, and other developers answer in the community.

Contact support

Popular

API docs