When your webhook endpoint (`POST /webhooks/stripe` or `POST /webhooks/github`) sits exposed on the public internet, anyone who discovers that URL can send a forged `{"event": "invoice.paid"}` JSON payload unless you cryptographically verify the provider’s **HMAC-SHA256 signature** before touching your database.
Even more common than skipping verification is implementing it slightly wrong—causing legitimate Stripe, GitHub, or Shopify webhooks to fail with `400 Bad Request` because your framework parsed JSON before computing the HMAC digest.
Provider Signature Header Formats Compared (Stripe vs. GitHub vs. Shopify)
| Provider | HTTP Signature Header | Signed Message Format | Encoding & Replay Guard |
|---|---|---|---|
| Stripe | Stripe-Signature (t=...,v1=...) |
"{timestamp}.{raw_body}" |
Hex HMAC-SHA256 + timestamp tolerance (`≤ 300s`) |
| GitHub | X-Hub-Signature-256 (sha256=...) |
"{raw_body}" |
Hex HMAC-SHA256 + `X-GitHub-Delivery` UUID idempotency |
| Shopify | X-Shopify-Hmac-Sha256 |
"{raw_body}" |
Base64 HMAC-SHA256 + `X-Shopify-Webhook-Id` |
Rule #1: Always Hash the Exact Raw Request Bytes, Never Re-Encoded JSON
Calling `json_encode($request->getJSON(true))` or `JSON.stringify(req.body)` changes whitespace, newline characters (`\n` vs `\r\n`), and Unicode escaping (`\/` in PHP!). A single changed byte produces a completely different SHA-256 HMAC digest. Always read `php://input` (or CodeIgniter 4’s `$this->request->getBody()`) directly.
1. Verifying Stripe-Style Timestamped HMAC Webhooks in PHP 8.3 / CodeIgniter 4
Notice three critical defenses below: (1) reading raw bytes via `$this->request->getBody()`, (2) rejecting timestamps older than 5 minutes (`300s`) to prevent **replay attacks**, and (3) comparing signatures with **`hash_equals()`** so timing side-channels cannot leak signature bytes:
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\ResponseInterface;
class StripeWebhookController extends BaseController
{
public function handle(): ResponseInterface
{
$rawPayload = (string) $this->request->getBody(); // Raw php://input bytes!
$sigHeader = (string) $this->request->getHeaderLine('Stripe-Signature');
$secret = (string) env('STRIPE_WEBHOOK_SECRET', '');
if ($rawPayload === '' || $sigHeader === '' || $secret === '') {
return $this->response->setStatusCode(400)->setJSON(['error' => 'Missing payload or signature']);
}
// Parse "t=1735689600,v1=abcdef..."
$parts = [];
foreach (explode(',', $sigHeader) as $kv) {
[$k, $v] = array_pad(explode('=', trim($kv), 2), 2, '');
if ($k !== '' && $v !== '') {
$parts[$k][] = $v;
}
}
$timestamp = (int) ($parts['t'][0] ?? 0);
$v1Sigs = $parts['v1'] ?? [];
// Enforce 5-minute replay window
if ($timestamp === 0 || abs(time() - $timestamp) > 300 || $v1Sigs === []) {
return $this->response->setStatusCode(400)->setJSON(['error' => 'Stale or malformed signature timestamp']);
}
$expectedHmac = hash_hmac('sha256', "{$timestamp}.{$rawPayload}", $secret);
$matched = false;
foreach ($v1Sigs as $candidate) {
if (hash_equals($expectedHmac, $candidate)) {
$matched = true;
break;
}
}
if (! $matched) {
return $this->response->setStatusCode(401)->setJSON(['error' => 'Invalid HMAC signature']);
}
$event = json_decode($rawPayload, true, 512, JSON_THROW_ON_ERROR);
// Persist $event['id'] in a UNIQUE `webhook_events(event_id)` table before acting!
return $this->response->setStatusCode(200)->setJSON(['received' => true]);
}
}
2. Verifying GitHub / Generic HMAC-SHA256 Webhooks in Node.js (Express / Fastify)
In Node.js, make sure your body-parser middleware captures the raw `Buffer` (`verify: (req, res, buf) => { req.rawBody = buf; }`) before `express.json()` parses it:
import crypto from 'node:crypto';
export function verifyGitHubSignature(req, webhookSecret) {
const sigHeader = req.get('X-Hub-Signature-256') || '';
if (!sigHeader.startsWith('sha256=') || !Buffer.isBuffer(req.rawBody)) {
return false;
}
const expected = 'sha256=' + crypto
.createHmac('sha256', webhookSecret)
.update(req.rawBody) // Exact raw Buffer bytes!
.digest('hex');
const a = Buffer.from(sigHeader, 'utf8');
const b = Buffer.from(expected, 'utf8');
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
3. Production Webhook Reliability: Idempotency + Async Queue
- Exclude webhook routes from CSRF filters: External providers do not have your session CSRF cookie. Exclude `webhooks/*` in CodeIgniter’s `app/Config/Filters.php` and rely on HMAC verification instead.
- Deduplicate deliveries via a `UNIQUE(provider, event_id)` table: Providers retry webhooks automatically if your server takes > 5 seconds to answer. Store the event ID, return `200 OK` immediately, and process heavy PDF/email/ERP work asynchronously.
- Compare token vs webhook security: Building authenticated client APIs alongside webhooks? Read How to Decode & Verify JWT Signatures Safely in PHP and Node.js.
Frequently Asked Questions
Why can’t I use `===` in PHP or JS to compare HMAC signatures?
Standard string equality (`===`) returns immediately on the first mismatched character, leaking tiny microsecond timing clues under repeated probing. Always use constant-time `hash_equals()` in PHP or `crypto.timingSafeEqual()` in Node.js.