Fuel Card Integration

Learn how to build a Fuel Card Integration for the Samsara App Marketplace

How to build a Fuel Card Integration

Before you begin: Check if an existing Samsara Marketplace integration already meets your needs. Samsara’s App Marketplace offers many turnkey fuel card integrations (e.g. WEX, FLEETCOR, EFS, etc.) that automatically import fuel transactions and detect suspicious fuel activities. If a suitable integration exists on the Fuel Management Marketplace, using it is recommended for faster deployment.

This guide is intended for developers building a Fuel Management app for the Samsara Marketplace.

Setting Up a Fuel Management App in Samsara

  1. Register as a Samsara Developer: Ensure you have access to the Samsara Developer portal or an organizational Samsara account with admin privileges. Apply here to become a partner. Select ISV during the process if building a shared marketplace application.
  2. Create a New OAuth App: In the Samsara Dashboard, navigate to Settings > OAuth 2.0 Apps (under Integrations or Developer Tools). Click "Create App". Provide an app name, redirect URL (for OAuth callbacks), select the required scopes/permissions, and upload an app logo. Scopes define what data your app can access – for fuel integrations you’ll likely need Fuel & Energy (read/write), Vehicles (read), Addresses (read), Compliance/IFTA (read), Alerts (write), etc.
  3. App Credentials: After creation, Samsara will provide an OAuth Client ID and Client Secret. Keep these credentials secure – you'll use them for OAuth exchanges.

If you are building an internal integration for a single Samsara customer (rather than a marketplace app for many customers), you can alternatively create an API Token from the Samsara Dashboard (Settings > API Tokens). API Tokens are organization-specific and have configurable scope permissions. They're quicker to set up for one-off integrations, but not suitable for multi-client apps.

Authentication Options: OAuth vs API Tokens

Samsara supports two authentication methods for API access: OAuth 2.0 and API tokens.

  • OAuth 2.0 (Recommended for Multi-Customer Apps): OAuth is the preferred method for marketplace integrations where multiple Samsara customers will install your app. Users grant your app specific permissions via Samsara’s OAuth consent screen, eliminating the need to manually share API keys. Your app will use the OAuth Client ID/Secret to obtain an access token (and refresh token) for each customer. Tokens are short-lived and can be refreshed securely. OAuth enhances security and user control, especially at scale. (For detailed steps, see Samsara’s OAuth guide or OAuth 2.0 sample code.)

  • API Token (Simpler for Single Customer): For a single-fleet integration or testing, an API token can be used. An API token is a long-lived bearer token generated in the Samsara dashboard (under API Tokens). It is tied to one organization and carries whatever scopes you enable on it. Using a token is as simple as including an HTTP header Authorization: Bearer <APIToken>. This approach is straightforward (no OAuth flow needed), but not suitable if you plan to distribute the integration to others, since it grants broad access to one org’s data.

Example – Using an API Token in a Request:

curl "https://api.samsara.com/fleet/vehicles/list" -H "Authorization: Bearer <YOUR_API_TOKEN>"

In the above example, replace <YOUR_API_TOKEN> with the token string. (If using OAuth, you would use the Authorization: Bearer <access_token> obtained via the OAuth flow.)

Logging Fuel Purchases via the Samsara API

One core feature is pushing fuel card transaction data into Samsara. Samsara provides a Fuel Purchase API to create fuel purchase records in the platform. This allows Samsara to log the fill-ups, associate them with vehicles, and incorporate them into reports (Fuel Purchase Report, IFTA, etc.).

Endpoint: POST https://api.samsara.com/fuel-purchase – Create a fuel purchase transaction.
Scope Required: The API token or OAuth token must include the “Write Fuel Purchase” permission under the “Fuel & Energy” category.

Sample cURL Request – Logging a Fuel Transaction:

curl -X POST "https://api.samsara.com/fuel-purchase" \
  -H "Authorization: Bearer <API_OR_OAUTH_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
        "fuelQuantityLiters": 120.5,
        "iftaFuelType": "Diesel",
        "transactionLocation": "350 Rhode Island St, San Francisco, CA 94103",
        "transactionPrice": { "amount": 640.20, "currency": "usd" },
        "transactionReference": "TXN-1000456",
        "transactionTime": "2025-05-10T14:05:50-07:00",
        "vehicleId": "570"
      }'

