# Spoonity Wallet API

Spoonity Wallet issues and maintains **Apple Wallet and Google Wallet loyalty passes** for a
merchant's customers. A merchant designs a pass (in Prism's Brand section, or the older Pass
Studio), and their customers add it to their phone's wallet app, where it shows their points
balance, tier, and a barcode their till can scan. Wallet keeps every issued pass up to date:
balance changes, tier changes, and design edits all push a live update to the pass already on a
customer's phone, with no app of the merchant's own required.

This page documents the surface a vendor's own backend or app integrates against: enrolling a
customer into a wallet pass without sending them through Spoonity's own signup page, and keeping
an enrolled member's favorite store current. It also writes up a handful of operator-only routes
that Prism calls (site settings, pass artwork hosting, archiving), and lists the rest of the
service by name near the bottom so the page is honest about what else the host serves.

**Base URL:** `https://wallet-api.spoonity.com`

The service is `Spoonity/spoonity-passkit-integration`. It has no OpenAPI file; this page is its
reference.

## Authentication

Wallet uses **one API key per program**. A "program" is a specific pass design your customers
enroll into (a merchant running two loyalty tiers as separate pass designs would have two
programs, and could generate a separate key for each). This is different from Spoonity CMS and
Links, which issue a key scoped to your whole vendor account: a Wallet key only ever works for the
one `programId` it was generated against, and a request naming a different `programId` is
rejected with a `403`, even if that other program belongs to the same merchant.

Generate a key in Prism under **Settings, API keys** (the Wallet panel, then pick the program), or
from the older Pass Studio's **Integrations** tab while that is still online. Both call the same
`POST /v1/api-keys` route. Send the key as a bearer token:

