---
title: "PHP webhook signature verifier"
description: "Run the complete PHP raw-byte notification verifier with authenticated event and environment checks."
slug: "/docs/v1/guides/verify-webhook-signatures/php"
section: "Webhook verification examples"
order: 217
audience: "all"
level: "advanced"
last_updated: "2026-10-18"
version: "v1"
related: ["/docs/v1/guides/verify-webhook-signatures", "/docs/v1/guides/test-webhooks-locally"]
draft: false
---
Authenticate [KDPika Licensing](/docs/v1/start/glossary#kdpika-licensing) notification bytes with the complete PHP verifier.

## What you will learn

- Install and execute this exact sample.
- Verify raw bytes, event metadata and the pinned environment.
- Identify the boundary between authentication and durable business processing.

## Prerequisites

- PHP 8.2 or newer with JSON and hash extensions; no Composer packages.
- The [notification source archive](/docs/downloads/webhook-receivers.zip), extracted locally.
- The [signature contract](/docs/v1/guides/verify-webhook-signatures) and a private [Sandbox](/docs/v1/start/glossary#sandbox) test secret.

## Prepare a request

1. Work inside the extracted [webhooks](/docs/v1/start/glossary#webhook) directory, which contains contract.json.
2. Set KDP_WEBHOOK_SECRET through your private process environment.
3. Set KDP_WEBHOOK_ENVIRONMENT to sandbox.
4. Use Python 3.11+ to create a fresh private synthetic request.

```bash
python3 make-test.py events/test-ping.json private/request-1
```

Expected output: Created private test request files. Use a new directory for each generated request; existing files are not overwritten. The helper signs a captured synthetic body, not a real payment or [license](/docs/v1/start/glossary#license) authorization. Keep contract.json in place: it supplies the shared event list, 300-second receiver freshness policy and 1 MiB receiver body cap.

## Build and run

```bash
php verify.php private/request-1/body.json private/request-1/headers.json
```

Expected result: exit 0 with verified=true, event_id=evt_ffa11b785e0ede73d9e69801, event=test.ping and environment=sandbox. Property order is not significant. This source was executed in the recorded macOS contract suite; native Windows and Linux execution are not claimed.

## Complete source

```php
<?php
declare(strict_types=1);
// Notification authenticity, not license validity. PHP 8.2+, JSON/hash extensions.
// Run with KDP_WEBHOOK_SECRET and KDP_WEBHOOK_ENVIRONMENT: php verify.php body.json headers.json
// Expected: verified=true JSON; invalid input prints verified=false and exits 1.
function verifyKdpWebhook(string $body,array $headers,string $secret,string $environment,int $now): array
{
    $contract=json_decode((string)file_get_contents(__DIR__.'/contract.json'),true,flags:JSON_THROW_ON_ERROR);
    if($secret===''||!in_array($environment,$contract['environments'],true)||strlen($body)>$contract['body_limit'])throw new RuntimeException('Invalid configuration or body size');
    $signature=$headers['x-lmp-signature']??null;
    if(!is_string($signature)||!preg_match('/^t=([1-9][0-9]{0,10}),v1=([0-9a-f]{64})$/D',$signature,$parts)||abs($now-(int)$parts[1])>$contract['tolerance_seconds'])throw new RuntimeException('Invalid or stale signature');
    if(!hash_equals(hash_hmac('sha256',$parts[1].'.'.$body,$secret),$parts[2]))throw new RuntimeException('Signature mismatch');
    $event=json_decode($body,false,64,JSON_THROW_ON_ERROR);
    if(!is_object($event)||!is_string($event->id??null)||!preg_match('/^evt_[A-Za-z0-9_-]{1,100}$/D',$event->id))throw new RuntimeException('Invalid event');
    if(!in_array($event->event??null,$contract['events'],true)||($event->environment??null)!==$environment||$event->id!==($headers['x-lmp-event-id']??null)||$event->event!==($headers['x-lmp-event']??null))throw new RuntimeException('Event metadata mismatch');
    if(!is_object($event->data??null)||!is_string($event->created_at??null)||$event->created_at==='')throw new RuntimeException('Invalid envelope');
    return json_decode($body,true,64,JSON_THROW_ON_ERROR);
}
function readKdpBounded(string $path,int $limit): string
{
    $stream=fopen($path,'rb');if(!$stream)throw new RuntimeException('Input unavailable');
    try{$value=stream_get_contents($stream,$limit+1);if($value===false||strlen($value)>$limit)throw new RuntimeException('Oversized input');return $value;}finally{fclose($stream);}
}
if(PHP_SAPI==='cli'&&realpath($_SERVER['SCRIPT_FILENAME'])===__FILE__){
    try{
        if($argc!==3)throw new RuntimeException('Two file paths required');
        $headers=json_decode(readKdpBounded($argv[2],32768),true,64,JSON_THROW_ON_ERROR);if(!is_array($headers))throw new RuntimeException('Invalid headers');
        $event=verifyKdpWebhook(readKdpBounded($argv[1],1048576),$headers,(string)getenv('KDP_WEBHOOK_SECRET'),strtolower((string)getenv('KDP_WEBHOOK_ENVIRONMENT')),time());
        echo json_encode(['verified'=>true,'event_id'=>$event['id'],'event'=>$event['event'],'environment'=>$event['environment']],JSON_THROW_ON_ERROR).PHP_EOL;
    }catch(Throwable){echo '{"verified":false}'.PHP_EOL;exit(1);}
}
```

## Connect to an HTTP adapter

1. Read a bounded raw HTTP body before JSON middleware changes it.
2. Reject duplicate signature, event-ID and event-name header fields.
3. Normalize header names to lowercase without changing their values.
4. Pass the exact raw body, headers, configured endpoint secret and expected environment to the verifier.
5. Atomically persist the verified event ID and work item before sending a 2xx response.

Expected result: only authenticated recent notifications reach your inbox. The CLI tool does not start an HTTP listener, save deduplication records, call licensing APIs, send email or unlock an application. Use the [local inbox example](/docs/v1/guides/test-webhooks-locally) to test the durable acknowledgement boundary.

## Expected result

All captured event types pass when signed with the right current secret and pinned environment. Changed raw bytes, a wrong secret, stale/future attempt timestamp, malformed envelope or wrong environment print exactly {"verified":false} and exit 1. The shared suite exercises positive events, negative input and size boundaries against the exact file above.

## Common mistakes

- Reading contract.json from a different working directory or copying only one source without its companion files.
- Re-encoding JSON before HMAC verification.
- Reusing an expired test signature instead of generating a current one.
- Assuming successful authentication deduplicates an additive renewal.

## Security notes

Never print the secret or full signature in logs. Use the endpoint's plaintext HMAC secret, not a [developer API key](/docs/v1/start/glossary#developer-api-key) or an Ed25519 public key. A verified notification is not an authoritative license-validity response. Timestamp filtering does not stop duplicate [delivery](/docs/v1/start/glossary#delivery) inside its window; use a durable authenticated event-ID ledger and an independent business-operation key.

## Troubleshooting

| Symptom | Cause | Fix |
| --- | --- | --- |
| verified=false for an unchanged fixture | Timestamp expired, wrong secret or wrong environment | Regenerate the private request using the intended Sandbox configuration |
| Companion file cannot be found | Working directory or extraction incomplete | Restore the complete source archive and work inside webhooks |
| The same ID verifies again | Verifier only authenticates bytes | Commit a unique inbox record before applying an effect |

## Next steps

Run the [local HTTP, replay and storage-failure tests](/docs/v1/guides/test-webhooks-locally).

## Related

- [All verifier languages](/docs/v1/guides/verify-webhook-signatures)
- [Delivery and retries](/docs/v1/guides/webhook-delivery)
- [Webhook event catalog](/docs/v1/guides/webhook-events)
