punchrelay / sdk
Client for the PunchRelay API: attendance from ZKTeco devices, devices, employees, locations, webhooks and webhook signature verification.
Requires
- php: ^8.2
- php-http/discovery: ^1.19
- psr/http-client: ^1.0
- psr/http-client-implementation: ^1.0
- psr/http-factory: ^1.0
- psr/http-factory-implementation: ^1.0
- psr/http-message: ^1.1 || ^2.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.75
- guzzlehttp/guzzle: ^7.9
- php-http/mock-client: ^1.6
- phpstan/phpstan: ^2.1
- phpstan/phpstan-phpunit: ^2.0
- phpunit/phpunit: ^11.5
Suggests
- guzzlehttp/guzzle: A PSR-18 HTTP client, if your app has none yet
- symfony/http-client: A PSR-18 HTTP client (with nyholm/psr7), if your app has none yet
Provides
None
Conflicts
None
Replaces
None
README
A client for the PunchRelay API. Use it to read attendance from your ZKTeco devices, manage devices, employees, locations and webhooks, and verify webhook signatures.
- PHP 8.2 or later
- Package:
punchrelay/sdk, namespacePunchRelay\, typed for PHPStan and Psalm - HTTP through any PSR-18 client your app already has (Guzzle, Symfony HttpClient, …), found with php-http/discovery. No other runtime dependencies.
- API reference:
https://<api-host>/docs
Install
composer require punchrelay/sdk
If your app has no PSR-18 client yet, install one too, for example composer require guzzlehttp/guzzle.
Quick start
Create a key on the dashboard's API keys page. Use a read key if you only read data, and a read_write key if you also make changes. The key tells the API which organisation you are, so no call takes a tenant id.
use PunchRelay\Client; $client = new Client(apiKey: getenv('PUNCHRELAY_API_KEY'), baseUrl: 'https://adms.example.com'); $key = $client->getKeyInfo(); echo "{$key->tenantName} ({$key->scope})\n"; // Every punch in the last day, newest first. Pages are fetched as you iterate. foreach ($client->attendance->listAll(from: new DateTimeImmutable('-1 day')) as $punch) { echo $punch->punchedAt->format(DATE_ATOM), " {$punch->userId} {$punch->userName} @ {$punch->deviceName}\n"; }
Create one client per key and reuse it. It caches the key's organisation after the first call.
What's covered
| Area | Methods |
|---|---|
$client->attendance |
list, listAll, get, getStats, exportCsv, delete, deleteRange |
$client->devices |
list, listModels, create, update, delete, activate, deactivate, reboot, pullAttendance, pullUsers, queueCommand, listCommands, setServerAddress |
$client->users |
list, listAll, create, bulkUpsert, update, delete, sync, syncOne |
$client->locations |
list, create, update, delete |
$client->webhooks |
list, listEventTypes, get, create, update, delete, rotateSecret, enable, disable, sendTest, listDeliveries, listAllDeliveries, getDelivery, redeliver |
Filters and paging are named arguments: from, to, userId, deviceId, locationId, page, pageSize.
Responses are typed objects, requests are arrays
Responses are readonly classes in PunchRelay\Generated (AttendanceItem, DeviceItem, StatsResponse, …), generated from the API's OpenAPI document. Properties use the API's camelCase names, timestamps are DateTimeImmutable in UTC, and lists are arrays of models:
$stats = $client->attendance->getStats(from: '2026-11-01', to: '2026-11-07'); foreach ($stats->perDay as $day) { echo "{$day->date}: {$day->count} punches by {$day->users} people\n"; }
Fields the API adds later are ignored until the SDK is updated, so they never break your code. A field the API promised that is missing or of the wrong type throws UnexpectedValueException, naming the model and field.
Request bodies are plain arrays with the API's camelCase keys:
$user = $client->users->create(['pin' => '1005', 'name' => 'Ama Mensah']); echo $user->id;
PHPStan and Psalm check the keys: each request is an array shape in PunchRelay\Generated\RequestShapes (UpsertUserRequest, CreateDeviceRequest, …). Every key is optional, because the API fills in defaults.
Times and dates
- Timestamps (
fromandtoon attendance) accept anyDateTimeInterfaceor an ISO 8601 string. ADateTimeInterfaceis converted to UTC; a string is sent as you wrote it. - Calendar dates (
getStats,pullAttendance) are days in your organisation's time zone. Pass'YYYY-MM-DD'or aDateTimeInterface, whose own date is used without converting it.
Anything not wrapped yet
$client->request() sends any API call with the same key, retries and exceptions as the methods above. {tenantId} in the path is filled in for you:
$response = $client->request('GET', '/api/tenants/{tenantId}/devices', ['search' => 'front']); $devices = json_decode((string) $response->getBody(), true);
Errors
Any non-2xx response throws PunchRelay\Exception\PunchRelayException. It carries:
getStatus(): the HTTP status (alsogetCode())getErrorCode(): the API's error code, such asinvalid_rangeorforbiddengetMessage()getResponseBody(): the raw response bodygetRetryAfter(): seconds, set on a 429
When the subscription is suspended (402), the exception is a SubscriptionSuspendedException. It adds getInvoiceNumber(), getPayUrl(), getSubscriptionStatus() and getReason().
use PunchRelay\Exception\PunchRelayException; use PunchRelay\Exception\SubscriptionSuspendedException; try { $client->devices->reboot($deviceId); } catch (SubscriptionSuspendedException $e) { echo "Suspended: pay {$e->getInvoiceNumber()} at {$e->getPayUrl()}\n"; } catch (PunchRelayException $e) { if ($e->getStatus() !== 403) { throw $e; } echo "This key is read-only.\n"; }
A request that cannot be sent at all throws your HTTP client's PSR-18 exception (Psr\Http\Client\NetworkExceptionInterface for connection failures).
Retries and timeouts
These failures are retried up to maxRetries times (default 3), with jittered exponential backoff:
- 429 Too Many Requests, on any method. The SDK waits for the server's
Retry-After. - 500, 502, 503 and 504, only on
GET,PUT,DELETE,HEADandOPTIONS. - Network errors, on the same methods.
A POST is never retried after a 5xx or a network error, because it may already have run on the server.
If Retry-After is longer than maxRetryDelay (default 30 s), the SDK throws the 429 immediately instead of waiting. Each key may make 120 requests per minute.
timeout (default 100 s) covers a whole call, retries included: a retry whose wait would run past it throws the last error instead. PSR-18 has no timeout setting, so how long one request may take is up to the HTTP client. When the SDK finds Guzzle and creates the client itself, it sets Guzzle's timeout to timeout. If you pass your own client, configure its timeout there.
Verifying webhooks
WebhookVerifier::verify($rawBody, $headers, $secret) checks a webhook and returns its event. It does three things:
- checks the HMAC-SHA256 signature, using a constant-time comparison (
hash_equals) - rejects timestamps more than 5 minutes from your clock (change this with the
toleranceargument, in seconds) - parses the event
It throws WebhookVerificationException when any check fails.
Pass the raw body, exactly as it was received. If you decode the JSON and encode it again, the bytes change and the signature no longer matches. $headers can be getallheaders(), $_SERVER, a PSR-7 request, or Laravel's or Symfony's $request->headers; names are matched case-insensitively.
Plain PHP
use PunchRelay\Webhooks\WebhookVerificationException; use PunchRelay\Webhooks\WebhookVerifier; try { $event = WebhookVerifier::verify(file_get_contents('php://input'), getallheaders(), getenv('PUNCHRELAY_WEBHOOK_SECRET')); } catch (WebhookVerificationException) { http_response_code(401); exit; } if ($event->isAttendanceCreated()) { // Queue it for processing. $event->id stays the same across retries, so de-duplicate on it. $punch = $event->asAttendanceCreated(); error_log("{$punch->userId} punched at {$punch->punchedAt->format(DATE_ATOM)}"); } http_response_code(204);
Laravel
Exclude the route from CSRF protection (in bootstrap/app.php, $middleware->validateCsrfTokens(except: ['webhooks/punchrelay'])), then:
use Illuminate\Http\Request; use PunchRelay\Webhooks\WebhookVerificationException; use PunchRelay\Webhooks\WebhookVerifier; Route::post('/webhooks/punchrelay', function (Request $request) { try { $event = WebhookVerifier::verify($request->getContent(), $request->headers, config('services.punchrelay.webhook_secret')); } catch (WebhookVerificationException) { return response()->noContent(401); } if ($event->isAttendanceCreated()) { ProcessPunch::dispatch($event->id, $event->data); } return response()->noContent(); });
Use $request->getContent(), not $request->all() or $request->json().
Symfony
use PunchRelay\Webhooks\WebhookVerificationException; use PunchRelay\Webhooks\WebhookVerifier; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Attribute\Route; #[Route('/webhooks/punchrelay', methods: ['POST'])] public function punchrelay(Request $request): Response { try { $event = WebhookVerifier::verify($request->getContent(), $request->headers, $this->webhookSecret); } catch (WebhookVerificationException) { return new Response(status: 401); } if ($event->isAttendanceCreated()) { // ... } return new Response(status: 204); }
Event types
$event->type |
Check | Typed data |
|---|---|---|
attendance.created |
$event->isAttendanceCreated() |
$event->asAttendanceCreated(): the punch, with id, userId, userName, deviceId, deviceSerial, punchedAt, status, punch |
webhook.test |
$event->isTest() |
$event->asTest() |
$event->data is always the event's data as a decoded array. New event types may be added. Ignore types you don't recognise and still answer 2xx.
WebhookVerifier::computeSignature($secret, $timestamp, $body) produces a valid signature for your own tests.
Options
| Argument | Default | |
|---|---|---|
apiKey |
(required) | prk_live_… |
baseUrl |
(required) | The API host |
tenantId |
looked up | Set it to skip the one-time GET /api/key-info call |
maxRetries |
3 | 0 turns retries off |
retryBaseDelay |
0.5 | Seconds |
maxRetryDelay |
30 | Seconds |
timeout |
100 | Seconds per call, including retries. null or 0 turns it off |
httpClient |
discovered | Any PSR-18 client |
requestFactory, streamFactory |
discovered | PSR-17 factories, for when discovery can't find them |
In Laravel, bind one client in a service provider and inject it:
$this->app->singleton(PunchRelay\Client::class, fn () => new PunchRelay\Client( apiKey: config('services.punchrelay.key'), baseUrl: config('services.punchrelay.url'), ));
Contributing
This package is developed in the PunchRelay repository under sdks/php and published from a read-only mirror. Open issues and pull requests against the main repository.
src/Generated/ is written by bin/generate.php from sdks/openapi/v1.json. Never edit it by hand. After the spec changes:
cd sdks/php composer install composer generate # or sdks/generate.sh php composer cs # php-cs-fixer, dry run composer analyse # PHPStan, level max composer test # PHPUnit
tests/CoverageTest.php fails when an operation in the spec has no method in the SDK, or when a method calls a path or HTTP method the spec doesn't have. Webhook signing is tested against sdks/testdata/webhook-vectors.json, which the other SDKs also use and the API test suite checks against the server's signer.