```
Authorization: Bearer sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

`x-api-key: sk_live_...` is also accepted, but only when no `Authorization` header is present.
Every key Wallet issues is `sk_live_` followed by 43 base64url characters; there are no test-mode
keys. Only a SHA-256 hash is stored server side, so the raw value is shown once, at creation, and
cannot be retrieved again. Generate a new key if you lose it, and revoke the old one.

**Keep this key server side.** It must never ship inside a mobile app bundle or run in a browser.
See [`POST /enroll/app-session`](#post-enrollapp-session) below if your enrollment has to happen
from the customer's own device with no backend of yours in the loop.

## Rate limits

Limits are per client IP over a 15 minute window, and each limit is one shared bucket across
every route that uses it:

| Bucket | Routes | Limit |
|---|---|---|
| API key | `POST /v1/enroll/session`, `POST /v1/members/favorite-store` | 600 requests per 15 minutes, combined |
| Public lookup | `GET /enroll/s/:sessionKey`, `POST /enroll/app-session`, `POST /enroll/app-session/go`, `POST /enroll`, `GET /api/member/:id`, `GET /api/site/*` | 120 requests per 15 minutes, combined |
| Operator login | `POST /auth/login`, `POST /auth/select` | 30 requests per 15 minutes |

Responses carry the standard `RateLimit-Policy`, `RateLimit-Limit`, `RateLimit-Remaining` and
`RateLimit-Reset` headers. A `429` body is the plain-text sentence
`Too many requests, please try again later.`, not JSON, so do not parse it as the usual
`{"error": "..."}` envelope. The operator-session routes documented further down have no rate
limiter.

## Enrolling a customer: how the pieces fit together

The endpoint most integrations need is `POST /v1/enroll/session`. It is the only step that touches
your API key, and it never issues a pass directly. It hands you a one-time link, and the actual
pass is issued when your customer opens it. A typical integration looks like this:

1. **Your customer signs up or logs in on your own site or app**, the way they always do. Wallet
   is never involved in this step and never sees a password or your login flow. It only needs a
   name, an email, and a stable id you already have for this customer.
2. **Your backend calls `POST /v1/enroll/session`**, sending that customer's name, email, and your
   own id for them, authenticated with your program's API key. You must already have this
   customer's explicit consent to enroll them in the loyalty program before you make this call.
3. **Wallet creates a single-use enrollment session** (15 minute time to live) and responds with
   an opaque `sessionUrl`. No customer data travels in that URL. If this customer (by your
   `externalId`) already has a pass in this program, you get `alreadyEnrolled: true`, and the link
   takes them to their existing pass instead of creating a duplicate.
4. **Your backend sends the customer to `sessionUrl`** however fits your flow: an HTTP redirect
   right after signup, a link in a welcome email, an SMS, or a button in your app.
5. **The customer's browser opens that link.** Wallet atomically claims the session (so it can
   only ever be used once), issues the Apple or Google Wallet pass, and redirects them to their
   device's Add to Wallet page. If the link was already used or its 15 minutes ran out, the
   customer sees an expired-link page instead. Call step 2 again to mint a fresh one.
6. **The customer taps Add to Apple Wallet or Save to Google Wallet.** From here, Wallet owns
   keeping the pass current; you don't call anything further for the pass itself to keep working.

The `sessionUrl` host is Wallet's customer-facing pass domain, which today is
`https://pass.spnty.co`, not `wallet-api.spoonity.com`. Both hostnames are the same service. Treat
the whole URL as opaque and send the customer to it exactly as returned.

If you already know one of a customer's phone number, your own merchant card number, an imported
partner card number, or a Spoonity shortcode/token, you can pass it in step 2 alongside `user`.
See [`POST /v1/enroll/session`](#post-v1enrollsession)'s body parameters below. Wallet's own signup
form only ever collects a name and email, so it never generates these itself; sending one is a
pass-through for a store that already has it, and it only changes anything if the pass's barcode
is configured (in the pass designer's **Barcode** setting) to encode that same source. Whatever
source a pass encodes, a member with no value on file for it falls back, first to `phone` or a
live barcode token if one is on file, otherwise to their email, rather than the barcode ever being
left empty or the call failing. A barcode token whose recorded expiry has passed counts as absent.

**When step 2 is authenticated with `spoonitySessionKey` instead of a `user` object, Wallet also
mints this customer's barcode token for you, automatically.** Spoonity's own token-minting
endpoint (`POST /user/token/request`) only accepts a customer's session key, and there is no
operator-token equivalent anywhere in the platform, so the session-key flow is the only moment
Wallet can capture one. It calls that endpoint itself while it still holds the session key, and
stores the result (`barcodeToken` and `barcodeTokenExp`) on the enrollment session next to the
member's name and email. The same capture runs on `POST /enroll/app-session`, below, which is
session-key-authenticated by construction. A `barcodeToken` you send explicitly always wins;
minting is only a fallback for the common case where nobody supplied one. It is best effort: a
mint failure just leaves the member on an email barcode. It never shows up on the wire, either:
the response shape stays `{sessionUrl, expiresAt, alreadyEnrolled}`, so nothing about the
member's token travels back to a browser or into a store's own logs. The captured value is stored
and encoded on the pass **verbatim**, because Spoonity's mint API already applies the vendor's own
Barcode Behaviour setting.

## Endpoints

### POST /v1/enroll/session

Pre-enroll an already-authenticated customer of yours and get back a one-time link that issues
their wallet pass.

#### Auth

Per-program API key (`Authorization: Bearer sk_live_...` or `x-api-key`). The `programId` in the
request body must match the key's own program.

#### Body parameters

| Field | Type | Required | Notes |
|---|---|---|---|
| `programId` | string | yes | Must match the program your API key was issued for. |
| `consentGiven` | boolean | yes | Must be `true`. You must already have the customer's explicit consent to enroll them. |
| `user.name` | string | yes* | Display name on the pass. |
| `user.email` | string | yes* | Must be a valid email address. Stored lower-cased. |
| `user.externalId` | string | yes* | Your own stable id for this customer. It is also the de-duplication key: calling this again with the same `externalId` returns `alreadyEnrolled: true` and leads to the existing pass rather than a duplicate. |
| `spoonitySessionKey` | string | yes* | Alternative to `user`: a live Spoonity session key for this customer, if you already hold one. Wallet looks up their name, email and Spoonity user id from Spoonity directly (the user id becomes `externalId`) and mints their barcode token (see above). |
| `phone` | string | no | The customer's phone number, if you already have it. |
| `cardNumber` | string | no | Your own merchant loyalty card number for this customer, if you already have it. |
| `card3rdpartyNumber` | string | no | An imported or partner card number for this customer, if you already have it. Distinct from `cardNumber`: a merchant's till may accept one and not the other. |
| `barcodeToken` | string | no | A Spoonity shortcode or token already minted for this customer, if you already have it. Wins over any token Wallet would otherwise mint from `spoonitySessionKey`. Stored and encoded on the pass exactly as sent. |

\* Send either `user` (with `name`, `email` and `externalId` all present) **or**
`spoonitySessionKey`. If both are present, `spoonitySessionKey` is used and `user` is ignored.

#### Request

```bash
curl -X POST https://wallet-api.spoonity.com/v1/enroll/session \
  -H "Authorization: Bearer sk_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "programId": "YOUR_PROGRAM_ID",
    "user": {
      "name": "Jane Doe",
      "email": "jane@example.com",
      "externalId": "your_user_id_123"
    },
    "consentGiven": true
  }'
```

#### Response

```json
{
  "sessionUrl": "https://pass.spnty.co/enroll/s/kQ2fN8pXw1vC7hT4rY9zLmB6",
  "expiresAt": "2026-08-31T16:45:00.000Z",
  "alreadyEnrolled": false
}
```

| Field | Notes |
|---|---|
| `sessionUrl` | Single use, expires in 15 minutes. Send the customer here to complete enrollment. The key in the path is 43 base64url characters (32 random bytes); the example above is shortened. |
| `expiresAt` | When the link stops working. Call this endpoint again to mint a fresh one if it lapses unused. |
| `alreadyEnrolled` | `true` if this `externalId` already had a pass for this program. The link still works and takes them to their existing pass. |

#### Errors

Error bodies are `{"error": "<sentence>"}`.

| Status | Meaning |
|---|---|
| 400 | Missing or non-string `programId`; `consentGiven` not `true`; neither `user` nor `spoonitySessionKey` given; or a `user` field missing or invalid (for example `user.email` not a valid address). |
| 401 | Missing API key, a value that does not start with `sk_`, or an invalid or revoked key. On the session-key flow, also an invalid or expired `spoonitySessionKey`. |
| 403 | `programId` doesn't match the API key's own program (`programId does not match this API key's scope.`). |
| 429 | Rate limit exceeded (600 requests per 15 minutes per IP, shared with `POST /v1/members/favorite-store`). Plain-text body. |
| 500 | Server error, including a failed key lookup; safe to retry. |

### GET /enroll/s/:sessionKey

Not an endpoint you call directly. It's the link your customer's browser follows to finish
enrollment, documented here because it's part of the flow above: it claims the single-use
session, issues the pass, and redirects the browser to the customer's Add to Wallet page.

#### Auth

None. The session key itself (32 random bytes) is the credential, and it works exactly once.

#### Path parameters

| Field | Type | Required | Notes |
|---|---|---|---|
| `sessionKey` | string | yes | The opaque token from `sessionUrl`. You never construct this yourself. |

#### Request

```bash
curl -i https://pass.spnty.co/enroll/s/kQ2fN8pXw1vC7hT4rY9zLmB6
```

#### Response

A `302` redirect to the customer's Add to Wallet page (`/passes/:memberId` on the same pass
domain) on success. There is no JSON body on the success path; send the browser here and let it
follow the redirect.

#### Errors

Every error is an HTML page for the customer, not JSON.

| Status | Meaning |
|---|---|
| 400 | Malformed session key (anything outside `[A-Za-z0-9_-]`). |
| 410 | Link already used or its 15 minute window expired. Call `POST /v1/enroll/session` again for a fresh one. |
| 429 | Rate limit exceeded (the shared 120 per 15 minutes public-lookup bucket). Plain-text body. |
| 500 | Pass issuance failed; the customer sees an error page and should be sent back to your enrollment flow. |

### POST /enroll/app-session

The mobile-app equivalent of `POST /v1/enroll/session`, for when there is no backend of yours in
the loop. Your app calls it directly, with no API key involved. It's authenticated by the
customer's own live Spoonity session key instead, which proves the caller is the customer being
enrolled without ever shipping a server secret inside your app.

#### Auth

None (no API key). Authenticity comes from the request body's `spoonitySessionKey`, which Wallet
resolves against the program's own vendor, so it cannot be used to enroll anyone other than the
customer it belongs to.

#### Body parameters

| Field | Type | Required | Notes |
|---|---|---|---|
| `programId` | string | yes | The program to enroll into. |
| `spoonitySessionKey` | string | yes | The customer's own live Spoonity session key. |
| `consentGiven` | boolean | yes | Must be `true`. |

The alternate barcode fields (`phone`, `cardNumber`, `card3rdpartyNumber`, `barcodeToken`) are not
accepted here.

#### Request

```bash
curl -X POST https://wallet-api.spoonity.com/enroll/app-session \
  -H "Content-Type: application/json" \
  -d '{
    "programId": "YOUR_PROGRAM_ID",
    "spoonitySessionKey": "the-customers-live-session-key",
    "consentGiven": true
  }'
```

#### Response

```json
{
  "sessionUrl": "https://pass.spnty.co/enroll/s/aB3dE9fGhJ2kL5mN8pQr1sTu",
  "expiresAt": "2026-08-31T16:45:00.000Z",
  "alreadyEnrolled": false
}
```

Same shape and meaning as `POST /v1/enroll/session`'s response, above. Like that endpoint's
session-key flow, this route also mints and stores the member's barcode token from
`spoonitySessionKey` while it's still held. See
[Enrolling a customer](#enrolling-a-customer-how-the-pieces-fit-together), above.

On Android, open `sessionUrl` from a link the customer actually taps, or use the form variant
`POST /enroll/app-session/go` (listed at the bottom of this page): Chrome only hands a navigation
to the Google Wallet app when it carries a user gesture.

#### Errors

| Status | Meaning |
|---|---|
| 400 | Missing or non-string `programId`, `consentGiven` not `true`, or missing `spoonitySessionKey`. |
| 401 | Invalid or expired Spoonity session key. |
| 404 | `programId` doesn't exist. |
| 429 | Rate limit exceeded (the shared 120 per 15 minutes public-lookup bucket). Plain-text body. |
| 500 | Server error; safe to retry. |

### POST /v1/members/favorite-store

Refresh an **existing** wallet-pass member's favorite store, so a pass that shows a nearest or
favorite location keeps it current. This is not part of enrollment (a brand-new member may have
no purchase history yet to rank a favorite from). Wallet also refreshes the same field by itself
on every Spoonity balance-update webhook, so this route is the pull-based option for a caller that
has a Spoonity user id but no event to ride on.

#### Auth

Per-program API key (`Authorization: Bearer sk_live_...` or `x-api-key`). Same key as
`POST /v1/enroll/session`.

#### Body parameters

| Field | Type | Required | Notes |
|---|---|---|---|
| `programId` | string | yes | Must match the API key's own program. |
| `spoonityUserId` | string or number | yes | The customer's Spoonity user id. It is matched against the member's `externalId`, which is the Spoonity user id for anyone enrolled with `spoonitySessionKey`, or whatever you sent as `user.externalId`. |

#### Request

```bash
curl -X POST https://wallet-api.spoonity.com/v1/members/favorite-store \
  -H "Authorization: Bearer sk_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "programId": "YOUR_PROGRAM_ID",
    "spoonityUserId": "123456"
  }'
```

#### Response

```json
{
  "ok": true,
  "updated": true,
  "favoriteLocation": {
    "storeId": "4410",
    "name": "Example Coffee Co, Main Street",
    "lat": 43.6532,
    "lon": -79.3832,
    "address": "100 Main Street",
    "favoriteProduct": "Latte",
    "geofenceable": true
  }
}
```

`updated` is `false` (not an error) when the customer has no ranked favorite location yet, or the
ranking service could not be reached. In that case `favoriteLocation` is `null` and whatever was
previously on file is left untouched.

The best-ranked store is named whenever one is known, even when it has no geocode on file; then
`lat` and `lon` are `null` and `geofenceable` is `false`. `address` and `favoriteProduct` are
`null` when unknown. This same shape is what `GET /v1/programs/:programId/members` returns per
member. Records written before `geofenceable` existed carry no such key at all; treat that as
`lat != null && lon != null` rather than as "not geofenceable".

#### Errors

| Status | Meaning |
|---|---|
| 400 | Missing `programId` or `spoonityUserId`. |
| 401 | Missing, invalid, or revoked API key. |
| 403 | `programId` doesn't match the API key's own program. |
| 404 | This customer doesn't have a wallet pass in this program yet. |
| 429 | Rate limit exceeded (600 requests per 15 minutes per IP, shared with `POST /v1/enroll/session`). Plain-text body. |
| 500 | Server error; safe to retry. |

## Site settings

Three routes that read and write a program's **public microsite** (the customer-facing site at
`wallets.spoonity.com/<slug>`, or a vendor's own custom domain): its language, per-section colour
overrides, legal pages, and developer-mode CSS/HTML, plus the public address itself (`slug` and
`siteDomain`). They power Prism's site editor at `/brand/site` (the old `/wallet/site` path
redirects there; see `docs/design/site-editor-plan.md` in the Prism repository).

**Why this exists at all:** the public microsite renders the same program document that
`POST /design` writes, but `POST /design` re-provisions the entire pass: it re-uploads images,
re-upserts every Apple and Google Wallet class, then pushes an APNs update to every device that
holds the pass. That's a lot of machinery for saving a privacy-policy edit. These routes write the
same program document fields and trigger **none** of that pass-provisioning work. This is
enforced, not just documented: `test/site-admin.test.js` in `Spoonity/spoonity-passkit-integration`
statically walks the handler's import graph and fails if it ever reaches the pass-provisioning
modules, and separately asserts that a publish only touches `wallet_programs`, `site_slugs` and
`site_domains` in Firestore.

**`POST /design` still accepts the four site-only fields today, gated by
`DESIGN_ACCEPTS_SITE_FIELDS` (default `true`, and unset in production).** While the flag is on,
which covers the legacy Brand Editor on `wallets.spoonity.com` until it's retired, a `/design`
body carrying `legal`, `language`, `sectionColors`, or `dev` still applies them. Once the flag is
`false`, `/design` drops those four keys before provisioning (the program's live values are left
untouched) and adds a `warnings` entry to its response if the body carried any of them; the design
itself still succeeds. `slug` and `siteDomain` are **not** covered by this flag: `POST /design`
legitimately sends both.

**Ownership split.** These routes own the site-only fields (`language`, `sectionColors`, `legal`,
`dev`) plus the public address (`slug`, `siteDomain`). Name, company, colours, logo, icon and hero
image are the **pass's** fields, set via `POST /design`, and the site inherits them read-only
(returned under `inherited`, below). These routes never accept or change them; other keys in the
body are ignored, not rejected.

**Auth is different from the API-key endpoints above.** There is no `sk_live_` program key here.
All three routes use Wallet's operator gate (`requireAuth`): either a signed-in operator session
(the `spoonity_session` cookie, or the same token as `Authorization: Bearer`), or a Google-signed
OIDC ID token from an allow-listed service account (today only Prism's BFF) with
`X-Spoonity-Vendor` naming the tenant. See
[Authentication](./authentication.md#service-to-service-internal--not-callable-by-integrators).
The caller's authorized vendor list, not a per-program key, is what scopes access: the route 404s
for an unknown `programId` and 403s when the program's `vendorId` isn't in that list.

There is no rate limiter on these three routes. The request body is subject to the service's
default 512 KB JSON body limit (`/v1/programs/*` is not on the 10 MB allow-list reserved for
image-carrying routes like `/design`).

### GET /v1/programs/{programId}/site

Everything about a program's site: what's live, what's drafted but not yet published, and the
pass-owned fields the editor shows read-only.

#### Auth

Operator session or Prism service identity (see above). The program's `vendorId` must be in the
caller's authorized vendor list.

#### Path parameters

| Field | Type | Required | Notes |
|---|---|---|---|
| `programId` | string | yes | The program whose site settings to read. |

#### Request

```bash
curl https://wallet-api.spoonity.com/v1/programs/YOUR_PROGRAM_ID/site \
  -H "Authorization: Bearer <operator session token>"
```

#### Response

```json
{
  "live": {
    "programId": "prog-a",
    "vendorId": "101",
    "slug": "acme",
    "siteDomain": null,
    "siteUrl": "https://wallets.spoonity.com/acme",
    "enrollUrl": "https://pass.spnty.co/enroll/prog-a?v=101",
    "name": "Acme Rewards",
    "company": "Acme",
    "colors": { "background": "#101820", "foreground": "#ffffff", "label": "#F47920" },
    "logo": "https://img/logo.png",
    "icon": "https://img/icon.png",
    "strip": "https://img/hero.png",
    "pointsLabel": null,
    "language": "en",
    "sectionColors": { "--color-primary": "#1B3564" },
    "legal": { "privacy": "<p>...</p>", "terms": null, "cookies": null, "accessibility": null, "custom": [] },
    "dev": { "css": ".old{}", "html": null }
  },
  "draft": null,
  "inherited": {
    "name": "Acme Rewards",
    "company": "Acme",
    "colors": { "background": "#101820", "foreground": "#ffffff", "label": "#F47920" },
    "logo": "https://img/logo.png",
    "icon": "https://img/icon.png",
    "strip": "https://img/hero.png"
  }
}
```

| Field | Notes |
|---|---|
| `live` | What the microsite renders right now: `programId`, `vendorId`, `slug`, `siteDomain`, `siteUrl`, `enrollUrl`, `name`, `company`, `colors`, `logo`, `icon`, `strip`, `pointsLabel`, plus the four site-only fields `language`, `sectionColors`, `legal`, `dev`. `siteUrl` is `https://<siteDomain>` when the program has a custom domain, otherwise `https://wallets.spoonity.com/<slug>`, or `null` if it has neither. `enrollUrl` is Wallet's own hosted signup form on the pass domain. |
| `draft` | `null` when nothing is drafted, otherwise whatever subset of the patch fields (see `PUT .../site/draft` below) was last autosaved, plus `updatedAt`. |
| `inherited` | The pass-owned fields the site editor shows read-only: `name`, `company`, `colors`, `logo`, `icon`, `strip`. Set these via `POST /design`, not here. |
| `warnings` | Never present on `GET`. It only appears on `PUT .../site`, and only when non-empty. |

#### Errors

| Status | Meaning |
|---|---|
| 401 | No valid operator session or service identity. |
| 403 | The program exists, but its `vendorId` is not in the caller's authorized vendor list. |
| 404 | `programId` does not match any program. |
| 500 | Server error; safe to retry. |

### PUT /v1/programs/{programId}/site

Publish: patch the live site fields and, if `slug` or `siteDomain` is included, claim the public
address. On success, any autosaved draft is cleared: a publish consumes the draft, since the
fields it carried are now live.

#### Auth

Same as `GET`, above.

#### Body parameters

**Patch semantics apply to every field below:** a key **absent** from the body is left untouched;
a key present with **`null`** clears it; a key present with **a value** replaces it. Nested
objects (`sectionColors`, `legal`, `dev`) are replaced **wholesale**, never deep-merged. A patch
that fails validation is rejected **as a whole**, and nothing partially applies.

| Field | Type | Notes |
|---|---|---|
| `slug` | string or null | The program's address on the shared `wallets.spoonity.com` domain. Normalized: lower-cased, accents stripped, any run of characters outside `[a-z0-9]` collapsed to a single `-`, leading and trailing `-` trimmed, capped at 48 characters. A value that normalizes to nothing (for example `"???"`) clears the address, the same as sending `null`. A non-string is a 400 (`slug must be a string`). **Not rejected here if reserved or taken**: that's resolved at claim time (see below) and reported as a `warnings[]` entry, not a 400. |
| `siteDomain` | string or null | A custom hostname (for example `rewards.acme.com`). Lower-cased; a leading `http://` or `https://`, any path, and any `:port` are stripped before validating. Must have at least two dot-separated labels, each 1 to 63 characters of `[a-z0-9]` with optional internal hyphens (no label may start or end with `-`), total length at most 253 characters. A bare word like `"acme"` is a 400 (`siteDomain "acme" is not a valid hostname`). An empty string clears it, like `null`. |
| `language` | string or null | One of `en`, `es`, `fr`, `pt` (case-insensitive, trimmed). An empty string clears it. Anything else is a 400: `language must be one of en, es, fr, pt`. |
| `sectionColors` | object or null | A map of CSS custom-property name to colour override, for the 33 variables the microsite's Brand Editor exposes: `--color-primary`, `--color-primary-600`, `--color-primary-700`, `--color-primary-050`, `--color-primary-100`, `--color-accent`, `--color-accent-050`, `--color-ink`, `--color-body`, `--color-muted`, `--color-surface`, `--color-bg`, `--color-border`, `--color-border-strong`, `--header-bg`, `--hero-spot-1`, `--hero-spot-2`, `--pass-bg-1`, `--pass-bg-2`, `--pass-bg-3`, `--pass-text`, `--pass-text-muted`, `--pass-barcode`, `--btn-primary-bg`, `--btn-primary-fg`, `--btn-primary-hover`, `--cta-bg-end`, `--footer-bg-1`, `--footer-bg-2`, `--footer-border`, `--footer-text`, `--footer-nav-text`, `--footer-legal`. A key outside this list is a 400 (`sectionColors: "<key>" is not a known site colour variable`). Each value must be `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb(...)` or `rgba(...)` (inside the parentheses only digits, `.`, `%`, `,`, `/` and whitespace are accepted); anything else is a 400 (`sectionColors: "<key>" must be a hex or rgb()/rgba() colour`). An empty string or `null` for a key clears that one variable (it falls back to the pass's own colours); an object left with no overridden keys is stored as `null`. |
| `legal` | object or null | Four fixed pages plus up to 6 custom ones. Shape: `{ privacy, terms, cookies, accessibility, custom }`. Each of `privacy`, `terms`, `cookies` and `accessibility` is an HTML string, or `null` or empty to clear that page; each is capped at **32 KB** measured on the raw input, before sanitizing (a 400 if exceeded: `legal.<page> is over the 32 KB limit`). `custom` is an array of at most **6** pages (a 400 above that: `legal.custom may hold at most 6 pages`), each `{ id, title, body }`. `id` is derived from the input (lower-cased, runs outside `[a-z0-9_-]` replaced with `-`, trimmed, capped at 64 characters), must be non-empty, and must not collide with a fixed key or another custom page's id (400 if it does). `title` is plain text (any markup stripped), capped at 120 characters, and required. `body` is HTML with the same 32 KB raw-input cap, optional. **Every legal HTML field is sanitized server side**: only `p`, `br`, `strong`, `b`, `em`, `i`, `u`, `ul`, `ol`, `li`, `h3`, `h4`, `blockquote` and `div` survive; every attribute is stripped (no `href`, `style`, `id` or `class`); `script`, `style`, `iframe`, `object` and `embed` are removed together with their contents; every other disallowed tag is unwrapped (content kept, tag dropped); comments and doctype or processing-instruction nodes are dropped; stray `<` and `>` are escaped; and the result is well formed. The response always echoes the sanitized HTML, never the input. |
| `dev` | object or null | `{ css, html }`, each a string, or `null` or empty to clear that one, each capped at **64 KB** of UTF-8 (a 400 if exceeded: `dev.css is over the 64 KB limit` or `dev.html is over the 64 KB limit`). **Not sanitized**, by design: it is the one place an admin can inject arbitrary markup or CSS, which is why Prism shows the field to admin-role operators only. This route's only job is the size cap, which keeps a runaway paste from pushing the program document over Firestore's 1 MiB document limit. An object left with no `css` and no `html` is stored as `null`. |

A body that is not a JSON object is a 400 (`request body must be a JSON object`).

#### Request

```bash
curl -X PUT https://wallet-api.spoonity.com/v1/programs/YOUR_PROGRAM_ID/site \
  -H "Authorization: Bearer <operator session token>" \
  -H "Content-Type: application/json" \
  -d '{
    "language": "fr",
    "sectionColors": { "--color-primary": "#1B3564" },
    "legal": { "privacy": "<p>Updated privacy policy.</p>" }
  }'
```

#### Response

`200` on success, with the same shape as `GET`'s response, above, reflecting the write (`draft`
is `null`), plus `warnings` when there is something to report:

```json
{
  "live": { "...": "as GET, above, with the patched fields applied" },
  "draft": null,
  "inherited": { "...": "as GET, above" },
  "warnings": ["the address \"beta\" is already taken"]
}
```

| Field | Notes |
|---|---|
| `warnings` | **Present only when non-empty.** A publish that otherwise succeeded but couldn't claim the requested address: `slug` is a reserved word (`"<slug>" is a reserved address`) or already claimed by a different program (`the address "<slug>" is already taken`); `siteDomain` is already registered to a different program (`the domain "<domain>" is already registered to another program`). In each case the rest of the patch still publishes, and the program's own `slug` or `siteDomain` is left as it was (the response's `live.slug` and `live.siteDomain` reflect what's actually registered). Re-claiming the slug a program already holds is idempotent and never warns. |

**The address is claimed before the program document is written**, and the document only records
a slug or domain the registry accepted. `POST /design` uses the same contract for `slug`; this
route also applies it to `siteDomain`, so a hostname already registered to a different program is
reported rather than overwritten. Clearing an address (`slug: null` or `siteDomain: null`)
releases its registry row, not just the program's own copy. On success, `siteDraft` is cleared,
**even when a warning was raised**, since the rest of the patch did publish.

#### Errors

| Status | Meaning |
|---|---|
| 400 | The body isn't a JSON object, or the first field that fails validation (see the table above). The body is `{ "error": "<message>" }` with one of the messages listed above. |
| 401 | No valid operator session or service identity. |
| 403 | The program exists, but its `vendorId` is not in the caller's authorized vendor list. |
| 404 | `programId` does not match any program. |
| 500 | Server error; safe to retry. |

### PUT /v1/programs/{programId}/site/draft

Autosave: the same body and validation, patched into `program.siteDraft` instead of the live
fields, so the editor can save as the operator types without publishing anything. Unlike
`PUT .../site`, this route makes **no registry claims**: a `slug` typed into a draft that another
program already holds never warns, because nothing was claimed. Any clash is evaluated only when
the operator publishes.

#### Auth

Same as `GET`, above.

#### Body parameters

Identical to `PUT /v1/programs/{programId}/site`, above: same fields, same validation, same
messages. Both routes call the same validator, so a draft can never hold something a publish
would refuse.

One difference in how the result is stored: `siteDraft` is **merged** with whatever was already
drafted (`{ ...existing, ...patch, updatedAt: <now, ISO 8601> }`), so a second autosave that only
sends `dev` leaves an earlier-drafted `language` in place. A key present in this request with
`null` **is stored as `null` in the draft** (not dropped), because it records the operator's
intent to clear that field on the next publish.

#### Request

```bash
curl -X PUT https://wallet-api.spoonity.com/v1/programs/YOUR_PROGRAM_ID/site/draft \
  -H "Authorization: Bearer <operator session token>" \
  -H "Content-Type: application/json" \
  -d '{ "language": "fr", "dev": null }'
```

#### Response

`200`, same shape as `GET`'s response, above. `draft` reflects the merged draft (including its
`updatedAt`); `live` is unchanged, since nothing was published. `warnings` never appears on this
route's response.

#### Errors

| Status | Meaning |
|---|---|
| 400 | Same validation failures as `PUT /v1/programs/{programId}/site`, above. |
| 401 | No valid operator session or service identity. |
| 403 | The program exists, but its `vendorId` is not in the caller's authorized vendor list. |
| 404 | `programId` does not match any program. |
| 500 | Server error; safe to retry. |

## Pass artwork hosting

`POST /media/pass-image` resizes an operator-uploaded pass image to the exact size its slot needs,
hosts it in the vendor's **Spoonity CMS** media library, and returns the URL a draft should store
instead of the image's raw bytes.

**Why this exists:** drafts are Firestore documents, capped at 1 MiB. Inlining artwork as base64
`data:` URIs, with base64's own roughly 33% inflation, was enough on its own to push a real
vendor's draft past that cap and make every autosave fail. Hosting the bytes and storing a URL
takes one image slot from roughly 600 KB of document down to about 100 bytes. Every image this
returns is re-encoded as **PNG**, which matters: the pass-building pipeline embeds these files'
bytes verbatim into the signed `.pkpass`, and JPEG bytes in a file Apple expects as PNG is invalid
pass data. Wallet can respond to an invalid update by removing the pass from the customer's device.

### POST /media/pass-image

Resize and host one pass image, and return its hosted URL.

#### Auth

Operator session or Prism service identity, the same gate as [Site settings](#site-settings),
above. The vendor is the session's active vendor by default; an explicit `vendorId` in the body
must be in the caller's authorized vendor list.

#### Body parameters

| Field | Type | Required | Notes |
|---|---|---|---|
| `type` | string | yes | Which pass slot this image is for, and its target size: `hero` 1032 x 336, `strip` 1125 x 432, `icon` 180 x 180, `logo` 660 x 660. `hero`, `strip` and `icon` are cropped to fill exactly that size; `logo` only ever scales down to fit inside its box, never up and never cropped. |
| `image` | string | yes | A `data:` URI or a bare base64 string. An already-hosted `https://` URL is rejected; there's nothing to upload. |
| `vendorId` | string | no | Defaults to the session's active vendor. An explicit value must be in the caller's authorized vendor list. |

#### Example request

```bash
curl -X POST https://wallet-api.spoonity.com/media/pass-image \
  -H "Authorization: Bearer <operator session token>" \
  -H "Content-Type: application/json" \
  -d '{ "type": "icon", "image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." }'
```

#### Example response

```json
{
  "ok": true,
  "url": "<the CMS asset's original_url>",
  "assetId": "media_8f2a",
  "width": 180,
  "height": 180,
  "bytes": 24186
}
```

`url` is the CMS asset's format-preserved `original_url` (the PNG), not its WebP rendition, which
neither Google's image fetcher nor Apple's `.pkpass` builder accepts. `width` and `height` are the
slot's target size; for a `logo` that was already smaller than 660 x 660 they are the box, not the
image's own dimensions. The asset is uploaded to the vendor's `wallet-passes` media folder and
marked `protected` so a dashboard tidy-up can't hard-delete an image a live pass still points at
(best effort: a failure to mark it doesn't fail the upload).

#### Errors

Error bodies are `{"error": "<code>", "message": "<sentence>"}`.

| Status | Code | Meaning |
|---|---|---|
| 400 | `no_image` | the `image` field is empty |
| 400 | `already_hosted` | an `https://` URL was sent instead of raw image bytes |
| 400 | `bad_image` | the bytes don't decode as a readable image |
| 400 | `unknown_type` | `type` isn't one of `hero`, `strip`, `icon`, `logo` |
| 401 | | no valid operator session or service identity (body is `{"error": "<sentence>"}`) |
| 403 | `no_vendor` | no active vendor in the session, or an explicit `vendorId` outside the caller's authorized vendor list |
| 413 | `image_too_large` | the decoded input is over 8 MB, checked on the base64 length before any bitmap is allocated |
| 502 | `cms_upload_failed` | the CMS rejected or errored on the upload |
| 503 | `cms_unconfigured` | no CMS service identity or API key is available in this environment (a local dev box, not a broken deployment) |

A draft that still ends up over Firestore's document cap gets a
`413 {"error": "draft_too_large", "message": "..."}` from `POST /drafts` instead, naming the
oversized image slot, not a bare `500`.

## Archiving programs and drafts

Retire a published pass or an in-progress draft without deleting it. An archived program's or
draft's card drops out of the designer's normal lists, but a member's existing pass in that
program keeps working exactly as before, and either can be restored later. Same operator-only auth
as [Site settings](#site-settings), above, scoped by the caller's active or authorized vendor, not
an `sk_live_` API key.

### GET /v1/programs

The active vendor's published programs (not drafts), which is what the pass designer's "Created
passes" grid and the Analytics program picker list from.

#### Auth

Operator session or Prism service identity, scoped to the session's active vendor.

#### Query parameters

| Field | Type | Required | Notes |
|---|---|---|---|
| `includeArchived` | `"1"` or `"true"` | no | When present, archived programs are included in `programs` too. They're filtered out by default. |

#### Example request

```bash
curl "https://wallet-api.spoonity.com/v1/programs?includeArchived=1" \
  -H "Authorization: Bearer <operator session token>"
```

#### Example response

```json
{
  "programs": [{ "programId": "prog-a", "name": "Acme Rewards", "...": "the full pass-state shape" }],
  "archivedProgramIds": ["prog-b"]
}
```

`archivedProgramIds` is returned on **every** call, regardless of `includeArchived`. It's how the
drafts view (which carries its own copy of a program's design) knows to stop showing a card for a
pass the vendor just archived.

#### Errors

| Status | Meaning |
|---|---|
| 400 | No active vendor in the session. |
| 401 | No valid operator session or service identity. |
| 500 | Server error; safe to retry. |

### POST /v1/programs/{programId}/archive

Archive a published program, or restore one with `{ "archived": false }`.

#### Auth

Operator session or Prism service identity, scoped to the session's active vendor.

#### Path parameters

| Field | Type | Required |
|---|---|---|
| `programId` | string | yes |

#### Body parameters

| Field | Type | Required | Notes |
|---|---|---|---|
| `archived` | boolean | no | Defaults to `true`. Send `false` to restore. |

#### Example request

```bash
curl -X POST https://wallet-api.spoonity.com/v1/programs/YOUR_PROGRAM_ID/archive \
  -H "Authorization: Bearer <operator session token>" \
  -H "Content-Type: application/json" \
  -d '{ "archived": true }'
```

#### Example response

```json
{ "programId": "prog-a", "archived": true }
```

Publishing a program again (another `POST /design` against it) always lifts its archive.

#### Errors

| Status | Meaning |
|---|---|
| 400 | No active vendor in the session. |
| 401 | No valid operator session or service identity. |
| 404 | `programId` doesn't belong to the active vendor. |
| 500 | Server error; safe to retry. |

### GET /drafts

Lists this vendor's editor drafts, newest first. Otherwise not part of the documented surface
(see [Other wallet-api endpoints](#other-wallet-api-endpoints-not-part-of-this-integration-surface),
below); called out here only for its archive-related query parameter:

| Field | Type | Required | Notes |
|---|---|---|---|
| `includeArchived` | `"1"` or `"true"` | no | Include archived drafts in the result. The designer's normal "Load draft" picker omits it; only its collapsed "Show archived" section asks for them. |
| `vendorId` | string | no | Explicit vendor, which must be in the caller's authorized vendor list; defaults to the session's active vendor. |

### POST /drafts/{id}/archive

Archive an in-progress draft (one with no published program of its own yet), or restore one with
`{ "archived": false }`. The published-pass equivalent is `POST /v1/programs/{programId}/archive`,
above.

#### Auth

Operator session or Prism service identity. 403s if the draft belongs to a different vendor, 404s
if it doesn't exist.

#### Path parameters

| Field | Type | Required |
|---|---|---|
| `id` | string | yes |

#### Body parameters

| Field | Type | Required | Notes |
|---|---|---|---|
| `archived` | boolean | no | Defaults to `true`. Send `false` to restore. |
| `vendorId` | string | no | Same explicit-vendor override as the other draft routes (also accepted as a `vendorId` query parameter); defaults to the session's active vendor. |

#### Example request

```bash
curl -X POST https://wallet-api.spoonity.com/drafts/YOUR_DRAFT_ID/archive \
  -H "Authorization: Bearer <operator session token>" \
  -H "Content-Type: application/json" \
  -d '{ "archived": true }'
```

#### Example response

```json
{ "id": "draft-123", "archived": true }
```

Saving a draft that now carries a `programId` (because it has since been published) always
clears its archive too, the same publish-lifts-archive rule as the program route, above.

#### Errors

| Status | Meaning |
|---|---|
| 401 | No valid operator session or service identity. |
| 403 | No active vendor, an explicit `vendorId` outside the caller's list, or the draft belongs to a different vendor. |
| 404 | Draft not found. |
| 500 | Server error; safe to retry. |

## Other wallet-api endpoints (not part of this integration surface)

`wallet-api.spoonity.com` also serves the pass designer, the Spoonity operator tools, Apple
Wallet's device web service, and Spoonity's own public wallet microsite. Apart from the Apple and
public routes, those endpoints are operator-authenticated (an operator's login, or Google-signed
service-to-service identity for Prism), not the per-program API-key surface documented above,
and none of them accept an `sk_live_` key. The [site settings](#site-settings),
[pass artwork hosting](#pass-artwork-hosting), and
[program and draft archival](#archiving-programs-and-drafts) routes above are the ones written up
in full; everything below intentionally has no documented request or response shape:

- **Liveness**: `GET /health` returns `{"status": "ok", "service": "spoonity-passkit-integration", "time": "..."}` with no auth.
- **Pass design and drafts**: `POST /design`, `GET /design/:programId/preview.pkpass`,
  `GET /drafts`, `POST /drafts`, `GET /drafts/find`, `DELETE /drafts/:id`. `POST /design`'s full
  body is intentionally undocumented here (not part of this integration surface, and it carries
  every pass-builder field), but three fields that landed in the 2026-10-01 parity sync are worth
  naming for anyone maintaining the Pass Studio port:

  | Field | Type | Scope | Notes |
  |---|---|---|---|
  | `showBarcodeNumber` | boolean | Program-level, not per-tier | `false` hides the human-readable code Apple/Google print beneath the barcode (Apple `altText` / Google `alternateText`); absent or `true` keeps it. Stored under its own key, not the legacy `barcode.showAltText` (whose stale `false` values are ignored on purpose). A barcode that encodes the customer's email never prints a number either way. |
  | `googleLogo` | string (data URI or hosted `https://` URL) | Per-tier, alongside `logo`/`icon`/`strip` | Optional override for Google Wallet's circular `programLogo`. When absent, Google falls back to `logo`, then `icon` (unchanged). Useful when the shared logo is a wide wordmark that would otherwise square-crop into a blank circle. |
  | `pointsMessageTemplate` | string | Per-tier, unchanged shape | Gained a `{{label}}` token, resolved server-side (`renderPointsMessage`) to the same string printed on the pass face for that currency field — alongside the existing `{{customerName}}` and `{{points}}` (which itself now renders as Apple's own `%@` substitution rather than a value baked in at build time). |
- **Brand**: `GET /api/brand`, `PUT /api/brand`, `GET /api/brand/sync`, `POST /api/brand/sync`,
  `POST /api/brand/from-url`, `GET /api/brand/:domain`. `GET /api/brand` still returns the same
  camelCase core fields, and still 404s (`no brand yet`) when the vendor has no brand, which
  first-run onboarding depends on. The core brand is stored in the **Spoonity CMS** (its
  `GET`/`PUT /brand`, see the CMS page), with the legacy Firestore document as a read-only fallback
  for vendors not yet migrated. Brand Kit additions (`brandColors`, `fonts`, and a per-surface
  `sync` status) live in Firestore, and a save fans out to live programs, the CMS and Links vendor
  rows, and the vendor's app-config theme; `/api/brand/sync` reads that status or re-runs one
  surface.
- **API key self-service** (how the keys used above are generated, from Prism or the Pass Studio):
  `POST /v1/api-keys`, `GET /v1/api-keys?programId=`, `DELETE /v1/api-keys/:keyId`.
- **Programs and analytics**:
  `GET /v1/programs/:programId/{members,signups,platforms,devices,retention,engagement,funnel,overview}`.
  (`GET /v1/programs` and its `includeArchived` query are documented above.)
- **Tier rules**: `GET /v1/tier-rules`, `PUT /v1/tier-rules`, `DELETE /v1/tier-rules/:tierName`.
- **Member erasure** (right to erasure, operator-triggered): `DELETE /v1/members/:externalId`.
- **Wallet pass messaging**: `POST /api/wallet/push` sends an ad-hoc broadcast message (100 per 15
  minutes per IP), and `DELETE /v1/programs/:programId/announcement` retracts one before it
  expires on its own.
- **Operator tools**: `POST /api/ai/chat` (an AI assistant proxy), `POST /feedback` and
  `POST /feedback/evaluate` (in-product feedback; `evaluate` is an advisory pre-submit verdict with
  its own 300 per 15 minutes limiter, `503` when unconfigured, and never blocks a submission).
- **Operator login**: `POST /auth/login`, `POST /auth/select`, `POST /auth/switch`,
  `POST /auth/logout`, `GET /auth/session`.
- **Inbound events**: `POST /webhooks/spoonity/:token` receives Spoonity loyalty events (balance
  and tier changes) and is authenticated by a secret token in the path; `POST /internal/location-refresh`
  is an internal scheduler trigger. Neither is for integrators.
- **Apple Wallet device web service** (called by iOS itself, never by an integration): pass
  registration, updates, and logging under `/v1/devices/*`, `/v1/passes/*` and `/v1/log`.
- **Pass install pages**: `GET /passes/:memberId` (the smart Add to Wallet page every enrollment
  redirects to) and `GET /passes/:memberId.pkpass`.
- **Public microsite plumbing** behind `wallets.spoonity.com`'s own pages, not something to
  integrate against directly: member lookup (`GET /api/member/:id`), site lookups
  (`GET /api/site/program`, `GET /api/site/directory`, `GET /api/site/tiers`), Wallet's hosted
  signup form (`GET /enroll/:programId`, with `POST /enroll/start` and `GET /enroll/confirm` for
  the email-confirmation flow, and a direct `POST /enroll`), and `POST /enroll/app-session/go`, a
  form-post variant of `POST /enroll/app-session` reached as a top-level form target instead of a
  fetch call, so an Android Chrome to Google Wallet handoff still carries the user gesture it
  requires. It answers with an HTML page or a redirect, never JSON. A bare `GET /enroll` names no
  program and answers `404`.

## See also

- [Authentication across Spoonity's APIs](./authentication.md)
- [Cross-service conventions](./conventions.md): error envelope, timestamps, rate limits
