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) andwebhooks: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"
]
}' const res = await fetch("https://api.rabbitflare.com/v1/webhooks/endpoints", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
"url": "https://www.example.com/wp-json/rabbitflare/v1/webhooks",
"description": "WordPress",
"events": [
"server.unreachable",
"site.ready"
]
}),
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data } = await res.json();
console.log(data); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
const data = await rf.webhooks.endpoints.create({
url: "https://www.example.com/wp-json/rabbitflare/v1/webhooks",
description: "WordPress",
events: ["server.unreachable", "site.ready"],
});
console.log(data); <?php
$ch = curl_init('https://api.rabbitflare.com/v1/webhooks/endpoints');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'url' => 'https://www.example.com/wp-json/rabbitflare/v1/webhooks',
'description' => 'WordPress',
'events' => [
'server.unreachable',
'site.ready',
],
]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
print_r(json_decode($body, true)['data']); import os
import requests
response = requests.post(
"https://api.rabbitflare.com/v1/webhooks/endpoints",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
},
json={
"url": "https://www.example.com/wp-json/rabbitflare/v1/webhooks",
"description": "WordPress",
"events": [
"server.unreachable",
"site.ready",
],
},
timeout=120,
)
response.raise_for_status()
print(response.json()["data"]) 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.
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" const res = await fetch("https://api.rabbitflare.com/v1/webhooks/endpoints/3c6f9a1e-2b4d-4e8f-9a0b-1c2d3e4f5a6b/actions/send-test", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
},
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data } = await res.json();
console.log(data); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
const data = await rf.webhooks.endpoints.sendTest({
endpointId: "3c6f9a1e-2b4d-4e8f-9a0b-1c2d3e4f5a6b",
});
console.log(data); <?php
$ch = curl_init('https://api.rabbitflare.com/v1/webhooks/endpoints/3c6f9a1e-2b4d-4e8f-9a0b-1c2d3e4f5a6b/actions/send-test');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
print_r(json_decode($body, true)['data']); import os
import requests
response = requests.post(
"https://api.rabbitflare.com/v1/webhooks/endpoints/3c6f9a1e-2b4d-4e8f-9a0b-1c2d3e4f5a6b/actions/send-test",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
},
timeout=120,
)
response.raise_for_status()
print(response.json()["data"]) 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.phpis missing or isn't this endpoint's, or the site's clock is more than 5 minutes off (see Verify signatures). 401or403-
Something in front of WordPress answered instead, like a security plugin or a firewall that blocks requests to the REST API: let
POSTrequests to/wp-json/rabbitflare/v1/webhooksthrough. - A redirect
- Redirects aren't followed: use the site's final address, with or without
wwwas 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
/**
* 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.