In this request:

  • fuelQuantityLiters – Amount of fuel purchased in liters. (Fuel card data might be in gallons; convert to liters for Samsara's API if needed, since Samsara stores fuel in liters for IFTA calculations.)
  • iftaFuelType – Fuel type for IFTA reporting. Examples: "Diesel", "Gasoline", "Propane", "CNG", etc. (Use the appropriate type; Samsara supports a range of fuel types including diesel, gasoline, ethanol, LNG, biodiesel, etc.).
  • transactionLocation – The location of the purchase. This should be a human-readable address suitable for geocoding with Google Maps. Samsara will use this to help verify and assign the purchase to a vehicle if one isn’t explicitly provided.
  • transactionPrice – Total sale amount and currency (ISO currency code).
  • transactionReference – A unique reference ID for the transaction (often the fuel card transaction ID). Providing a unique ID helps avoid duplicating records if the same transaction is sent again.
  • transactionTime – Timestamp of the purchase in RFC 3339 format.
  • vehicleId – Samsara ID for the vehicle that was fueled. If you know which vehicle the transaction corresponds to (e.g. the fuel card is assigned to a specific vehicle or the driver entered a vehicle ID), include it. Samsara will then attach the fuel record to that vehicle.

The API will respond with the UUID of the fuel purchase. Make sure your token has the correct scope; if using an API token, ensure “Write Fuel Purchase” was enabled when generating it.

How Samsara Uses This Data: Once fuel transactions are in Samsara, fleet managers can view them in the Fuel Purchases Report on the dashboard. Samsara will cross-reference vehicle GPS and fuel level data to verify transactions. If the vehicleId wasn’t provided or multiple vehicles were near the location, the transaction may be marked “Unverified” or have multiple possible vehicles. Integrating this data allows features like fuel efficiency tracking and automated IFTA tax calculations.

Retrieving Idling Events (Fuel Waste Monitoring)

Fuel card vendors often want to track fuel waste and efficiency. Engine idling is a major source of fuel waste. Samsara’s API allows you to fetch idling events, which detail when and for how long vehicles were idling (engine on, vehicle not moving).

Endpoint: GET https://api.samsara.com/idling/events – Retrieve granular idling events in a given time range.
Scope: Read Fuel & Energy (under Fuel & Energy category) is required.

This endpoint returns a list of individual idling occurrences, each typically including: asset ID (vehicle), start time of idling, duration, and various contextual data. (Note: As of this writing, the idling events API provides data from 2024 onward. For older data, a summarized idling report endpoint is available.)

Why fetch idling events? For a fuel management integration, idling events help identify where fuel is being burned unnecessarily. For example, if a truck was idling for 30 minutes at a truck stop immediately after a fuel purchase, that’s fuel being wasted. By pulling idling data, your system can calculate fuel lost to idling or coach drivers on reducing idle time to save fuel. It also provides more context around fuel transactions – e.g., a driver who fuels and then idles might indicate a rest stop or potential misuse.

Get Idling Events: (Example: fetch idling events in Jan 2025)

curl -G "https://api.samsara.com/idling/events" \
  -H "Authorization: Bearer <TOKEN>" \
  --data-urlencode "startTime=2025-01-01T00:00:00Z" \
  --data-urlencode "endTime=2025-02-01T00:00:00Z"

This will return an array of events. Each event will have fields such as startTime, endTime, assetId, and durationMilliseconds, etc., describing each idling instance. Your integration can aggregate these or tie them to fuel usage (available as gaseousFuelConsumedGrams).

Fuel Level Alerts and Webhook Notifications

A powerful feature for fuel management is real-time alerts when certain fuel conditions occur (e.g. fuel drops, low fuel, or unexpected refuels). Samsara allows configuration of alerts for fuel level changes, which can trigger a webhook to your integration. This means your system can get instant notification when, say, a vehicle’s fuel drops by more than X% (possible theft) or when a fuel refill occurs (sudden rise).

Configuring a Fuel Level Alert

Samsara supports fuel level alerts by percentage. Two common triggers are: Fuel level falls below a threshold (low fuel) and Fuel level decreases rapidly by a percentage within minutes (rapid drop, indicating possible siphoning or leak). There is also a trigger for sudden fuel level rise (indicating a refuel event). Fuel alerts are among the alert types that can be managed via the API.

You can set up an alert via the Samsara Dashboard (Alerts section) or via the Alerts API.

  • Dashboard Method: Go to Alerts in Samsara, click “Create Alert”, choose Fuel Level as the trigger. Configure the condition (e.g. “fuel level below 15% for at least 5 minutes” or “fuel level drops 20% within 10 minutes”), and select which vehicles or groups it applies to (all vehicles or specific ones/tags). In the Alert Actions, add a Send Webhook action. (You’ll need to have a webhook endpoint set up – see next section – and selected here.) Save the alert. Samsara will now monitor fuel data and trigger the alert when conditions are met.

  • API Method: Use the Alerts API to programmatically create an alert configuration. The endpoint is POST /alerts/configurations (with Write Alerts scope needed). In the JSON body, you’d specify the trigger type and parameters. For example, to create a “Fuel Level Below” alert, you might use:

    {
      "isEnabled": true,
      "operationalSettings": {
        "timeRangeType": "activeBetween"
      },
      "scope": {
        "all": true
      },
      "triggers": [{
        "triggerParams": {
          "fuelLevel": {
            "operation": "LESS",
            "fuelLevelPercent": 20,
            "minDurationMilliseconds": 600000
          },
        }
      }],
      "actions": [
        {
          "actionParams": {
            "webhooks": {
              "payloadType": "enriched",
              "webhookdIds": ["12345"]
            }
          }
        }
      ]
    }
    

    This is a conceptual example – the actual schema uses specific field names for threshold, duration, etc. (Refer to Samsara’s Alerts API docs for exact format.) The key idea is you define the trigger (“fuel level below 15% for 5 minutes”) and attach an action that points to a webhook ID.

Tip: To get the webhookIds, you may first need to create a webhook endpoint (see below). Alternatively, if you set up the webhook via the dashboard, you can query the existing webhooks via GET /webhooks to find its ID.

Setting Up a Webhook Endpoint

A webhook is a listener URL on your side that Samsara will call (HTTP POST) whenever the alert triggers. To use webhooks with alerts, you must register your webhook with Samsara, either through the UI (Settings > Integrations > Webhooks) or the API.

  • Via Dashboard: Under Settings > Webhooks, add a new webhook. Provide a name, the URL of your endpoint (must be HTTPS), and optionally a secret key (or Samsara may generate one). You can choose which event types to subscribe to – for fuel alerts, choosing Alerts (all alerts) is simplest.

  • Via API: Use POST /webhooks (the Create a webhook endpoint). For example:

    curl -X POST "https://api.samsara.com/webhooks" \
      -H "Authorization: Bearer <TOKEN>" \
      -H "Content-Type: application/json" \
      -d '{
            "name": "FuelAlertWebhook",
            "url": "https://your.server.com/samsara-webhook",
            "version": "2018-01-01",
            "eventTypes": ["Alert"]
          }'
    

    This registers a webhook named "FuelAlertWebhook" that will receive Alert events. (The version: "2018-01-01" designates the payload schema version 2.0). Samsara will respond with a JSON containing an id for the webhook. Save that ID for linking in the alert config. Samsara also provides a secretKey in the response – use this to validate signatures.

