# Hosting Tracking – External API & Webhooks

Version 1 · base URL: `https://fms.hosting-tracking.com/api/external/v1`

This API lets your system (ERP, shop, dispatch software) **push delivery orders** into Hosting Tracking, read their status back,
cancel them, and **receive webhooks** when an order changes or when a vehicle raises a tracking event (over-speed, SOS, ...).

- JSON over HTTPS, UTF-8. Send `Content-Type: application/json` on POST.
- All data belongs to the account that owns the API key. A key can never see another account.
- The examples below are real answers of the live service (only the key is replaced by `htk_xxxxxxxx`).

---

## 0. Quick start (ملخص بالعربية)

1. صاحب الحساب يدخل **اللوجستيات ← التكامل (Integration)** وينشئ **مفتاح API**. يظهر المفتاح **مرة واحدة فقط** (يبدأ بـ `htk_`) — احفظه.
2. أرسل الطلبات: `POST /orders` مع الترويسة `Authorization: Bearer htk_...`.
3. اقرأ الحالة: `GET /orders/{externalRef}` أو `GET /orders?since=...`، أو استقبل إشعارًا فوريًا عبر **Webhook** (من نفس الصفحة، يظهر السرّ `whsec_...` مرة واحدة).
4. `externalRef` هو رقم الطلب عندكم؛ إعادة إرسال نفس الرقم **تحدّث** الطلب ولا تكرّره (آمن لإعادة المحاولة).
5. لا يمكن تعديل/إلغاء الطلب بعد أن يبدأه السائق (خطأ 409/422 `conflict`).
6. الحدّ: 120 طلبًا في الدقيقة لكل مفتاح، وحتى 100 طلب في الرسالة الواحدة، وحجم أقصاه 1 ميغابايت.
7. الـWebhook موقَّع بـHMAC-SHA256 — تحقّق من التوقيع دائمًا (القسم 6.3)، والعنوان يجب أن يكون `https` عامًّا على المنفذ 443.

---

## 1. Authentication

Create a key in the web app: **Logistics → Integration → API keys** (account owner only). The key is shown **once**; the server keeps only its SHA-256 hash.
Revoke it from the same page at any time.

```
Authorization: Bearer htk_xxxxxxxxxxxxxxxxxxxxxxxx
```

| Problem | HTTP | Body |
|---|---|---|
| Header missing / malformed | 401 | `{"error":{"code":"unauthorized","message":"Send the key as \"Authorization: Bearer htk_...\""}}` |
| Unknown or revoked key | 401 | `{"error":{"code":"unauthorized","message":"Unknown or revoked key."}}` |

Keep the key on your server. Never put it in a browser page or a mobile app.

## 2. Limits and errors

| Limit | Value |
|---|---|
| Requests per key | **120 per minute** (sliding window). Over the limit → `429` until the window frees up |
| Orders per POST | **100** |
| Request body | **1 MB** (`413 too_large`) |
| `GET /orders` page | `limit` 1–200 (default 100) |

Every error that is not a per-order result has this shape:

```json
{ "error": { "code": "rate_limited", "message": "At most 120 requests per minute per key." } }
```

| HTTP | `code` | Meaning |
|---|---|---|
| 400 | `bad_request` | Body is not JSON / empty / more than 100 orders |
| 401 | `unauthorized` | See section 1 |
| 404 | `not_found` | No order with this `externalRef` |
| 409 | `conflict` | (DELETE) the driver already started or finished the order |
| 413 | `too_large` | Body over 1 MB |
| 429 | `rate_limited` | Slow down; retry after a few seconds |
| 5xx | – | Temporary problem; retry with back-off (it is safe, see section 7) |

## 3. Order lifecycle

```
new ──► assigned ──► in_progress ──► completed
  │         │              └────────► failed
  └─────────┴──► cancelled
```

