KDPika Licensing Sign inStart free
API v1
Show all languages
Browse documentation

Choose a page in the navigation drawer.

KDPika Licensing · API v1 Advanced

PHP webhook signature verifier

Run the complete PHP raw-byte notification verifier with authenticated event and environment checks.

On this page
Updated 2026-10-18 UTCDownload Markdown

Authenticate 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

Prepare a request

  1. Work inside the extracted webhooks 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.
bashbash
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 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

bashbash
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

verify.phpphp
<?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 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 or an Ed25519 public key. A verified notification is not an authoritative license-validity response. Timestamp filtering does not stop duplicate delivery inside its window; use a durable authenticated event-ID ledger and an independent business-operation key.

Troubleshooting

SymptomCauseFix
verified=false for an unchanged fixtureTimestamp expired, wrong secret or wrong environmentRegenerate the private request using the intended Sandbox configuration
Companion file cannot be foundWorking directory or extraction incompleteRestore the complete source archive and work inside webhooks
The same ID verifies againVerifier only authenticates bytesCommit a unique inbox record before applying an effect

Next steps

Run the local HTTP, replay and storage-failure tests.

Was this page helpful?

Choose an answer

Do not include personal data, license keys or credentials. Retained for up to 30 days. This is not a support inbox.

Search documentation

Arrow keys to move, Enter to open, Escape to close. Search stays in your browser.

Cookie settings