Handling Webhook Notifications: Once an alert is configured and a webhook is set, Samsara will send an HTTP POST to your URL every time the alert condition is met. The request will include headers like X-Samsara-Event-Type: Alert and X-Samsara-Signature (HMAC signature of the payload). The body will contain a JSON object with details about the alert event.

For a fuel level alert, the payload (simplified) looks like:

{
  "eventId": "uuid-1234...",
  "eventTime": "2025-05-16T15:42:20.495Z",
  "eventType": "AlertIncident",
  "data": {
    "configurationId": "4981c97b-02ff-40a6-9b33-0c083bdbd607",
    "updatedAtTime": "2025-05-16T15:42:21Z",
    "resolvedAtTime": "2025-05-16T15:42:20Z",
    "happenedAtTime": "2025-05-16T15:42:20Z",
    "isResolved": true,
    "incidentUrl": "https://cloud.samsara.com/o/4007512/fleet/workflows/incidents/4981c97b-02ff-40a6-9b33-0c083bdbd607/5/52514325/1747410140495",
    "conditions": [
      {
        "triggerId": 5023,
        "description": "Fuel Level",
        "details": {
          ...
        }
      }
    ]
  }
}

Use Case: Fuel level alerts enable proactive fuel theft detection. For instance, a "fuel level drop >20% in <5 min" alert will cause a webhook if someone siphons fuel from a truck's tank. Your integration can immediately flag this and perhaps cross-check if no fuel purchase was logged at that time (indicating theft). Likewise, a "fuel level rise" alert could notify your system that a vehicle was refueled outside of an authorized fuel stop, prompting you to verify the transaction.

