From 5c9669a688bb9e559287af231b50707097cc52e5 Mon Sep 17 00:00:00 2001 From: Stefan Schmidt-Egermann Date: Sat, 25 Apr 2026 12:26:06 +0200 Subject: [PATCH] feat: initial php content (v0.1.0) - Composer-Package, PSR-4-Autoload - Client mit Sync, Async (mit Polling), Webhook, Verify, Download - PHP 8.1+ mit readonly-Properties - Webhook-Signatur-Verifikation (hash_equals) - PHPUnit-Tests --- LICENSE | 20 ++- README.md | 169 ++++++++++++-------- SECURITY.md | 6 - composer.json | 50 ++++++ examples/quickstart.php | 63 ++++++++ phpunit.xml | 17 ++ src/Client.php | 335 ++++++++++++++++++++++++++++++++++++++++ src/Exceptions.php | 40 +++++ src/Webhook.php | 29 ++++ tests/WebhookTest.php | 53 +++++++ 10 files changed, 704 insertions(+), 78 deletions(-) create mode 100644 composer.json create mode 100644 examples/quickstart.php create mode 100644 phpunit.xml create mode 100644 src/Client.php create mode 100644 src/Exceptions.php create mode 100644 src/Webhook.php create mode 100644 tests/WebhookTest.php diff --git a/LICENSE b/LICENSE index c7ebe92..ed12564 100644 --- a/LICENSE +++ b/LICENSE @@ -1,9 +1,21 @@ MIT License -Copyright (c) 2026 hightrusted +Copyright (c) 2026 hightrusted GmbH -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 699fa7e..69cc61e 100644 --- a/README.md +++ b/README.md @@ -5,19 +5,7 @@ Offizielles PHP-SDK für die [hightrusted CAPTURE API](https://capture.hightrusted.net) — forensische Web-Captures mit qualifiziertem Zeitstempel nach RFC 3161 / eIDAS Art. 41. -**Made in Germany.** Server in Deutschland. DSGVO-nativ. Kein US-Cloud-Anbieter -in der Verarbeitungskette. Quelloffen unter MIT-Lizenz. - -## Was die CAPTURE API tut - -Sie nimmt eine URL entgegen, rendert die Seite vollständig (inkl. JavaScript), -liefert sie als PDF/A zurück und versieht das Ergebnis mit einem qualifizierten -Zeitstempel. Das Ergebnis ist gerichtsverwertbar und Jahre später noch -verifizierbar — auch nachdem die Original-Seite längst offline ist. - -Anwendungsfälle: Markenrechtsverletzungen dokumentieren, Auftragsbedingungen -zum Buchungszeitpunkt sichern, Compliance-Nachweise für Behörden, Beweissicherung -durch Anwälte und Sachverständige. +**Made in Germany.** Server in Deutschland. DSGVO-nativ. Quelloffen unter MIT. ## Installation @@ -36,66 +24,111 @@ $client = new Client(['api_key' => 'ht_live_...']); // Synchron — wartet bis zu 30 s auf das fertige PDF $capture = $client->capture(['url' => 'https://example.com']); -echo $capture->id . PHP_EOL; -echo $capture->verifyUrl . PHP_EOL; -echo $capture->timestamp->issuedAt . PHP_EOL; +echo $capture['id']; +echo $capture['verify_url']; +echo $capture['timestamp']['issued_at']; // PDF herunterladen -$capture->download('./beweis.pdf'); +$client->downloadPdf($capture['id'], './beweis.pdf'); ``` -## Authentifizierung +## Drei Aufruf-Modi -Bearer-Token mit API-Key. Key-Erzeugung im Dashboard: +### Synchron (Default) +```php +$capture = $client->capture(['url' => 'https://example.com']); +``` + +### Asynchron mit Polling +```php +$capture = $client->captureAsync( + ['url' => 'https://example.com', 'reference' => 'case-001'], + waitForReady: true, + maxWaitSec: 60.0, +); +``` + +### Webhook +```php +$job = $client->captureWebhook([ + 'url' => 'https://example.com', + 'webhook_url' => 'https://your-app.tld/webhooks/capture', + 'reference' => 'case-001', +]); +``` + +## Verifikation (kostenlos, ohne Quota) + +```php +// Per Capture-ID +$result = $client->verify(source: 'cap_...'); + +// Per Verify-URL +$result = $client->verify(source: 'https://verify.hightrusted.net/c/...'); + +// Per PDF-Upload +$result = $client->verify(pdfPath: './beweis.pdf'); + +echo $result['valid'] ? 'gültig' : 'ungültig'; +``` + +## Webhook-Signatur prüfen + +```php +use Hightrusted\Capture\Webhook; + +// In deinem Webhook-Endpoint: +$body = file_get_contents('php://input'); // RAW body! +$sig = $_SERVER['HTTP_X_HIGHTRUSTED_SIGNATURE'] ?? ''; + +if (!Webhook::verifySignature($body, $sig, 'wh_secret_...')) { + http_response_code(401); + exit('invalid_signature'); +} + +$payload = json_decode($body, true); +// ... +``` + +## Fehler-Behandlung + +```php +use Hightrusted\Capture\{ + Client, + InvalidApiKeyException, + QuotaExceededException, + RateLimitedException, + UnreachableUrlException, +}; + +try { + $capture = $client->capture(['url' => 'https://example.com']); +} catch (InvalidApiKeyException $e) { + echo "API-Key ungültig\n"; +} catch (QuotaExceededException $e) { + echo "Quota erschöpft\n"; +} catch (RateLimitedException $e) { + echo "Rate-limited, retry in {$e->retryAfterSeconds}s\n"; +} catch (UnreachableUrlException $e) { + echo "Quelle nicht erreichbar\n"; +} +``` + +## API-Key + +Bearer-Token, Erzeugung unter https://capture.hightrusted.net/dashboard/api-keys ```php -// API-Key direkt $client = new Client(['api_key' => 'ht_live_...']); - -// oder über Umgebungsvariable HIGHTRUSTED_API_KEY +// alternativ über Umgebungsvariable HIGHTRUSTED_API_KEY $client = new Client(); ``` -## Asynchrone Captures + Webhooks - -```php -$job = $client->captureAsync([ - 'url' => 'https://example.com', - 'webhook_url' => 'https://your-app.tld/webhooks/capture', -]); -// $job->status === 'queued' - -// später, sobald der Webhook capture.ready geliefert hat: -$capture = $client->get($job->id); -$capture->download('./beweis.pdf'); -``` - -## Verify - -```php -$result = $client->verify('cap_...'); -echo $result->valid ? 'OK' : 'INVALID'; // OK -echo $result->timestamp; // 2026-04-25T11:29:40Z -``` - -## Rate Limits - -Limits werden pro API-Key gemessen. Bei Überschreitung: HTTP 429 mit -`Retry-After`-Header. Das SDK respektiert den Header automatisch und retried. - -| Plan | req/min | Calls/Monat | -|-----------|---------|-------------| -| Developer | 5 | 100 | -| Starter | 30 | 300 | -| Growth | 120 | 2.000 | -| Scale | 600 | 10.000 | - ## Voraussetzungen - PHP 8.1 oder höher -- `ext-curl`, `ext-json` -- `guzzlehttp/guzzle` (wird via Composer installiert) +- `ext-curl`, `ext-json`, `ext-hash` ## Entwicklung @@ -103,13 +136,13 @@ Limits werden pro API-Key gemessen. Bei Überschreitung: HTTP 429 mit git clone ssh://git@git.hightrusted.net:2222/hightrusted-capture/php.git cd php composer install -vendor/bin/phpunit +composer test ``` ## Roadmap -- [ ] v0.1 — Basis-Client, Verify, Download -- [ ] v0.2 — Retry-Logik, Webhook-Signatur-Verifikation, PSR-18-kompatibel +- [x] v0.1 — Basis-Client, Verify, Download, typisierte Exceptions +- [ ] v0.2 — PSR-18-kompatibel (HTTP-Client austauschbar) - [ ] v0.3 — Laravel Service-Provider als separates Package - [ ] v1.0 — Stabile API, semantische Versionierung @@ -117,24 +150,24 @@ vendor/bin/phpunit **Im selben Produkt** ([`hightrusted-capture`](https://git.hightrusted.net/hightrusted-capture)): -- [`openapi`](https://git.hightrusted.net/hightrusted-capture/openapi) — OpenAPI 3.1 Spec (Single Source of Truth) +- [`openapi`](https://git.hightrusted.net/hightrusted-capture/openapi) — OpenAPI 3.1 Spec - [`postman`](https://git.hightrusted.net/hightrusted-capture/postman) — Postman Collection -- [`examples`](https://git.hightrusted.net/hightrusted-capture/examples) — Beispiel-Anwendungen +- [`examples`](https://git.hightrusted.net/hightrusted-capture/examples) — Beispiel-Anwendungen (inkl. WordPress-Plugin) - [`python`](https://git.hightrusted.net/hightrusted-capture/python) — Python-SDK - [`node`](https://git.hightrusted.net/hightrusted-capture/node) — Node.js-SDK **Plattform-übergreifend** ([`hightrusted`](https://git.hightrusted.net/hightrusted)): -- [`platform`](https://git.hightrusted.net/hightrusted/platform) — Plattform-Übersicht, Architektur, Produkt-Liste -- [`developer-portal`](https://git.hightrusted.net/hightrusted/developer-portal) — gemeinsame Konventionen, Auth, Errors, Rate-Limits -- [`compliance`](https://git.hightrusted.net/hightrusted/compliance) — DSGVO, AGB-Templates, Whitepaper +- [`platform`](https://git.hightrusted.net/hightrusted/platform) +- [`developer-portal`](https://git.hightrusted.net/hightrusted/developer-portal) +- [`compliance`](https://git.hightrusted.net/hightrusted/compliance) ## Support - **Doku:** https://capture.hightrusted.net/api/docs -- **Status-Page:** https://status.hightrusted.net +- **Status:** https://status.hightrusted.net - **Developer Support:** developers@hightrusted.net -- **Sicherheitslücken:** siehe [SECURITY.md](./SECURITY.md) +- **Sicherheit:** siehe [SECURITY.md](./SECURITY.md) ## Lizenz diff --git a/SECURITY.md b/SECURITY.md index 9ed887a..63ed5b2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -25,9 +25,3 @@ Während der `v0.x`-Phase werden nur die jeweils aktuellste Minor-Version und deren letzte zwei Patch-Versionen aktiv mit Sicherheits-Updates versorgt. Ab `v1.0` gilt: aktuelle Major + vorherige Major (12 Monate Übergangsfrist). - -## Out of Scope - -Diese Policy gilt für die SDKs in diesem Repository und die zugehörige -hightrusted CAPTURE API. Für Schwachstellen in anderen hightrusted-Produkten -(SIGN, ID, MEET, PAY, …) gilt jeweils die dortige `SECURITY.md`. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..08eef89 --- /dev/null +++ b/composer.json @@ -0,0 +1,50 @@ +{ + "name": "hightrusted/capture", + "description": "PHP SDK für die hightrusted CAPTURE API — forensische Web-Captures mit qualifiziertem Zeitstempel", + "type": "library", + "license": "MIT", + "keywords": ["capture", "screenshot", "rfc3161", "timestamp", "eidas", "forensic", "evidence"], + "homepage": "https://capture.hightrusted.net", + "authors": [ + { + "name": "hightrusted GmbH", + "email": "developers@hightrusted.net", + "homepage": "https://hightrusted.net" + } + ], + "support": { + "email": "developers@hightrusted.net", + "issues": "https://git.hightrusted.net/hightrusted-capture/php/issues", + "source": "https://git.hightrusted.net/hightrusted-capture/php", + "docs": "https://capture.hightrusted.net/api/docs" + }, + "require": { + "php": ">=8.1", + "ext-curl": "*", + "ext-json": "*", + "ext-hash": "*" + }, + "require-dev": { + "phpunit/phpunit": "^10.5", + "friendsofphp/php-cs-fixer": "^3.50" + }, + "autoload": { + "psr-4": { + "Hightrusted\\Capture\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Hightrusted\\Capture\\Tests\\": "tests/" + } + }, + "scripts": { + "test": "phpunit", + "format": "php-cs-fixer fix" + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "stable", + "prefer-stable": true +} diff --git a/examples/quickstart.php b/examples/quickstart.php new file mode 100644 index 0000000..2711f9a --- /dev/null +++ b/examples/quickstart.php @@ -0,0 +1,63 @@ + getenv('HIGHTRUSTED_API_KEY')]); + +// ────────────────────────────────────────────────────────────────── +// 1. Synchrone Capture +// ────────────────────────────────────────────────────────────────── +echo "→ Erstelle Capture (synchron)...\n"; +$capture = $client->capture([ + 'url' => 'https://example.com', + 'reference' => 'quickstart-demo', + 'viewport' => ['width' => 1920, 'height' => 1080], +]); +echo " ID: {$capture['id']}\n"; +echo " Status: {$capture['status']}\n"; +echo " Verify-URL: {$capture['verify_url']}\n"; +echo " Zeitstempel: {$capture['timestamp']['issued_at']}\n"; + +// ────────────────────────────────────────────────────────────────── +// 2. Verifikation (kostenlos) +// ────────────────────────────────────────────────────────────────── +echo "\n→ Verifiziere die Capture...\n"; +$result = $client->verify(source: $capture['id']); +echo " Gültig: ".($result['valid'] ? 'true' : 'false')."\n"; + +// ────────────────────────────────────────────────────────────────── +// 3. PDF herunterladen +// ────────────────────────────────────────────────────────────────── +echo "\n→ Lade PDF herunter...\n"; +$path = $client->downloadPdf( + $capture['id'], + './capture_'.substr($capture['id'], 0, 8).'.pdf', +); +echo " Gespeichert: {$path}\n"; + +// ────────────────────────────────────────────────────────────────── +// 4. Quota +// ────────────────────────────────────────────────────────────────── +echo "\n→ Quota-Status...\n"; +try { + $usage = $client->usage(); + echo " Plan: {$usage['plan']}\n"; + echo " Verbraucht: {$usage['used_calls']}/{$usage['included_calls']}\n"; +} catch (RateLimitedException $e) { + echo " Rate-limited, retry in {$e->retryAfterSeconds}s\n"; +} diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..c0382fa --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,17 @@ + + + + + tests + + + + + src + + + diff --git a/src/Client.php b/src/Client.php new file mode 100644 index 0000000..9d448ac --- /dev/null +++ b/src/Client.php @@ -0,0 +1,335 @@ + 'ht_live_...']); + * $capture = $client->capture(['url' => 'https://example.com']); + * echo $capture['verify_url']; + */ +class Client +{ + public const VERSION = '0.1.0'; + public const DEFAULT_BASE_URL = 'https://capture.hightrusted.net/api/v1'; + public const DEFAULT_TIMEOUT = 35; + private const USER_AGENT = 'hightrusted-capture-php/0.1.0'; + + private const ERROR_CODE_MAP = [ + 'invalid_api_key' => InvalidApiKeyException::class, + 'quota_exceeded' => QuotaExceededException::class, + 'capture_not_found' => CaptureNotFoundException::class, + 'capture_not_ready' => CaptureNotReadyException::class, + 'unreachable_url' => UnreachableUrlException::class, + 'rate_limited' => RateLimitedException::class, + 'tsa_unavailable' => TsaUnavailableException::class, + ]; + + private string $apiKey; + private string $baseUrl; + private int $timeout; + private int $maxRetries; + + /** + * @param array{api_key?: string, base_url?: string, timeout?: int, max_retries?: int} $config + */ + public function __construct(array $config = []) + { + $key = $config['api_key'] ?? getenv('HIGHTRUSTED_API_KEY') ?: null; + if (!$key) { + throw new \InvalidArgumentException( + 'API-Key fehlt. Setze entweder den Schlüssel `api_key` im Config-Array ' + .'oder die Umgebungsvariable HIGHTRUSTED_API_KEY.' + ); + } + $this->apiKey = $key; + $this->baseUrl = rtrim($config['base_url'] ?? self::DEFAULT_BASE_URL, '/'); + $this->timeout = $config['timeout'] ?? self::DEFAULT_TIMEOUT; + $this->maxRetries = $config['max_retries'] ?? 3; + } + + // ──────────────────────────────────────────────────────────────── + // Public API + // ──────────────────────────────────────────────────────────────── + + /** + * Synchrones Capture — wartet bis zu 30 s auf das fertige PDF. + * + * @param array{url: string, reference?: string, viewport?: array, wait_until?: string, full_page?: bool, co_branding?: array} $params + */ + public function capture(array $params): array + { + return $this->request('POST', '/captures', $this->buildBody($params, mode: null)); + } + + /** + * Asynchrones Capture mit optionalem Polling. + */ + public function captureAsync(array $params, bool $waitForReady = true, float $pollIntervalSec = 2.0, float $maxWaitSec = 60.0): array + { + $queued = $this->request('POST', '/captures', $this->buildBody($params, mode: 'async')); + if (!$waitForReady) { + return $queued; + } + + $deadline = microtime(true) + $maxWaitSec; + usleep((int) (min(3.0, $pollIntervalSec) * 1_000_000)); // initial 3 s + + while (microtime(true) < $deadline) { + $detail = $this->get($queued['id']); + if ($detail['status'] === 'ready') { + return $detail; + } + if ($detail['status'] === 'failed') { + throw new HightrustedException( + 'Capture failed: '.($detail['error'] ?? 'unknown'), + 'capture_failed', + raw: $detail, + ); + } + usleep((int) ($pollIntervalSec * 1_000_000)); + } + + throw new \RuntimeException(sprintf( + 'Capture %s nicht fertig nach %.1fs', + $queued['id'], + $maxWaitSec, + )); + } + + /** + * Webhook-Capture — Server liefert das Ergebnis per HTTP-POST aus. + */ + public function captureWebhook(array $params): array + { + if (empty($params['webhook_url'])) { + throw new \InvalidArgumentException('webhook_url ist Pflicht für captureWebhook'); + } + + return $this->request('POST', '/captures', $this->buildBody($params, mode: 'webhook')); + } + + /** Status / Detail einer einzelnen Capture. */ + public function get(string $id): array + { + return $this->request('GET', '/captures/'.rawurlencode($id)); + } + + /** Captures auflisten (paginiert per Cursor). */ + public function list(array $filters = []): array + { + $params = array_filter([ + 'limit' => $filters['limit'] ?? 25, + 'status' => $filters['status'] ?? null, + 'reference' => $filters['reference'] ?? null, + 'cursor' => $filters['cursor'] ?? null, + ], fn ($v) => $v !== null); + + return $this->request('GET', '/captures?'.http_build_query($params)); + } + + /** + * Lädt das PDF einer fertigen Capture lokal herunter. + * + * @return string Der Zielpfad + */ + public function downloadPdf(string $id, string $targetPath): string + { + $url = $this->baseUrl.'/captures/'.rawurlencode($id).'/pdf'; + + $fp = fopen($targetPath, 'wb'); + if (!$fp) { + throw new \RuntimeException("Cannot open $targetPath for writing"); + } + + $ch = curl_init($url); + curl_setopt_array($ch, [ + CURLOPT_HTTPHEADER => $this->headers(), + CURLOPT_FILE => $fp, + CURLOPT_TIMEOUT => $this->timeout, + CURLOPT_FOLLOWLOCATION => true, + ]); + $ok = curl_exec($ch); + $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + curl_close($ch); + fclose($fp); + + if (!$ok || $status >= 400) { + @unlink($targetPath); + throw new HightrustedException("PDF-Download fehlgeschlagen (HTTP $status)", statusCode: $status); + } + + return $targetPath; + } + + /** + * Verifiziert ein Capture per ID, Verify-URL oder PDF-Upload. + * + * Genau einer der Parameter muss gesetzt sein: + * - source: Capture-ID oder Verify-URL + * - pdf_path: Pfad zur PDF-Datei + */ + public function verify(?string $source = null, ?string $pdfPath = null): array + { + if (($source === null) === ($pdfPath === null)) { + throw new \InvalidArgumentException('Genau einer von `source` oder `pdf_path` muss gesetzt sein.'); + } + + $url = $this->baseUrl.'/verify'; + $ch = curl_init($url); + + if ($source !== null) { + curl_setopt_array($ch, [ + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => json_encode(['source' => $source], JSON_THROW_ON_ERROR), + CURLOPT_HTTPHEADER => array_merge($this->headers(), ['Content-Type: application/json']), + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => $this->timeout, + ]); + } else { + $cfile = new \CURLFile($pdfPath, 'application/pdf', basename($pdfPath)); + curl_setopt_array($ch, [ + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => ['pdf' => $cfile], + CURLOPT_HTTPHEADER => $this->headers(), // KEIN Content-Type — multipart! + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => $this->timeout, + ]); + } + + $body = curl_exec($ch); + $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + $headers = curl_getinfo($ch); + curl_close($ch); + + return $this->handleResponse($status, $body ?: '', []); + } + + public function usage(): array + { + return $this->request('GET', '/usage'); + } + + // ──────────────────────────────────────────────────────────────── + // Internals + // ──────────────────────────────────────────────────────────────── + + private function buildBody(array $params, ?string $mode): array + { + if (empty($params['url'])) { + throw new \InvalidArgumentException('url ist Pflicht'); + } + $body = ['url' => $params['url']]; + if ($mode !== null) $body['mode'] = $mode; + if (!empty($params['webhook_url'])) $body['webhook_url'] = $params['webhook_url']; + if (!empty($params['reference'])) $body['reference'] = $params['reference']; + if (!empty($params['viewport'])) $body['viewport'] = $params['viewport']; + if (!empty($params['wait_until'])) $body['wait_until'] = $params['wait_until']; + if (isset($params['full_page'])) $body['full_page'] = (bool) $params['full_page']; + if (!empty($params['co_branding'])) $body['co_branding'] = $params['co_branding']; + + return $body; + } + + private function headers(): array + { + return [ + 'Authorization: Bearer '.$this->apiKey, + 'User-Agent: '.self::USER_AGENT, + ]; + } + + private function request(string $method, string $path, ?array $body = null): array + { + $url = $this->baseUrl.$path; + $attempt = 0; + + while (true) { + $ch = curl_init($url); + $headers = array_merge($this->headers(), ['Content-Type: application/json']); + + curl_setopt_array($ch, [ + CURLOPT_CUSTOMREQUEST => $method, + CURLOPT_HTTPHEADER => $headers, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_HEADER => true, + CURLOPT_TIMEOUT => $this->timeout, + ]); + + if ($body !== null) { + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR)); + } + + $response = curl_exec($ch); + $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); + $rawHeaders = substr($response, 0, $headerSize); + $rawBody = substr($response, $headerSize); + curl_close($ch); + + $parsedHeaders = $this->parseHeaders($rawHeaders); + + if ($status === 429 && $attempt < $this->maxRetries) { + $retryAfter = (int) ($parsedHeaders['retry-after'] ?? '1'); + sleep($retryAfter); + $attempt++; + continue; + } + + if ($status >= 500 && $status < 600 && $attempt < $this->maxRetries) { + sleep(2 ** $attempt); + $attempt++; + continue; + } + + return $this->handleResponse($status, $rawBody, $parsedHeaders); + } + } + + private function handleResponse(int $status, string $rawBody, array $headers): array + { + $payload = json_decode($rawBody, true); + + if ($status >= 200 && $status < 300) { + if (!is_array($payload)) { + throw new HightrustedException("Ungültiger JSON-Response (HTTP $status)", statusCode: $status); + } + + return $payload; + } + + $err = $payload['error'] ?? []; + $code = $err['code'] ?? 'unknown_error'; + $message = $err['message'] ?? "HTTP $status"; + $requestId = $err['request_id'] ?? null; + + $excClass = self::ERROR_CODE_MAP[$code] ?? HightrustedException::class; + + if ($excClass === RateLimitedException::class) { + $retryAfter = isset($headers['retry-after']) ? (int) $headers['retry-after'] : null; + throw new RateLimitedException($message, $code, $requestId, $status, $payload, $retryAfter); + } + + throw new $excClass($message, $code, $requestId, $status, $payload); + } + + private function parseHeaders(string $raw): array + { + $headers = []; + foreach (explode("\r\n", $raw) as $line) { + if (str_contains($line, ':')) { + [$k, $v] = explode(':', $line, 2); + $headers[strtolower(trim($k))] = trim($v); + } + } + + return $headers; + } +} diff --git a/src/Exceptions.php b/src/Exceptions.php new file mode 100644 index 0000000..4d6bb11 --- /dev/null +++ b/src/Exceptions.php @@ -0,0 +1,40 @@ +`. + * Das Webhook-Secret wird im Dashboard pro API-Key konfiguriert. + * + * @param string $body Roh-Body des Requests + * @param string $signatureHeader Wert von `X-Hightrusted-Signature` + * @param string $secret Webhook-Secret aus dem Dashboard + */ + public static function verifySignature(string $body, string $signatureHeader, string $secret): bool + { + if ($body === '' || $signatureHeader === '' || $secret === '') { + return false; + } + + $expected = 'sha256='.hash_hmac('sha256', $body, $secret); + + return hash_equals($expected, $signatureHeader); + } +} diff --git a/tests/WebhookTest.php b/tests/WebhookTest.php new file mode 100644 index 0000000..7e8f00a --- /dev/null +++ b/tests/WebhookTest.php @@ -0,0 +1,53 @@ +assertTrue(Webhook::verifySignature($body, $sig, $secret)); + } + + public function testWrongSecretIsRejected(): void + { + $body = '{"event":"capture.ready"}'; + $sig = 'sha256='.hash_hmac('sha256', $body, 'right_secret'); + + $this->assertFalse(Webhook::verifySignature($body, $sig, 'wrong_secret')); + } + + public function testEmptyInputsAreRejected(): void + { + $this->assertFalse(Webhook::verifySignature('', 'sha256=x', 'secret')); + $this->assertFalse(Webhook::verifySignature('x', '', 'secret')); + $this->assertFalse(Webhook::verifySignature('x', 'sha256=x', '')); + } + + public function testTamperedBodyIsRejected(): void + { + $original = '{"event":"capture.ready"}'; + $tampered = '{"event":"capture.failed"}'; + $secret = 'wh_secret'; + $sig = 'sha256='.hash_hmac('sha256', $original, $secret); + + $this->assertFalse(Webhook::verifySignature($tampered, $sig, $secret)); + } +}