@invonetwork/web-sdk 3.6.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,18 +2,19 @@
2
2
 
3
3
  First-party TypeScript SDK for integrating **INVO** into partner **web** platforms (storefronts, web games, dashboards). It wraps INVO's web money flows behind a typed, versioned API — the web analog of the Unity/Unreal plugins.
4
4
 
5
- > **Status:** `v3.5.0` — stable, published on npm. The backend it wraps is **live** on sandbox + production. The API is covered by a [stability commitment](#stability): no breaking changes without a major bump. Recent highlights: **3.4.0** documents that a Steam title now bills through **its own Steam application** — the studio registers their appid + publisher Web API key and keeps a payment method on file, because Valve pays the studio and INVO settles afterwards (new `isSteamNotConfigured`, `isPartnerBillingNotSetUp`, `isPartnerSettlementUnavailable`, `isSteamAppChanged` error helpers); **3.2.3** corrects the base path and auth header in the Steam snippets (`/api/currency-purchases`, `X-Game-Secret-Key`) — 3.2.2 published both wrong, and copying them returned a 404; **3.2.x** documents **Steam currency purchases on a pack model** — INVO owns the catalogue, you pass a `pack_id` and never a price, and the currency inside a pack varies by country because Steam prices are VAT-inclusive; **3.1.0** makes the authentication guidance explicit — **[passkeys are the gold standard](#passkeys-are-the-gold-standard-dont-build-on-sms)** and the SMS-PIN completion (`verifySmsTransfer`/`verifySmsSend`) is **deprecated and being phased out** (documentation only — no behavior change, no runtime warnings); **3.0.0** moves the Platform Commerce card leg to **INVO's hosted checkout** — the server `purchase()` now returns a `checkoutUrl` and the browser just sends the buyer there (redirect or `mountCheckout` iframe); the 2.5.x card-element surface (`confirmCardPayment`/`mountCardPayment`, `billingAddress`, `commercePublishableKey`) is **removed** — see the [CHANGELOG](CHANGELOG.md) migration note; **2.5.0** added **Platform Commerce** (ecommerce) — a platform tenant selling items funded by balance **or** card, with `invo.platformCommerce.purchase/getStatus/refund` (server) and the `platform_commerce.*` webhooks; **2.4.0** adds Steam transfer-policy handling (`isSteamValueNonTransferable`/`isNonSteamValueIntoSteamBlocked` + `DestinationGame.acceptsSteamOriginValue`); **2.3.0** surfaces the claim-time phone-share `409` on `confirmReceipt*`/`claim*` (+ `err.phoneShareLast4`). Full history in the [CHANGELOG](CHANGELOG.md).
5
+ > **Status:** `v3.8.0` — stable, published on npm. The backend it wraps is **live** on sandbox + production. The API is covered by a [stability commitment](#stability): no breaking changes without a major bump. Recent highlights: **3.8.0** adds **[Subscriptions](#subscriptions-recurring-billing)** as a first-class server surface on both rails — `invo.subscriptions.create/get/listForPlayer/cancel/changeAmount/setPaymentMethod/refund/steamInit/steamFinalize`, the off-session card capture (`invo.cards.beginSetup/confirmSetup/list`), the sandbox clock tools (`invo.sandbox.subscriptions.*`, which post to `/subscriptions/<id>/...` **relative to the sandbox base, not under `/api`**, with the new `sandboxClockKey`), typed `data` for all seven `subscription.*` webhook events, and eleven new error classifiers; **3.7.0** makes the **device approval grant a first-class SDK surface** — `beginDeviceApproval`, `pollDeviceApproval`, `confirmDeviceEnrollment` and, the step that actually moves the money, **`approveWithDeviceCode`** (plus the optional `completeDeviceApproval` loop); a grant that is polled to `approved` and left there settles **nothing**, which is the failure this release exists to make impossible, and `TRANSACTION_NOT_PENDING` now comes back as a typed `status: "not_pending"` result with `alreadySettled` rather than a thrown error you would have to string-match; **3.4.0** documents that a Steam title now bills through **its own Steam application** — the studio registers their appid + publisher Web API key and keeps a payment method on file, because Valve pays the studio and INVO settles afterwards (new `isSteamNotConfigured`, `isPartnerBillingNotSetUp`, `isPartnerSettlementUnavailable`, `isSteamAppChanged` error helpers); **3.2.3** corrects the base path and auth header in the Steam snippets (`/api/currency-purchases`, `X-Game-Secret-Key`) — 3.2.2 published both wrong, and copying them returned a 404; **3.2.x** documents **Steam currency purchases on a pack model** — INVO owns the catalogue, you pass a `pack_id` and never a price, and the currency inside a pack varies by country because Steam prices are VAT-inclusive; **3.1.0** makes the authentication guidance explicit — **[passkeys are the gold standard](#passkeys-are-the-gold-standard-dont-build-on-sms)** and the SMS-PIN completion (`verifySmsTransfer`/`verifySmsSend`) is **deprecated and being phased out** (documentation only — no behavior change, no runtime warnings); **3.0.0** moves the Platform Commerce card leg to **INVO's hosted checkout** — the server `purchase()` now returns a `checkoutUrl` and the browser just sends the buyer there (redirect or `mountCheckout` iframe); the 2.5.x card-element surface (`confirmCardPayment`/`mountCardPayment`, `billingAddress`, `commercePublishableKey`) is **removed** — see the [CHANGELOG](CHANGELOG.md) migration note; **2.5.0** added **Platform Commerce** (ecommerce) — a platform tenant selling items funded by balance **or** card, with `invo.platformCommerce.purchase/getStatus/refund` (server) and the `platform_commerce.*` webhooks; **2.4.0** adds Steam transfer-policy handling (`isSteamValueNonTransferable`/`isNonSteamValueIntoSteamBlocked` + `DestinationGame.acceptsSteamOriginValue`); **2.3.0** surfaces the claim-time phone-share `409` on `confirmReceipt*`/`claim*` (+ `err.phoneShareLast4`). Full history in the [CHANGELOG](CHANGELOG.md).
6
6
  > Canonical partner reference: **https://docs.invo.network/docs/currency-purchase** and **https://docs.invo.network/docs/game-developer-integration**.
7
7
 
8
8
  ## What it does
9
9
 
10
- Five money flows plus passkey (WebAuthn) authentication, split across a trusted server entry and an untrusted browser entry:
10
+ Six money flows plus passkey (WebAuthn) authentication, split across a trusted server entry and an untrusted browser entry:
11
11
 
12
12
  | Flow | Direction | Real money? | Passkey? | Where |
13
13
  |---|---|---|---|---|
14
14
  | **Currency purchase** | real money **→** game currency | yes (card/rails) | no | server initiates, browser opens hosted checkout |
15
15
  | **Item purchase** | game currency **→** in-game item | no (balance debit) | no | server only |
16
16
  | **Platform Commerce** (ecommerce) | balance **or** card **→** a storefront item | card leg only | no | server creates; buyer pays on INVO's **hosted checkout** |
17
+ | **Subscriptions** | a fixed USD price on a fixed interval **→** game currency each period (card **or** Steam rail) | yes (the wallet shortfall) | no | server creates, cancels, reprices; renewals arrive by webhook |
17
18
  | **Send** | currency **→** another player (cross-game) | no | yes (sender approves) | server initiates, browser approves/claims |
18
19
  | **Transfer** | currency **→** another player (transfer rail) | no | yes (sender approves) | server initiates, browser approves/claims |
19
20
 
@@ -35,7 +36,8 @@ So:
35
36
  |---|---|---|
36
37
  | Sender approves a send/transfer | `client.enrollPasskey()` once, then `client.approveSend` / `approveTransfer` | a PIN pad as the default flow |
37
38
  | `initiate*` returns `verificationMethod: "sms"` | read it as *"this user has no passkey"* → offer enrollment | route straight to PIN entry |
38
- | Recipient collects | `client.confirmReceiptSend` / `confirmReceiptTransfer` (passkey) | claim code as the primary path |
39
+ | Recipient collects | `client.confirmReceiptSend` / `confirmReceiptTransfer` (passkey), or the QR flow with `flow: "send_receipt"` / `"transfer_receipt"` | claim code as the primary path |
40
+ | Console / TV / native client | the QR device-approval grant, **then `server.approveWithDeviceCode`** | polling to `approved` and stopping — that settles nothing |
39
41
 
40
42
  ### Prerequisite: which passkey path serves your tenant
41
43
 
@@ -79,7 +81,7 @@ The right approval method is a property of the **client the player is sitting in
79
81
  | Mobile app & mobile web (iOS 16+ / Android 9+) | **a passkey, directly** | the platform authenticator (Face ID / Touch ID / fingerprint) is available in-client — strongest option, zero messaging cost |
80
82
  | Desktop web (browser) | **a passkey, directly** | Touch ID / Windows Hello are available to the browser |
81
83
  | Web, player has no in-app passkey yet | **INVO's hosted page in a popup** ([`approveHosted`](#web-games--approving-on-invos-hosted-page), below) | the same page a console scans, opened by the SDK from the browser; the player enrols an INVO passkey on INVO's own domain and the SDK polls and approves — one call, nothing new on your server |
82
- | Consoles (PlayStation / Xbox / Switch) | **the QR device-approval flow** ([RFC 8628](#consoles-and-tvs--approving-without-a-browser-rfc-8628), below) | no browser and no WebAuthn in-client — show the QR, the player scans it and completes the passkey on their phone, and the console polls for approval |
84
+ | Consoles (PlayStation / Xbox / Switch) | **the QR device-approval flow** ([RFC 8628](#consoles-and-tvs--approving-without-a-browser-rfc-8628), below) | no browser and no WebAuthn in-client — show the QR, the player scans it and completes the passkey on their phone, your server polls, and **your server then calls `approveWithDeviceCode`** — the poll proves who, that call moves the money |
83
85
  | Native Steam / desktop game clients (Mac & Windows) | **the QR device-approval flow** ([RFC 8628](#consoles-and-tvs--approving-without-a-browser-rfc-8628), below) | the OS supports passkeys, but the embedded game client can't invoke the platform authenticator from inside the engine — it is the **client**, not the OS, that forces QR here |
84
86
 
85
87
  **When there is no passkey path at all** — a remote approval that can't run a ceremony (a guardian, a phone's existing owner) — INVO goes **email first, SMS on request**: a signed link to a hosted page to the oldest verified address, and a text only when there is no verified email, the email could not be delivered, or the player asks for one. SMS is the last resort, not the primary channel.
@@ -94,8 +96,14 @@ The right approval method is a property of the **client the player is sitting in
94
96
  - [Currency purchase (real money in)](#currency-purchase-real-money-in)
95
97
  - [Item purchase (spend game currency)](#item-purchase-spend-game-currency)
96
98
  - [Platform Commerce (ecommerce)](#platform-commerce-ecommerce)
99
+ - [Subscriptions (recurring billing)](#subscriptions-recurring-billing)
97
100
  - [Player balance](#player-balance)
98
101
  - [Sends & transfers (move currency between players)](#sends--transfers-move-currency-between-players)
102
+ - [Legacy fallback: the SMS PIN (being retired)](#legacy-fallback-the-sms-pin-being-retired)
103
+ - [Sends and transfers, stage by stage](#sends-and-transfers-stage-by-stage)
104
+ - [What your server must call, in order](#what-your-server-must-call-in-order)
105
+ - [Errors on the money path](#errors-on-the-money-path)
106
+ - [Common mistakes](#common-mistakes)
99
107
  - [Passkeys (enroll, approve, link, recover)](#passkeys-enroll-approve-link-recover)
100
108
  - [Web games — approving on INVO's hosted page](#web-games--approving-on-invos-hosted-page)
101
109
  - [Consoles and TVs — approving without a browser (RFC 8628)](#consoles-and-tvs--approving-without-a-browser-rfc-8628)
@@ -229,6 +237,7 @@ INVO enables each flow for your tenant in the [console](#get-your-account--game-
229
237
  - **For passkeys (sends/transfers):** nothing to configure — new titles approve on INVO's hosted page ([`approveHosted()`](#web-games--approving-on-invos-hosted-page)); there is no partner domain to verify. Only a tenant that verified an **RP ID + web origin(s)** before the freeze uses the in-app `enrollPasskey()` / `approveSend` path, and those passkeys only validate on the approved origins. **Wire the approve step before launch:** until a sender is enrolled the backend falls back to the deprecated SMS-PIN path, which is the flow you don't want your users on (see [Passkeys are the gold standard](#passkeys-are-the-gold-standard--dont-build-on-sms)).
230
238
  - **For currency purchase:** card checkout works out of the box; ask INVO to enable the `game`/`steam` rails if you need them. **The `steam` rail additionally requires the studio to register their own Steam app id + publisher Web API key and put a payment method on file** — see [Steam purchases](#steam-purchases-packs-not-prices).
231
239
  - **For item purchase:** nothing extra — it's a currency-balance debit.
240
+ - **For subscriptions:** the game must be **`live`** (a `testing` game cannot create one), a **webhook target must be registered first** (several `subscription.*` events carry data you cannot fetch any other way), and a card subscription needs a card captured **off-session** via `cards.beginSetup` — the hosted checkout does not save one. See [Subscriptions](#subscriptions-recurring-billing).
232
241
 
233
242
  If a flow isn't enabled for your tenant yet, calls return a clear `InvoError` (e.g. `TENANT_NOT_MIGRATED`, `WEBAUTHN_NOT_ENABLED_FOR_TENANT`, or `flow_paused`) — coordinate with your INVO contact to turn it on.
234
243
 
@@ -246,6 +255,7 @@ const server = new InvoServer({
246
255
  // retryBaseDelayMs: 250, // optional backoff base
247
256
  // fetch: customFetch, // optional override
248
257
  // hooks: { onRequest, onResponse, onError }, // optional observability (see below)
258
+ // sandboxClockKey: process.env.INVO_SANDBOX_CLOCK_KEY, // optional: the sandbox subscription clock tools only
249
259
  });
250
260
 
251
261
  const client = new InvoClient({
@@ -592,6 +602,314 @@ const ref = await server.platformCommerce.refund({ orderId: r.orderId, reason: "
592
602
 
593
603
  ---
594
604
 
605
+ ## Subscriptions (recurring billing)
606
+
607
+ A subscription is a standing agreement, created by **your server**, under which INVO bills one of your players a fixed USD price on a fixed interval and grants them your game's currency each period. **You keep the entitlement** (what the member gets in your game). INVO keeps the clock, the charges, the retries, the notifications and the revenue split. Two rails, fixed at creation:
608
+
609
+ | `fundingRail` | How the shortfall is funded | Created by |
610
+ |---|---|---|
611
+ | `card` | the member's saved card on file with INVO | `server.subscriptions.create(...)` |
612
+ | `steam` | the member's Steam wallet, through a recurring agreement they authorise once | `server.subscriptions.steamInit(...)` then `steamFinalize(...)` |
613
+
614
+ Each period INVO works out what the period is worth in coins (card: price × the 10-coins-per-USD peg; Steam: what the price buys through Steam for the member's country), **spends the member's wallet first**, tops up from the rail for the **shortfall only**, and splits the coins spent between INVO's platform fee (10% by default, plus $0.30 on the card-funded portion of a renewal) and your revenue. Every figure is reported on the `subscription.renewed` event.
615
+
616
+ **Three rules to carry through everything below.**
617
+
618
+ 1. **Two clocks.** `subscription.currentPeriodEnd` is the *billing window*, a projection that exists from the instant of creation. `subscription.paidThrough` is the *entitlement boundary*: the furthest date the member has actually paid for (`null` until a period charges). **Grant access from `paidThrough`, never from `currentPeriodEnd`.**
619
+ 2. **One item id, shared across rails.** The recurring subscription's `itemId` is *your* entitlement handle (`"guild-42-membership"`). It is **rail-agnostic** and **different from any one-off pack id**: the one-live-subscription rule is per game + player + item, so a member with a live card subscription to `guild-42-membership` cannot start a Steam one to the same item, and a `steamPacks()` pack id is never a subscription item id.
620
+ 3. **Webhooks are the source of truth for entitlement.** `subscription.renewed` extends access; only `subscription.expired` and `subscription.canceled` revoke it. Nothing else does, and the create response is your only creation signal (there is no `subscription.created`).
621
+
622
+ **Before you start:** the game must be `live` in the environment you're calling (a `testing` game is refused `403 GAME_NOT_LIVE`, `err.isGameNotLive`, though it may still read/cancel/reprice existing subscriptions); register a webhook target first (several events carry data you cannot fetch any other way); use the primary game key (`ivsdk_...`) or a channel key in `X-Game-Secret-Key` (on the Steam rail only the primary key or the `steam` channel key may start a subscription: `err.isSteamChannelRequired`). Money and coin figures are **decimal strings** on the wire and in every typed result, so nothing rounds silently.
623
+
624
+ ### The card road
625
+
626
+ **1. Capture a card (off-session).** A card subscription needs a card saved for later, off-session use. The subscription endpoints never receive card data and neither does this SDK: the card form on your client tokenises it. Two ways to save one, and **the hosted checkout is not one of them** (a member who paid through the hosted checkout page does *not* thereby have a card on file for recurring billing; neither does a card saved through a `savedCardId` purchase):
627
+
628
+ ```ts
629
+ // Option A: the setup flow (charges nothing). The player must already exist in this game.
630
+ const setup = await server.cards.beginSetup({
631
+ playerEmail: "member@example.com",
632
+ setupReference: "setup-guild-42-member-7", // idempotency anchor: resend the same value on a retry
633
+ paymentMethodId, // a card tokenised on the client (sandbox: "pm_card_visa")
634
+ });
635
+ switch (setup.status) {
636
+ case "succeeded": // setup.card.id is your playerCardId
637
+ break;
638
+ case "requires_action": // the issuer wants the cardholder to authenticate:
639
+ case "requires_confirmation": // hand setup.clientSecret to the card form on the
640
+ case "requires_payment_method": // client, let it finish, then confirm server-side:
641
+ await sendToClient(setup.clientSecret);
642
+ const saved = await server.cards.confirmSetup({ setupIntentId: setup.setupIntentId });
643
+ // saved.card.id (a 400 with body.status === "still_requires_action" means the client hasn't finished)
644
+ break;
645
+ }
646
+
647
+ // Option B: save the card during a purchase, purchaseCurrency(...) with a new paymentMethodId and
648
+ // `save_card: true` in the body saves it with the off-session consent as a side effect.
649
+
650
+ const { cards } = await server.cards.list("member@example.com"); // unexpired, newest first; `id` is the only handle
651
+ ```
652
+
653
+ **2. Create the subscription.** `create` **charges the first period before responding** (unless it is a trial), so expect it to take as long as a card charge.
654
+
655
+ ```ts
656
+ const r = await server.subscriptions.create({
657
+ clientRequestId: "guild-42-member-7", // generate ONCE per subscription, persist it, reuse on every retry
658
+ playerEmail: "member@example.com",
659
+ playerName: "Member", // used only if the player is created
660
+ itemId: "guild-42-membership", // your entitlement handle; one live subscription per (player, item)
661
+ itemName: "Guild 42 membership",
662
+ amountUsd: "9.99", // 0.01..999999.99; keep it <= 500.00 or it is never charged
663
+ interval: "month", // "month" (default) | "year"
664
+ // intervalCount: 3, // quarterly; 1..36
665
+ // trialDays: 7, // or trialEnd: "2026-10-01T00:00:00Z"
666
+ // playerCardId: cards[0].id, // omitted: INVO attaches the newest unexpired saved card
667
+ // walletOnly: true, // never charge a card; dunning when the wallet is short
668
+ metadata: { guild_id: "42" }, // echoed on every read and event (`_invo` is reserved)
669
+ consent: { // send it: INVO is merchant of record and a dispute is argued from this
670
+ consentAt: new Date().toISOString(),
671
+ consentIp: memberIp, // the MEMBER's IP as your server saw it
672
+ consentUserAgent: memberUserAgent,
673
+ disclosedAmountUsd: "9.99",
674
+ disclosedInterval: "month",
675
+ termsVersion: "2026-09",
676
+ },
677
+ // revenueShare: { recipientPlayerEmail: "founder@example.com", percent: "70" }, // attribution only: INVO pays nobody
678
+ });
679
+ ```
680
+
681
+ **3. Branch on `r.firstCharge.status`.** The object always carries all its keys; read the ones your branch knows exist.
682
+
683
+ ```ts
684
+ switch (r.firstCharge.status) {
685
+ case "paid": // money moved, currency granted; r.firstCharge.paidPeriodSeq === 1
686
+ grantAccessUntil(r.subscription.paidThrough!);
687
+ break;
688
+ case "requires_action": // NOTHING has been charged; status is awaiting_authentication
689
+ relayToMember(r.firstCharge.confirmationUrl!, r.firstCharge.expiresAt!); // a single-use bearer link: never log it
690
+ break; // access follows on subscription.renewed; if the link lapses INVO retries on its own
691
+ case "skipped_trial": // status is trialing; the first charge runs at trialEnd
692
+ grantTrialUntil(r.subscription.trialEnd!);
693
+ break;
694
+ case "failed": // status is past_due, in dunning; INVO retries at nextRetryAt
695
+ tellMemberToFixCard(r.firstCharge.failureCode);
696
+ break;
697
+ case "pending": // an ambiguous processor answer; INVO resolves it within ~30 minutes
698
+ break; // wait for subscription.renewed / subscription.payment_failed
699
+ }
700
+ ```
701
+
702
+ > **Period numbering.** After a paid first charge `r.subscription.periodSeq` already reads `2`: period 1 was just paid and the subscription points at the *next* window. The `subscription.renewed` webhook for that first period reports `period_seq: 1`. Key your entitlement on **`r.firstCharge.paidPeriodSeq`** (or the webhook's `period_seq`), never on `subscription.periodSeq`; the two count differently by design.
703
+
704
+ **4. Replay before retry.** `create` is idempotent on `clientRequestId`: a repeat returns HTTP 200 with the identical shape and `r.idempotentReplay === true`, nothing is charged again, and `firstCharge` is re-derived from what already happened (so a replay after the charge settled reports `paid`). The SDK auto-retries transient failures with the same key. **On any timeout or 5xx, replay the same key before you do anything else.** A fresh key inside a retry loop lands on `409 ACTIVE_SUBSCRIPTION_EXISTS` (`err.isActiveSubscriptionExists`, the live id on `err.existingSubscriptionId`) at best and a second subscription at worst; the same key with different terms is `err.isIdempotentReplayMismatch` (`err.mismatchedFields`).
705
+
706
+ ### The Steam road
707
+
708
+ A Steam subscription is funded from the member's Steam wallet through a recurring agreement they authorise **once, in Steam**. INVO still owns the clock. Valve pays you through your Steamworks account; INVO mints the currency and settles with you afterwards. The title must be enabled for Steam in INVO (`err.isSteamRailNotEntitled` / `err.isSteamNotConfigured` otherwise), and the coins a period is worth depend on the member's country because Steam prices include VAT: **show `amountCoins` from the init response, never price × 10.**
709
+
710
+ ```ts
711
+ // 1) init: creates the subscription in pending_steam_authorization and starts the Steam authorisation.
712
+ const init = await server.subscriptions.steamInit({
713
+ clientRequestId: "guild-42-member-7-steam",
714
+ playerEmail: "member@example.com",
715
+ playerName: "Member",
716
+ itemId: "guild-42-membership", // the SAME item id as the card rail would use
717
+ amountUsd: "9.99",
718
+ interval: "month", // monthly and yearly only; intervalCount must be 1
719
+ steamId: "76561198702247638",
720
+ userSession: "client", // "client" (Steam overlay, default) | "web" (hosted checkout URL; needs playerIp)
721
+ consent: { /* as above */ },
722
+ });
723
+ // init.status === "pending_steam_authorization"; nothing charged yet
724
+ // init.amountCoins → "69" for a US member (what one period is worth for THIS member; fixed at init)
725
+ // init.steamOrderId → the uint64 the Steam client callback's order_id echoes: MATCH THE CALLBACK WITH THIS
726
+ // init.steamTransid → Steam's transaction reference, for your support tooling only
727
+ // init.pendingReuse → true when a pending authorisation with the same terms was handed back (finalize that one)
728
+
729
+ // 2) the client step: "client" → the overlay shows the authorisation inside the game (nothing to open);
730
+ // "web" → open init.steamCheckoutUrl as a TOP-LEVEL window or tab (it cannot be framed).
731
+
732
+ // 3) finalize, from your server, after the overlay/checkout closes. Steam does not tell INVO the member authorised.
733
+ try {
734
+ const fin = await server.subscriptions.steamFinalize(init.subscriptionId);
735
+ // fin.firstCharge.status === "paid", fin.firstCharge.paidPeriodSeq === 1, fin.steamAgreementStatus === "active"
736
+ // fin.alreadyProcessed === true on a repeat (treat as success). fin.sandboxAutoApproved === true in sandbox.
737
+ // fin.warning set: Steam charged but period 1 could not settle in one step, the money is taken, do NOT retry the charge.
738
+ grantAccessUntil(fin.subscription.paidThrough!);
739
+ } catch (e) {
740
+ if (e instanceof InvoError && e.isNotAuthorized) scheduleFinalizeRetry(); // the normal wait state; member has 24 h
741
+ else throw e;
742
+ }
743
+ ```
744
+
745
+ Not available on Steam, and refused by the SDK before the network: trials, `walletOnly`, card fields, `intervalCount` other than 1. A **price increase** is refused (`err.isSteamReauthorizationRequired`: the member consented to a ceiling; start a new Steam subscription at the new price and cancel this one); a decrease stages. `setPaymentMethod` is refused (`err.isNotACardSubscription`). A member can cancel from their Steam account: you learn it from `subscription.canceled` with `canceled_by: "steam"`. Replaying `steamInit` returns the row's **current** status (already `active`, `canceled`, `expired`, ...). A pending row for the same player + item with **different** terms throws `409 STEAM_AUTHORIZATION_PENDING` (`err.isSteamAuthorizationPending`, the pending id on `err.existingSubscriptionId`); with the **same** terms it is handed back as `pendingReuse: true`. A row never finalised expires after 24 hours with `subscription.expired` and `failure_code: "steam_authorization_abandoned"`.
746
+
747
+ ### Renewals, dunning and the seven events
748
+
749
+ INVO bills **in advance**, at `nextChargeAt`, within a minute or two. Do not poll for renewals; handle the events. When a charge fails the subscription goes `past_due` and INVO retries on the dunning ladder (default: after 2 days, then 3, then 2, then `expired`), **retaining access through the whole grace window**. A card issuer that wants the cardholder to authenticate moves the subscription to `awaiting_authentication` with no retry consumed: **not a failure**; relay the link.
750
+
751
+ ```ts
752
+ import { createWebhookHandler } from "@invonetwork/web-sdk/server";
753
+
754
+ export const POST = createWebhookHandler({
755
+ secret: process.env.INVO_WEBHOOK_SECRET!,
756
+ onEvent: async (event, { idempotencyKey }) => {
757
+ if (await seen(idempotencyKey)) return; // at-least-once delivery, possibly out of order
758
+ switch (event.event_type) {
759
+ case "subscription.renewed": { // THE source of truth for entitlement (event.data is typed)
760
+ const d = event.data; // d.period_seq is the period JUST PAID; d.period_end is the new paid_through
761
+ await extendAccess(d.subscription_id, d.period_end);
762
+ // d.funding.rail ("card" | "steam"), d.funding.card_charged_usd / steam_charged_usd (the shortfall only)
763
+ // d.split.basis: "price" on card; "steam_net" on Steam, where d.split.total_usd is what the coins are worth,
764
+ // not the price (the price is d.amount_usd). d.split.partner_revenue_usd is what you earned.
765
+ // d.revenue_share_attribution?.attributed_amount_usd: what to pay your recipient yourself (settled_by_invo: false)
766
+ break;
767
+ }
768
+ case "subscription.payment_failed": // every failed attempt; access RETAINED. Do not revoke.
769
+ await notifyCardProblem(event.data.subscription_id, event.data.failure_code, event.data.retry_at);
770
+ break;
771
+ case "subscription.past_due": // once, on ENTERING past_due. Access retained.
772
+ break;
773
+ case "subscription.authentication_required": // NOT a failure: send the member the link, not a "payment failed" message
774
+ await relayToMember(event.data.confirmation_url, event.data.expires_at);
775
+ break;
776
+ case "subscription.canceled": // once, at request time, both modes. Revoke at access_until.
777
+ await revokeAt(event.data.subscription_id, event.data.access_until); // event.data.canceled_by: "partner" | "steam"
778
+ break;
779
+ case "subscription.expired": // the retry budget ran out (or a Steam row was never authorised)
780
+ await revokeAt(event.data.subscription_id, event.data.final_period_end); // NOT ended_at; null if nothing was ever paid
781
+ break; // failure_code "steam_containment": retired with NO payment_failed before it
782
+ case "subscription.refunded": // your revenue for the refunded portion is reversed; INVO's fee is retained
783
+ await recordReversal(event.data.subscription_id, event.data.refund.partner_revenue_reversed_usd);
784
+ break;
785
+ }
786
+ },
787
+ });
788
+ ```
789
+
790
+ | Question | Answer |
791
+ |---|---|
792
+ | Has the member paid for the period they are in? | `subscription.renewed` for that period, or `paidThrough` on `get` |
793
+ | Should I revoke access? | only on `subscription.expired` (at `final_period_end`) or `subscription.canceled` (at `access_until`); **never** on `payment_failed`, `past_due` or `authentication_required` |
794
+ | What did I earn? | `split.partner_revenue_usd` on `subscription.renewed`, minus `refund.partner_revenue_reversed_usd` on any `subscription.refunded` |
795
+
796
+ A few renewal outcomes are **deferrals**, not failures, with no event and no retry consumed (a price above the 500.00 per-charge ceiling; wallet value that cannot be spent in this game; on Steam, your billing setup or Steam configuration being unusable). You see them on `get` as an unchanged (or `past_due`) status with `nextChargeAt` about 24 hours out.
797
+
798
+ ### Reading, cancelling, repricing, changing the card
799
+
800
+ ```ts
801
+ const { subscription } = await server.subscriptions.get(id); // { includePlayer: true } adds a player block
802
+ const page = await server.subscriptions.listForPlayer("member@example.com", { status: ["live", "canceled"], limit: 50 });
803
+ // page.subscriptions (newest first), page.pagination.hasMore; an unknown player is an empty list, not a 404
804
+
805
+ const c = await server.subscriptions.cancel(id, { atPeriodEnd: true, reason: "member request" });
806
+ // atPeriodEnd (default true): stays live with cancelAtPeriodEnd, retired at paidThrough with no further charge.
807
+ // c.terminatedImmediately === true: nothing had been paid, so the at-period-end cancel was DOWNGRADED to immediate.
808
+ // c.alreadyCanceled === true: it was already terminal (a 200, never thrown). Revoke access at c.accessUntil.
809
+
810
+ const a = await server.subscriptions.changeAmount(id, "14.99");
811
+ // Staged: the current window bills at the old price, the new price applies from a.appliesFromPeriodSeq. No proration.
812
+ // Sending the current price clears a staged change. More than double, or above 500.00, stays pending forever.
813
+
814
+ await server.subscriptions.setPaymentMethod(id, { playerCardId: 43 }); // used from the next charge, incl. a pending retry
815
+ await server.subscriptions.setPaymentMethod(id, { playerCardId: 43, walletOnly: false }); // convert a wallet-only subscription back
816
+ await server.subscriptions.setPaymentMethod(id, { walletOnly: true }); // stop charging a card until you flip it back
817
+ ```
818
+
819
+ ### Refunds
820
+
821
+ ```ts
822
+ const receipt = await server.subscriptions.refund(id, {
823
+ clientRequestId: "refund-2026-11-guild-42-member-7", // one per refund; reuse it on retries (the receipt replays)
824
+ // periodSeq: 2, // default: the most recent billed period
825
+ // amountUsd: "4.00", // default: the full remaining refundable amount
826
+ reason: "member request",
827
+ });
828
+ // receipt.isFullRefund, receipt.fundingShape ("wallet" | "card" | "mixed"), receipt.cardRefundedUsd,
829
+ // receipt.balanceDeltaCoins (signed: coins the card charge minted are taken back; can go negative),
830
+ // receipt.partnerRevenueReversedUsd (your revenue reversed; INVO's fee is retained),
831
+ // receipt.revenueShareAttribution?.netAttributedAmountUsd (the corrected figure to pay your recipient),
832
+ // receipt.idempotentReplay === true on a repeat.
833
+ ```
834
+
835
+ A full refund returns the whole card charge for that period and reclaims the coins that charge minted; a partial refund credits the wallet in coins at the 10:1 peg. A fully refunded period no longer counts toward `paidThrough`; **the subscription itself is not cancelled** (cancel it separately if that is what the member wants). **Refunds of periods charged through Steam are not supported yet**: `409 STEAM_REFUND_NOT_SUPPORTED` (`err.isSteamRefundNotSupported`); periods of a Steam subscription that the wallet covered entirely are refundable in coins.
836
+
837
+ ### Sandbox: the clock tools
838
+
839
+ Sandbox runs the real renewal engine every minute, so a subscription you create there renews on its own a month later. Four sandbox-only endpoints move a subscription's clock and drive the real engine so you can get there in minutes:
840
+
841
+ ```ts
842
+ const server = new InvoServer({
843
+ gameSecret: process.env.INVO_SANDBOX_GAME_SECRET!,
844
+ baseUrl: "https://sandbox.invo.network/sandbox",
845
+ sandboxClockKey: process.env.INVO_SANDBOX_CLOCK_KEY!, // the SECOND credential, see below
846
+ });
847
+
848
+ const sb = server.sandbox.subscriptions;
849
+ await sb.advanceClock(id); // makes the next period due now ({ intervals: 1 }; 0 = "due now, don't move the window")
850
+ const run = await sb.forceRenewal(id); // runs the renewal immediately. CHARGES THE TEST CARD. run.engineStats → { renewed: 1 }
851
+ await sb.forceFailure(id); // synthesises a failed attempt and runs real dunning (no charge); call it 4× to reach expired
852
+ await sb.forceFailure(id, "insufficient_funds", { failureMessage: "wallet short" });
853
+ await sb.forceAuthChallenge(id); // moves it to awaiting_authentication (no charge; mints no link)
854
+ ```
855
+
856
+ > **Path note, loudly.** These four endpoints live **directly under the sandbox base, not under `/api`**: the full URL is `https://sandbox.invo.network/sandbox/subscriptions/<id>/advance-clock`. Because `baseUrl` already ends in `/sandbox`, the SDK posts to `/subscriptions/<id>/advance-clock` relative to it. They do not exist in production at all (404).
857
+ >
858
+ > **Second credential.** Every clock call sends `X-Game-Secret-Key` *and* `X-Sandbox-Clock-Key`, a separate per-game key (`ivclk_...`). Get it from the sandbox console: open the game, **Game Settings**, the **"Sandbox clock key"** card (generated the first time you reveal it; the same card rotates it, with a 7-day grace). Pass it as `sandboxClockKey`; a missing key throws `INVALID_INPUT` before the network, a wrong one is `401 SANDBOX_CLOCK_UNAUTHORIZED` (`err.isSandboxClockUnauthorized`). Keep it out of game clients and source control. None of these calls is auto-retried: each one moves the clock or runs the engine.
859
+
860
+ **Card recipe.** Make the sandbox game live and register a webhook. Save a card with `cards.beginSetup` using `paymentMethodId: "pm_card_visa"` (immediate) or `"pm_card_threeDSecure2Required"` (returns `requires_action`; finish on the client, then `confirmSetup`). `subscriptions.create` with that `playerCardId`: expect `firstCharge.status: "paid"`, `subscription.periodSeq: 2`, and a `subscription.renewed` delivery with `period_seq: 1`. Replay the same input: expect `idempotentReplay: true`. Then `advanceClock` + `forceRenewal` for as many periods as you like (`engineStats.renewed: 1`, `period_seq` advancing on each `subscription.renewed`); `forceFailure` four times (or swap in `"pm_card_chargeDeclined"` through `setPaymentMethod`, then advance + force four times) to walk `past_due` to `expired` with `final_period_end`; `changeAmount` then advance + force to see the old price on that renewal and the new one on the next; `cancel({ atPeriodEnd: true })` then advance + force to get `action: "retired-at-period-end"`; `refund` a paid period; and create one with `trialDays: 7` to see `skipped_trial` convert.
861
+
862
+ **Steam recipe.** In sandbox `steamFinalize` **does not call Steam**: it auto-approves a stand-in agreement and runs the real settlement (`fin.sandboxAutoApproved === true`), and `forceRenewal` treats the Steam charge as captured (`engineStats.steam_charged: 1, sandbox_synthetic: 1`). So sandbox proves INVO's currency path (coins, split, events, dunning), not Valve's charge: do one real Steam sandbox authorisation before launch. Credit the wallet above the price (a sandbox purchase), advance + force, and expect `funding.steam_charged_usd: "0.00"`.
863
+
864
+ ### Subscription errors
865
+
866
+ Match on `err.code` (and on `body.status` where the body carries one), never on the message.
867
+
868
+ | Helper / code | Meaning |
869
+ |---|---|
870
+ | `.isGameNotLive` | (403) create refused; the game is `testing`. Make it live in the console |
871
+ | `.isActiveSubscriptionExists` + `.existingSubscriptionId` | (409) the player already has a live subscription to this item. You regenerated `clientRequestId` in a retry loop |
872
+ | `.isIdempotentReplayMismatch` + `.mismatchedFields` | (409) same key, same player + item, different material terms. Use `changeAmount`/`setPaymentMethod`, or a new key |
873
+ | `.isFlowPaused` | (503) maintenance pause. Retry later with the **same** key |
874
+ | `.isSubscriptionTerminal` | (409) the subscription is `canceled`/`expired`. Start a new one |
875
+ | `.isSteamReauthorizationRequired` | (409) a price **increase** on Steam. Start a new Steam subscription at the new price |
876
+ | `.isNotACardSubscription` | (409) `setPaymentMethod` on a Steam subscription |
877
+ | `.isSteamChannelRequired` | (409) a non-Steam channel key tried to start a Steam subscription |
878
+ | `.isSteamAuthorizationPending` + `.existingSubscriptionId` | (409) `steamInit` for a player + item with a pending authorisation on different terms; or `steamFinalize` before the member authorised (`body.status: "not_authorized"`) |
879
+ | `.isNotAuthorized` | (409) `steamFinalize` before the member authorised. The normal wait state: call it again |
880
+ | `.isSteamRefundNotSupported` | (409) `refund` on a period charged through Steam |
881
+ | `.isAlreadyRefunded` | (409) the period was already refunded; treat as done |
882
+ | `.isSandboxClockUnauthorized` | (401) missing/wrong `X-Sandbox-Clock-Key`; reveal it in the sandbox console |
883
+ | `.isPhoneShareApprovalRequired` | (409) the supplied `playerPhone` belongs to another identity; run the phone-share flow, then retry |
884
+ | `PAYMENT_METHOD_NOT_FOUND` / `PAYMENT_METHOD_EXPIRED` / `PAYMENT_METHOD_INVALID` | the card is not this player's in this game, is expired, or the id is malformed |
885
+ | `WALLET_ONLY_SUBSCRIPTION` / `WALLET_ONLY_CONFLICT` | `walletOnly: true` with a card; or a wallet-only subscription needs `walletOnly: false` beside the new card |
886
+ | `NO_PAID_PERIOD` / `PERIOD_NOT_REFUNDABLE` / `AMOUNT_EXCEEDS_REMAINING` | refund refusals (the last carries `remaining_refundable_usd`) |
887
+ | `AMOUNT_TOO_SMALL_FOR_STEAM` / `STEAM_CHARGE_UNPLANNABLE` / `STEAM_UNAVAILABLE` / `STEAM_ERROR` | Steam init refusals; the last three abandoned the row (its id on `.existingSubscriptionId`): retry with a **new** key |
888
+ | `SETUP_REFERENCE_REUSED` / `PLAYER_NOT_FOUND` / `CARD_DECLINED` / `RAW_CARD_NOT_SUPPORTED` / `CARD_PERSIST_FAILED` | card capture; on `CARD_PERSIST_FAILED` (500) retry `confirmSetup` with the same `setupIntentId` |
889
+
890
+ Client-side guards (missing key, a `sub_`-prefixed key, a bad amount, a non-E.164 `playerPhone`, a trial or card field on Steam, a web session without `playerIp`, a missing `sandboxClockKey`) throw `InvoError` with `.status === 0` **before** any network call.
891
+
892
+ ### Traps
893
+
894
+ 1. **Replay before retry.** Same key on any timeout or 5xx. Never mint a new key inside a retry loop.
895
+ 2. **`requires_action` is not `paid`.** Nothing has been charged. Do not grant paid access until `subscription.renewed`.
896
+ 3. **`pending` is not `failed`.** Wait for the event; INVO resolves it.
897
+ 4. **`currentPeriodEnd` is not entitlement.** Use `paidThrough`.
898
+ 5. **`payment_failed` and `past_due` do not revoke access.** Only `expired` (at `final_period_end`) and `canceled` (at `access_until`) do.
899
+ 6. **`authentication_required` is not a failure.** Send the link, not a "payment failed" message.
900
+ 7. **Do not poll for renewals.** Handle `subscription.renewed`.
901
+ 8. **One live subscription per item, across rails.** Cancel the old one before creating a new one for the same `itemId`, or reprice with `changeAmount`.
902
+ 9. **Period numbers differ by road.** `subscription.periodSeq` after a paid charge is the *next* period; `firstCharge.paidPeriodSeq` and the webhook's `period_seq` are the period *just paid*. Key entitlement on the latter.
903
+ 10. **A card saved without off-session consent cannot back a subscription.** Hosted checkout and `savedCardId` purchases do not save one; use `cards.beginSetup` or a `save_card: true` purchase.
904
+ 11. **`walletOnly` is absolute.** A card attached later is ignored until you pass `walletOnly: false` on `setPaymentMethod`.
905
+ 12. **Price changes apply next period, and big jumps never apply.** More than double, or above 500.00, stays pending.
906
+ 13. **`sub_` is reserved** as a prefix for every idempotency key on the platform.
907
+ 14. **Do not store or log `confirmationUrl`** beside anything you publish. It is a bearer link.
908
+ 15. **Steam: finalize is your call**, the member has 24 hours, `web` needs `playerIp` and a top-level window, match the client callback on `steamOrderId`, show `amountCoins` (country-dependent, fixed at init), and `split.total_usd` on a Steam renewal is *not* the price.
909
+ 16. **Sandbox does not exercise Valve.** `sandboxAutoApproved: true` means the charge was simulated.
910
+
911
+ ---
912
+
595
913
  ## Player balance
596
914
 
597
915
  Read a player's currency balances (server-side, game-secret) **by email**:
@@ -609,7 +927,16 @@ comes from the token, no PII).
609
927
 
610
928
  ## Sends & transfers (move currency between players)
611
929
 
612
- Move already-owned game currency from one player to another, authorized by the **sender's passkey** — the [gold standard](#passkeys-are-the-gold-standard--dont-build-on-sms). (A deprecated SMS-PIN fallback exists for senders who aren't enrolled; treat it as a last resort, not a design.) **Send** and **transfer** are parallel flows:
930
+ Move already-owned game currency from one player to another, authorized by the **sender's passkey** — the [gold standard](#passkeys-are-the-gold-standard--dont-build-on-sms).
931
+
932
+ **There are exactly two approval paths, and both are passkeys:**
933
+
934
+ - **In-app passkey** — wherever WebAuthn can run in the client: a browser, or a web game on INVO's [hosted approval page](#web-games--approving-on-invos-hosted-page). `approveSend` / `approveTransfer` / `approveHosted`.
935
+ - **Device approval (QR)** — wherever it cannot: consoles, TVs, native Steam and desktop clients. The player approves on their phone; **your server then makes the call that moves the money**. See [Consoles and TVs](#consoles-and-tvs--approving-without-a-browser-rfc-8628) and [Sends and transfers, stage by stage](#sends-and-transfers-stage-by-stage).
936
+
937
+ A legacy SMS-PIN fallback still exists for a sender who cannot use either — it is [being retired](#legacy-fallback-the-sms-pin-being-retired) and new integrations should not build on it.
938
+
939
+ **Send** and **transfer** are parallel flows:
613
940
 
614
941
  | | Send | Transfer |
615
942
  |---|---|---|
@@ -644,14 +971,17 @@ const t = await server.initiateTransfer({
644
971
 
645
972
  // Check guardianApproval FIRST — the guardian path takes precedence.
646
973
  switch (true) {
647
- case !!t.guardianApproval: // minor/guardian path (HTTP 202) → pending approval, no PIN UI
648
- case t.verificationMethod === "in_app": // sender HAS a passkey → approve in the browser. The good path.
649
- case t.verificationMethod === "sms": // sender has NO passkey → offer enrollPasskey() and approve;
650
- // show the PIN pad only if they can't or won't enroll.
974
+ case !!t.guardianApproval: // minor/guardian path (HTTP 202) → a guardian is emailed a
975
+ // signed approve/decline link; poll, show no approval UI.
976
+ case t.verificationMethod === "in_app": // sender HAS a passkey → approve in the client. The good path.
977
+ default: // sender has NO passkey yet → enrol one (enrollPasskey() or
978
+ // approveHosted()), or run the QR flow on a console.
651
979
  }
652
980
 
653
981
  // 2. BROWSER — the sender approves with their passkey (give them t.transactionId + the player token)
654
982
  const approved = await client.approveTransfer(t.transactionId); // or approveSend(...)
983
+ // On a console / TV / native client there is no browser: run the device approval grant
984
+ // instead — begin → show QR → poll → approveWithDeviceCode. See "stage by stage".
655
985
  // approved.claimCode + approved.claimCodeExpiresAt (transfer only) — deliver if the recipient can't self-claim
656
986
 
657
987
  // 3. BROWSER — the recipient claims with their passkey; fall back to the claim code if not enrolled
@@ -668,10 +998,14 @@ try {
668
998
  }
669
999
  ```
670
1000
 
671
- - **`verificationMethod`** (from initiate): `"in_app"` → the sender has a passkey, go approve (the recommended path); `"sms"` → **the sender has no passkey** and a PIN was sent as a deprecated fallback — the best response is to offer `enrollPasskey()` and then `approveSend`/`approveTransfer`, showing the PIN pad only if they can't or won't enroll; `undefined` + `guardianApproval` → minor/guardian (HTTP 202), do **not** show the PIN UI. On the guardian path the SDK reports `verificationMethod: undefined` (even though the raw 202 body also carries `"sms"`) so `guardianApproval` wins — but branch on it first to be safe.
1001
+ - **`verificationMethod`** (from initiate): `"in_app"` → the sender has a passkey, go approve — the path you want. `"sms"` → read it as **"this sender has no passkey yet"**: offer enrollment (`enrollPasskey()`, or `approveHosted()` where you hold no verified domain), or run the [device approval grant](#consoles-and-tvs--approving-without-a-browser-rfc-8628) on a console. `undefined` + `guardianApproval` → minor/guardian (HTTP 202), show no approval UI. On the guardian path the SDK reports `verificationMethod: undefined` (even though the raw 202 body also carries `"sms"`) so `guardianApproval` wins — but branch on it first to be safe.
672
1002
  - **Claim codes** are returned only by `approveTransfer`; they're the out-of-band fallback when the recipient isn't enrolled.
673
1003
  - **`err.isReceiverNotEnrolled`** on `confirmReceipt*` is the explicit signal to switch to claim-code entry.
674
- - **Recipients without the game collect from the SMS.** The claim text a send's receiver gets
1004
+ - **The one message that is still a text: the claim link to a phone-only recipient.** A
1005
+ send can be addressed to someone INVO has never met — the sender knows their phone number
1006
+ and nothing else, so there is no email to write to and no session to notify. That is the
1007
+ only remaining place INVO sends an SMS by default; everything else that needs a human
1008
+ (guardian consent, enrolment backup, phone-share) goes by **email first**. The claim text a send's receiver gets
675
1009
  now ends with a link to a hosted INVO page ("Or collect here: …"). They see who sent what in
676
1010
  which game, enter **one email** (the same thing in-game claim already requires), confirm it
677
1011
  with an emailed 6-digit code, and their phone's fingerprint / face / screen lock creates an
@@ -724,6 +1058,186 @@ try {
724
1058
  > **Seeing incoming transfers from other games?** They come back as **`kind: "receiving_confirm"`** — render **both** kinds (a UI that only shows `identity_gate` will miss all inbound). The list is scoped to the token's player, so mint the token for the **recipient**. PII-free (no claim code / phone).
725
1059
  - **Server (game-secret):** `server.getInboundPending({ playerEmail | playerPhone })` — richer, includes `toPhone`/`toIdentityId` for routing a notification to the right account. Match `toPhone` to the player (`toIdentityId` is null when the phone maps to >1 of your players).
726
1060
 
1061
+ ### Legacy fallback: the SMS PIN (being retired)
1062
+
1063
+ **This is the legacy path. It is being retired, and new integrations should not build on
1064
+ it.** It is kept working only for a sender who genuinely cannot approve with a passkey:
1065
+ an unsupported device with no platform authenticator, or a player who declines both the
1066
+ in-app ceremony and the QR flow.
1067
+
1068
+ When a sender has no enrolled approver, `initiateSend` / `initiateTransfer` return
1069
+ `verificationMethod: "sms"` and a one-time PIN is texted. The completion calls are
1070
+ `server.verifySmsTransfer(txnId, pin)` / `verifySmsSend(txnId, pin)` — **deprecated since
1071
+ 3.1.0**, still fully functional, no runtime warning. They will be removed at some future
1072
+ major; no date is being promised.
1073
+
1074
+ Why it is going away: a PIN in a text is a shared secret on a channel exposed to SIM swap,
1075
+ SS7 interception and social engineering, it costs real money per message at every scale,
1076
+ and it depends on carrier delivery INVO does not control. A passkey — in the client where
1077
+ WebAuthn can run, on the player's phone by QR where it cannot — is stronger, faster and
1078
+ free. Read `verificationMethod: "sms"` as *"this sender has no passkey yet"* and offer them
1079
+ one; show a PIN pad only when there is no other way to serve that specific player.
1080
+
1081
+
1082
+ ---
1083
+
1084
+ ## Sends and transfers, stage by stage
1085
+
1086
+ One reference for the whole money path — **both flows** (send and transfer) and **both
1087
+ sides** (the sender who authorises, the recipient who collects). It exists because the
1088
+ stages are easy to read as three when there are four, and the fourth one is the money.
1089
+
1090
+ > Companion page, same title, on the docs site:
1091
+ > [**Sends and transfers, stage by stage**](https://docs.invo.network/docs/sends-and-transfers-stage-by-stage)
1092
+ > — the same walkthrough with the raw REST calls, for stacks that don't use this package.
1093
+
1094
+ **The four stages.**
1095
+
1096
+ 1. **Initiate** (your server). Nothing has moved; a transaction now exists, pending the
1097
+ sender's approval.
1098
+ 2. **Prove who is approving.** A passkey ceremony in the browser, on INVO's hosted page,
1099
+ or — where no browser exists — a device approval grant on the player's phone.
1100
+ 3. **Settle** (your server, for the grant path). **A proof is not a payment.** The
1101
+ approval says *who*; a separate call moves the value and runs every gate (guardian,
1102
+ risk, recovery cooldown). In the browser `approveSend` / `approveTransfer` does both
1103
+ at once, which is why the split only becomes visible on the grant path.
1104
+ 4. **Collect.** The recipient confirms receipt (their own passkey, or the grant), or
1105
+ redeems the claim code. Reconcile off webhooks, never off stage 3's response alone.
1106
+
1107
+ ### What your server must call, in order
1108
+
1109
+ | # | Stage | Send | Transfer | Auth |
1110
+ |---|---|---|---|---|
1111
+ | 1 | Initiate | `server.initiateSend(...)` | `server.initiateTransfer(...)` | game secret |
1112
+ | 2 | Mint the player's session | `server.mintPlayerToken({ playerEmail })` | same | game secret |
1113
+ | 3a | Sender approves — **browser** | `client.approveSend(txnId)` | `client.approveTransfer(txnId)` | player token |
1114
+ | 3b | Sender approves — **web, hosted page** | `client.approveHosted({ transactionId, flow: "send" })` | `… flow: "transfer"` | player token |
1115
+ | 3c | Sender approves — **console / TV / native** | `server.beginDeviceApproval({ flow: "send" })` → `pollDeviceApproval` | `… flow: "transfer"` | **player** token |
1116
+ | 4 | **Settle the grant** (3c only) | **`server.approveWithDeviceCode({ flow: "send", deviceCode })`** | **`… flow: "transfer"`** | **player** token |
1117
+ | 5a | Recipient collects — browser | `client.confirmReceiptSend(txnId)` | `client.confirmReceiptTransfer(txnId)` | player token |
1118
+ | 5b | Recipient collects — console | `begin`/`poll` `flow: "send_receipt"` → **`approveWithDeviceCode`** | `… flow: "transfer_receipt"` → **`approveWithDeviceCode`** | **player** token |
1119
+ | 5c | Recipient collects — claim code | `server.claimCurrency({ claimCode, … })` | `server.claimTransfer({ claimCode, … })` | game secret |
1120
+ | 6 | Reconcile | `transfer.claim_pending` → `transfer.received` webhooks | same | webhook secret |
1121
+
1122
+ Steps 3c, 4 and 5b take the **player token explicitly** — on a console the game *server*
1123
+ holds the token it minted, and the game secret is never sent on any of them.
1124
+
1125
+ ### The four device-approval flows
1126
+
1127
+ `flow` picks which endpoint stage 4 settles against. Begin with one flow and settle with
1128
+ the same one: a grant approved for `transfer` settles nothing else.
1129
+
1130
+ | Side | `flow` | What `approveWithDeviceCode` calls | Success looks like |
1131
+ |---|---|---|---|
1132
+ | Sender, send | `send` | `POST /api/sdk/send/{id}/approve` | `status: "approved"`, `next: "pending_claim"` |
1133
+ | Sender, transfer | `transfer` | `POST /api/sdk/transfers/{id}/approve` | `status: "approved"`, `next: "pending_claim"`, `claimCode` |
1134
+ | Recipient, send | `send_receipt` | `POST /api/sdk/send/{id}/confirm-receipt` | `status: "completed"`, `amountReceived` |
1135
+ | Recipient, transfer | `transfer_receipt` | `POST /api/sdk/transfers/{id}/confirm-receipt` | `status: "completed"`, `amountReceived` |
1136
+
1137
+ ### Errors on the money path
1138
+
1139
+ | Code | HTTP | Means | Do |
1140
+ |---|---|---|---|
1141
+ | `TRANSACTION_NOT_PENDING` | 400 | The transaction is not at this step. Three different situations: your earlier attempt **already landed**; the transaction is **dead** (expired / refunded); or — on a receipt flow — it has **not got here yet**, because the sender's own approval is still pending or held at a guardian. | **Not thrown by `approveWithDeviceCode`** — it comes back as `{ status: "not_pending", alreadySettled, currentStatus }`. `alreadySettled` separates the first case from the other two. When it is `false`, go read `getTransferStatus` / `getSendStatus` rather than assuming; never retry-loop. |
1142
+ | `DEVICE_APPROVAL_NOT_APPROVED` | 400 | The `device_code` was unknown, another player's, bound to a different transaction, bound to a different **flow**, or the player has not approved yet. One answer for all five, deliberately — distinguishing them would leak which transactions have a live approval. | `err.isDeviceApprovalNotApproved`. Check the `flow` matches the `begin`, and that the poll actually said `approved`. |
1143
+ | `DEVICE_APPROVAL_ALREADY_PENDING` | 409 | An **approved** grant for this transaction and flow is still inside its window. The player already approved. | `err.isDeviceApprovalAlreadyPending`, `err.deviceApprovalExpiresAt`. You are missing stage 4, not a new code — call `approveWithDeviceCode` with the code you have. (A merely *pending* earlier grant does **not** 409; `begin` supersedes it.) |
1144
+ | `PASSKEY_RECOVERY_COOLDOWN` | 403 | Money **out** is paused for 24 h after a passkey recovery (SIM-swap protection). Receiving and collecting are unaffected. | `err.isPasskeyRecoveryCooldown`, `err.retryAfterAt` (ISO; the body also carries `retry_after_seconds`). Expect a fresh initiate later — do not retry-loop. |
1145
+ | `SEND_APPROVE_FAILED`, `TRANSFER_APPROVE_FAILED`, `CONFIRM_RECEIPT_FAILED` | 400 | A **fault** on INVO's side, not a rule. `err.isSettleFault`; the body carries **`error_ref`** (`err.errorRef`). | Never retryable. See the ambiguity note below — do **not** tell the player it failed until you have read the transaction. Quote `errorRef` to INVO support; it names the exact server log line. |
1146
+ | guardian hold | 202 | A minor's transaction is waiting on a guardian. **The money is held, not refused.** | Returned as a result with `holdReason`; poll `getGuardianApprovalStatus`. Terminal outcomes (`GUARDIAN_APPROVAL_REJECTED` / `_EXPIRED`) throw as 410. |
1147
+
1148
+ **Also reachable from a receipt settle** (`send_receipt` / `transfer_receipt`) — a console
1149
+ recipient built only from the table above ships with no fallback for these:
1150
+
1151
+ | Code | HTTP | Means | Do |
1152
+ |---|---|---|---|
1153
+ | `receiver_not_enrolled_use_claim_code` | 409 | The recipient has no passkey in this game, so there is no in-app confirm to run. | `err.isReceiverNotEnrolled`. Fall back to the claim code — show it, or point them at the hosted claim link from their text. |
1154
+ | `not_intended_receiver` | 403 | The token's identity is not the addressed recipient. | Not retryable. You minted the token for the wrong player, or the send was addressed to a different phone. |
1155
+ | `PHONE_SHARE_APPROVAL_REQUIRED` | 409 | The receiver phone is contested, so INVO **holds the money** and asks its owner to approve. | `err.isPhoneShareApprovalRequired`. Not a failure: show `err.message` verbatim (`err.phoneShareLast4` names the phone), then **retry the same call** once approved — it then succeeds idempotently. On denial/expiry the sender is refunded. |
1156
+ | `RECIPIENT_IDENTITY_PENDING` | 202 | Same shape, on the identity check: **money held**, the phone's owner emailed. | Comes back as a result with `holdReason`, not a throw. Keep the collect pending and retry later. |
1157
+ | `RECIPIENT_IDENTITY_DECLINED` | 403 | The phone's owner said no. | Terminal. The sender is refunded; do not retry. |
1158
+
1159
+ > ⚠️ **A settle FAILURE is ambiguous about the money.** INVO commits the transfer and
1160
+ > *then* builds its `200` by reading the transaction back — so a fault raised after that
1161
+ > commit answers `400 *_FAILED` for money that **already moved**. A `err.status === 0`
1162
+ > (timeout, dropped connection) is ambiguous for exactly the same reason, and this call is
1163
+ > deliberately never auto-retried. On either: read `getTransferStatus` / `getSendStatus`,
1164
+ > or wait for the `transfer.claim_pending` webhook, **before** you tell the player it
1165
+ > failed — and never auto-start a replacement transaction.
1166
+
1167
+ ### "Already settled" is not a refusal
1168
+
1169
+ The integrator question this section was written for: *did the guard stop me, or is her
1170
+ gold stuck?* You must be able to answer that without matching on message text.
1171
+
1172
+ `approveWithDeviceCode` **does not throw** for `TRANSACTION_NOT_PENDING`. It returns:
1173
+
1174
+ ```ts
1175
+ const r = await server.approveWithDeviceCode({ playerToken, transactionId, flow: "transfer", deviceCode });
1176
+ if (r.status === "not_pending") {
1177
+ if (r.alreadySettled) {
1178
+ // This step already happened — typically your first attempt landed and the response
1179
+ // was lost. r.currentStatus says where it is now (pending_claim, completed…).
1180
+ } else {
1181
+ // NOT settled. Either dead (expired / failed / refunded), or — on a receipt flow —
1182
+ // not there YET: the sender has not approved, or their approval is held at a
1183
+ // guardian. It is also what an unrecognised status returns, deliberately.
1184
+ // Go and read it; do not guess and do not start a replacement transaction:
1185
+ const t = await server.getTransferStatus(transactionId);
1186
+ }
1187
+ } else {
1188
+ // status "approved" (+ next: "pending_claim", claimCode on a transfer)
1189
+ // or "completed" (+ amountReceived) on the receipt flows
1190
+ // or a 202 hold — r.holdReason names it.
1191
+ }
1192
+ ```
1193
+
1194
+ Every other refusal is a normal thrown `InvoError` with a typed predicate, so a
1195
+ `try`/`catch` around this call still means "something is wrong". Nothing in your code has
1196
+ to read an English sentence to tell the two apart.
1197
+
1198
+ **`alreadySettled` fails closed.** It is `true` only for a status INVO knows to be past
1199
+ this flow's step — and the two receipt flows have a *different* set from the two sender
1200
+ flows, because the four endpoints gate on different statuses. Anything else, including a
1201
+ status this SDK version has never seen, answers `false` with `currentStatus` set. Cautious
1202
+ and wrong costs you a status lookup; confident and wrong credits goods for money that
1203
+ never arrived.
1204
+
1205
+ *(Older INVO deployments answered this case with only a message — "Transaction not pending
1206
+ PIN verification…", "…cannot be confirmed…" — and no machine code. The SDK matches those
1207
+ shapes too, so `alreadySettled` is correct against an older backend without any
1208
+ string-matching in your code. That fallback requires HTTP 400, one of those two phrases,
1209
+ **and** a readable `(current status: …)` / `(status: …)` clause: "cannot be confirmed" is
1210
+ ordinary English, so a phrase match alone is never allowed to assert that money moved.)*
1211
+
1212
+ ### Common mistakes
1213
+
1214
+ > **1. Polling to `approved` and stopping.** The one that costs real money. A device
1215
+ > approval grant is a **factor**, not a payment: `approved` means the player proved who
1216
+ > they are, and the transaction is still sitting at `pending_pin_verification`. **You must
1217
+ > call `approveWithDeviceCode`.** Nothing else in this SDK settles it, and no webhook does
1218
+ > it for you — `device_approval.approved` is the *cue* to call it. Left alone, the
1219
+ > transaction expires on its own window and is refunded.
1220
+ >
1221
+ > **2. Treating "already settled" as a failure.** A repeat call after a crash or a lost
1222
+ > response answers `TRANSACTION_NOT_PENDING`. That is your earlier attempt succeeding, not
1223
+ > a refusal. Branch on `r.alreadySettled` — never on the message.
1224
+ >
1225
+ > **3. Sending the game secret on the grant calls.** Every device-approval call
1226
+ > authenticates with the **player token**. A game secret in a console build is a game
1227
+ > secret in a disassembler.
1228
+ >
1229
+ > **4. Beginning a second grant instead of settling the first.** If `begin` answers
1230
+ > `409 DEVICE_APPROVAL_ALREADY_PENDING`, the player has already approved; you need stage
1231
+ > 4, not another QR.
1232
+ >
1233
+ > **5. Polling faster than `interval`.** You get `slow_down`; add 5 seconds and resume.
1234
+ >
1235
+ > **6. Using the wrong `flow` at stage 4.** The sender's grant (`transfer`) cannot settle
1236
+ > the recipient's step (`transfer_receipt`) — it answers `DEVICE_APPROVAL_NOT_APPROVED`,
1237
+ > which reads like a broken code and is really a wrong flow.
1238
+ >
1239
+ > **7. Granting value off stage 3's HTTP response.** Reconcile off webhooks.
1240
+
727
1241
  ---
728
1242
 
729
1243
  ## Passkeys (enroll, approve, link, recover)
@@ -894,13 +1408,42 @@ Security notes, in plain language:
894
1408
 
895
1409
  A console has no browser, so it cannot run a passkey ceremony at all. **Device
896
1410
  Approval** moves the ceremony to a device that can: your game shows a short code, the
897
- player approves on their phone, your server polls until it hears back. It is the
1411
+ player approves on their phone, your server polls until it hears back — **and then your
1412
+ server makes the call that actually moves the money.** It is the
898
1413
  [OAuth 2.0 Device Authorization Grant, RFC 8628](https://datatracker.ietf.org/doc/html/rfc8628)
899
1414
  — the same flow every console and TV app uses — so a standard client library understands
900
1415
  the responses.
901
1416
 
902
- **Not an SDK method** — it is a server-to-server REST flow, because the polling has to
903
- happen on your backend, not in the game client.
1417
+ > **The grant is a factor, not a payment.** Reaching `approved` proves *who* approved and
1418
+ > settles **nothing**. The transaction is still waiting. `approveWithDeviceCode` is the
1419
+ > money step, and without it the transaction expires and is refunded. This is the single
1420
+ > most common integration failure on this flow — see
1421
+ > [Sends and transfers, stage by stage](#sends-and-transfers-stage-by-stage).
1422
+
1423
+ **Four SDK methods, since 3.7.0** (`server.beginDeviceApproval`, `pollDeviceApproval`,
1424
+ `confirmDeviceEnrollment`, **`approveWithDeviceCode`**), plus the optional
1425
+ `completeDeviceApproval` loop. Earlier versions documented this as raw REST only, which is
1426
+ how a grant could be polled to `approved` and then dropped. The REST endpoints are
1427
+ unchanged and still usable directly.
1428
+
1429
+ Every one of these calls authenticates with the **player token**, never the game secret —
1430
+ on a console it is your *server* that holds the token it minted for the player.
1431
+
1432
+ **The endpoints underneath**, for a stack that is not using this package. All four take
1433
+ `Authorization: Bearer <player token>`; none takes the game secret:
1434
+
1435
+ | SDK method | Endpoint |
1436
+ |---|---|
1437
+ | `beginDeviceApproval` | `POST /api/sdk/approvals/device/begin` |
1438
+ | `pollDeviceApproval` | `POST /api/sdk/approvals/device/poll` |
1439
+ | `confirmDeviceEnrollment` | `POST /api/sdk/approvals/device/confirm-enrollment` |
1440
+ | **`approveWithDeviceCode`**, `flow: "send"` | **`POST /api/sdk/send/{transaction_id}/approve`** |
1441
+ | **`approveWithDeviceCode`**, `flow: "transfer"` | **`POST /api/sdk/transfers/{transaction_id}/approve`** |
1442
+ | **`approveWithDeviceCode`**, `flow: "send_receipt"` | **`POST /api/sdk/send/{transaction_id}/confirm-receipt`** |
1443
+ | **`approveWithDeviceCode`**, `flow: "transfer_receipt"` | **`POST /api/sdk/transfers/{transaction_id}/confirm-receipt`** |
1444
+
1445
+ Each settle call takes the body `{"device_code": "..."}` and the player's bearer token —
1446
+ the same token that began the grant.
904
1447
 
905
1448
  **Available to every title, with nothing to configure.** The constraint is a property of
906
1449
  the *device*, not your game: a title with a website *and* a console build uses the normal
@@ -912,52 +1455,133 @@ authenticator from inside the engine — so a native desktop title uses this QR
912
1455
  a console does. It is the **client** that forces QR here, not the OS.
913
1456
 
914
1457
  ```ts
915
- // 1. Your server starts an approval for ONE transaction.
1458
+ import { InvoServer } from "@invonetwork/web-sdk/server";
1459
+
1460
+ const server = new InvoServer({
1461
+ gameSecret: process.env.INVO_GAME_SECRET!,
1462
+ baseUrl: "https://sandbox.invo.network/sandbox",
1463
+ });
1464
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
1465
+
1466
+ // The player token your server minted for this player (mintPlayerToken).
1467
+ const playerToken = session.invoPlayerToken;
1468
+
1469
+ // 1. BEGIN — start an approval for ONE transaction.
916
1470
  // flow: "transfer" | "send" | "send_receipt" | "transfer_receipt"
917
- // channel (optional, default "qr"): how the page is delivered — "qr" (console / TV /
918
- // native desktop), "popup" (the browser itself calls begin: that is approveHosted),
919
- // "app_browser" (the Unity / Unreal plugin opens the system browser)
920
- const start = await fetch(`${INVO_BASE}/api/sdk/approvals/device/begin`, {
921
- method: "POST",
922
- headers: { Authorization: `Bearer ${sdkSessionToken}`, "Content-Type": "application/json" },
923
- body: JSON.stringify({ transaction_id: transferId, flow: "transfer", channel: "qr" }),
924
- }).then((r) => r.json());
925
- // -> { device_code, user_code, verification_uri, verification_uri_complete,
926
- // expires_in, interval, channel }
927
-
928
- // 2. The game renders `verification_uri_complete` as a QR and prints `user_code`
929
- // under it. The QR already contains the code, so most players never type.
930
-
931
- // 3. Poll from your SERVER, never faster than `interval` seconds.
932
- const poll = await fetch(`${INVO_BASE}/api/sdk/approvals/device/poll`, {
933
- method: "POST",
934
- headers: { Authorization: `Bearer ${sdkSessionToken}`, "Content-Type": "application/json" },
935
- body: JSON.stringify({ device_code: start.device_code }),
936
- }).then((r) => r.json());
937
- // approved -> { status: "approved", transaction_id, flow }
938
- // authorization_pending -> keep polling
939
- // slow_down -> back off, then resume
940
- // expired_token -> start a new approval
941
- // access_denied -> the player declined; do not retry silently
942
- // invalid_grant -> unknown or not yours
1471
+ // channel (optional, default "qr"): "qr" (console / TV / native desktop),
1472
+ // "app_browser" (the Unity / Unreal plugin opens the system browser).
1473
+ // "popup" is browser-only — that is client.approveHosted().
1474
+ const grant = await server.beginDeviceApproval({
1475
+ playerToken,
1476
+ transactionId,
1477
+ flow: "transfer",
1478
+ });
1479
+ // grant: { deviceCode, userCode, verificationUri, verificationUriComplete,
1480
+ // expiresIn, interval, channel, raw }
1481
+
1482
+ // 2. SHOW — render grant.verificationUriComplete as a QR and print grant.userCode
1483
+ // under it. The QR already carries the code, so most players never type.
1484
+ // Keep grant.deviceCode on your server: it is a bearer credential.
1485
+
1486
+ // 3. POLL — never faster than grant.interval seconds.
1487
+ let interval = grant.interval;
1488
+ for (;;) {
1489
+ await sleep(interval * 1000);
1490
+ const poll = await server.pollDeviceApproval({ playerToken, deviceCode: grant.deviceCode });
1491
+
1492
+ if (poll.status === "authorization_pending") {
1493
+ // A first-time phone may be waiting on YOUR screen — see `enrollment` below.
1494
+ if (poll.enrollment) showMatchPrompt(poll.enrollment);
1495
+ if (poll.interval) interval = poll.interval;
1496
+ continue;
1497
+ }
1498
+ if (poll.status === "slow_down") { interval += 5; continue; } // RFC 8628 §3.5
1499
+ if (poll.status === "access_denied") return playerDeclined();
1500
+ if (poll.status === "expired_token") return startOver(); // begin again
1501
+
1502
+ // 4. APPROVED → **CALL THE MONEY STEP.** Nothing has moved until this returns.
1503
+ const settle = await server.approveWithDeviceCode({
1504
+ playerToken,
1505
+ transactionId,
1506
+ flow: "transfer", // the SAME flow you began with
1507
+ deviceCode: grant.deviceCode,
1508
+ });
1509
+
1510
+ if (settle.status === "not_pending") {
1511
+ // Your earlier attempt already landed (settle.alreadySettled) or the transaction
1512
+ // is dead (expired / refunded). Read settle.currentStatus. Not a refusal.
1513
+ } else {
1514
+ // "approved" + next: "pending_claim" (+ settle.claimCode on a transfer), or
1515
+ // "completed" + settle.amountReceived on the receipt flows, or a 202 hold
1516
+ // (settle.holdReason).
1517
+ }
1518
+ break;
1519
+ }
943
1520
  ```
944
1521
 
1522
+ **Or let the SDK run stages 3 and 4** — `completeDeviceApproval` polls on `interval`,
1523
+ adds 5 s on `slow_down`, surfaces the enrollment prompt, and on `approved` calls
1524
+ `approveWithDeviceCode` for you:
1525
+
1526
+ ```ts
1527
+ const done = await server.completeDeviceApproval({
1528
+ playerToken,
1529
+ transactionId,
1530
+ flow: "transfer",
1531
+ deviceCode: grant.deviceCode,
1532
+ interval: grant.interval,
1533
+ onEnrollment: (e, respond) => {
1534
+ if (!e) return hideMatchPrompt();
1535
+ showMatchPrompt(e); // "Set up INVO on <e.deviceLabel>? Code <e.matchCode>"
1536
+ // ALWAYS attach a .catch: this is called without await, and an unhandled rejection
1537
+ // exits a Node process. A prompt the grant has outlived resolves quietly, but any
1538
+ // other refusal rejects — log it and move on; the next poll reports the real state.
1539
+ onPlayerAnswer((yes) =>
1540
+ respond(yes ? "approve" : "deny").catch((err) => log.warn("enrolment answer lost", err)),
1541
+ );
1542
+ },
1543
+ });
1544
+ // done.status: "approved" (done.settlement carries the result) | "denied" | "expired" | "aborted"
1545
+ ```
1546
+
1547
+ > **Convenience only.** It holds a request open for as long as the player takes, so it
1548
+ > suits a job or a per-player worker, not a request handler with a short timeout. And
1549
+ > because it moves money from inside a loop, **record the attempt in your own store before
1550
+ > the loop starts** — if your process dies between the approve call and its response, the
1551
+ > only way to know whether the money moved is a record you wrote first, plus
1552
+ > `getTransferStatus` / `getSendStatus`. Servers that can't hold a loop open should use
1553
+ > the three calls directly and keep `deviceCode` in their own store.
1554
+
945
1555
  - **One approval authorises one transaction.** Unlike the plain RFC 8628 grant, which
946
- authorises a *client*, an INVO device code is bound to the transaction you named and is
947
- consumed when used. It cannot approve anything else and cannot be reused.
948
- - **`user_code` is meant to be seen; `device_code` is not.** Poll from your backend.
949
- - **One live code per transaction.** Starting a second returns
950
- `409 DEVICE_APPROVAL_ALREADY_PENDING` — reuse the one you have or let it expire. Once an
951
- *approved* code's own window has passed, `begin` works again for the same transaction
952
- (useful if your server lost the `device_code` after the player approved — that used to
953
- 409 until the transaction itself expired).
1556
+ authorises a *client*, an INVO device code is bound to the transaction **and the flow**
1557
+ you named. It cannot approve anything else.
1558
+ - **When the code is spent: at the money step, not at approval.** The `device_code` stops
1559
+ being usable when `approveWithDeviceCode` settles the transaction — because the
1560
+ transaction is then no longer pending, and that is what the settle call checks under a
1561
+ row lock. Polling to `approved` consumes nothing; a *second* `approveWithDeviceCode`
1562
+ with the same code answers `TRANSACTION_NOT_PENDING` (returned as
1563
+ `status: "not_pending"`, not thrown) — which, on a sender flow, is how you confirm that a
1564
+ settle whose response you lost did in fact land.
1565
+ - **`userCode` is meant to be seen; `deviceCode` is not.** Poll from your backend, never
1566
+ from the game client, and never log or render the device code.
1567
+ - **One live code per transaction and flow.** Calling `begin` again while an earlier grant
1568
+ is merely *pending* **supersedes** it — you get a fresh code and a page still open on the
1569
+ old one is told to scan again (that is the right answer when a player retries after a
1570
+ crash or an abandoned phone ceremony). If the earlier grant was already **approved**, the
1571
+ begin is refused with `409 DEVICE_APPROVAL_ALREADY_PENDING` + `expires_at`
1572
+ (`err.isDeviceApprovalAlreadyPending`, `err.deviceApprovalExpiresAt`): the player has
1573
+ approved and you are missing the money step, not a new code. Once that approved grant's
1574
+ own window passes, `begin` works again for the same transaction. The sender's grant and
1575
+ the recipient's are scoped separately, so `transfer` and `transfer_receipt` never block
1576
+ each other.
954
1577
  - **Starting an approval extends the transaction's window.** For `transfer` and `send`,
955
1578
  `begin` pushes the transaction's own approval window past the code's expiry, so an
956
1579
  approval at minute nine can't land on a transfer that has already expired and been
957
1580
  refunded.
958
1581
  - **Subscribe to `device_approval.approved`** to learn the moment an approval lands
959
- instead of waiting for the next poll. Polling still works alone; the webhook is a
960
- latency improvement, not a replacement.
1582
+ instead of waiting for the next poll — then **call `approveWithDeviceCode`**. The
1583
+ webhook is a latency improvement, not the money step and not a replacement for it; the
1584
+ `transfer.*` lifecycle events that follow are what you reconcile against.
961
1585
  - **First-time approvers enrol on the spot — your only job is one Yes/No prompt.** The
962
1586
  approval page uses a passkey registered with INVO, on INVO's own domain; a passkey the
963
1587
  player set up on *your* domain is a different credential and cannot be used there — that
@@ -987,20 +1611,20 @@ const poll = await fetch(`${INVO_BASE}/api/sdk/approvals/device/poll`, {
987
1611
  *replacing* a lost INVO passkey — word the prompt "Replace your INVO passkey with this
988
1612
  iPhone? Code 48-27" and answer through the same `confirm-enrollment` (see *Recovering a
989
1613
  lost passkey* below).
990
- - **Answer it: `POST /api/sdk/approvals/device/confirm-enrollment`** — same auth as
991
- begin/poll (the sender's SDK session token).
1614
+ - **Answer it: `confirmDeviceEnrollment`** — same player token as begin/poll
1615
+ (`POST /api/sdk/approvals/device/confirm-enrollment` underneath).
992
1616
 
993
1617
  ```ts
994
- const r = await fetch(`${INVO_BASE}/api/sdk/approvals/device/confirm-enrollment`, {
995
- method: "POST",
996
- headers: { Authorization: `Bearer ${sdkSessionToken}`, "Content-Type": "application/json" },
997
- body: JSON.stringify({ device_code: start.device_code, decision: "approve" }), // or "deny"
998
- }).then((r) => r.json());
999
- // 200 { status: "confirmed" | "denied" }
1000
- // 409 DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED { decided, via }
1618
+ const r = await server.confirmDeviceEnrollment({
1619
+ playerToken,
1620
+ deviceCode: grant.deviceCode,
1621
+ decision: "approve", // or "deny"
1622
+ });
1623
+ // r.status: "confirmed" | "denied"
1624
+ // throws 409 DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED { decided, via }
1001
1625
  // -> the backup email answered first; take the prompt down quietly
1002
- // 409 DEVICE_APPROVAL_NO_ENROLLMENT_PENDING -> no phone has asked
1003
- // 400 invalid_grant / expired_token
1626
+ // throws 409 DEVICE_APPROVAL_NO_ENROLLMENT_PENDING -> no phone has asked
1627
+ // throws 400 invalid_grant / expired_token
1004
1628
  ```
1005
1629
 
1006
1630
  **Deny ends the grant**: poll returns `access_denied`, and the phone says it was declined
@@ -1103,6 +1727,12 @@ export const POST = createWebhookHandler({
1103
1727
  | `item.purchased` | every item purchase | **grant the in-game item** (payload includes `transaction_id, order_id, player_email, identity_id, item_id, item_name, item_quantity, unit_price, total_price, currency_name, new_balance, fee_breakdown`) |
1104
1728
  | `platform_commerce.purchased` | every Platform Commerce purchase (balance immediately; **card after payment settles**) | **fulfill the ecommerce order** — never on the browser confirm (payload: `transaction_id, order_id, funding_source, player_email, identity_id, item_id, item_name, item_quantity, total_price`; + `unit_price, currency_name, new_balance` on balance; `total_price_usd` on card; `fee_breakdown`) |
1105
1729
  | `platform_commerce.refunded` | a Platform Commerce refund | handle the reversal (payload: `order_id, funding_source, player_email, refunded_amount, amount_unit, fee_retained`) |
1730
+ | `subscription.renewed` | every successfully charged subscription period, **including period 1** | **extend access** to `period_end` (the new `paid_through`) — the source of truth for entitlement (payload: `subscription_id, item_id, period_seq, transaction_id, order_id, mint_order_id, player_email, identity_id, amount_usd, amount_coins, period_start, period_end, current_period_*, next_charge_at, funding { rail, balance_applied_coins, card_charged_usd, steam_charged_usd, minted_coins, new_balance }, split { basis, total_usd, invo_fee_usd, partner_revenue_usd, … }, revenue_share_attribution, metadata`) |
1731
+ | `subscription.payment_failed` / `subscription.past_due` | every failed attempt / entering `past_due` once | notify the member; **access is retained** — do not revoke (`failure_code, retry_at, retries_remaining, grace_period_end, access_retained`) |
1732
+ | `subscription.authentication_required` | a card issuer wants the cardholder to authenticate (card rail) | **not a failure** — relay `confirmation_url` before `expires_at` |
1733
+ | `subscription.canceled` | a cancel request (yours, or the member's from Steam: `canceled_by`) | revoke at `access_until` |
1734
+ | `subscription.expired` | the retry budget ran out, a Steam row was never authorised (`steam_authorization_abandoned`), or Steam value could no longer be spent here (`steam_containment`) | **revoke at `final_period_end`** (not `ended_at`; `null` if nothing was ever paid) |
1735
+ | `subscription.refunded` | a period refund | record the reversal (`refund.partner_revenue_reversed_usd`, `is_full_refund`, `revenue_share_attribution`) |
1106
1736
  | `transfer.received` / `transfer.claim_expired` / `transfer.refunded` | sends & transfers | reconcile claim state — credited to the recipient (by any claim path, the hosted claim page included) / not collected within 24h / returned to the sender |
1107
1737
 
1108
1738
  Don't block waiting on `purchase.failed` for the `game`/`steam` rails — they only emit `completed`/`refunded`. Reconcile off `*.completed` + the status endpoints. For Platform Commerce **card** orders, fulfill on `platform_commerce.purchased`, not the browser confirmation.
@@ -1195,6 +1825,7 @@ Helpers:
1195
1825
  | `.isPhoneShareAlreadyApproved` | phone-share was already approved (e.g. from a `/reject`) |
1196
1826
  | `.isSourceGameNotLive` | **(403)** the caller's OWN game is in testing → **self-serve**: switch it to Live in the console (Game Settings → Status). Show `.message`; `.gameStatus` has the current state |
1197
1827
  | `.isTargetGameNotLive` | **(403)** the DESTINATION game is in testing → the caller usually **can't fix this** (someone else's game). Show `.message`; steer to another destination via `getDestinations`. Deliberately **distinct** from `.isSourceGameNotLive` — don't collapse them, the remediation differs |
1828
+ | `.isActiveSubscriptionExists` / `.isIdempotentReplayMismatch` / `.isSubscriptionTerminal` / `.isSteamReauthorizationRequired` / `.isNotACardSubscription` / `.isSteamChannelRequired` / `.isNotAuthorized` / `.isSteamRefundNotSupported` / `.isSandboxClockUnauthorized` / `.isFlowPaused` / `.isGameNotLive` | the subscription refusals — see [Subscriptions → Errors](#subscription-errors) |
1198
1829
  | `.isWebauthnNotEnabledForTenant` | **(403)** tenant has no partner passkey domain — the normal state now that new domains are frozen → **configuration state, not a failure**. Approve on INVO's hosted page (`approveHosted`); see [which passkey path serves your tenant](#prerequisite-which-passkey-path-serves-your-tenant) |
1199
1830
 
1200
1831
  Client-side guards (bad amount, missing idempotency key, `rail:"steam"` on `purchaseCurrency`, item validation) throw `InvoError` with `.status === 0` **before** any network call. Notable backend codes: `SDK_TOKEN_EXPIRED`, `TENANT_NOT_MIGRATED`, `WEBAUTHN_NOT_ENABLED_FOR_TENANT`, `WEBAUTHN_UV_REQUIRED`, `ENROLLMENT_REQUIRES_PROOF`, `ENROLLMENT_CODE_INVALID`, `PASSKEY_RECOVERY_COOLDOWN` (403, `retryAfterAt`), `no_channel_on_file`, `rate_limited`, `WRONG_RAIL_ENDPOINT`, `flow_paused`.
@@ -1231,6 +1862,19 @@ try {
1231
1862
  | `platformCommerce.purchase(input)` | `{ status, fundingSource, orderId?, transactionId?, newBalance?, financialBreakdown?, sessionId?, checkoutUrl?, expiresAt?, amountUsd?, idempotentReplay?, raw }` — **ecommerce** (platform tenant); `balance` settles now, `card` returns a hosted-checkout `checkoutUrl` |
1232
1863
  | `platformCommerce.getStatus(orderId)` | `{ orderId, status, gameCurrencyAmount?, usdAmount?, paymentMethod?, createdAt?, raw }` |
1233
1864
  | `platformCommerce.refund({ orderId? \| clientRequestId?, reason? })` | `{ status, orderId?, fundingSource?, refundedAmount?, amountUnit?, feeRetained?, raw }` — pass **exactly one** id; INVO keeps its fee |
1865
+ | `subscriptions.create(input)` | `SubscriptionResult` — `{ status, idempotentReplay, subscription, card, firstCharge, warning?, raw }`; **card rail**, charges the first period before answering; branch on `firstCharge.status` (`paid` \| `requires_action` \| `skipped_trial` \| `failed` \| `pending`); idempotent on `clientRequestId` (a repeat is `idempotentReplay: true`, never thrown) |
1866
+ | `subscriptions.get(id, { includePlayer? })` | `{ subscription, player?, raw }` — `subscription.paidThrough` is the entitlement boundary; `currentPeriodEnd` is only the billing window |
1867
+ | `subscriptions.listForPlayer(playerEmail, { status?, limit?, offset?, includePlayer? })` | `{ playerEmail, subscriptions, pagination: { totalCount, limit, offset, hasMore }, raw }` — newest first; `status: "live"` expands to the four live statuses |
1868
+ | `subscriptions.cancel(id, { atPeriodEnd?, reason? })` | `CancelResult` — `{ alreadyCanceled, cancelAtPeriodEnd, terminatedImmediately, effectiveAt, accessUntil, paidThrough, subscription, raw }`; an already-terminal row is a 200 with `alreadyCanceled: true` |
1869
+ | `subscriptions.changeAmount(id, amountUsd)` | `ChangeAmountResult` — `{ oldAmountUsd, newAmountUsd, pendingAmountUsd, changeQueued, appliesFrom, appliesFromPeriodSeq, prorated, subscription, raw }`; staged for the next renewal (Steam: increases throw `isSteamReauthorizationRequired`) |
1870
+ | `subscriptions.setPaymentMethod(id, { playerCardId, walletOnly? } \| { walletOnly: true })` | `{ status, replaced, walletOnly, card, subscription, raw }` — card rail only (`isNotACardSubscription` on Steam) |
1871
+ | `subscriptions.refund(id, { clientRequestId, periodSeq?, amountUsd?, reason? })` | `RefundResult` — the receipt (`isFullRefund, fundingShape, balanceDeltaCoins, cardRefundedUsd, partnerRevenueReversedUsd, revenueShareAttribution, idempotentReplay, raw`); idempotent on `clientRequestId`; Steam-charged periods throw `isSteamRefundNotSupported` |
1872
+ | `subscriptions.steamInit(input)` | `SteamInitResult` — `{ status, subscriptionStatus, idempotentReplay, pendingReuse, subscription, subscriptionId, orderId, steamOrderId, steamTransid, steamCheckoutUrl, amountUsd, amountCoins, steamChargeUsd, recurringAmountUsd, firstCharge, message, raw }`; **Steam rail**, nothing charged until finalize; match the Steam client callback on `steamOrderId` |
1873
+ | `subscriptions.steamFinalize(subscriptionId)` | `SteamFinalizeSubscriptionResult` — the `SubscriptionResult` plus `{ alreadyProcessed, steamAgreementStatus, sandboxAutoApproved }`; `isNotAuthorized` (409) is the normal wait state |
1874
+ | `cards.beginSetup({ playerEmail, setupReference, paymentMethodId? })` | `CardSetupResult` — `{ status, setupIntentId, clientSecret?, publishableKey?, card, alreadySaved, raw }`; off-session card capture for subscriptions (charges nothing; idempotent on `setupReference`) |
1875
+ | `cards.confirmSetup({ setupIntentId })` | `{ status, setupIntentId, card, alreadySaved, raw }` — finish a client-confirmed setup |
1876
+ | `cards.list(playerEmail)` | `{ cards: SavedCard[], raw }` — unexpired cards, newest first; `card.id` is the `playerCardId` |
1877
+ | `sandbox.subscriptions.advanceClock(id, intervals?)` / `forceRenewal(id)` / `forceFailure(id, outcome?, { failureCode?, failureMessage? })` / `forceAuthChallenge(id, { failureMessage? })` | `SandboxClockResult` — `{ status, action, subscription, before?, after?, engineStats?, retryScheduleDays?, retriesRemaining?, authChallengesUsed?, …, raw }`; **sandbox only**, posts to `/subscriptions/<id>/...` relative to the sandbox base (not `/api`), needs `sandboxClockKey`; never auto-retried |
1234
1878
  | `getPlayerBalance({ playerEmail })` | `{ player, balances, summary, raw }` — **by email only** (no by-id route; use `InvoClient.getBalance()` client-side) |
1235
1879
  | `getInboundPending({ playerEmail? \| playerPhone? })` | `{ inboundPending, raw }` — live unclaimed inbound sends/transfers |
1236
1880
  | `getLinkedIdentities({ playerEmail? \| playerPhone? })` | `{ walletUserId, primaryEmail, primaryPhone, isMinor, emails, notFound, raw }` — **server-only** (returns PII) |
@@ -1239,6 +1883,11 @@ try {
1239
1883
  | `getTransferStatus(txnId)` / `getSendStatus(txnId)` | `TransactionStatusResult` — poll outbound state (`verificationState`) |
1240
1884
  | `getGuardianApprovalStatus(txnId)` | `GuardianApprovalStatusResult` — poll a guardian hold to resolution (`state`) |
1241
1885
  | `getDestinations({ sourceGameId, direction? })` | `DestinationsResult` — server-side (game-secret) destinations; same rows as the browser variant |
1886
+ | `beginDeviceApproval({ playerToken, transactionId, flow, channel? })` | `DeviceApprovalGrant` — `{ deviceCode, userCode, verificationUri, verificationUriComplete, expiresIn, interval, channel, raw }`. **Player token**, never the game secret. Show `verificationUriComplete` as a QR |
1887
+ | `pollDeviceApproval({ playerToken, deviceCode })` | `DeviceApprovalPollResult` — `status: "approved" \| "authorization_pending" \| "slow_down" \| "expired_token" \| "access_denied"` (+ `enrollment` while a first-time phone waits on your screen). `invalid_grant` throws |
1888
+ | `confirmDeviceEnrollment({ playerToken, deviceCode, decision })` | `{ status, raw }` — answers the on-screen match-code prompt; `decision: "approve" \| "deny"` |
1889
+ | **`approveWithDeviceCode({ playerToken, transactionId, flow, deviceCode })`** | **The money step.** `DeviceApprovalSettleResult` — routes by `flow` to the transfer/send approve or confirm-receipt endpoint. `TRANSACTION_NOT_PENDING` comes back as `status: "not_pending"` + `alreadySettled` + `currentStatus`, **not** thrown |
1890
+ | `completeDeviceApproval({ playerToken, transactionId, flow, deviceCode, interval?, onEnrollment?, signal? })` | `{ status: "approved" \| "denied" \| "expired" \| "aborted", settlement?, lastPoll? }` — convenience loop: polls honouring `interval`/`slow_down`, then calls `approveWithDeviceCode` |
1242
1891
  | `phoneShareInitiate({ phone, email })` / `phoneShareApprove({ approvalId, otp })` / `phoneShareStatus({ phone, email })` | phone-share OTP handshake (unauthenticated) to resolve a `PHONE_SHARE_APPROVAL_REQUIRED` (409); then re-issue the original request |
1243
1892
  | `iterateItemPurchaseHistory({ playerEmail, pageSize? })` | async iterator over all history rows |
1244
1893
  | `verifyWebhook(rawBody, signatureHeader, secret \| secrets, opts?)` | typed `InvoWebhookEvent` (throws on bad signature) |