# Gifty integration — partner contract

> **Context.** C3S does **not** have access to the Gifty server, and no official Gifty API documentation has been provided.
> This document is therefore written as the **contract C3S offers to Gifty**: everything C3S needs Gifty to do, in a form the Gifty team can implement or map onto their existing capabilities.
> Nothing here claims that Gifty already supports a given feature. Items marked **[GIFTY DOC REQUIRED]** must be confirmed against official Gifty documentation (or by the Gifty team) before going live.

## 1. Division of responsibilities

| Step | Gifty | C3S |
|---|---|---|
| Show QR | — | generates token, Pi displays QR |
| Scan QR | reads URL, extracts token | — |
| Validate | calls `POST /api/machine/session/validate` | checks token, reserves machine, returns menu |
| Menu & selection | displays products, customer chooses | supplies menu & prices |
| Order | calls `POST /api/orders/create` | creates order, computes amount |
| Payment | **processes payment** (its own payment system) | never sees card data |
| Notification | calls `POST /api/orders/payment-confirmation` (server-to-server, signed) | verifies, queues dispense |
| Progress (optional) | polls `GET /api/orders/status` to show the customer | reports status |
| Refund | executes refunds in Gifty **[GIFTY DOC REQUIRED]** | flags orders needing refunds |

## 2. What we need to receive from Gifty (checklist)

| # | Item | Why | Where it goes in C3S |
|---|---|---|---|
| 1 | **QR / deep-link URL format** the Gifty app recognises (e.g. `https://…/vend?m=…&t=…` or `gifty://…`) **[GIFTY DOC REQUIRED]** | the QR must open Gifty with the token | `config.php` → `qr.url_template` |
| 2 | Confirmation that Gifty can call an external REST API from its backend with custom headers (HMAC scheme §4) **[GIFTY DOC REQUIRED]** | all calls are signed | — |
| 3 | Agreement on the payment-notification payload & **payload signature** (§5), or Gifty's own signature scheme **[GIFTY DOC REQUIRED]** | C3S must verify payments independently | `gifty.verifier` (+ new verifier class if Gifty uses another scheme) |
| 4 | Exact **payment status values** meaning "paid/captured" **[GIFTY DOC REQUIRED]** | only those trigger dispensing | `gifty.success_statuses` |
| 5 | Gifty's outbound **IP addresses** (optional) | firewall allow-list | web server / firewall |
| 6 | **Refund** procedure or API **[GIFTY DOC REQUIRED]** | failed dispenses must be refunded | today: manual, recorded in admin → Payments |
| 7 | Optional: a server-side **"get transaction" API** **[GIFTY DOC REQUIRED]** | second, independent payment check | implement `PaymentVerifierInterface` |
| 8 | Supported currency/currencies | amounts must match exactly | `products.currency` |

What C3S gives Gifty: base URL, `partner_key_id`, `api_secret` (request signing), `webhook_secret` (payload signing) — via a secure channel, never by email in clear.

## 3. Customer flow (Gifty side)

```
scan QR → extract token (query parameter "t" in the default template)
  → POST /api/machine/session/validate {token, client_ref}
       200 → show products (response.products)
       404/410 → "This QR code is no longer valid, please scan the code on the machine screen"
       409 session_in_use → "Someone is already ordering on this machine"
       409 machine_unavailable → "Machine temporarily unavailable"
  → customer selects → POST /api/orders/create {session_id, product_id, quantity:1}
       → charge EXACTLY amount + currency from the response, before payment_deadline
  → payment succeeds in Gifty → POST /api/orders/payment-confirmation (from Gifty's backend, NOT from the customer's phone)
  → optional: poll GET /api/orders/status every 3–5 s to show "preparing… ready"
  → customer cancels → POST /api/machine/session/expire {session_id, reason}
```

Timeouts (defaults, configurable): reservation 300 s after scan; extended by 300 s when the order is created. Payment notifications received after the deadline are recorded and flagged for refund — **nothing is dispensed**.

## 4. Request authentication

Identical to the machine scheme (see `API.md §1`) with `X-Partner-Key`:

```
X-Partner-Key: gifty
X-Timestamp:   1795687421
X-Nonce:       9f86d081884c7d659a2feaa0c55ad015
X-Signature:   hex(hmac_sha256(api_secret, METHOD\nTARGET\nTIMESTAMP\nNONCE\nhex(sha256(body))))
```

Node-free, language-neutral; any HTTP client with HMAC-SHA256 can implement it. `server/tools/gifty_simulator.php` is a complete reference client.

## 5. Payment notification

Sent by Gifty's **backend** once the payment is final. Fields (all required unless noted):

| Field | Type | Notes |
|---|---|---|
| `gifty_transaction_id` | string ≤100 `[A-Za-z0-9._:-]` | unique per payment — idempotency key |
| `machine_id` | string | from the validate response |
| `session_id` | UUID | from the validate response (QR session reference) |
| `order_id` | UUID, optional | from `orders/create`; checked when present |
| `product_id` | int | |
| `product_name` | string | informational |
| `quantity` | int | always 1 |
| `amount` | decimal string | must equal the order amount exactly |
| `currency` | ISO 4217 | must equal the order currency |
| `payment_status` | string | must be in `gifty.success_statuses` to dispense |
| `transaction_timestamp` | ISO-8601 with timezone | |
| `transaction_reference` | string, optional | receipt / reference shown to the customer |
| `signature` | 64 hex | see below |

```
signature = hex(hmac_sha256(webhook_secret,
   gifty_transaction_id + "|" + machine_id + "|" + session_id + "|" + product_id + "|" + quantity
   + "|" + amount + "|" + currency + "|" + payment_status + "|" + transaction_timestamp))
```

**Retries:** on timeout/5xx, resend the identical body (new nonce/timestamp headers). C3S guarantees at-most-once dispensing per `gifty_transaction_id` and per order.

**If Gifty cannot sign payloads this way**: send us its official webhook/signature documentation. A verifier class implementing `server/src/Payment/PaymentVerifierInterface.php` is then added (e.g. RSA/ECDSA signature with Gifty's public key, or a server-side lookup of the transaction through a Gifty API). The rest of C3S does not change. Until verification is possible by one of these means, **do not go live with real payments**.

## 6. Security rules C3S applies to Gifty traffic

* HTTPS only; HMAC per request; ±300 s clock window; single-use nonces.
* Payload signature verified independently of the request signature.
* Amount/product/session/machine re-checked against the server-side order.
* No customer-side redirect or "success page" is ever trusted.
* All notifications are audited (`audit_logs`), all signed ones stored (`payments.raw_payload`).

## 7. Testing without Gifty

```bash
php server/tools/c3s.php current-qr VM-001          # get the current token/QR URL
php server/tools/gifty_simulator.php --base=https://c3s.local --key=gifty \
    --secret="$GIFTY_API_SECRET" --webhook-secret="$GIFTY_WEBHOOK_SECRET" \
    --qr="<qr_url>" --watch
```
Options `--replay`, `--tamper`, `--cancel`, `--status=FAILED` exercise idempotency, signature rejection, cancellation and failed payments (see `TESTING.md`).