IFTA Jurisdiction Data for Fuel Tax Reporting

One big benefit of integrating fuel cards with telematics is simplifying IFTA (International Fuel Tax Agreement) reporting. IFTA requires tracking miles driven in each jurisdiction (state/province) and fuel purchased in each jurisdiction, to calculate tax owed or credits.

Samsara automatically calculates vehicle distance traveled per state using its GPS data. The IFTA Jurisdiction Reports API provides these totals:

Endpoint: GET https://api.samsara.com/fleet/reports/ifta/jurisdiction – Get all jurisdiction IFTA reports for a specified time period.
Scope: Read IFTA (US) under Compliance.

Given a time range (typically a quarter, since IFTA reports are quarterly). The API returns data grouped by jurisdiction for that period. Each entry includes total miles driven in that state (for the fleet or per vehicle, depending on the endpoint), and potentially total fuel purchased in that state if fuel purchases were recorded with location. (Samsara’s system can match fuel purchase location to jurisdictions if provided.)

For example, a response for Q1 2025 might show: "California: 23,000 miles, 2,100 gallons fuel" and so on for each state. This data is in your organization’s set timezone. Note that the most recent ~72 hours of data may still be processing and subject to change, so avoid pulling data for today’s date if you need final numbers.

There is also GET /fleet/reports/ifta/vehicle for per-vehicle breakdowns (miles per vehicle per state). Additionally, Samsara can generate IFTA CSV files via an async job endpoint if needed.

How to use this: Your fuel card integration can use Samsara's IFTA data combined with fuel purchase data to automate tax reports. For each jurisdiction, you’d have total miles (from this API) and total fuel (sum of all gallons from transactions in that jurisdiction). You can then compute fuel economy and the tax due or credit (each jurisdiction has a fuel tax rate; if a truck bought less fuel in a state than it burned there, you owe tax, etc.). Samsara’s IFTA report essentially does this calculation as well, so leveraging it can save a lot of manual work.

Accessing Vehicle GPS and Telematics Data (Locations & Stats)

