# Logistics Tracking API Integration Guide

For customers with an active account. Integrate this API to query shipment tracking status and events from your own systems.

- **Endpoint**: `https://track.monina.xyz/api/track`
- **Format**: JSON (UTF-8)
- **Protocol**: HTTPS

---

## 1. Quick Start

Three steps to integrate.

**Step 1**: Obtain your API key

Provided by the service provider, in the form `tk_xxxxxxxxxxxxxxxxxxxxxxxx`. Keep it secret — never expose it in client-side code.

**Step 2**: Send a query

**Put your key in the `key` field of the JSON body** (recommended), or in the `?key=` query parameter. Do NOT use the `X-API-Key` request header — the deployment gateway strips custom headers, so your key never reaches the server and the request gets billed as anonymous.

```bash
curl -s -X POST "https://track.monina.xyz/api/track" \
  -H "Content-Type: application/json" \
  -d '{"key":"tk_yourKey","numbers":["QYAL260907001"]}'
```

**Step 3**: Parse the response

```json
{
  "ok": true,
  "auth": "key",
  "results": [
    {
      "number": "QYAL260907001",
      "status": "signed",
      "statusLabel": "Delivered",
      "statusDesc": "Shipment has been delivered",
      "channel": "c2",
      "latestInfo": "Delivered 【FR ANNECY】",
      "latestTime": "2026-09-18 13:00:34",
      "destination": "France 74960",
      "carrier": "",
      "note": "",
      "traceCount": 19,
      "traces": [
        { "time": "2026-09-18 13:00:34", "info": "Delivered 【FR ANNECY】" }
      ]
    }
  ],
  "summary": {
    "total": 1, "signed": 1, "inTransit": 0,
    "abnormal": 0, "offline": 0, "notFound": 0, "failed": 0
  },
  "cached": 0,
  "queried": 1,
  "elapsedMs": 1801
}
```

