Webhooks are often protected only by using a complex endpoint URL such as `/wp-json/my-plugin/v1/notify/long-secret-string`. This is not full authentication: the address can appear in access logs, monitoring systems, chat histories or third-party services.
A more reliable approach is to verify the HMAC signature of every request before WordPress processes the JSON. The sender signs the timestamp and the exact request body with a shared secret, and the website calculates the signature again. You must also limit the request lifetime and prevent the same event from being processed more than once.
Why a Secret URL Is Not Enough
A complex endpoint path can reduce the number of random requests, but it works like a password that is transmitted in every URL. URLs are commonly stored in web server logs, reverse proxies, analytics systems, monitoring tools and request histories.
If such a URL becomes known, an attacker can send their own data. WordPress will have no way to distinguish the real webhook provider from an unauthorized client.
HMAC does not hide the request contents or encrypt the connection. It confirms that the request was created by someone who knows the secret and that the body was not modified after signing. Always use HTTPS to protect data during transmission.
- A secret URL can remain as an additional compatibility layer, but not as the only security mechanism.
- The signature must be verified before json_decode(), side effects or writing data to the database.
- The signing scheme must be agreed with the sending service in advance: algorithm, string format, signature encoding and header names.
How an HMAC Webhook Scheme Works
A typical scheme uses three values: a timestamp, the raw HTTP request body and a shared secret. The sender creates a string such as `timestamp.body` and calculates an HMAC-SHA256 value. The result is sent in a header together with the timestamp.
WordPress receives the same values, checks whether the timestamp is still valid, calculates the expected signature and compares it with the header using hash_equals(). If the request body changes by even one character, the signatures will not match.
The signature format must be identical on both sides. The example below uses the hexadecimal string returned by hash_hmac() by default. Some APIs use Base64 or a prefix such as `sha256=`; this must be handled separately.
- Signing string: `timestamp.body`.
- Algorithm: HMAC-SHA256.
- Comparison: constant-time comparison using `hash_equals()`.
- Time window: for example, 300 seconds if that is the interval agreed with the sender.
Verifying the Signature in the WordPress REST API
In the REST API, the raw request body can be obtained with `$request->get_body()`. Save this value before decoding the JSON. Re-serializing an already decoded array can change whitespace, key order or number formatting, causing the signature verification to fail.
The simplified endpoint below checks the headers, time window and HMAC before decoding the JSON. Replace the header names and signature format with those defined by your webhook provider.
add_action('rest_api_init', function () {
register_rest_route('my-plugin/v1', '/webhook', [
'methods' => 'POST',
'callback' => 'my_plugin_handle_webhook',
'permission_callback' => '__return_true',
]);
});
function my_plugin_handle_webhook(WP_REST_Request $request) {
$body = $request->get_body();
$timestamp_header = $request->get_header('x-webhook-timestamp');
$signature = $request->get_header('x-webhook-signature');
$secret = getenv('WEBHOOK_SECRET');
if ($secret === false || $secret === '') {
return new WP_Error(
'webhook_not_configured',
'Webhook secret is not configured',
['status' => 500]
);
}
if (!is_string($timestamp_header) || !ctype_digit($timestamp_header)) {
return new WP_Error(
'invalid_timestamp',
'Invalid timestamp',
['status' => 401]
);
}
$timestamp = (int) $timestamp_header;
if (abs(time() - $timestamp) > 300) {
return new WP_Error(
'expired_request',
'Request expired',
['status' => 401]
);
}
$expected = hash_hmac(
'sha256',
$timestamp_header . '.' . $body,
$secret
);
if (!is_string($signature) || $signature === '' || !hash_equals($expected, $signature)) {
return new WP_Error(
'invalid_signature',
'Invalid signature',
['status' => 401]
);
}
$data = json_decode($body, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
return new WP_Error(
'invalid_json',
'Invalid JSON',
['status' => 400]
);
}
// You can validate event_id and run business logic here.
return new WP_REST_Response(['ok' => true], 200);
}
Important Details in the Example
The signing string uses the original timestamp header rather than a reformatted number. This removes ambiguity around leading zeros and must match the sender's implementation.
A 401 response is appropriate for an expired or unsigned request. Server configuration errors should generally return 500 and be fixed separately, without exposing the secret in the public response.
The `permission_callback` does not replace HMAC verification. Because webhook authentication is performed inside the callback, the endpoint can be public at the WordPress REST API level.
Where to Store the Webhook Secret
Do not store the secret in a repository, plugin file or a value edited through a public administration form without additional controls. The best practical option is an environment variable named `WEBHOOK_SECRET`, available to the PHP process.
Make sure the variable is actually passed to PHP-FPM, Apache or the container. On some hosting platforms, `getenv()` may not see a value that is available in the shell. After configuration, verify the setup without displaying the secret in a browser or log.
If the environment does not support environment variables, use a protected hosting configuration store or a secret that is excluded from version control. Do not write the secret to logs or include it in error messages.
- Use a long, random secret rather than the site name or an administrator password.
- Use separate secrets for staging and production.
- Plan a rotation procedure: a short transition period with two secrets or a simultaneous change on the sender and WordPress sides.
- Restrict access to the environment and backups.
Protecting Against Duplicate Webhook Delivery
Timestamp verification protects against old requests, but it does not always prevent the same request from being sent again within the permitted five-minute window. This is known as a replay attack or duplicate delivery.
If the provider sends a unique `event_id`, store it before performing an irreversible action such as creating an order, applying a payment, sending an email or changing a status. Create a unique index for this identifier in your own table.
The most reliable approach is to attempt to insert the `event_id` into the table and process the event only after the insert succeeds. If the database reports a unique constraint violation, the event has already been accepted. For complex processes, consider adding `received`, `processing`, `completed` and `failed` statuses, along with a recovery process for failures.
- Do not rely only on a PHP check such as SELECT followed by INSERT: two parallel requests can both pass that check.
- The database unique index should be the final safeguard against duplication.
- If `event_id` is not available, ask the provider to add it or generate your own identifier only according to a clearly defined scheme.
What to Check Before Launch
A secure webhook is more than a PHP snippet. Check the entire chain: TLS, proxy, web server, WordPress, database and the service that sends the events.
During testing, do not use the real production secret in local examples or submit it to publicly available online services. For signature testing, it is useful to have a small local script that creates the same signing string and HMAC value.
- A request with the correct signature is accepted.
- A modified body is rejected.
- An incorrect or missing signature is rejected.
- A timestamp outside the permitted window is rejected.
- A repeated `event_id` does not trigger the business operation again.
- Invalid JSON does not reach the business logic.
- A missing server secret does not cause unverified requests to be accepted.
- Logs do not contain the complete secret, signature or sensitive body contents.
Limits and Observability
Add a request body size limit at the web server or reverse proxy level if the webhook is not expected to accept large payloads. This reduces the risk of memory consumption and unnecessary PHP load.
Log technical results without secrets: time, HTTP status code, event type, event_id in a masked or permitted format and the reason for rejection. Do not record the full body if it contains personal or payment data.
Common Implementation Mistakes
The most common mistake is signing the result of `json_encode()` after the body has already been decoded. Even logically identical JSON objects can have different whitespace, key order or number formatting.
Another problem is comparing signatures with the regular `===` operator. Use `hash_equals()` for secret values to avoid timing-dependent comparisons.
Do not accept a request simply because it contains a signature header. Confirm that the timestamp has a valid format, the secret is configured, the algorithm matches the provider's documentation and HTTPS is enabled.
Do not return HTTP 200 for every error. Otherwise, the provider may consider the event delivered and will not retry it. At the same time, after successfully accepting an event, respond quickly and perform long-running work through a queue or background process if the site's architecture allows it.
- Do not decode JSON before verifying the HMAC.
- Do not use a URL secret as the only security mechanism.
- Do not log secrets, Authorization headers or complete sensitive payloads.
- Do not increase the time window unnecessarily: this makes it easier to reuse an intercepted request.
- Do not treat HMAC as a replacement for HTTPS or input structure validation.
Frequently asked questions
Is HMAC necessary if the webhook has a very complex URL?
Yes. A complex URL can provide an additional barrier, but it may appear in logs or become known to unauthorized parties. HMAC verifies the authenticity of every request.
Can the signature be verified after json_decode()?
No, if the signature is created from the HTTP body. You must verify the original request string and decode the JSON only afterward.
Does HMAC prevent duplicate webhook delivery?
Not completely. The same correctly signed request can be replayed within the permitted time window. Protection requires an event_id, a unique database index and duplicate-processing checks.
What timestamp lifetime should be used?
Use an interval agreed with the sending service, usually a few minutes. It should account for possible system clock differences without being significantly longer than necessary.
Does HMAC encrypt webhook data?
No. HMAC confirms the authenticity and integrity of a request but does not hide its contents. Use HTTPS to protect data in transit, and restrict access to logs and the database separately.
Conclusion
For WordPress webhooks, build security around HMAC rather than a secret URL. Verify the timestamp and signature against the raw request body before any JSON processing, keep the secret outside the code and compare values with hash_equals().
Implement idempotency separately using event_id and a unique database index. This approach protects the endpoint against impersonation, accidental payload changes and duplicate event processing while also simplifying error handling and retries.