# C3S REST API reference

Base URL: `https://<your-c3s-host>` · JSON only (`Content-Type: application/json`) · UTC ISO-8601 dates · amounts are decimal **strings** (`"14.00"`).

## 1. Authentication (all endpoints)

Every request is signed with HMAC-SHA256.

| Header | Raspberry Pi | Gifty |
|---|---|---|
| `X-Machine-Id` | machine code, e.g. `VM-001` | — |
| `X-Partner-Key` | — | partner key id (config `gifty.partner_key_id`) |
| `X-Timestamp` | unix seconds | unix seconds |
| `X-Nonce` | 16–64 chars `[A-Za-z0-9_-]`, single use | same |
| `X-Signature` | hex HMAC (see below) | same |

```
canonical = METHOD + "\n" + REQUEST_TARGET + "\n" + X-Timestamp + "\n" + X-Nonce + "\n" + hex(sha256(raw_body))
X-Signature = hex(hmac_sha256(secret, canonical))
```

* `REQUEST_TARGET` = path + query string exactly as sent (e.g. `/api/orders/status?order_id=8f…`).
* For GET requests the body is empty: `sha256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`.
* Timestamps must be within ±300 s (keep NTP enabled). Nonces are stored; a reused nonce is rejected (**replay protection**).
* Secrets: machine → per-machine secret (admin → Machines). Gifty → `gifty.api_secret`.

### Reference implementation (PHP)

```php
$ts = (string)time(); $nonce = bin2hex(random_bytes(16)); $body = json_encode($payload);
$sig = hash_hmac('sha256', "POST\n/api/orders/create\n$ts\n$nonce\n" . hash('sha256', $body), $secret);
```

### Error format

```json
{ "error": { "code": "token_expired", "message": "This QR code has expired", "details": {} } }
```

| HTTP | Meaning |
|---|---|
| 400 | malformed JSON |
| 401 | `auth_missing`, `auth_invalid`, `auth_timestamp`, `auth_nonce`, `auth_replay`, `payment_signature_invalid` |
| 403 | `https_required` |
| 404 | resource not found (`token_invalid`, `session_not_found`, `order_not_found`, `command_not_found`, `product_unavailable`) |
| 405 | wrong method |
| 409 | conflict with current state (`machine_unavailable`, `session_in_use`, `order_not_payable`, `invalid_state_transition`, `transaction_conflict`) |
| 410 | gone (`token_expired`, `token_consumed`, `session_expired`) |
| 413 / 415 | body too large / not JSON |
| 422 | `validation_error` (with `details.field`), `quantity_not_supported`, `payment_mismatch`, `confirmation_required` |
| 500 | `internal_error` (details only in server log) |

---

## 2. QR and session management

### POST /api/machine/session/create — *machine*
Returns the machine's current state and QR session, issuing a new session if the machine is AVAILABLE and online. Body: `{}` (empty object allowed).

### GET /api/machine/session/current — *machine*
Same response as `create`; never changes anything except time-based rules (expiry, rotation).

**Response 200** (shared by `session/create`, `session/current`, `raspberry/machine/status`, `raspberry/machine/heartbeat`):
```json
{
  "machine_id": "VM-001",
  "name": "Lobby coffee machine",
  "state": "QR_ACTIVE",
  "state_changed_at": "2026-11-26T10:00:03Z",
  "online": true,
  "session": {
    "session_id": "1b4e28ba-2fa1-4d3b-a3f5-ef19b5a7633b",
    "status": "ACTIVE",
    "expires_at": "2026-11-26T10:15:03Z",
    "reserved_until": null,
    "token": "q8m3lM0b9q1C2pX7Zl2b3cYwP6Qe0yN7VjXk4o9Hh1E",
    "qr_url": "https://<gifty-scan-url>/vend?m=VM-001&t=q8m3lM0b9q1C2pX7Zl2b3cYwP6Qe0yN7VjXk4o9Hh1E"
  },
  "active_order": null,
  "timing": { "completed_display_seconds": 8, "expected_prep_seconds": 60 },
  "server_time": "2026-11-26T10:00:05Z"
}
```
`token` and `qr_url` are only present while the session is `ACTIVE` (QR displayed). During `ORDER_PENDING` the session is `RESERVED` and the QR is not shown.
During a dispense, `active_order` is filled:
```json
"active_order": { "order_id": "8f2a…", "command_id": "c41d…", "product_name": "Cappuccino",
                  "status": "IN_PROGRESS", "progress": 45, "paid_at": "…", "started_at": "…" }
```

### POST /api/machine/session/validate — *Gifty*
Request:
```json
{ "token": "q8m3lM0b9q1C2pX7Zl2b3cYwP6Qe0yN7VjXk4o9Hh1E", "client_ref": "gifty-cust-7781" }
```
`client_ref` (optional, ≤100 chars) is an opaque customer/session reference; re-validating with the same `client_ref` while reserved returns 200 again (page refresh), any other caller gets 409.