> **Note on `statusLabel`**: the API returns labels in both Chinese and English.
> Chinese responses carry `statusLabel` in Chinese and `statusLabelEn` in English.
> See [Section 7](#7-status-reference) for details.

---

## 2. Endpoint Details

### Query Tracking

| Item | Value |
|---|---|
| URL | `https://track.monina.xyz/api/track` |
| Method | `GET` or `POST` |
| Encoding | UTF-8 |

#### Parameters

| Name | Location | Type | Required | Description |
|---|---|---|---|---|
| `numbers` | Query / Body | String / Array | Yes | Tracking numbers. Separate with **newline, comma, semicolon, space or tab** |
| `number` | Query / Body | String | No | Alias for `numbers`; use either one |
| `key` | Query / Body | String | Yes | API key. Put it in the JSON body `key` field for POST (recommended), or in the `?key=` query parameter for GET. **Do NOT use the `X-API-Key` header** — the deployment gateway strips custom headers |

> **Number format**: plain text, no spaces. Case-insensitive — values are normalized to upper case. Anything shorter than 6 characters is ignored.
> Duplicates are removed, so submitting the same number twice will not produce duplicate results.

> **Security note on `?key=`**: the key stays in the URL (visible in browser history and access logs). Prefer POST + JSON body when security matters.

#### GET example

```bash
curl "https://track.monina.xyz/api/track?numbers=QYAL260907001,QLAG260908002&key=tk_yourKey"
```

#### POST example (recommended for production)

Use POST + JSON for large batches, special characters — and to keep the key out of the URL.

```bash
curl -X POST "https://track.monina.xyz/api/track" \
  -H "Content-Type: application/json" \
  -d '{"key":"tk_yourKey","numbers":["QYAL260907001","QLAG260908002"]}'
```

### Request Signature (when enabled)

If the provider has enabled **mandatory request signing** for your key, every request must
additionally carry `timestamp`, `nonce` and `sign` in the JSON body, otherwise the API
returns `401`. When signing is not enabled you may omit these fields (sending a valid
signature anyway is also accepted).

**Signature algorithm** (HMAC-SHA256):

```javascript
const crypto = require('crypto');

const SIGN_SECRET = 'ss_yourSignSecret'; // provided by the provider, independent of the API key

const timestamp = Math.floor(Date.now() / 1000);          // Unix time in seconds
const nonce = crypto.randomBytes(8).toString('hex');      // a fresh random value per request
const numbersStr = numbers.join(',');                     // array → comma-joined; string → as-is

const sign = crypto.createHmac('sha256', SIGN_SECRET)
  .update(`${timestamp}|${nonce}|${numbersStr}`, 'utf8')
  .digest('hex');

// Body:
// { "key": "tk_yourKey", "numbers": [...], "timestamp": timestamp, "nonce": nonce, "sign": sign }
```

**Validation rules** (server side):

| Rule | Description |
|---|---|
| Time window | `timestamp` must be within ±90 seconds of server time. **Keep your server clock accurate** (NTP recommended) |
| One-time use | The same `nonce` can only be used once within 5 minutes — **never reuse a nonce for retries**; generate a fresh one for every request, including retries |
| Numbers binding | The numbers string inside the signature must match the `numbers` in the request **exactly** (array joined with commas, in order) |

> Common causes of failure: clock skew beyond the time window (most common), reusing a nonce,
> or case/order mismatch between the signed numbers string and the request.

---

## 3. Response Fields

### Top-level

| Field | Type | Description |
|---|---|---|
| `ok` | Boolean | Whether the request succeeded. `true` means the query completed |
| `auth` | String | Billing identity for this call: `key` = billed to your key; `anonymous` = no key recognised (check how you send it) |
| `results` | Array | Tracking results. See below |
| `summary` | Object | Aggregated status counts for this batch |
| `cached` | Number | Numbers served from cache (no upstream request) |
| `queried` | Number | Numbers actually queried upstream |
| `elapsedMs` | Number | Query duration in milliseconds |

> `cached + queried` equals the total number of unique values you submitted.

### `summary`

| Field | Description |
|---|---|
| `total` | Total numbers submitted |
| `signed` | Delivered |
| `inTransit` | In transit |
| `abnormal` | Abnormal — shipment has an issue |
| `offline` | Not yet picked up (carrier has no scan; not an error) |
| `notFound` | Not found (no carrier holds this number) |
| `failed` | Query failed (upstream error, retryable) |

### `results[]`

| Field | Type | Description |
|---|---|---|
| `number` | String | Tracking number |
| `status` | String | Status code. See Section 7 |
| `statusLabel` | String | Localized status name, ready to display |
| `statusLabelEn` | String | English status name (added for integration convenience) |
| `statusDesc` | String | Longer explanation of the current status |
| `channel` | String / null | Internal source code. **Use it only to judge data reliability — do not display it to end users** |
| `latestInfo` | String | Most recent tracking event |
| `latestTime` | String | Timestamp of that event, `YYYY-MM-DD HH:mm:ss` |
| `destination` | String | Destination, e.g. `France 74960` |
| `carrier` | String | Last-mile carrier tracking number. Empty string if unavailable |
| `note` | String | Additional advisory. **Display it when non-empty** — see Section 5 |
| `traceCount` | Number | Total number of tracking events |
| `traces` | Array | Event list, **newest first** |

### `traces[]`

| Field | Type | Description |
|---|---|---|
| `time` | String | `YYYY-MM-DD HH:mm:ss` |
| `info` | String | Event description |

> **Trace limit**: up to 100 events are returned per response. `traceCount` reports the true total and may exceed the length of `traces`.

---

## 4. Localization

Tracking data originates from carrier systems worldwide and is returned as provided. Two fields are normalized by this API:

| Field | Behavior |
|---|---|
| `statusLabel` / `statusLabelEn` | Localized by this API. Use these for status display |
| `latestInfo` / `traces[].info` | Carrier event text. English-origin events are translated into Chinese; other languages are returned as-is |

If your UI requires a single consistent language, map `status` to your own translation table rather than relying on event text.

---

## 5. The `note` Field

`note` carries advisories in certain situations:

| Value | Meaning | Suggested action |
|---|---|---|
| `本次查询未命中，显示上次结果（2026-09-18 13:00:34）` | No result this time; the last known tracking data is returned | Display normally, optionally note that data may be stale |
| `承运方提示清关异常` | Customs clearance issue reported | Advise the user to contact the carrier |
| `承运方提示派送异常` | Delivery issue reported | Advise the user to contact the carrier |

---

## 6. Error Handling

Errors return an appropriate **HTTP status code** plus:

```json
{
  "ok": false,
  "error": "Human-readable description",
  "code": "error_code"
}
```

### Error codes

| HTTP | `code` | Meaning | Recommended action |
|---|---|---|---|
| 400 | — | Bad parameters (empty/invalid numbers, or batch too large) | Check the request |
| 401 | `auth` | Authentication failed: key missing, invalid, disabled — or signature check failed | Check in order: key is present and free of stray whitespace; signature fields (`timestamp`/`nonce`/`sign`) are present, fresh and correct. Contact the provider if it still fails |
| 429 | `quota` | Daily quota exhausted | See `Retry-After`; resets at 00:00 (UTC+8) |
| 429 | `rate` | Rate limit exceeded | Back off per `Retry-After` |
| 502 | — | Upstream error | Retry later |
| 404 | — | Wrong path | Check the endpoint URL |

> **About the `auth` code**: the server deliberately does not distinguish between
> "key missing", "key invalid", "key disabled" and "bad signature" — all of them return the
> identical status code, `code` and message. This is part of the anti-credential-stuffing design.
> When troubleshooting, walk through the checklist above step by step.

> The `error` field is a human-readable description suitable for end users.

### Retry guidance

- `rate` / `quota`: **must** honour `Retry-After`. Do not retry immediately.
- `502`: exponential backoff, ~2 seconds, up to 2 attempts.
- Results with status `failed`: retry after ~30 seconds.
- Set a **30-second timeout** per request; treat timeouts as failures and queue them for retry.

---

## 7. Status Reference

| `status` | English label | Meaning and recommended action |
|---|---|---|
| `signed` | Delivered | Query succeeded. Shipment delivered |
| `inTransit` | In transit | Query succeeded. Show the latest event |
| `abnormal` | Abnormal | **Query succeeded**, but the carrier reports a customs or delivery issue. Contact the carrier |
| `offline` | Not yet picked up | The carrier has no scan yet, usually just shipped or just collected. Recheck tomorrow — **not an error** |
| `notFound` | Not found | No carrier holds this number. It may not be registered yet |
| `failed` | Query failed | The upstream query itself failed; data is unreliable. Retry later |

> **`abnormal` vs `failed` — do not conflate them**:
> - `abnormal` means the **shipment** has a problem; the data is trustworthy.
> - `failed` means the **query** failed; the data is not trustworthy.
>
> This distinction matters operationally. Handle them differently.

You can fetch the status dictionary at runtime instead of hard-coding labels:

```bash
curl "https://track.monina.xyz/api/status-meta"
```

---

## 8. Rate Limits and Quota

| Item | Limit |
|---|---|
| Max numbers per request | 50 (exceeding returns 400) |
| Requests per IP | 30 / minute (exceeding returns 429) |
| Requests per key | typically 60 / minute (exceeding returns 429; actual value is set by the provider) |
| Daily request quota | 3000 (exceeding returns 429, resets at midnight UTC+8) |

> Limits can be adjusted on request — contact the service provider.

### Caching (important)

To protect upstream systems and keep latency low, the server caches results:

- **Delivered** shipments: cached for **7 days** (status no longer changes)
- **All other statuses**: cached for **30 minutes**

Practical consequences:

1. Repeated queries for the same number within the cache window return cached data; `cached` increases and `elapsedMs` drops sharply.
2. In-transit shipments refresh at most every 30 minutes — no need for aggressive polling.
3. You do not need your own caching layer; pass through.

### Latency

A query tries multiple sources sequentially and stops at the first hit. Typical ranges:

- **Cache hit**: returns in tens of milliseconds
- **Cache miss (upstream query)**: roughly 2–8 seconds, depending on batch size

Recommendations:

- Split large jobs into batches of 20–50 numbers to avoid timeouts
- Show a loading state in your UI; do not leave users waiting silently

---

## 9. Code Examples

All examples below use **POST + JSON body** (`key` field) — the recommended production pattern.

### cURL

```bash
curl -s -X POST "https://track.monina.xyz/api/track" \
  -H "Content-Type: application/json" \
  -d '{"key":"tk_yourKey","numbers":["QYAL260907001"]}'
```

### PHP

```php
<?php
function trackShipment(string $numbers, string $apiKey): array
{
    $ch = curl_init('https://track.monina.xyz/api/track');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode([
            'key'     => $apiKey,                              // key goes in the body
            'numbers' => explode(',', $numbers),
        ]),
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
        ],
    ]);

    $body  = curl_exec($ch);
    $errno = curl_errno($ch);
    $err   = curl_error($ch);   // read before curl_close
    curl_close($ch);

    if ($errno !== 0) {
        throw new RuntimeException('Network error: ' . $err);
    }

    $data = json_decode((string)$body, true);
    if (!is_array($data)) {
        throw new RuntimeException('Response is not valid JSON');
    }
    if (empty($data['ok'])) {
        // The error field is human-readable and safe to show to users
        throw new RuntimeException($data['error'] ?? 'Query failed');
    }

    return $data['results'];
}

// Usage
foreach (trackShipment('QYAL260907001', 'tk_yourKey') as $item) {
    echo $item['number'] . ' ' . $item['statusLabelEn'] . ' ' . $item['latestInfo'] . PHP_EOL;

    // Surface the advisory when present
    if (!empty($item['note'])) {
        echo '  Note: ' . $item['note'] . PHP_EOL;
    }
}
```

### Python

```python
import requests

API_URL = "https://track.monina.xyz/api/track"
API_KEY = "tk_yourKey"

def track(numbers, api_key=API_KEY, timeout=30):
    """Query tracking. Returns the results list; raises on failure."""
    try:
        resp = requests.post(
            API_URL,
            json={"key": api_key, "numbers": numbers},  # key goes in the body
            timeout=timeout,
        )
        data = resp.json()
    except requests.Timeout:
        raise RuntimeError("Request timed out; please retry")
    except ValueError:
        raise RuntimeError("Response is not valid JSON")

    if not data.get("ok"):
        # The error field is human-readable and safe to show to users
        raise RuntimeError(data.get("error", "Query failed"))

    return data["results"]

# Usage
for item in track(["QYAL260907001", "QLAG260908002"]):
    print(item["number"], item.get("statusLabelEn", item["statusLabel"]), item["latestInfo"])

    if item.get("note"):
        print("  Note:", item["note"])
```

### JavaScript (Node.js)

```javascript
const API_URL = 'https://track.monina.xyz/api/track';
const API_KEY = 'tk_yourKey';

async function track(numbers) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 30000);

  try {
    const res = await fetch(API_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ key: API_KEY, numbers }),  // key goes in the body
      signal: controller.signal,
    });

    const data = await res.json();
    if (!data.ok) {
      // The error field is human-readable and safe to show to users
      throw new Error(data.error || 'Query failed');
    }
    return data.results;
  } finally {
    clearTimeout(timer);
  }
}

// Usage
(async () => {
  const results = await track(['QYAL260907001', 'QLAG260908002']);
  for (const r of results) {
    console.log(r.number, r.statusLabelEn || r.statusLabel, r.latestInfo);
    if (r.note) console.log('  Note:', r.note);
  }
})();
```

### Browser (testing only)

CORS is enabled, so the API can be called directly from a browser. **Do not do this in production** — an API key cannot be hidden in client-side code.

```javascript
fetch('https://track.monina.xyz/api/track?numbers=QYAL260907001&key=tk_yourKey')
  .then(r => r.json())
  .then(data => console.log(data.results));
```

---

## 10. Go-Live Checklist

- [ ] API key stored **server-side**, absent from front-end code and pages
- [ ] Key sent via the **JSON body `key` field** (POST, recommended) or the `?key=` parameter — not the `X-API-Key` header
- [ ] Responses show `"auth": "key"` (if you see `"anonymous"`, your key is not reaching the server)
- [ ] Request timeout set to at least 30 seconds
- [ ] HTTP 429 handled, honouring `Retry-After`
- [ ] Display logic in place for a non-empty `note`
- [ ] `abnormal` and `failed` handled as distinct cases
- [ ] No more than 50 numbers per request
- [ ] Loading state shown during queries

---

## 11. FAQ

**Q · Why does some tracking number return "Not found"?**
A · No carrier holds that number. This usually means it has not been registered in the carrier system yet (just shipped, not yet collected, or a typo). Recheck the next day. If an already-delivered historical number cannot be found, verify the number is correct.

**Q · Is "Not yet picked up" an error?**
A · No. It means the carrier has no scan yet — typically just shipped or just collected. This is normal; recheck the next day.

**Q · What is the difference between "Abnormal" and "Query failed"?**
A · "Abnormal" means the **shipment** has an issue (customs or delivery), so the data is trustworthy — contact the carrier. "Query failed" means the **query itself** failed, so the data is unreliable — retry later. Do not treat them the same.

**Q · Why does the same number return different `cached` values across queries?**
A · The server caches results (7 days for delivered, 30 minutes otherwise). Cache hits skip the upstream request and return faster. This is expected behaviour.

**Q · Which numbers are supported? Can I query both waybills and house bills?**
A · Both are supported. Numbers are normalized to upper case; case does not matter.

**Q · What is the `channel` field?**
A · An internal source code, useful for judging data reliability. **Do not display it to end users or explain its meaning in your UI.**

**Q · Why is the number of events truncated?**
A · Up to 100 events are returned per response. `traceCount` reports the true total, which may exceed the array length.

**Q · Is the data real-time?**
A · It syncs from carrier systems, so delays are expected. In-transit shipments refresh at most every 30 minutes; avoid high-frequency polling.

**Q · I sent my key, so why are calls logged as "anonymous" and my quota unchanged?**
A · Most likely you used the `X-API-Key` header — the deployment gateway strips custom headers, so the key never reaches the server. Switch to the **POST body `key` field** (recommended) or the `?key=` parameter. Every successful response carries an `auth` field: `"key"` means your key was recognised, `"anonymous"` means it was not. You can also call `GET /api/header-echo` to see which request headers reach the server (header names only, never values).

**Q · What should I do if my API key leaks?**
A · Contact the service provider immediately to revoke and regenerate it.

---

## 12. Support

| Item | Value |
|---|---|
| Base URL | `https://track.monina.xyz` |
| Health check | `GET /api/health` |
| Status dictionary | `GET /api/status-meta` |
| Header diagnostics | `GET /api/header-echo` (shows which request headers reach the server) |

For technical support or quota adjustments, contact your service representative.

---

*Document version: v1.0 · Updated: 2026-10-16*
