Human Capital Management (HCM)
Create a Samsara API integration for payroll or time tracking.
Introduction
Integrating Samsara with Human Capital Management (HCM) systems (such as payroll or time tracking software) enables seamless transfer of driver hours and work activity. This eliminates manual data entry and ensures payroll accuracy. The following is a comprehensive overview covering typical workflows, relevant API endpoints, and best practices. The intended audience is software engineers familiar with RESTful APIs and OAuth, looking to create an app for the Samsara Marketplace or a custom integration with third-party HCM solutions.
What You Will Learn: This guide will walk through common HCM integration scenarios – syncing HOS logs to payroll systems, automating time clock punches from HOS data, mapping Samsara drivers and vehicles to HCM records, and validating driver shifts for payroll periods. You'll walk away with a clear blueprint for building a robust HCM integration with Samsara.
Workflows for HCM Integration with Samsara
Syncing Samsara HOS Logs to Payroll Systems
One core workflow is exporting driver Hours of Service logs from Samsara and importing them into a payroll system to automate timesheets and driver pay calculation. Samsara’s HOS logs API provides detailed records of each driver’s duty status changes (e.g. Off Duty, On Duty, Driving) within a time range. By pulling these logs for a given pay period, an integration can determine how many hours each driver worked and at what times. We recommend fetching HOS logs for the start and end of a payroll period (e.g. weekly or bi-weekly) and then translating those into payroll entries for total hours worked and clock-in/clock-out events.
Using the HOS Logs API: To retrieve HOS logs, you can call the GET /fleet/hos/logs
endpoint with a startTime
and endTime
filter. You may also filter by specific drivers (by Samsara driver ID or external ID) or by tags (e.g. to only sync a subset of drivers).
Example request:
curl --request GET "https://api.samsara.com/fleet/hos/logs?startTime=2025-05-01T00:00:00Z&endTime=2025-05-08T00:00:00Z" \
--header "Authorization: Bearer $SAMSARA_API_KEY"
Example response:
{
"data": [
{
"driver": {
"id": "52970611",
"name": "Test Driver"
},
"hosLogs": [
{
"codrivers": [],
"hosStatusType": "onDuty",
"logEndTime": "2025-05-01T13:25:02.230Z",
"logRecordedLocation": {
"latitude": 0,
"longitude": 0
},
"logStartTime": "2025-05-01T13:24:43.000Z",
"vehicle": {
"id": "0"
}
},
{
"codrivers": [],
"hosStatusType": "offDuty",
"logEndTime": "2025-05-02T00:00:00.000Z",
"logRecordedLocation": {
"latitude": 0,
"longitude": 0
},
"logStartTime": "2025-05-01T13:25:02.230Z",
"vehicle": {
"id": "0"
}
}
]
}
],
"pagination": {
"endCursor": "ea2c4155-b53a-4134-8a02-7f586e13335c",
"hasNextPage": true
}
}
This call returns a JSON array of HOS log records (duty status events) between the specified times. Each record includes the driver, timestamp, location (if available), and status type (driving
, onDuty
, offDuty
, etc.). Your integration can aggregate these logs per driver to calculate total working hours or identify shift start/end times. Samsara also offers a daily summary endpoint (GET /fleet/hos/daily-logs
) that provides a per-driver summary of hours for each day. The daily logs API can be useful if you only need total hours per day for payroll (e.g. to quickly get each driver’s hours-worked for each day in the pay period). Keep in mind that HOS data may have slight delays in availability if drivers are still uploading logs from their mobile app; it’s a best practice to wait until data is fully uploaded (e.g. end-of-day or +24 hours) before finalizing payroll sync. An especially important consideration for routes in very remote areas.
Automating Time Punches from HOS Data
Another common use-case is to automate driver time punches (clock-ins and clock-outs) in an HCM time tracking system using Samsara’s HOS events. Instead of drivers manually punching a time clock, their status in Samsara can trigger these events. For instance, some integrations generate “sign-in” and “sign-out” events in the payroll system based on HOS logs. When a driver goes On Duty in Samsara (or logs into the Samsara Driver App), the integration can treat that as a clock-in; when the driver goes Off Duty or signs out, that becomes a clock-out. This ensures that driver timecards are automatically populated with work times captured by Samsara’s ELD, improving accuracy and compliance.
To implement automated punches, your integration can monitor for shift start or end. There are a couple of approaches:
-
Using HOS Duty Status Logs: Filter HOS logs for the first On Duty status of the day as a “punch in” and the last Off Duty status as a “punch out”. For example, you might query
GET /fleet/hos/logs
for each driver and identify the timestamp they went on duty after being off (shift start) and the timestamp they went off duty at day’s end (shift end). You can then send these timestamps to the HCM system as clock-in/out times. -
Using Sign-In/Sign-Out Events: Samsara provides a legacy API endpoint for driver login/logout events,
GET /v1/fleet/hos_authentication_logs
, which returns when drivers sign into or out of the ELD. This can directly provide clock-in/clock-out moments. If you prefer to use the newer APIs, an alternative is to call the driver-vehicle assignment API (described below) to infer login sessions: whenever a driver has a vehicle assignment interval, it generally corresponds to them being logged in (especially if using the Samsara Driver App assignment as trigger).
Regardless of approach, once you obtain the punch times, use the HCM system’s API to create time entries. Ensure that each Samsara driver is correctly mapped to the corresponding employee record in the HCM system so the punch is attributed to the right person (see Mapping Driver Identities below for strategies). It’s also wise to include some buffer or validation: for instance, only create a clock-out punch if the driver remained off duty for a certain duration, to avoid generating multiple “lunch break” off-duty events as payroll clock-outs. By aligning HOS events with time punches, drivers’ work hours are recorded in near real-time in the HCM system, reducing administrative overhead.
Mapping Driver and Vehicle Data Between Systems
Successful integration requires robust mapping of drivers (and sometimes vehicles) between Samsara and the HCM platform. Each Samsara driver should be matched to an employee record in the external system. We recommend using External IDs to maintain this relationship. Samsara lets you assign custom external IDs for various entities including drivers and vehicles. For example, you might use an external ID key like "payrollId"
on each Samsara driver to store the employee’s ID from the payroll system. Conversely, store Samsara’s driver ID in the HCM system’s records. This two-way reference makes it easy to look up the corresponding record in either system. We recommend storing your own database’s driver ID as an external ID on the Samsara driver object, and storing the Samsara driver ID in your database.
When retrieving drivers via the API (GET /fleet/drivers
), the response includes any externalIds
that have been set for each driver. Here’s a simplified example of creating a Samsara driver with an external ID, using a key payrollId
:
curl --request POST "https://api.samsara.com/fleet/drivers" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer $SAMSARA_API_KEY" \
--data '{
"name": "Alice Doe",
"username": "alice.doe",
"password": "TempPassword123",
"externalIds": {
"payrollId": "EMP001234"
}
}'
In this example, "payrollId": "EMP001234"
links the new Samsara driver to an employee ID in the HCM system. Later, when your integration pulls driver data or HOS logs, it can use these external IDs to map records to the correct HCM employee. Ensure that the mapping field is unique and consistent across both systems. It’s also helpful to restrict syncing to relevant drivers: for instance, you might use Samsara Tags to group drivers that need to be synced -- for instance, one integration only syncs drivers with a "Regulated"
tag, indicating they use HOS and thus need their hours synced.
Mapping vehicles can be important if your HCM integration cares about which vehicle was used (for example, for equipment-specific pay rates or for logging mileage). Samsara’s APIs allow similar external IDs for vehicles (e.g., a “truck number” or asset ID from your maintenance system). If needed, you can retrieve vehicle details (GET /fleet/vehicles
) to map Samsara vehicles to records in the external system. In many pure payroll use-cases, vehicle mapping isn’t required, but it becomes relevant if you’re tracking mileage or assigning costs per vehicle.
Additionally, Samsara offers driver-vehicle assignment endpoints that detail which vehicle a driver was operating and when. The endpoint GET /fleet/drivers/vehicle-assignments
returns, for each driver, the list of vehicles they drove over a given time range and the timestamps of each assignment. Similarly, GET /fleet/vehicles/driver-assignments
does the inverse (lists drivers per vehicle in a time range). These are useful for mapping context, such as confirming which trips or vehicles correspond to a driver’s shift. For example, to get a driver’s vehicle assignments for the past day you could call:
curl --request GET "https://api.samsara.com/fleet/drivers/vehicle-assignments" \
-G \
--data-urlencode "startTime=2025-05-18T00:00:00Z" \
--data-urlencode "endTime=2025-05-19T00:00:00Z" \
--header "Authorization: Bearer $SAMSARA_API_KEY"
Example response:
{
"data": [
{
"id": "52970611",
"name": "Test Driver",
"driverActivationStatus": "active",
"vehicleAssignments": []
},
{
"id": "53145842",
"name": "Steve Jones",
"driverActivationStatus": "active",
"vehicleAssignments": []
},
{
"id": "53147904",
"name": "Alice Doe",
"driverActivationStatus": "active",
"externalIds": {
"payrollId": "EMP001234"
},
"vehicleAssignments": []
}
],
"pagination": {
"endCursor": "",
"hasNextPage": false
}
}
Vehicle assignment data can also be cross-checked with HOS logs to validate that all driving time is accounted for (see next section).
Validating Driving Activity and Shifts for Payroll
When integrating HOS data into payroll, it’s crucial to validate that the information is complete and accurate for each payroll period. This involves verifying that each driver’s shifts (work periods) are captured correctly and aligning with the pay period boundaries. Here are some best practices for validation:
-
Reconcile Hours with HOS Summaries: Compare the hours recorded in the HCM system against Samsara’s source data. You can use the Daily HOS Logs or Summaries to get total on-duty and driving hours per driver per day and ensure these match what you expect to pay. If a driver’s hours seem low or high, you may need to check for missing logs or unassigned driving time. Samsara’s HOS reports (accessible via API or dashboard) can help identify if a driver has any unassigned HOS logs or violations that might indicate issues. It’s a good practice to only sync certified logs (logs that the driver has reviewed and certified as accurate) for payroll, to ensure the driver approves of the recorded time.
-
Cross-Verify Shift Boundaries: Use the driver-vehicle assignment data to double-check shift start and end times. If a driver is assigned to a vehicle from 8 AM to 5 PM, you would expect an On Duty status around 8 AM and Off Duty around 5 PM. If the HOS logs show something different (e.g., no off-duty until 7 PM), that could indicate the driver forgot to log off or an error in the data. Your integration might flag such discrepancies for manual review. Similarly, if a driver had a long gap in the middle of a day with no HOS status (e.g., neither On nor Off), it could mean missing data or an unaccounted break – you may need to handle that according to company policy (some companies might default missing logs to Off Duty for payroll, for example).
-
Tracking Miles (if Applicable): Some fleets pay drivers based on mileage or need mileage totals for reimbursement. Samsara provides a reliable way to compute distance driven in a time period. The recommended approach is a two-step process: (1) call the
/fleet/drivers/vehicle-assignments
API to get all driving segments for each driver in the period, and (2) call the/fleet/vehicles/stats/history
API to retrieve odometer readings for those segments. The first call gives you each segment’s start/end timestamps and vehicle ID; the second call, with parametersvehicleIds
,startTime
,endTime
, andtypes=obdOdometerMeters,gpsOdometerMeters
, returns the vehicle’s odometer data over that interval. By taking the first and last odometer values, you can calculate distance traveled. For example, to get distance for a specific driving segment you might query:curl --request GET "https://api.samsara.com/fleet/vehicles/stats/history" \ -G \ --data-urlencode "startTime=2025-05-18T14:16:17Z" \ --data-urlencode "endTime=2025-05-18T18:54:07Z" \ --data-urlencode "vehicleIds=281474977075805" \ --data-urlencode "types=obdOdometerMeters,gpsOdometerMeters" \ --header "Authorization: Bearer $SAMSARA_API_KEY"
This returns an odometer time series for that vehicle in the interval, from which you can derive miles driven. Verifying mileage can complement hours-worked in payroll or help calculate driver pay if they are paid per mile. It’s also a way to sanity-check that a driver’s reported hours line up with distance (e.g., a driver who drove 500 miles in a day should have a substantial number of driving hours). Refer to the Mileage and distance guide for more information about calculating distance.
-
Handling Edge Cases: Be prepared to handle scenarios like a shift that crosses midnight (and thus a pay period boundary), or a driver who forgot to log out. For shifts spanning a cutoff time, you may need to split the time appropriately between pay periods. If a driver remains in a driving or on-duty status beyond their normal hours (e.g., they forgot to go Off Duty), you might implement a rule to auto-clock them out at a certain cut-off or send an alert for correction. Samsara’s data (especially if you use the “Get HOS clocks” endpoint for current status) can tell you if a driver is still active; you could use the Set Duty Status API to adjust statuses if your integration has permission and logic to do so (this should be done carefully and in line with compliance rules).
By validating activity and shifts, you ensure that the data sent to payroll is correct and that drivers are paid for all their work time (and only their work time). This step is often implemented as a final check or report that an admin can review in the HCM system, but much of it can be automated using the Samsara APIs as described.
Key Samsara API Endpoints for HCM Integrations
To summarize, here are the key Samsara API endpoints and capabilities used in an HCM integration, along with their purpose:
-
Drivers API (
GET /fleet/drivers
and related endpoints): Used to list drivers, retrieve driver details, and create or update drivers. This is essential for mapping driver identities. The driver objects can includeexternalIds
for custom IDs (e.g. payroll IDs). Ensure your API token or OAuth scope includes “Read Drivers” (and “Write Drivers” if you need to create/update). -
HOS Logs API (
GET /fleet/hos/logs
andGET /fleet/hos/daily-logs
): Provides detailed HOS events and daily summary data. Use this to extract raw work log data for each driver. The response can be filtered by time range, driver IDs, or tags. These endpoints require the appropriate compliance scope (e.g. “Read ELD Compliance”) on the API token. The rate limit for HOS log queries is 5 requests per second, so if you have many drivers or large date ranges, you may need to batch requests accordingly. -
Driver Vehicle Assignments API (
GET /fleet/drivers/vehicle-assignments
and/fleet/vehicles/driver-assignments
): Returns the mapping of drivers to vehicles over time. This is helpful for determining who was driving when, identifying shift boundaries, or calculating distance by segment. Provide astartTime
andendTime
to constrain the time range. The response will include each driver (or vehicle) with a list of assignments. Each assignment entry hasstartTime
,endTime
, vehicle info, and anassignmentType
(e.g.driverApp
, which indicates the driver was assigned via the Samsara Driver App login). -
Vehicle Stats History API (
GET /fleet/vehicles/stats/history
): Allows retrieval of historical vehicle telemetry data within a time range. By specifying stat types likeobdOdometerMeters
and/orgpsOdometerMeters
, you can obtain odometer readings used to calculate distance. This is useful for mileage-based payroll or validating trip distances. You must specify thevehicleIds
and the same start/end timestamps obtained from the assignments. Note that this endpoint can return large data sets if the interval is long; it’s often best to call it per driving segment or per day. As of recent updates, you can request up to 4 stats at once (e.g., OBD and GPS odometers together). -
Location History API (
GET /fleet/vehicles/locations/history
): Not explicitly covered above, but this endpoint returns GPS location breadcrumbs for vehicles over time. In an HCM context, it’s less commonly needed, but it could be used to verify where a driver started or ended a shift (for example, to confirm they returned to a terminal location). If geospatial data is relevant (say to determine if a driver’s shift began at a specific site or if they traveled out of state for IFTA/tax purposes), this API can provide the coordinates and timestamps of vehicle movement. Coupling this with Samsara’s Addresses (geofence) API can allow you to map coordinates to named locations. The Addresses API (GET /addresses
) lets you retrieve custom landmark locations (each of which can have external IDs too). Thus, if your HCM system has location codes (e.g., a depot or job site ID), you could tag Samsara addresses with those IDs to translate GPS points into meaningful place names or codes for payroll entries. -
HOS Authentication Logs API (
GET /v1/fleet/hos_authentication_logs
– Legacy): Provides driver login/logout events (sign-ins and sign-outs). This is mainly useful for time punch generation as discussed. Because it’s a legacy v1 endpoint, it requires using the older base path. In many cases, the driver-vehicle assignment endpoint now serves a similar purpose with more context, so consider using that first. If you do use this endpoint, note it has similar data delay caveats (wait for uploads to complete). Make sure to include the compliance scope “Read ELD Hours of Service” for this API.
All the above endpoints require authentication via a Samsara API token or OAuth access token. Responses are in JSON and typically include a top-level data
array with results, and possibly a pagination
object if the data spans multiple pages.
Getting Started with Authentication (OAuth 2.0)
Samsara supports two authentication methods for API access: API tokens and OAuth 2.0. For a Marketplace app integration, OAuth 2.0 is the recommended approach. OAuth allows each customer to securely authorize your application to access their Samsara data without sharing an API key. In an OAuth flow, your app will obtain an access token (and refresh token) specific to each customer organization.
App Registration: Begin by registering your application in the Samsara Developer Dashboard. In Samsara’s dashboard, navigate to Settings > OAuth 2.0 Apps to create a new app. You’ll be asked for details like the app name, an OAuth redirect URL (where Samsara will send the authorization code), the scopes your app needs, and an optional logo. For an HCM integration, you will likely request scopes such as Read Drivers, Read Vehicles, Read Hours of Service, etc., depending on which data you need. Each API endpoint documents the required scope; for example, to use the HOS logs endpoints you need the ELD Compliance read scope. Once created, you will have an OAuth Client ID and Client Secret for your app.
OAuth Flow: The high-level OAuth 2.0 flow for Samsara is as follows:
-
User Authorization: Direct the user (or admin of the Samsara account) to Samsara’s authorize URL in a browser, e.g.
https://api.samsara.com/oauth2/authorize?response_type=code&client_id=<YOUR_CLIENT_ID>&redirect_uri=<YOUR_REDIRECT_URI>&scope=<REQUESTED_SCOPES>
(plus any state parameters). This prompts the user to log in to Samsara (if not already) and approve the scopes your app requested. -
Receive Authorization Code: If the user approves, Samsara will redirect the browser to your provided redirect URI with a query parameter
code=<authorization_code>
. Your application should capture this one-time code. -
Exchange Code for Tokens: Your backend server will then make a POST request to Samsara’s token endpoint (
https://api.samsara.com/oauth2/token
) with the authorization code, your client ID & secret, and the redirect URI, in order to obtain an access token and refresh token. The response will includeaccess_token
(typically valid for a limited time, e.g. 6 hours) andrefresh_token
(to get new tokens when the access token expires). -
Use the Access Token: Once you have the access token, include it in the
Authorization
header for all API calls:Authorization: Bearer <token>
. Your app can now query Samsara endpoints on behalf of the user’s organization. For example, a simple test call with cURL might be:curl --header "Authorization: Bearer <ACCESS_TOKEN>" "https://api.samsara.com/fleet/vehicles"
This would return the list of vehicles accessible with the token.
-
Token Refresh: When the access token expires, use the refresh token by making another POST to
/oauth2/token
(withgrant_type=refresh_token
) to get a new access token without user intervention. This allows your integration to run continuously. Samsara’s OAuth tokens use expiration and refresh for security, so your code should handle the HTTP 401 Unauthorized response by triggering a refresh token flow automatically.
For private, direct integrations (where an organization is just using their own data), Samsara also allows the use of API tokens generated via the dashboard. However, for third-party apps intended for multiple customers, OAuth 2.0 is preferred as it is more secure and user-friendly. It prevents the need for sharing API keys and gives users fine-grained control over what data they permit your app to access. For further details, see Samsara’s OAuth 2.0 documentation and the Getting Started with Samsara API guide.
Updated about 14 hours ago