- `new`: saved, no vehicle yet. `assigned`: has a vehicle (sent to the driver's phone).
- `in_progress` / `completed` / `failed` are set by the **driver's app**. From `in_progress` on, your system can no longer change or cancel the order.
- `cancelled`: by your `DELETE` (or by the dispatcher in the web app).

## 4. Endpoints

### 4.1 `POST /orders` – create or update (batch)

Send one order object, or `{ "orders": [ ... ] }` (max 100). The call is an **upsert keyed by `externalRef`**: a new reference creates the order, an existing one updates it (only while it is `new` or `assigned`).

**Order fields**

| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `externalRef` | string 1–100 | **yes** | – | Your own order id. Unique per account |
| `name` | string ≤255 | **yes** | – | Title shown to the driver |
| `address` | string ≤500 | no | `""` | Used for geocoding when no coordinates are sent |
| `lat`, `lng` | number (-90..90, -180..180) | no | – | Send both. `0,0` is treated as "no place" |
| `clientName` | string ≤255 | no | `""` | |
| `phone1`, `phone2` | string ≤32 | no | `""` | The driver can call from the app |
| `email` | string ≤255 | no | `""` | |
| `comment` | string ≤2000 | no | `""` | |
| `deliveryBegin`, `deliveryEnd` | ISO-8601 string | no | – | Delivery window, e.g. `2026-10-20T08:00:00+03:00`. Stored in UTC |
| `cost`, `weight`, `volume` | number ≥0 | no | 0 | |
| `radiusMeters` | integer 10–5000 | no | 100 | "Arrived" radius used to judge the driver's confirmation |
| `serviceTimeMinutes` | integer 0–1440 | no | 10 | |
| `priority` | integer 0–10 | no | 0 | |
| `vehicleImei` | string ≤50 | no | – | Assign directly. Must be a vehicle that has an active driver in this account (see `GET /drivers`) |
| `autoAssign` | boolean | no | false | Give the order to the nearest free vehicle after saving |
| `onShiftOnly` | boolean | no | false | With `autoAssign`: only drivers currently on shift |

If an address has no coordinates the server geocodes it, but only the **first 10 such orders per request** (≈1 per second); the rest are saved with `place: null` and `placeFound:false`. **For bulk imports send `lat`/`lng`.**

**Example – one order assigned to a vehicle**

```bash
curl -X POST https://fms.hosting-tracking.com/api/external/v1/orders \
  -H "Authorization: Bearer htk_xxxxxxxx" -H "Content-Type: application/json" \
  -d '{"externalRef":"DOC-1002","name":"Order 1002","address":"Hawally, Block 5",
       "lat":29.3328,"lng":48.0286,"vehicleImei":"DOC-TEST-VEHICLE-1"}'
```

```json
{"received":1,"saved":1,"results":[
  {"externalRef":"DOC-1002","result":"updated","id":41,"orderNumber":"ORD-MV7RBUQS-PM9",
   "status":"assigned","assignedTo":"Doc Test Driver","placeFound":true}]}
```

**Response**: `received` (how many you sent), `saved` (created+updated) and one `results[]` item per order, **in the same order you sent them**.

| `results[].result` | Meaning |
|---|---|
| `created` / `updated` | Saved. Contains `id`, `orderNumber` (ours), `status`, `assignedTo` (vehicle name or `null`), `placeFound` |
| `conflict` | The order is already `in_progress`/`completed`/`failed`/`cancelled`; not changed. `message` says which |
| `error` | Validation or assignment problem for that one order; `message` lists the fields |

**HTTP status of the call**: `200` all saved · `207` some saved, some not · `422` none saved. Always read `results[]`, not only the status code.

```json
{"received":1,"saved":0,"results":[{"externalRef":"","result":"error",
  "message":"externalRef: Too small: expected string to have >=1 characters; lat: Too big: expected number to be <=90"}]}
```
```json
{"received":1,"saved":0,"results":[{"externalRef":"DOC-1001","result":"conflict",
  "message":"The order is already in_progress; it cannot be changed from outside."}]}
```

### 4.2 `GET /orders/{externalRef}` – one order

```json
{"externalRef":"DOC-1002","orderNumber":"ORD-MV7RBUQS-PM9","name":"Order 1002 (updated)","address":"Hawally, Block 5",
 "place":{"lat":29.3328,"lng":48.0286},"status":"new","assignedTo":null,
 "deliveryBegin":null,"deliveryEnd":null,"startedAt":null,"completedAt":null,"mileageKm":null,"confirmation":null}
```

`404 not_found` when the reference is unknown.

### 4.3 `GET /orders` – list

Only orders that came with an `externalRef` (i.e. yours). Newest change first.

| Query | Meaning |
|---|---|
| `status` | one of `new, assigned, in_progress, completed, cancelled, failed` (other values are ignored) |
| `since` | ISO-8601 time; orders **changed** at or after it |
| `limit` | 1–200, default 100 |

Result: `{ "orders": [ ...same object as 4.2... ] }`. There is no page cursor: poll with `since` = the time of your last successful poll (minus a minute of overlap), or better, use webhooks.

**Order object**

| Field | Notes |
|---|---|
| `externalRef`, `orderNumber`, `name`, `address` | |
| `place` | `{lat,lng}` or `null` (not located) |
| `status` | see section 3 |
| `assignedTo` | `null` or `{ "imei": "...", "vehicleName": "..." }` |
| `deliveryBegin`, `deliveryEnd`, `startedAt`, `completedAt` | ISO-8601 UTC or `null` |
| `mileageKm` | Distance driven for the order, when completed; else `null` |
| `confirmation` | `null` until the driver finishes. Then `{ action: "done"|"failed", at, phoneToTargetM, trackerToTargetM, phoneToTrackerM, phoneAtThePoint }` – distances in meters between the driver's phone, the vehicle tracker and the order point (proof of delivery); each may be `null` |

### 4.4 `DELETE /orders/{externalRef}` – cancel

Works while the order is `new` or `assigned`. Cancelling an already cancelled order returns success again (idempotent).

```json
{"externalRef":"DOC-1004","status":"cancelled"}
```

`404 not_found` unknown reference · `409 conflict` driver already started/finished:

```json
{"error":{"code":"conflict","message":"The driver already started or finished this order."}}
```

### 4.5 `GET /drivers` – vehicles you can assign to

```json
{"drivers":[{"name":"Demo Driver","imei":"DEMO-REVIEW-0001","onShift":false,"openOrders":2}]}
```

`imei` is the value for `vehicleImei`. `onShift`: the driver has an open shift (started in the last 24 h). `openOrders`: orders currently `assigned` or `in_progress`.

---

## 5. Typical flow

1. `GET /drivers` once (cache it) → pick vehicles, or just use `autoAssign:true`.
2. `POST /orders` with your id as `externalRef`.
3. Receive `order.assigned`, `order.in_progress`, `order.completed` webhooks (or poll `GET /orders?since=`).
4. On `order.completed` read `confirmation` for proof (distance to the delivery point) and `mileageKm`.
5. Customer cancels? `DELETE /orders/{externalRef}`; on `409` tell your user the driver already started.

---

## 6. Webhooks

Create them in the web app: **Logistics → Integration → Webhooks** (account owner). At most **5** per account. When you create one, a secret `whsec_...` is shown **once**; you use it to verify signatures. There is a **Send test** button that posts a signed `ping`.

Two kinds:

- **Orders** – one call each time an order created through the API changes status or vehicle.
- **Tracking events** – vehicle events from the fleet system (over-speed, SOS, geofence, ...). You may restrict a webhook to chosen event types (lower-case words); empty = all types. Only vehicles the account owner may see are sent.

### 6.1 Address rules

`https://` only, port 443 only, no user/password in the URL, and the host must resolve to a **public** address (localhost, private ranges 10.x/172.16-31.x/192.168.x, link-local, `.local`, `.internal` are refused; the check is repeated at every delivery).

### 6.2 What we send

`POST` to your URL, body is JSON, timeout **10 seconds**, any `2xx` answer = delivered (answer quickly, process afterwards).

| Header | Value |
|---|---|
| `Content-Type` | `application/json` |
| `User-Agent` | `HostingTracking-Webhook/1` |
| `X-Hosting-Event` | event name, e.g. `order.completed` |
| `X-Hosting-Delivery` | unique delivery id (use it to de-duplicate) |
| `X-Hosting-Signature` | `t=<unix seconds>,v1=<hex>` |

**Order events** – `order.assigned`, `order.in_progress`, `order.completed`, `order.failed`, `order.cancelled`, `order.reassigned` (vehicle changed without a status change):

```json
{ "event": "order.completed",
  "createdAt": "2026-10-20T07:41:12.310Z",
  "previousStatus": "in_progress",
  "order": { "externalRef": "DOC-1002", "orderNumber": "ORD-MV7RBUQS-PM9", "status": "completed", "...": "same object as GET /orders/{ref}" } }
```

**Tracking events** – `X-Hosting-Event: tracking.<type>`:

```json
{ "event": "tracking.event",
  "createdAt": "2026-10-20T07:41:12.310Z",
  "trackingEvent": {
    "id": 123456, "type": "overspeed", "description": "Overspeed",
    "time": "2026-10-20 10:41:05",
    "unit": { "imei": "DEMO-REVIEW-0001", "name": "Truck 12" },
    "position": { "lat": 29.3375, "lng": 48.0758 },
    "speedKmh": 112, "angle": 90, "altitude": 14 } }
```

`trackingEvent.time` is in the **account's own time zone** (as the Classic system shows it), not UTC. `type` values are the event types of the fleet system for the account (letters, digits, `_`).

**Test ping**: `{ "event": "ping", "createdAt": "...", "message": "Test from Hosting Tracking." }` with `X-Hosting-Event: ping`.

### 6.3 Verifying the signature (do this on every request)

The signature is `HMAC-SHA256(secret, "<t>.<raw body>")` in hex. Use the **raw body bytes exactly as received** (do not re-serialize the JSON), compare in constant time, and reject if `t` is more than 5 minutes from your clock (replay protection). The three samples below were tested against the server's own signing function.

**Node.js**
```js
import crypto from 'node:crypto';

export function verify(secret, rawBody, header, toleranceSec = 300) {
  const p = Object.fromEntries(header.split(',').map(x => x.split('=')));
  if (Math.abs(Date.now() / 1000 - Number(p.t)) > toleranceSec) return false;
  const expected = crypto.createHmac('sha256', secret).update(`${p.t}.${rawBody}`).digest();
  const got = Buffer.from(p.v1 || '', 'hex');
  return got.length === expected.length && crypto.timingSafeEqual(got, expected);
}
// Express: use express.raw({ type: 'application/json' }) and pass req.body.toString('utf8')
```

**Python**
```python
import hmac, hashlib, time

def verify(secret: str, raw_body: str, header: str, tolerance=300) -> bool:
    p = dict(x.split('=', 1) for x in header.split(','))
    if abs(time.time() - int(p['t'])) > tolerance:
        return False
    expected = hmac.new(secret.encode(), f"{p['t']}.{raw_body}".encode(), hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, p['v1'])
```

**PHP**
```php
function verify(string $secret, string $rawBody, string $header, int $tolerance = 300): bool {
    parse_str(str_replace(',', '&', $header), $p);   // $p['t'], $p['v1']
    if (abs(time() - (int)$p['t']) > $tolerance) return false;
    return hash_equals(hash_hmac('sha256', $p['t'] . '.' . $rawBody, $secret), $p['v1']);
}
// $rawBody = file_get_contents('php://input');
```

Known-answer test (secret `whsec_TESTSECRET`, `t=1760436000`, body `{"event":"ping","createdAt":"2026-10-14T10:00:00.000Z"}`):
`t=1760436000,v1=74630d70babf3f02fa10f8970776afff54e81eaf02dd7bc332498cfb2a4ed967`

### 6.4 Retries and switching off

- Not answered with `2xx` (or timeout / connection error) → retried after **1 min, 5 min, 30 min, 2 h, 6 h**; after the 5th retry the delivery is marked `failed`.
- A webhook with **30 failures in a row** is switched off automatically; switch it back on from the Integration page after fixing your endpoint.
- Delivery history (state, attempts, last HTTP status/error) is visible on the Integration page and kept **14 days**.
- Deliveries are polled about every 10 s (tracking events ≈ every 30 s), so expect a delay of up to a few seconds to half a minute.

---

## 7. Reliability and best practice

- **Idempotency**: `POST /orders` with the same `externalRef` updates instead of duplicating, and `DELETE` twice is fine. So if a call times out, simply repeat it.
- **Webhooks are at-least-once**: the same delivery can arrive twice (retry after a slow answer). De-duplicate with `X-Hosting-Delivery` or by `(externalRef, status)`.
- Order of webhooks is not guaranteed across retries; treat the `status` inside the payload as the truth, or call `GET /orders/{ref}`.
- Send **lat/lng** whenever you have them; geocoding by address is limited to 10 per request and may fail.
- Batch (up to 100) instead of many single calls to stay inside 120/min.
- Handle `429` with back-off; do not retry `4xx` other than 429 without changing the request.
- Dates: send ISO-8601 **with** an offset (`+03:00` or `Z`). Without an offset the result depends on the server's time zone, so always include one.
- Keep a key per integration so one can be revoked without stopping the others.

## 8. Changes and support

The API is versioned in the path (`/v1`). New optional fields and new event names may be added without a version change — ignore fields and events you do not know. Breaking changes will use `/v2`.
