jmrashed / zkteco
PHP library, with Laravel support, for ZKTeco attendance devices (fingerprint, face recognition, RFID) over UDP or TCP, with Comm Key authentication, real-time events, webhooks, HTTP sync and an ADMS push endpoint.
Requires
- php: ^8.1
- ext-sockets: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- phpstan/phpstan: ^1.12 || ^2.0
- phpunit/phpunit: ^10.0 || ^11.0 || ^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A PHP library, with Laravel support, for ZKTeco attendance devices (fingerprint, face recognition and RFID). It talks to the device directly from your server over UDP or TCP, with no extra desktop software.
📖 Read the full documentation: setup, every main feature, a Laravel sync example and troubleshooting.
Project statistics
These badges are live, so the numbers update automatically.
| Packagist | GitHub |
|---|---|
Contents
- Full documentation
- Features
- What you get, and how it was checked
- How it works
- Requirements
- Installation
- Quick start
- Connection options
- API reference
- Enhanced user management
- Advanced device management
- Device commands
- Bulk users and new records
- Sync to your API
- Webhooks
- ADMS / iClock push endpoint
- Laravel
- Known limitations
- Contributing
- Security
- License
Features
- Attendance: read, filter by date range or limit, and clear attendance logs
- Users: create, update and remove users, and manage user groups
- Biometrics: work with fingerprint and face templates
- Device: read device information, set the time, restart, and write to the LCD
- Door and events: door control and real-time event monitoring, on Linux and Windows
- Connection: UDP or TCP, Comm Key authentication, timeouts and retries
- Integration: HTTP sync, signed webhooks, an ADMS / iClock push endpoint, and Laravel config with a facade
Support varies between device models and firmware. Test against your own device before using it in production.
What you get, and how it was checked
Added or changed in 2.2.0. The last column shows the evidence behind each row, so you can decide what to test before you rely on it.
| Feature | What it does | How it was checked |
|---|---|---|
| UDP, TCP and auto mode | UDP by default, or TCP, or TCP with UDP fallback | Simulated device |
| Comm Key | Connects to password-protected devices | Simulated device |
| Real-time events | Receives and acknowledges live events, on Linux and Windows | Simulated device |
| API sync | Sends batches and never clears the device log. With a state file, it resumes after a failure | Automated tests |
| Signed webhooks | HMAC-SHA256 signatures, with a time limit against replayed requests | Automated tests, plus a manual check over local HTTP |
| ADMS push | Receives device data over HTTP, only from listed serial numbers [1] | Simulated requests |
| Laravel | Auto-discovery, config file and facade | Manual smoke test on Laravel 13 [2] |
| PHP 8.1 to 8.5 | The test suite runs on each version | CI on Linux |
[1] Serial numbers can be faked. Also restrict access by IP address or VPN.
[2] The discovery entry was checked, but the test registered the provider manually.
Hardware status: the new 2.2.0 device features and the ADMS endpoint have not been verified on physical hardware. The simulated device was written together with this library (for Comm Key, it uses the library's own key function), so passing tests show that the code behaves as intended, not that your device agrees. Please report your results with the device model, firmware version and transport (UDP or TCP). Remove names, passwords and biometric data first.
By design: this library does not create attendance punches on a device. It can still clear the attendance log with clearAttendance().
How it works
There are two ways to get data from a device: your server connects to it, or the device sends data to your server.
Choose A when your server can reach the device, and B when only the device can reach your server.
| Diagram | What it shows |
|---|---|
| Connecting | UDP, TCP, auto mode and the Comm Key |
| Real-time events | Messages from subscribing to unsubscribing |
| API sync | Batches, failures and resuming |
| ADMS push | Requests for setup, attendance and commands |
Requirements
- PHP 8.1 or later, with the
socketsextension - Laravel 11, 12 or 13 if used in Laravel (the core library does not depend on Laravel)
- Network access to the device over UDP or TCP (default port
4370)
Tests run on PHP 8.1 to 8.5 on Linux.
Installation
composer require jmrashed/zkteco
If the sockets extension is disabled, enable it in php.ini:
extension=sockets
Restart PHP or your web server, then check it with php -m. The command line and web server can use different php.ini files. If a firewall sits between the server and the device, allow UDP (or TCP) traffic on the device port.
Upgrading from 1.x? Read the CHANGELOG first.
Quick start
use Jmrashed\Zkteco\Lib\ZKTeco; $zk = new ZKTeco('192.168.1.201'); // optional: port, Comm Key, protocol, timeout if ($zk->connect()) { $zk->disableDevice(); $attendance = $zk->getAttendance(); $zk->enableDevice(); $zk->disconnect(); }
Connection options
A true result without a Comm Key does not prove that you can read data.
New in 2.2.0. new ZKTeco($ip) works as before: UDP, no Comm Key, 60.5-second timeout.
// ($ip, $port, $commKey, $protocol, $timeout) $zk = new ZKTeco('192.168.1.201', 4370, 123456, 'auto', 5); $zk->connectWithRetry(3, 500); // 3 attempts, growing delay $zk->getActiveProtocol(); // 'tcp', 'udp', or null when not connected $zk->isConnected(); // local state; does not contact the device $zk->ping(); // milliseconds for a handshake, or false $zk->setTimeout(10); // seconds
| Argument | Values |
|---|---|
$commKey |
The Comm Key set on the device. 0 means none. With a wrong key, connect() returns false. Without a key, connect() still returns true for an "unauthorized" reply, as in 2.1.x, but reads return nothing. |
$protocol |
udp (default), tcp, or auto (TCP first, then UDP). With auto, a device that accepts TCP but stays silent costs one full timeout before UDP is tried, so use a short timeout. |
API reference
1. Connect to Device
// Connect to the ZKTeco device // Returns a boolean indicating whether the connection was successful $connected = $zk->connect();
2. Disconnect from Device
// Disconnect from the ZKTeco device // Returns a boolean indicating whether the disconnection was successful $disconnected = $zk->disconnect();
3. Enable Device
// Enable the ZKTeco device // Returns a boolean or mixed value indicating whether the device was enabled // Note: This method should be called after reading/writing any device information $enabled = $zk->enableDevice();
Note: It's important to call the enableDevice() method after any read or write operation on the device.
4. Disable Device
// Disable the ZKTeco device // Returns a boolean or mixed value indicating whether the device was disabled // Note: This method should be called before reading or writing any device information $disabled = $zk->disableDevice();
5. Device Version
// Get the firmware version of the ZKTeco device // Returns a boolean or mixed value containing the device version information $version = $zk->version();
6. Device OS Version
// Get the operating system version of the ZKTeco device // Returns a boolean or mixed value containing the device OS version information $osVersion = $zk->osVersion();
7. Power Off
// Turn off the ZKTeco device // Returns a boolean or mixed value indicating whether the device shutdown was successful $shutdown = $zk->shutdown();
8. Restart
// Restart the ZKTeco device // Returns a boolean or mixed value indicating whether the device restart was successful $restart = $zk->restart();
9. Sleep
// Put the ZKTeco device into sleep mode // Returns a boolean or mixed value indicating whether the device entered sleep mode $sleep = $zk->sleep();
10. Resume
// Resume the ZKTeco device from sleep mode // Returns a boolean or mixed value indicating whether the device resumed from sleep mode $resume = $zk->resume();
11. Voice Test
// Test the voice functionality of the ZKTeco device by saying "Thank you" // Returns a boolean or mixed value indicating whether the voice test was successful $voiceTest = $zk->testVoice();
12. Platform
// Get the platform information of the ZKTeco device // Returns a boolean or mixed value containing the platform information $platform = $zk->platform();
13. Firmware Version
// Get the firmware version of the ZKTeco device // Returns a boolean or mixed value containing the firmware version information $fmVersion = $zk->fmVersion();
14. Work Code
// Get the work code information of the ZKTeco device // Returns a boolean or mixed value containing the work code information $workCode = $zk->workCode();
15. Device Name
// Get the name of the ZKTeco device // Returns a boolean or mixed value containing the device name information $deviceName = $zk->deviceName();
16. Get Device Time
// Get the current time of the ZKTeco device // Returns a boolean or mixed value containing the device time information // Format: "Y-m-d H:i:s" $deviceTime = $zk->getTime();
17. Set Device Time
// Set the time of the ZKTeco device // Parameters: // - string $t: Time string in format "Y-m-d H:i:s" // Returns a boolean or mixed value indicating whether the device time was successfully set $setTimeResult = $zk->setTime($timeString);
18. Get Users
// Get the list of users stored in the ZKTeco device // Returns an array containing user information $users = $zk->getUser();
19. Set Users
// Set a user in the ZKTeco device // Parameters: // - int $uid: Unique ID (max 65535) // - int|string $userid: ID in DB (max length = 24; many devices allow only 9 digits) // - string $name: User name (max length = 24) // - int|string $password: Password (max length = 8, only numbers - depends device setting) // - int $role: User role (default Util::LEVEL_USER) // - int $cardno: Card number (default 0, max length = 10, only numbers) // Returns a boolean or mixed value indicating whether the user was successfully set $setUserResult = $zk->setUser($uid, $userid, $name, $password, $role, $cardno);
19.1 Update An Existing User
To edit a user's userid, name, password, role, or card number without deleting them first, call updateUser() (or setUser() — they're the same operation) with their existing $uid. The device's set-user command overwrites the record for that $uid in place:
// $uid must match the existing user's uid (from getUser()) to update rather than create $updated = $zk->updateUser($uid, $newUserid, $newName, $newPassword, $role, $cardno);
20. Clear All Admin
// Remove all admin users from the ZKTeco device // Returns a boolean or mixed value indicating whether all admin users were successfully removed $clearedAdmin = $zk->clearAdmin();
21. Clear All Users
// Remove all users from the ZKTeco device // Returns a boolean or mixed value indicating whether all users were successfully removed $clearedUsers = $zk->clearUsers();
22. Remove A User
// Remove a user from the ZKTeco device by UID // Parameters: // - integer $uid: User ID to remove // Returns a boolean or mixed value indicating whether the user was successfully removed $removedUser = $zk->removeUser($uid);
23. Get Attendance Log
// Get the attendance log from the ZKTeco device // Returns an array containing attendance log information // Each entry in the array represents a single attendance record with fields: uid, id, state, timestamp, and type $attendanceLog = $zk->getAttendance();
23.1 Get Attendance Log With User Details
getAttendance() only returns the raw device fields (uid, id, state, timestamp, type) since that's all the device sends. To also get the matching user's name/userid/role/cardno (and human-readable state/type labels), use getAttendanceWithUser(), which fetches the user list once and merges it in:
$attendanceLog = $zk->getAttendanceWithUser();
Sample response:
array ( 'uid' => 33, 'id' => '108', 'state' => 1, 'timestamp' => '2024-04-24 18:13:47', 'type' => 1, 'user' => [ 'uid' => 33, 'userid' => '108', 'name' => 'John Doe', 'role' => 0, 'cardno' => '1234567890', ], 'state_name' => 'Fingerprint', 'type_name' => '1', )
If no matching user is found for a record's uid, user will be null.
24. Get Todays Attendance Log
24.1 getTodaysRecords()
// Get the today attendance log from the ZKTeco device // Returns an array containing attendance log information // Each entry in the array represents a single attendance record with fields: uid, id, state, timestamp, and type $attendanceLog = $zk->getTodaysRecords();
Sample response
array ( 'uid' => 33, 'id' => '108', 'state' => 1, 'timestamp' => '2024-04-24 18:13:47', 'type' => 1, )
24.2 Filter Today's Records Manually
public function zkteco() { $zk = new ZKTeco('192.168.1.201'); $connected = $zk->connect(); $attendanceLog = $zk->getAttendance(); // Get today's date $todayDate = date('Y-m-d'); // Filter attendance records for today $todayRecords = []; foreach ($attendanceLog as $record) { // Extract the date from the timestamp $recordDate = substr($record['timestamp'], 0, 10); // Check if the date matches today's date if ($recordDate === $todayDate) { $todayRecords[] = $record; } } // Now $todayRecords contains attendance records for today Log::alert($todayRecords); }
24.3 Get Latest Attendance with Limit
// Get the 5 latest attendance records $latestAttendance = $zk->getAttendanceWithLimit(5);
Note: the device protocol always transfers the entire attendance log first — this only limits what's returned client-side after that transfer, it doesn't make fetching faster.
24.4 Get Attendance Within A Date/Time Range
// Get attendance records between two dates/times (inclusive) // Accepts "Y-m-d H:i:s" or "Y-m-d" $rangeAttendance = $zk->getAttendanceByDateRange('2024-01-01', '2024-01-31 23:59:59');
Like the limit above, the device has no server-side time-range query, so this still downloads the full log and filters client-side — it's an ergonomics helper to avoid re-implementing the same date filtering loop in every project, not a way to speed up slow fetches from large logs.
24.4a Sanitized Attendance Log (corrupted-record mitigation)
Some devices (reported for the SpeedFace-V5L, see issues #7 / #12) return attendance records where only the first entry decodes correctly — later entries can contain uid = 0, non-printable badge ids, out-of-range state/type values, or garbage timestamps. This is a genuine record-format mismatch (the parsing in this library matches the iClock 680 layout, and some newer devices apparently use a different one) that needs a raw device packet capture to fix properly.
As a best-effort mitigation, getSanitizedAttendance() filters out records that fail basic sanity checks:
// Same as getAttendance(), but drops records that are clearly corrupted $attendanceLog = $zk->getSanitizedAttendance();
This is opt-in (not the default getAttendance() behavior) so it can't silently drop legitimate records on devices that already parse correctly. If you're affected by this and can share a raw packet capture, please comment on #7 or #12.
24.5 Clear Attendance Log
// Clear the attendance log from the ZKTeco device // Returns a boolean or mixed value indicating whether the attendance log was successfully cleared $clearedAttendance = $zk->clearAttendance();
Enhanced user management
25. Parse Fingerprint Template Data
// Parse raw fingerprint template data into structured format // Returns array with template metadata and quality score $parsedTemplate = $zk->parseFingerprintTemplate($rawTemplateData); // Example response: // [ // 'valid' => true, // 'template_size' => 512, // 'uid' => 123, // 'finger_id' => 1, // 'flag' => 1, // 'template_data' => '...', // 'quality_score' => 85 // ]
26. Enroll Fingerprint Template
// Enroll a new fingerprint template for a user // Parameters: uid, finger_id (0-9), template_data $enrolled = $zk->enrollFingerprint(123, 1, $templateData);
27. Get User Face Data
// Retrieve face recognition templates for a user // Returns array of face templates with quality scores $faceData = $zk->getFaceData(123); // Example response: // [ // 50 => [ // 'template' => '...', // 'size' => 1024, // 'quality' => 92 // ] // ]
28. Set User Face Data
// Set face recognition templates for a user $faceData = [ 50 => ['template' => $faceTemplateData] ]; $result = $zk->setFaceData(123, $faceData);
29. Enroll Face Template
// Enroll a face recognition template for a user // Automatically finds available slot $enrolled = $zk->enrollFaceTemplate(123, $faceTemplateData);
30. Get User Card Number
// Retrieve the card number for a specific user $cardNumber = $zk->getUserCardNumber(123); // Returns: "1234567890" or false if not found
31. Advanced User Role Management
31.1 Set User Role with Permissions
// Set advanced user role with granular permissions $permissions = ['attendance', 'reports', 'user_management']; $result = $zk->setUserRole(123, Util::LEVEL_ADMIN, $permissions);
31.2 Get User Role Information
// Get detailed role information for a user $roleInfo = $zk->getUserRole(123); // Example response: // [ // 'role_id' => 14, // 'role_name' => 'Administrator', // 'permissions' => ['all_access', 'user_management', 'system_config'], // 'can_enroll' => true, // 'can_manage_users' => true, // 'can_view_logs' => true // ]
31.3 Get Available Roles
// Get all available user roles and their descriptions $availableRoles = $zk->getAvailableRoles(); // Example response: // [ // 0 => [ // 'name' => 'User', // 'description' => 'Standard user with basic access', // 'permissions' => ['attendance', 'view_own_records'] // ], // 14 => [ // 'name' => 'Administrator', // 'description' => 'Full administrative access', // 'permissions' => ['all_access', 'user_management', 'system_config'] // ] // ]
32. Quality Assessment
32.1 Fingerprint Quality
// Get fingerprint template with quality assessment $fingerprints = $zk->getFingerprint(123); foreach ($fingerprints as $fingerId => $template) { $parsed = $zk->parseFingerprintTemplate($template); echo "Finger {$fingerId} quality: {$parsed['quality_score']}%"; }
32.2 Face Template Quality
// Get face templates with quality scores $faceData = $zk->getFaceData(123); foreach ($faceData as $faceId => $data) { echo "Face template {$faceId} quality: {$data['quality']}%"; }
Advanced device management
33. Custom LCD Message Display
33.1 Display Custom Message
// Display custom message on LCD screen // Parameters: message, line (1-4), duration in seconds (0 = permanent) $result = $zk->displayCustomMessage('Welcome John!', 1, 10);
33.2 Display Permanent Message
// Display permanent message (until manually cleared) $result = $zk->displayCustomMessage('System Maintenance', 2, 0);
33.3 Clear LCD Screen
// Clear all LCD content $result = $zk->clearLCD();
34. Door Control Functions
34.1 Open Door
// Open door remotely $result = $zk->openDoor(1); // Door ID 1
34.2 Close Door
// Close door remotely $result = $zk->closeDoor(1);
34.3 Lock Door
// Lock door remotely $result = $zk->lockDoor(1);
34.4 Unlock Door
// Unlock door remotely $result = $zk->unlockDoor(1);
34.5 Get Door Status
// Get current door status $status = $zk->getDoorStatus(1); // Example response: // [ // 'door_open' => true, // 'door_locked' => false, // 'sensor_active' => true, // 'alarm_active' => false, // 'timestamp' => '2024-10-01 15:30:45' // ]
35. Time Zone Synchronization
35.1 Sync with Server Timezone
// Sync device time with server's default timezone $result = $zk->syncTimeZone();
35.2 Sync with Custom Timezone
// Sync device time with specific timezone $result = $zk->syncTimeZone('America/New_York'); $result = $zk->syncTimeZone('Europe/London'); $result = $zk->syncTimeZone('Asia/Tokyo');
35.3 User Groups
Assign users to a group, and assign up to 3 time zones to a group. Note: unlike most methods in this library, this record layout hasn't been verified against a physical device capture — please report back if it doesn't behave as expected for your device.
// Assign user with uid 1 to group 5 $zk->setUserGroup(1, 5); // Get the group a user is assigned to $groupId = $zk->getUserGroup(1); // Assign up to 3 time zone IDs to group 5 $zk->setGroupTimezones(5, [1, 2]); // Get the time zone IDs assigned to group 5 $timezones = $zk->getGroupTimezones(5);
36. Real-time Event Monitoring
The device is acknowledged before your callback runs.
36.1 Get Real-time Events
// Get real-time events with timeout $events = $zk->getRealTimeEvents(30); // 30 seconds timeout // Example response: // [ // [ // 'type' => 'attendance', // 'uid' => 123, // 'timestamp' => '2024-10-01 15:30:45', // 'state' => 1, // 'raw_data' => '...' // ] // ]
36.2 Start Event Monitoring with Callback
// Start monitoring with custom callback $callback = function($event) { echo "Event: {$event['type']} - User: {$event['uid']} - Time: {$event['timestamp']}\n"; // Handle different event types switch($event['type']) { case 'attendance': // Process attendance event break; case 'door_open': // Handle door open event break; case 'alarm': // Handle alarm event break; } }; // Start monitoring (runs for 60 seconds) $zk->startEventMonitoring($callback, 60); // Return false from the callback to stop early. // An optional third argument selects events: Util::EF_ATTLOG | Util::EF_ALARM
Each event has type, uid, id (badge ID), timestamp, state (verification method), punch (check-in/out) and raw_data. For events other than attendance, only type, timestamp (server time) and raw_data carry information. In events, uid is the numeric badge ID (or 0), which can differ from the record number returned by getUser(), so match users by id.
36.3 Advanced Event Monitoring
// Get event monitor instance for advanced handling $monitor = $zk->getEventMonitor(); // Register specific event handlers $monitor->on('attendance', function($event) { echo "Attendance event for user {$event['uid']}\n"; }); $monitor->on('door_open', function($event) { echo "Door opened by user {$event['uid']}\n"; }); $monitor->on('alarm', function($event) { echo "ALARM: {$event['timestamp']}\n"; // Send notification, log to database, etc. }); // Register handler for all events $monitor->on('*', function($event) { // Log all events to database logEventToDatabase($event); }); // Start monitoring $monitor->start(); // Runs indefinitely // Stop monitoring $monitor->stop();
36.4 Stop Event Monitoring
// Stop real-time event monitoring $result = $zk->stopEventMonitoring();
37. Event Types
Real-time monitoring reports:
- attendance: a punch
- door_open: the door was unlocked
- alarm: an alarm
- user_enroll: a user was enrolled
- unknown: any other event, if you select it with the event mask
The package also defines constants for door_close, user_delete, system_start and system_shutdown, but monitoring does not report these.
38. Door Control Constants
// Door action constants Util::DOOR_ACTION_OPEN // Open door Util::DOOR_ACTION_CLOSE // Close door Util::DOOR_ACTION_LOCK // Lock door Util::DOOR_ACTION_UNLOCK // Unlock door // Event type constants Util::EVENT_TYPE_ATTENDANCE // Attendance event Util::EVENT_TYPE_DOOR_OPEN // Door open event Util::EVENT_TYPE_DOOR_CLOSE // Door close event Util::EVENT_TYPE_ALARM // Alarm event Util::EVENT_TYPE_USER_ENROLL // User enrollment event Util::EVENT_TYPE_USER_DELETE // User deletion event Util::EVENT_TYPE_SYSTEM_START // System start event Util::EVENT_TYPE_SYSTEM_SHUTDOWN // System shutdown event
39. Usage Examples
39.1 Complete Door Management
// Initialize device $zk = new ZKTeco('192.168.1.201'); $zk->connect(); // Check door status $status = $zk->getDoorStatus(1); if ($status['door_locked']) { // Unlock door for authorized access $zk->unlockDoor(1); $zk->displayCustomMessage('Door Unlocked', 1, 5); } // Open door $zk->openDoor(1); // Wait and close sleep(10); $zk->closeDoor(1); $zk->lockDoor(1); $zk->disconnect();
39.2 Real-time Monitoring System
$zk = new ZKTeco('192.168.1.201'); $zk->connect(); $monitor = $zk->getEventMonitor(); // Set up event handlers $monitor->on('attendance', function($event) use ($zk) { // Log attendance to database $user = getUserById($event['uid']); logAttendance($user, $event['timestamp'], $event['state']); // Display welcome message $zk->displayCustomMessage("Welcome {$user['name']}!", 1, 3); }); $monitor->on('alarm', function($event) use ($zk) { // Send alert notifications sendSecurityAlert($event); // Display alarm message $zk->displayCustomMessage('SECURITY ALERT!', 1, 0); }); // Start monitoring $monitor->start();
Device commands
New in 2.2.0. These return false when the device does not answer or rejects the command.
$zk->getDeviceOption('~SerialNumber'); // value as a string, or false $zk->setDeviceOption('Volume', '60'); // option names depend on the model $zk->refreshData(); // reload device data $zk->startEnroll('108', 0); // enroll finger 0 for badge ID 108 on the sensor $zk->startVerify(); // or startVerify($uid) $zk->cancelCapture(); $zk->testVoice(0); // voice index; the default stays 0 $zk->unlockDoorFor(5); // open the relay for 5 seconds (1 to 3600)
setDeviceOption() can misconfigure a device. unlockDoorFor() sends a different command from unlockDoor($doorId). If one of them does nothing on your model, try the other.
Bulk users and new records
New in 2.2.0.
$result = $zk->pushUsers([ ['uid' => 1, 'userid' => '1001', 'name' => 'John Doe', 'cardno' => 1016618], ['uid' => 2, 'userid' => '1002', 'name' => 'Jane Doe', 'role' => Util::LEVEL_ADMIN], ]); // ['total' => 2, 'succeeded' => 2, 'failed' => 0, 'failed_uids' => []] // Records strictly after this time (the full log is still downloaded) $records = $zk->getAttendanceSince('2026-12-01 09:00:00');
uid is required. userid defaults to the uid and name to the userid. An existing user with the same uid is overwritten, and fields you leave out (password, role, card number) are reset to empty or default.
Sync to your API
With a state file, a failed run continues from the first batch that was not delivered.
New in 2.2.0.
$zk->connect(); $result = $zk->postAttendance('https://example.com/api/attendance', [ 'token' => getenv('API_TOKEN'), // Authorization: Bearer ... 'secret' => getenv('SIGNING_SECRET'), // signs each request 'state_file' => __DIR__ . '/storage/zk-sync.json', 'batch_size' => 500, ]); // ['success' => true, 'total_records' => 12, 'sent_records' => 12, 'batches_sent' => 1, 'error' => null] $zk->postUsers('https://example.com/api/users'); // passwords are never sent
- With
state_file, each run sends only records not delivered before. Without it, every run sends the whole log. - Sending stops at the first failed batch, and the next run continues from there.
- Delivery is "at least once", so your API must ignore duplicates.
- The device log is never cleared by a sync.
total_records = 0can also mean the device read failed.- Records older than the saved position are skipped. If the device clock was moved backwards, delete the state file.
- Keep the state file outside the web root.
The request body is JSON: {"id": "...", "event": "attendance.sync", "timestamp": 1767225600, "data": {"records": [...]}}. For users, event is user.sync and the list is data.users.
Webhooks
New in 2.2.0.
use Jmrashed\Zkteco\Lib\Webhook\WebhookDispatcher; $webhooks = (new WebhookDispatcher()) ->addEndpoint('https://example.com/hooks/zkteco', getenv('SIGNING_SECRET'), ['attendance.*', 'door.unlocked']) ->on('*', function (string $event, array $data) { // local listener }); $zk->setWebhookDispatcher($webhooks);
| Event | Sent when |
|---|---|
device.connected, device.disconnected |
connect() / disconnect() succeed |
user.saved, user.deleted |
The device accepts setUser(), updateUser(), pushUsers() or removeUser(). No password is sent. |
attendance.cleared |
The device accepts clearAttendance() |
door.unlocked |
unlockDoorFor() succeeds |
attendance.punch, door.opened, device.alarm |
During startEventMonitoring() |
Delivery is synchronous: a slow endpoint delays your code, including real-time monitoring. In busy applications, use a local listener that puts the event on a queue. Network errors, 408, 429 and 5xx replies are retried (3 attempts by default), and redirects are not followed. dispatch() returns one result per endpoint, but events sent automatically by the client do not report failures to your code. Use a queue or the sync feature when no event may be lost.
Verify requests on the receiving side:
use Jmrashed\Zkteco\Lib\Webhook\WebhookDispatcher; $body = file_get_contents('php://input'); $valid = WebhookDispatcher::verify( $body, $_SERVER['HTTP_X_ZKTECO_SIGNATURE'] ?? '', $_SERVER['HTTP_X_ZKTECO_TIMESTAMP'] ?? null, getenv('SIGNING_SECRET') ); if (! $valid) { http_response_code(401); exit; }
The signature is sha256= plus HMAC-SHA256 of <timestamp>.<body>. Requests older than 5 minutes are rejected. To also block replays inside that window, store the payload id and reject repeats.
ADMS / iClock push endpoint
User commands are retried until confirmed. Unlock, reboot and clear-log commands are sent only once.
New in 2.2.0. Some devices can send data to your server over HTTP (their "Cloud Server" or "ADMS" setting). This helps when your server cannot reach the device. Route /iclock/cdata, /iclock/getrequest and /iclock/devicecmd to a script like this:
use Jmrashed\Zkteco\Lib\Adms\AdmsServer; $adms = new AdmsServer( allowedSerials: ['YOUR_DEVICE_SERIAL'], queueFile: __DIR__ . '/../storage/zk-adms.json', // only needed to send commands ); $adms->onAttendance(function (string $serial, array $records) { // Save the records. If this throws, the device is not told "OK" and can send them again. }); $adms->onOperationLog(function (string $serial, array $operations) { // User changes. Passwords and biometric templates are not passed on. }); $response = $adms->handle(); http_response_code($response['status']); foreach ($response['headers'] as $name => $value) { header("$name: $value"); } echo $response['body'];
Send commands from your application. The device collects them on its next poll:
$adms->queueUpdateUser('YOUR_DEVICE_SERIAL', '1001', 'John Doe'); $adms->queueDeleteUser('YOUR_DEVICE_SERIAL', '1001'); $adms->queueUnlockDoor('YOUR_DEVICE_SERIAL'); $adms->queueReboot('YOUR_DEVICE_SERIAL'); $adms->queueClearAttendance('YOUR_DEVICE_SERIAL'); // deletes the device log
User commands are sent again after 5 minutes, up to 3 times, until the device confirms them. Unlock, reboot and clear are sent once, and dropped if the device does not poll within 5 minutes, so a door never opens late.
Security: the ADMS protocol has no password. The allow list blocks unknown serial numbers, but a serial number is not a secret and can be faked. Anyone who knows it could post false punches or take queued commands. Also restrict the endpoint with an IP allow list or a VPN, use HTTPS if your devices support it, and exclude the routes from CSRF protection only for these three paths.
This endpoint is tested with simulated requests, not with a physical device.
Laravel
New in 2.2.0. The service provider and the ZKTeco facade are discovered automatically.
php artisan vendor:publish --tag=zkteco-config
ZKTECO_IP=192.168.1.201 ZKTECO_PORT=4370 ZKTECO_COMM_KEY=0 ZKTECO_PROTOCOL=udp ZKTECO_TIMEOUT=10 # Optional ZKTECO_WEBHOOK_URL= ZKTECO_WEBHOOK_SECRET=
use Jmrashed\Zkteco\Lib\ZKTeco; $zk = app(ZKTeco::class); // a new client each time, built from config/zkteco.php
The facade Jmrashed\Zkteco\Facades\ZKTeco (alias ZKTeco) keeps one client for the request. In long-running workers, use app(ZKTeco::class) and disconnect when done. new ZKTeco($ip) also still works.
Known limitations
- The device protocol has no server-side date filter or limit, so the full attendance log is always downloaded.
- Some newer devices, such as the SpeedFace-V5L, can return incorrectly parsed attendance records (issues #7 and #12). See
getSanitizedAttendance(). - Comm Key, TCP, real-time events, the new device commands and the ADMS endpoint are tested against a simulated device only. Please report results from real hardware, with the model and firmware.
openDoor(),closeDoor(),lockDoor(),unlockDoor()andgetDoorStatus()use commands that have not been verified on hardware.unlockDoorFor()uses a different one.- The package does not write attendance records to a device or delete them by time range.
- Traffic to the device is not encrypted. The Comm Key controls access; it does not protect the data. Keep devices on a private network or VPN.
- The user group record layout has not been verified against a physical device capture.
Changelog
See the CHANGELOG.
Contributing
See CONTRIBUTING. Run the tests with composer test.
Security
Please report security issues by email to jmrashed@gmail.com, not through the issue tracker.
License
Released under the MIT License.