Response 200 — machine is now `ORDER_PENDING`, session `RESERVED`:
```json
{
  "valid": true,
  "session_id": "1b4e28ba-2fa1-4d3b-a3f5-ef19b5a7633b",
  "session_status": "RESERVED",
  "reserved_until": "2026-11-26T10:05:10Z",
  "machine": { "machine_id": "VM-001", "name": "Lobby coffee machine", "location": "Main building", "state": "ORDER_PENDING" },
  "products": [
    { "product_id": 2, "sku": "CAPPUCCINO", "name": "Cappuccino", "description": "Espresso with milk foam",
      "image_url": null, "price": "14.00", "currency": "MAD", "prep_time_seconds": 60 }
  ]
}
```
Errors: 404 `token_invalid` · 410 `token_expired` / `token_consumed` · 409 `session_in_use` / `machine_unavailable`.

### POST /api/machine/session/expire — *machine or Gifty*
```json
{ "session_id": "1b4e28ba-2fa1-4d3b-a3f5-ef19b5a7633b", "reason": "customer cancelled" }
```
Response 200:
```json
{ "session_id": "1b4e28ba-…", "status": "CANCELLED", "changed": true, "machine_state": "QR_ACTIVE" }
```
Gifty may only cancel a `RESERVED` session (409 `session_not_reserved` otherwise). Paid sessions are `CONSUMED` and cannot be expired (`changed:false`). A new QR is issued immediately when the machine is online.

---

## 3. Products

### GET /api/machine/products?session_id={uuid} — *Gifty*
Response 200:
```json
{ "session_id": "1b4e…", "machine": { "machine_id": "VM-001", "…": "…" }, "products": [ { "product_id": 2, "…": "…" } ] }
```
Errors: 404 `session_not_found`, 410 `session_expired` / `token_consumed`, 409 `machine_unavailable`.

---

## 4. Orders

### POST /api/orders/create — *Gifty*
```json
{ "session_id": "1b4e28ba-2fa1-4d3b-a3f5-ef19b5a7633b", "product_id": 2, "quantity": 1 }
```
Response **201** (new) or **200** (customer changed selection — same `order_id`):
```json
{
  "order_id": "8f2a6c1e-5b7d-4c1a-9e3f-2d4b6a8c0e1f",
  "session_id": "1b4e28ba-…",
  "machine_id": "VM-001",
  "status": "PENDING_PAYMENT",
  "product": { "product_id": 2, "name": "Cappuccino" },
  "quantity": 1,
  "unit_price": "14.00",
  "amount": "14.00",
  "currency": "MAD",
  "payment_deadline": "2026-11-26T10:06:12Z"
}
```
The price is computed by C3S; Gifty must charge exactly `amount` `currency`. `quantity` must be 1 (one beverage per cycle) → otherwise 422 `quantity_not_supported`. After payment, 409 `order_not_modifiable`.

### GET /api/orders/status?order_id={uuid} — *Gifty*
```json
{
  "order_id": "8f2a…", "session_id": "1b4e…", "machine_id": "VM-001", "machine_state": "PREPARING",
  "status": "IN_PROGRESS", "status_reason": null, "progress": 40,
  "product": { "product_id": 2, "name": "Cappuccino" }, "quantity": 1, "amount": "14.00", "currency": "MAD",
  "created_at": "…", "paid_at": "…", "started_at": "…", "completed_at": null, "refund_required": false
}
```
Order statuses: `PENDING_PAYMENT`, `PAYMENT_CONFIRMED`, `QUEUED`, `PREPARATION_STARTED`, `IN_PROGRESS`, `COMPLETED`, `FAILED`, `UNKNOWN`, `CANCELLED`, `EXPIRED`, `REFUND_REQUIRED`.

### POST /api/orders/payment-confirmation — *Gifty, server-to-server*
```json
{
  "gifty_transaction_id": "GFT-20261126-000123",
  "machine_id": "VM-001",
  "session_id": "1b4e28ba-2fa1-4d3b-a3f5-ef19b5a7633b",
  "order_id": "8f2a6c1e-5b7d-4c1a-9e3f-2d4b6a8c0e1f",
  "product_id": 2,
  "product_name": "Cappuccino",
  "quantity": 1,
  "amount": "14.00",
  "currency": "MAD",
  "payment_status": "SUCCESS",
  "transaction_timestamp": "2026-11-26T10:03:41Z",
  "transaction_reference": "RCPT-99812",
  "signature": "5d41402abc4b2a76b9719d911017c592…(64 hex)"
}
```
`signature = hex(hmac_sha256(webhook_secret, "gifty_transaction_id|machine_id|session_id|product_id|quantity|amount|currency|payment_status|transaction_timestamp"))` with `amount` formatted with 2 decimals. `order_id` and `transaction_reference` are optional.