To integrate fuel transactions, you often need vehicle telematics data – primarily location history (to verify fueling location) and vehicle stats like fuel level or odometer. Samsara offers APIs for both current data and historical data:

  • Current Data – Vehicle Stats: GET /fleet/vehicles/stats can retrieve the latest telemetry for all vehicles or specified vehicles. You filter which “stat types” you want. For example, types=gps returns the last known GPS location for the vehicles (latitude, longitude, timestamp), and types=fuelPercents returns the latest fuel level reading (as a percentage of tank, if available). You can request multiple types in one call (e.g. GPS, fuel level, odometer, etc.). This endpoint is useful to quickly check a vehicle’s current status.

    Example:

    curl -G "https://api.samsara.com/fleet/vehicles/stats" \
      -H "Authorization: Bearer <TOKEN>" \
      --data-urlencode "types=gps,fuelPercents"
    

    This returns a list of vehicles with their current location (gps) and fuel level (fuelPercents). It’s commonly polled in integrations to get near-real-time updates (some integrations poll every few seconds for location updates).

  • Historical Data – Vehicle Stats History: For more in-depth analysis, GET /fleet/vehicles/stats/history is the recommended endpoint. It provides historical GPS and diagnostic data over a time range. You must specify a startTime and endTime (RFC 3389 timestamps or milliseconds) to define the window. You can filter by specific vehicles or get data for the whole fleet, and you can filter by stat types. This endpoint returns a sequence of data points over time.

    Example – Historical GPS trace:

    curl -G "https://api.samsara.com/fleet/vehicles/stats/history" \
      -H "Authorization: Bearer <TOKEN>" \
      --data-urlencode "vehicleIds=570" \
      --data-urlencode "types=gps" \
      --data-urlencode "startTime=2025-05-10T13:50:00Z" \
      --data-urlencode "endTime=2025-05-10T14:20:00Z"
    

    This would fetch GPS points for vehicle 570 between 13:50 and 14:20 UTC on May 10, 2025. The response includes an array of GPS records (with timestamps and lat-long coordinates). You could use this to reconstruct the vehicle’s route or find where it was at a specific time.

    Example – Historical Fuel Level:

    curl -G "https://api.samsara.com/fleet/vehicles/stats/history" \
      -H "Authorization: Bearer <TOKEN>" \
      --data-urlencode "vehicleIds=570" \
      --data-urlencode "types=fuelPercents" \
      --data-urlencode "startTime=2025-05-10T13:00:00Z" \
      --data-urlencode "endTime=2025-05-10T15:00:00Z"
    

    This retrieves fuel level percentage readings for vehicle 570 from 1pm to 3pm. If the Samsara device recorded fuel sensor data (requires the vehicle to have a fuel level sensor via the engine bus), you’ll get a time series of fuel percentages. You might see it drop gradually as fuel is consumed, then jump up at 14:05 if a refuel occurred (assuming a fuel-up at that time).

  • Streaming (Kafka Feed): For real-time streaming of data without polling, Samsara offers a Kafka connector. This allows Samsara to push live vehicle data to your Kafka cluster. It streams events such as GPS updates, engine data, and others continuously, which can then be consumed in real-time applications. Using the Kafka feed can be efficient for large fleets or high-frequency data needs, as it offloads the polling to a push-based model.

In summary, using the stats endpoints, your integration can query where a truck was (GPS), how much fuel it had at various times, its odometer readings, engine states, idling status, and more. This data is crucial to correlate with fuel transactions for validation and analysis.

Example Use Case: Fuel Transaction Validation Workflow

Putting it all together, let's walk through a common integration scenario: validating a fuel card transaction using Samsara data. Suppose a driver swipes their fuel card and buys fuel – your system receives the transaction (via the fuel card provider's feed) and now you want to verify it against telematics info. Key questions: Was the intended vehicle actually at the fuel station? Was the correct driver with that vehicle? And does the amount of fuel make sense for that vehicle?

1. Verify Vehicle Location at Time of Fuel-Up: Each fuel transaction has a timestamp and usually a location (address of fuel station). We can use Samsara GPS data to ensure the vehicle was indeed there at that time.

  • Use the Historical GPS API to get the vehicle’s location around the transaction time. For example, if transaction time is 2025-05-10 14:05:50Z and the vehicle ID (from Samsara) is 570, fetch GPS data for vehicle 570 from 14:00 to 14:10. This will give you the coordinates of the vehicle before, during, and after fueling.
  • Check the distance between the vehicle’s reported location at ~14:05 and the fuel station’s location. You may need to geocode the station address to lat/long coordinates. If the vehicle’s GPS point at 14:05 is, say, within 100 meters of the station, that’s a match. Samsara uses a 100 m / 10 minute rule internally for auto-assigning fuel purchases, which is a reasonable tolerance.
  • If the vehicle was far away or no GPS record exists near that time, this could indicate a problem (e.g., wrong vehicle ID on the transaction, or the card was used for a different vehicle). You would flag this for the fleet manager.

Implementation tip: The gps data points come with timestamps. If you get multiple points in the interval, you might pick the one closest to the transaction time. Also consider vehicle speed: if the vehicle was moving (not stationary at a fuel pump), that's suspicious for a fueling event. You can retrieve speed or engineStates via the stats API as well to see if the ignition was off (which it often is during fueling).

