# Webhooks

Instead of polling `GET /get-tracking`, Load Market can push tracking updates to an HTTPS endpoint of
yours.

## Enabling webhooks

Webhooks are configured per partner key by Load Market. Email office@load-market.com with:

- the HTTPS URL of your endpoint (one for the live key, optionally another for the test key),
- optionally a bearer token we should send in the `Authorization` header.

We reply with the signing secret (`whsec_...`) for each key. Store it like a password.

## When updates are sent

Once per minute the server collects every tracking created with your partner key (after webhooks were
enabled on it) that changed during the last minute:

- the driver (or the truck's ELD) reported a new position,
- the status changed (accepted, rejected, paused, resumed, finished, device issues, ...),
- the driver uploaded a file (then `driverFiles` is included),
- something happened that has an [event](#events) (the truck arrived at a stop, a Smart Arrival Alert
  turned `late`, the carrier approved, ...).

All of them are sent in **one** `POST` - the body is a JSON array with one item per tracking.
Nothing is sent for a minute in which nothing changed.

A tracking sends updates from its create. Until it reaches the driver's app (a pending installation, a
scheduled tracking, an [ELD or Hybrid request](/eld-tracking#webhooks) waiting for the carrier) it sends only
items with events, such as `carrier.rejected` or `driver.sms_undeliverable`, and their `data` is the pending
shape (`TrackingPendingData`). Once it starts (`driver.installed`, `tracking.started` or `carrier.approved`)
every change is sent. It stops after its final `done` or `cancel` update (`doneEld` or `cancelEld` for
ELD and Hybrid), when the driver of a phone tracking uninstalls the app or deletes the account, or when
you delete the tracking. Your own `PATCH /stop-tracking` also produces the final `done` (or `doneEld`)
update. A request that is removed without starting (it expired or was deleted) sends nothing more.

## Request

```http
POST /your/webhook/endpoint HTTP/1.1
Content-Type: application/json
Authorization: Bearer your-configured-token
webhook-id: msg_2b7c1f0e-5d3a-4c8e-9b61-7a4f0d2e9c35
webhook-timestamp: 1793644927
webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=

[
  {
    "message": "Ok",
    "data": {
      "trackingId": "api-7fK2mQ9xLpR4tN8vB1cD",
      "status": { "value": "active", "description": "Active" },
      "customId": "tms-load-48213",
      "expDate": 1793800800000,
      "publicLink": "https://tracking.load-market.com?track=Qm3xT8vN2kLp9RfW4bYc",
      "driverCoords": {
        "lat": 39.781721, "lng": -89.650148, "speed": 28.6, "battery": 0.82,
        "heading": 205, "accuracy": 6, "locationSource": "gps", "lastUpdate": 1793644890000
      },
      "stopLocations": []
    },
    "events": [
      { "id": "evt_3d8e0c41a7b29f6e15c0d2aa", "type": "stop.arrived", "at": 1793644410000, "stopIndex": 0, "customStopId": "PU-1" }
    ]
  }
]
```

Each item's `data` has the same shape as the `data` of `GET /get-tracking` (`TrackingData` in the
[API reference](/api)), shortened above, with these differences:

- `stopLocationsEta` and `driverCoords.location` are never included (they exist only on request).
- `driverFiles` is included only when the driver uploaded a file.
- `driverCoords` is `null` outside the live window, and on a mobile tracking until the phone sends its
  first position after the driver accepts - see [Tracking lifecycle](/tracking-lifecycle#driver-position). A position from the truck's ELD has
  `battery`, `accuracy` and `locationSource` `null` - see [ELD and Hybrid tracking](/eld-tracking#positions).
- `fraudAlerts` follows the same live window. A change in it alone does not send an update, the
  current value arrives with the next one - see [Potential Fraud Alerts](/fraud-alerts).

## Events

Each item's `events` lists what happened to the tracking since the last delivery, oldest first. It is empty
when only the snapshot changed (a new position). The snapshot in `data` is the state at the time of the
delivery, so it can be newer than the last event.

| `type` | When | Extra fields |
| --- | --- | --- |
| `driver.installed` | A pending installation is now in the driver's app | `status`, `previousStatus` |
| `driver.accepted` | The driver accepted the tracking | `status`, `previousStatus` |
| `driver.rejected` | The driver declined it (a Hybrid: the phone side) | `status`, `previousStatus` |
| `driver.paused` | The driver paused sharing | `status`, `previousStatus` |
| `driver.resumed` | The driver resumed sharing | `status`, `previousStatus` |
| `driver.sms_undeliverable` | The driver's number can never receive a text | `reason` |
| `driver.sms_opted_out` | The driver's number replied STOP | |
| `tracking.started` | A scheduled tracking started | `status`, `previousStatus` |
| `tracking.finished` | The tracking finished (`done` or `doneEld`) | `status`, `previousStatus` |
| `carrier.approved` | The carrier approved the ELD side | `status` |
| `carrier.rejected` | The carrier refused or cancelled the ELD side (`status` `cancelEld` ends the tracking, a Hybrid keeps its status) | `status` |
| `carrier.paused` | The carrier paused the ELD side | `status` |
| `carrier.resumed` | The carrier resumed the ELD side | `status` |
| `stop.arrived` | The truck arrived at a stop | `stopIndex`, `customStopId` |
| `stop.departed` | The truck left a stop | `stopIndex`, `customStopId` |
| `stop.arrival_cleared` | A user marked a confirmed arrival as not arrived - undo the arrival you recorded | `stopIndex`, `customStopId` |
| `stop.departure_cleared` | A user marked a confirmed departure as not completed | `stopIndex`, `customStopId` |
| `stop.alert_status_changed` | A stop's Smart Arrival Alert changed (PRO) | `stopIndex`, `customStopId`, `stopAlertStatus`, `previousStopAlertStatus` |
| `document.uploaded` | The driver uploaded a file (it is in `data.driverFiles`) | `fileId`, `fileType` |

Every event has an `id`, a `type` and `at` (epoch milliseconds, when it happened). New types may be added over
time, ignore a type you do not know. An event can arrive more than once - deduplicate by its `id`.

When the driver cannot receive a text (`driver.sms_undeliverable`, `driver.sms_opted_out`), `data.driverInvite`
says why and carries the driver app link (`appLink`) to share with the driver another way.

## Headers

| Header | Value |
| --- | --- |
| `webhook-id` | Unique message id, `msg_<uuid>`. **Identical on every retry** of the same delivery - use it to deduplicate. |
| `webhook-timestamp` | Unix time in **seconds** when the message was signed. |
| `webhook-signature` | `v1,<base64 signature>`. It can hold several space-separated entries. |
| `Authorization` | `Bearer <your token>`, only when a token is configured for your key. |

## Responding and retries

- Answer with any **2xx within 7 seconds**. Do the real work asynchronously (queue the payload,
  respond, then process).
- A timeout, a network error, `408`, `429` or any `5xx` is retried **up to 2 more times** with a short
  exponential backoff. A `Retry-After` (seconds) is honored, capped at 5 seconds.
- Any other `4xx` (for example `400` or `401`) is **not** retried.
- When every attempt failed, the tracking's **events** are sent again with its next item, for up to an
  hour (at most the newest 50 per tracking). The snapshot itself is not redelivered: the next change
  produces a new update, and you can always read the current state with `GET /get-tracking`.

Delivery is **best effort** and an update can arrive more than once: dedupe deliveries on `webhook-id` and
events on their `id`, apply updates idempotently per `trackingId` (ignore an item whose
`driverCoords.lastUpdate` is older than what you already stored), and fall back to `GET /get-tracking` for gaps.

## Verifying the signature

Signatures follow the [Standard Webhooks](https://www.standardwebhooks.com/) specification, so any
Standard Webhooks library works. To verify by hand:

1. Take the part of your secret after `whsec_` and base64-decode it - that is the HMAC key.
2. Build the signed content: `` `${webhook-id}.${webhook-timestamp}.${raw body}` ``. Use the **raw
   request body bytes** exactly as received - not a re-serialized JSON object.
3. Compute HMAC-SHA256 of it with the key and base64-encode the result.
4. Split `webhook-signature` on spaces. Accept the message when any `v1,<signature>` entry matches, using
   a constant-time comparison.
5. Reject the message when `webhook-timestamp` is more than 5 minutes away from your clock (replay
   protection).

<CodeTabs syncKey="lang">

```js title="Node.js"
import crypto from 'node:crypto';
import express from 'express';

const SECRET = process.env.LOADMARKET_WEBHOOK_SECRET; // whsec_...
const TOLERANCE_SECONDS = 5 * 60;

export function verifyWebhook(rawBody, headers, secret = SECRET) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signatures = headers['webhook-signature'];
  if (!id || !timestamp || !signatures) return false;

  const sentAt = Number(timestamp);
  const now = Math.floor(Date.now() / 1000);
  if (!Number.isInteger(sentAt) || Math.abs(now - sentAt) > TOLERANCE_SECONDS) return false;

  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = crypto
    .createHmac('sha256', key)
    .update(`${id}.${timestamp}.`)
    .update(rawBody) // Buffer with the raw request body
    .digest();

  return signatures.split(' ').some((entry) => {
    const [version, signature] = entry.split(',');
    if (version !== 'v1' || !signature) return false;
    const received = Buffer.from(signature, 'base64');
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}

const app = express();

// express.raw keeps the body as a Buffer - express.json() would lose the exact bytes.
app.post('/webhooks/loadmarket', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verifyWebhook(req.body, req.headers)) return res.sendStatus(401);

  res.sendStatus(204); // answer first, process afterwards
  const updates = JSON.parse(req.body.toString('utf8'));
  // enqueue(req.headers['webhook-id'], updates);
});
```

```python title="Python"
import base64
import hashlib
import hmac
import os
import time

from flask import Flask, request

SECRET = os.environ["LOADMARKET_WEBHOOK_SECRET"]  # whsec_...
TOLERANCE_SECONDS = 5 * 60


def verify_webhook(raw_body: bytes, headers, secret: str = SECRET) -> bool:
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not msg_id or not timestamp or not signatures:
        return False

    try:
        sent_at = int(timestamp)
    except ValueError:
        return False
    if abs(time.time() - sent_at) > TOLERANCE_SECONDS:
        return False

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()

    for entry in signatures.split(" "):
        version, _, signature = entry.partition(",")
        if version == "v1" and hmac.compare_digest(signature.encode(), expected.encode()):
            return True
    return False


app = Flask(__name__)


@app.post("/webhooks/loadmarket")
def loadmarket_webhook():
    if not verify_webhook(request.get_data(), request.headers):
        return "", 401
    updates = request.get_json()
    # enqueue(request.headers["webhook-id"], updates)
    return "", 204
```

```php title="PHP"
<?php

const TOLERANCE_SECONDS = 300;

function verifyWebhook(string $rawBody, array $headers, string $secret): bool
{
    $id = $headers['webhook-id'] ?? '';
    $timestamp = $headers['webhook-timestamp'] ?? '';
    $signatures = $headers['webhook-signature'] ?? '';
    if ($id === '' || $timestamp === '' || $signatures === '') {
        return false;
    }
    if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > TOLERANCE_SECONDS) {
        return false;
    }

    $key = base64_decode(preg_replace('/^whsec_/', '', $secret));
    $expected = base64_encode(hash_hmac('sha256', $id . '.' . $timestamp . '.' . $rawBody, $key, true));

    foreach (explode(' ', $signatures) as $entry) {
        $parts = explode(',', $entry, 2);
        if (count($parts) === 2 && $parts[0] === 'v1' && hash_equals($expected, $parts[1])) {
            return true;
        }
    }
    return false;
}

$rawBody = file_get_contents('php://input');
$headers = array_change_key_case(getallheaders(), CASE_LOWER);

if (!verifyWebhook($rawBody, $headers, getenv('LOADMARKET_WEBHOOK_SECRET'))) {
    http_response_code(401);
    exit;
}

http_response_code(204);
$updates = json_decode($rawBody, true);
// enqueue($headers['webhook-id'], $updates);
```

```csharp title="C#"
using System.Security.Cryptography;
using System.Text;

public static class LoadMarketWebhook
{
    private static readonly TimeSpan Tolerance = TimeSpan.FromMinutes(5);

    public static bool Verify(byte[] rawBody, string? id, string? timestamp, string? signatures, string secret)
    {
        if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(signatures))
            return false;
        if (!long.TryParse(timestamp, out var seconds))
            return false;
        if (seconds < 0 || seconds > 253402300799)
            return false;
        if ((DateTimeOffset.UtcNow - DateTimeOffset.FromUnixTimeSeconds(seconds)).Duration() > Tolerance)
            return false;

        var key = Convert.FromBase64String(secret.StartsWith("whsec_") ? secret["whsec_".Length..] : secret);
        var prefix = Encoding.UTF8.GetBytes($"{id}.{timestamp}.");
        var signed = new byte[prefix.Length + rawBody.Length];
        Buffer.BlockCopy(prefix, 0, signed, 0, prefix.Length);
        Buffer.BlockCopy(rawBody, 0, signed, prefix.Length, rawBody.Length);
        var expected = HMACSHA256.HashData(key, signed);

        foreach (var entry in signatures.Split(' ', StringSplitOptions.RemoveEmptyEntries))
        {
            var parts = entry.Split(',', 2);
            if (parts.Length != 2 || parts[0] != "v1") continue;

            byte[] received;
            try { received = Convert.FromBase64String(parts[1]); }
            catch (FormatException) { continue; }

            if (CryptographicOperations.FixedTimeEquals(received, expected)) return true;
        }
        return false;
    }
}

// ASP.NET Core minimal API
app.MapPost("/webhooks/loadmarket", async (HttpRequest request) =>
{
    using var buffer = new MemoryStream();
    await request.Body.CopyToAsync(buffer);
    var rawBody = buffer.ToArray();

    var valid = LoadMarketWebhook.Verify(
        rawBody,
        request.Headers["webhook-id"],
        request.Headers["webhook-timestamp"],
        request.Headers["webhook-signature"],
        Environment.GetEnvironmentVariable("LOADMARKET_WEBHOOK_SECRET")!);

    return valid ? Results.NoContent() : Results.Unauthorized();
});
```

</CodeTabs>

### Test vector

Check your verifier against this official Standard Webhooks vector before going live. With the
5-minute timestamp check turned off (the timestamp is from 2021), it must accept the message, and it
must reject it when a single byte of the body changes.

| Input | Value |
| --- | --- |
| Secret | `whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw` |
| `webhook-id` | `msg_p5jXN8AQM9LWM0D4loKWxJek` |
| `webhook-timestamp` | `1614265330` |
| Raw body | `{"test": 2432232314}` |
| Expected `webhook-signature` | `v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=` |

:::note{title="Keys issued before signing was introduced"}

Partner keys that existed before webhook signing receive their signing secret from Load Market
separately. Until you have it, deliveries to those keys are not signed and carry only the bearer token.
Once you have the secret, start verifying and reject unsigned requests.

:::

## Testing your endpoint

With a test key, every `POST /test/simulate` call sends one signed webhook with the new state to the
URL configured on the test key - once, no retries, 7-second timeout - and returns what your endpoint
answered in the `webhook` object. The item carries the event the simulate stands for in `events`
(`driver.accepted`, `carrier.rejected`, ...). This happens only when webhooks are enabled on the test key.
Otherwise `webhook.attempted` is `false`. See [Test mode](/test-mode).

## Checklist

- Verify the signature on the raw body and check the timestamp.
- Respond with 2xx within 7 seconds. Process asynchronously.
- Deduplicate deliveries on `webhook-id` and events on their `id`. Apply updates per `trackingId` idempotently.
- Handle an array with many items, and statuses or fields you do not know yet.
- Fall back to `GET /get-tracking` if you suspect you missed an update.