| Result | HTTP | Body highlights |
|---|---|---|
| Verified, dispense queued | 200 | `accepted:true, order_status:"QUEUED"` |
| Same transaction again | 200 | `duplicate:true` — nothing re-queued |
| Same transaction id, different data | 409 | `transaction_conflict` |
| Payment status not successful | 200 | `accepted:false, verification_result:"NOT_SUCCESSFUL"` |
| Bad payload signature | 401 | `payment_signature_invalid` (not stored as payment, audited) |
| Data ≠ order | 422 | `payment_mismatch`, `refund_required:true` if money was taken |
| Session expired / order already paid | 409 | `order_not_payable`, `refund_required:true` |
| Unknown session | 404 | `session_not_found`, `refund_required:true` |

Success response:
```json
{ "accepted": true, "duplicate": false, "gifty_transaction_id": "GFT-20261126-000123",
  "verification_result": "VERIFIED", "order_id": "8f2a…", "order_status": "QUEUED", "refund_required": false }
```
Gifty should retry on network errors / 5xx with the **same** body (idempotent) and stop on any 2xx/4xx.

---

## 5. Raspberry Pi communication

### POST /api/raspberry/machine/heartbeat — *machine* (every 3 s)
```json
{ "boot": false, "controller_ok": true, "controller_status": "ready",
  "firmware_version": "c3s-vending/1.0.0", "executing_command_id": null }
```
Effects: updates connectivity; `OFFLINE → INITIALIZING → AVAILABLE`; `controller_ok:false` while idle → `ERROR`; applies time rules and issues the next QR. Response: same object as `session/current`.

### GET /api/raspberry/machine/status — *machine*
Same response as `session/current` (used at boot for recovery).

### GET /api/raspberry/commands/pending — *machine* (every 2 s)
```json
{
  "commands": [
    { "command_id": "c41d2b7e-9a0f-4e5c-8b1d-3f6a7e9c2d40", "type": "DISPENSE",
      "order_id": "8f2a…", "selection_code": "A2", "product_name": "Cappuccino", "quantity": 1,
      "status": "DELIVERED", "expected_duration_seconds": 60, "created_at": "2026-11-26T10:03:42Z" }
  ]
}
```
Lists every non-terminal command (also STARTED/IN_PROGRESS, so a restarted Pi can reconcile). The Pi deduplicates with its local journal: a command is triggered at most once.

### POST /api/raspberry/commands/result — *machine*
```json
{ "command_id": "c41d2b7e-…", "phase": "IN_PROGRESS", "progress": 45,
  "confirmed_by_controller": true, "controller_response": "busy 27 s" }
```
| phase | meaning | machine state |
|---|---|---|
| `STARTED` | controller asserted BUSY | `PREPARING` |
| `IN_PROGRESS` | still busy (progress = estimate, max 95) | `PREPARING` |
| `DISPENSING` | controller dispensing signal (optional) | `DISPENSING` |
| `COMPLETED` | BUSY released, no error — **requires `confirmed_by_controller:true`** | `COMPLETED` |
| `FAILED` | definite failure (`error_code` e.g. `NOT_STARTED`, `CONTROLLER_ERROR`) | `ERROR`, refund flagged |
| `UNKNOWN` | outcome uncertain (`TIMEOUT`, `CONTROLLER_RESTART_DURING_DISPENSE`…) | `ERROR`, admin review |

Response:
```json
{ "command_id": "c41d…", "command_status": "IN_PROGRESS", "order_status": "IN_PROGRESS", "machine_state": "PREPARING", "duplicate": false }
```
Reports are idempotent; repeated or out-of-order reports return `duplicate:true`. A late `COMPLETED`/`FAILED` for an order C3S had marked `UNKNOWN` (Pi was offline) is accepted and recorded.

---

## 6. Local display API (Raspberry Pi, 127.0.0.1:8080 — not C3S)

`GET /api/state`
```json
{ "screen": "PREPARING", "detail": "in_progress", "progress": 45, "product": "Cappuccino",
  "qr_version": null, "online": true, "machine_name": "Lobby coffee machine", "machine_id": "VM-001",
  "brand": "C3S", "eta_seconds": 60, "elapsed_seconds": 27, "server_state": "PREPARING", "updated": 1795687421 }
```
`GET /api/qr.svg` → the current QR (404 if none). Screens: `STARTING, AVAILABLE, SESSION_ACTIVE, PAYMENT_CONFIRMED, PREPARING, COMPLETED, ERROR, MAINTENANCE`.