2. Verify the Driver-Assignment: Many fuel card systems track which driver fueled (e.g., via a driver PIN or the card tied to a driver). To ensure the correct driver-vehicle pairing, cross-check the Samsara driver assignment.

  • Samsara keeps logs of which driver is assigned to which vehicle at any given time (usually via ELD login, Dispatch assignment, or manual assignment). Use the Driver-Vehicle Assignments API to query this. The endpoint GET /fleet/driver-vehicle-assignments returns who was driving what in a time range.

  • If you have a Samsara Driver ID for the driver who made the transaction, you can query by driver. For example:

    curl -G "https://api.samsara.com/fleet/driver-vehicle-assignments" \
      -H "Authorization: Bearer <TOKEN>" \
      --data-urlencode "filterBy=drivers" \
      --data-urlencode "driverIds=1234" \
      --data-urlencode "startTime=2025-05-10T13:00:00Z" \
      --data-urlencode "endTime=2025-05-10T15:00:00Z"
    

    This asks: which vehicle was Driver 1234 in between 1pm and 3pm on May 10? The response will include the assignment if that driver was in a vehicle. You can then check if that vehicle matches the fuel transaction’s vehicle. If not, there’s a discrepancy (maybe the driver used their card for a different truck, which might violate policy).

  • If your fuel card data is organized by vehicle (e.g., each card belongs to a truck), you could do the inverse: query assignments by vehicle to see who was driving it at that time. That can be done by using filterBy=vehicles and providing the vehicle ID.

  • In either case, ensure that at the transaction timestamp, the driver and vehicle correlate. If Samsara shows a different driver for that vehicle at that time, or the driver was not logged in at all, it could indicate misuse (like someone else fuelled the vehicle, or the driver fueled the wrong vehicle).

3. Cross-Check Fuel Volume vs Tank Capacity: Fraud detection sometimes involves confirming that the amount of fuel purchased could actually fit in the vehicle’s tank. With Samsara’s fuel level data, you can estimate a vehicle’s fuel tank capacity and see if the purchased gallons make sense.

  • Use the fuelPercents history to get the vehicle’s fuel level before and after the transaction. For instance, if just before fueling the truck’s fuel level was 20% and just after fueling it was 80%, that’s a 60% increase.

  • Knowing the fuel volume added from the transaction (say 50 gallons, from Level 3 transaction data), you can estimate the tank size: if 50 gallons corresponds to 60% of the tank, the full tank would be roughly 50 / 0.60 ≈ 83.3 gallons.

  • Now, if the truck’s typical tank size is known (perhaps entered in Samsara or generally ~80 gallons for that vehicle class), this is consistent. But if a transaction claims, for example, 120 gallons for that same vehicle, and your data shows the tank went from near empty to full, 120 gallons would far exceed the tank capacity (~83 gal). That implies something is off – possibly the extra fuel was pumped into a separate container or another vehicle. This is a red flag you can raise.

  • Even without prior knowledge of tank capacity, you can use the before/after fuel% method to catch impossible scenarios. If fuel % went from 10% to 95% (85% increase) and 100 gallons were bought, estimated capacity = ~117.6 gal. If next time the tank goes from 5% to 100% with only 80 gallons, capacity estimate might drop to ~84 gal, which is inconsistent. Large variances could indicate the data isn’t aligning or dual-tank scenarios. Consistently, if a single fill shows more than ~100% worth of fuel added, it’s definitely suspicious.

  • To systematically do this, fetch fuelPercents around the transaction time. For example:

    curl -G "https://api.samsara.com/fleet/vehicles/stats/history" \
      -H "Authorization: Bearer <TOKEN>" \
      --data-urlencode "vehicleIds=570" \
      --data-urlencode "types=fuelPercents" \
      --data-urlencode "startTime=2025-05-10T13:30:00Z" \
      --data-urlencode "endTime=2025-05-10T14:30:00Z"
    

    From the returned data points, identify the fuel level before the fill (e.g. 13:50 reading 20%) and after the fill (e.g. 14:10 reading 80%). Calculate the difference and compare with the gallons. This helps validate the purchase. (Keep in mind slight timing differences – if the vehicle was off, the “after” reading might only update when the ignition turned on later. You might use the next available reading when the truck started moving.)

By combining these steps in your integration, you create a comprehensive verification system: each fuel card transaction is cross-checked against vehicle location, driver identity, and vehicle fuel system data. This can catch errors or fraudulent use in near real-time. For example, if a card was used at a gas station but Samsara shows that vehicle wasn’t there, you’d alert the fleet manager immediately. Or if a driver fueled more gallons than the truck can hold, you’d flag that as a potential fuel theft (perhaps the driver filled an external tank).