@invonetwork/web-sdk 3.8.1 → 3.10.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,7 +2,7 @@
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.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).
5
+ > **Status:** `v3.10.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.10.0** documents **card-only subscriptions** (the card pays the full price every period, the coin wallet never pays; `walletOnly` deprecated; new `failure_code` `wallet_negative`; a renewal's `purchase.completed` is not a purchase) and the **[subscription refund limits](#refunds)**: `subscriptions.refund` can now return a 202 `pending_approval` refund request (`isRefundPendingApproval`), with `warnings`, the processor fee you bear, `subscriptionCanceled` (a full refund cancels), new classifiers (`isRefundsNotEnabled`, `isRefundWindowClosed`, `isRefundRequestPending`, `isRefundRequestRejected`, `isConcurrentRequest`, `isRefundMismatch`) and typed `subscription.refund_requested` / `refund_approved` / `refund_rejected` events, all additive; **3.9.0** adds the **[INVO-hosted card page for subscriptions](#cards-for-subscriptions)**, `invo.cards.createSetupSession`: mint a 10-minute link server-side, send the member to it, read the card back from `cards.list`, with no browser code and no card processor named anywhere (`beginSetup`/`confirmSetup` remain as the processor-bound alternative), plus the `isPlayerNotFound`, `isInvalidPlayerEmail` and `isInvalidInput` classifiers and a fix that makes `includePlayer` reads actually surface `playerEmail`/`playerName`; **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
@@ -14,7 +14,7 @@ Six money flows plus passkey (WebAuthn) authentication, split across a trusted s
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
+ | **Subscriptions** | a fixed USD price on a fixed interval **→** game currency each period (card **or** Steam rail) | yes (card: the full price every period; Steam: the wallet shortfall) | no | server creates, cancels, reprices; renewals arrive by webhook |
18
18
  | **Send** | currency **→** another player (cross-game) | no | yes (sender approves) | server initiates, browser approves/claims |
19
19
  | **Transfer** | currency **→** another player (transfer rail) | no | yes (sender approves) | server initiates, browser approves/claims |
20
20
 
@@ -24,6 +24,8 @@ Six money flows plus passkey (WebAuthn) authentication, split across a trusted s
24
24
 
25
25
  The **game secret stays on your server**; the browser only ever holds a short-lived, game-scoped **player token** (and, for the card leg, a per-purchase `checkoutUrl`).
26
26
 
27
+ > **This applies to a game or a platform alike:** the SDK calls the tenant a game and names the option `gameSecret`, but a platform tenant uses the same option and the same flow.
28
+
27
29
  ## Passkeys are the gold standard — don't build on SMS
28
30
 
29
31
  **If you take one thing from this README: authorize money movement with a passkey. Do not design your verification UX around the SMS PIN.**
@@ -44,7 +46,7 @@ So:
44
46
  **Read this before you wire up `enrollPasskey()`.** There are two places a passkey ceremony can run, and which one serves your title is decided by whether you hold a partner passkey domain:
45
47
 
46
48
  - **No partner domain (every new title):** INVO runs the ceremony **on its own domain** — the hosted approval page — for every platform. There is **no domain to verify and nothing to configure**; submitting one is refused (`409 PARTNER_RP_FROZEN`). On the web the path is [`approveHosted()`](#web-games--approving-on-invos-hosted-page); on consoles it is the QR flow; on iOS/Android the mobile plugins open the same page. The in-app `enrollPasskey()` / `approveSend` / `approveTransfer` calls return `403 WEBAUTHN_NOT_ENABLED_FOR_TENANT` for you — that is the **expected state, not a setup gap** (the body's `hosted_flow` says so and points at `device_code`).
47
- - **A domain verified before the freeze (existing tenants):** your passkeys are bound to that RP ID for life, so `enrollPasskey()` and the in-app approves keep working exactly as documented below. You may still change or re-verify the domain. Removing it is **irreversible** — it can never be re-added, and the hosted flow serves the game from then on.
49
+ - **A domain verified before the freeze (existing tenants):** your passkeys are bound to that RP ID for life, so `enrollPasskey()` and the in-app approves keep working exactly as documented below. You may still change or re-verify the domain. Removing it is **irreversible**: it can never be re-added, and the hosted flow serves the title from then on.
48
50
 
49
51
  `WEBAUTHN_NOT_ENABLED_FOR_TENANT` is **configuration state, not an error** — the in-app ceremony was never available to fail. Don't show the player a failure; use the hosted page:
50
52
 
@@ -97,6 +99,7 @@ The right approval method is a property of the **client the player is sitting in
97
99
  - [Item purchase (spend game currency)](#item-purchase-spend-game-currency)
98
100
  - [Platform Commerce (ecommerce)](#platform-commerce-ecommerce)
99
101
  - [Subscriptions (recurring billing)](#subscriptions-recurring-billing)
102
+ - [Cards for subscriptions](#cards-for-subscriptions)
100
103
  - [Player balance](#player-balance)
101
104
  - [Sends & transfers (move currency between players)](#sends--transfers-move-currency-between-players)
102
105
  - [Legacy fallback: the SMS PIN (being retired)](#legacy-fallback-the-sms-pin-being-retired)
@@ -123,9 +126,9 @@ Node ≥ 18 on the server (uses the global `fetch`). The browser build ships ESM
123
126
 
124
127
  ## Get your account & game secret (INVO console)
125
128
 
126
- Sign up, create your game, and copy its credentials (the **game secret**, plus your WebAuthn **RP ID / origins**) in the INVO console. Use the console that matches the environment you're building against:
129
+ Sign up, create your title, and copy its credentials (the **game secret**, plus your WebAuthn **RP ID / origins**) in the INVO console. Use the console that matches the environment you're building against:
127
130
 
128
- | Environment | Console — sign up, manage games, copy your game secret | API `baseUrl` |
131
+ | Environment | Console: sign up, manage titles, copy your game secret | API `baseUrl` |
129
132
  |---|---|---|
130
133
  | **Testing / sandbox** | **https://dev.console.invo.network** | `https://sandbox.invo.network/sandbox` |
131
134
  | **Production** | **https://console.invo.network** | `https://invo.network` |
@@ -163,7 +166,7 @@ Build and test against the **dev console + sandbox** first, then switch to the *
163
166
  ### Player token (session mint for an existing player)
164
167
 
165
168
  `mintPlayerToken` mints a short-lived, game-scoped **session token** for a player who
166
- **already exists** on your game. It is *not* a registration call — the backend looks the
169
+ **already exists** on your title. It is *not* a registration call: the backend looks the
167
170
  player up by `playerEmail` and returns a token for their existing identity (or `404` if no
168
171
  such player exists). It only needs `playerEmail`:
169
172
 
@@ -237,7 +240,7 @@ INVO enables each flow for your tenant in the [console](#get-your-account--game-
237
240
  - **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)).
238
241
  - **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).
239
242
  - **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).
243
+ - **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.createSetupSession` (the INVO-hosted card page; `cards.beginSetup` is the processor-bound alternative); the hosted checkout does not save one. See [Cards for subscriptions](#cards-for-subscriptions).
241
244
 
242
245
  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.
243
246
 
@@ -604,14 +607,19 @@ const ref = await server.platformCommerce.refund({ orderId: r.orderId, reason: "
604
607
 
605
608
  ## Subscriptions (recurring billing)
606
609
 
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:
610
+ 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 title's currency each period. **You keep the entitlement** (what the member gets in your title). INVO keeps the clock, the charges, the retries, the notifications and the revenue split. Two rails, fixed at creation:
608
611
 
609
- | `fundingRail` | How the shortfall is funded | Created by |
612
+ | `fundingRail` | Who pays each period | Created by |
610
613
  |---|---|---|
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(...)` |
614
+ | `card` | the member's saved card on file with INVO, charged the **full price** every period | `server.subscriptions.create(...)` |
615
+ | `steam` | the member's Steam wallet, through a recurring agreement they authorise once (the INVO wallet is spent first; Steam tops up the shortfall) | `server.subscriptions.steamInit(...)` then `steamFinalize(...)` |
616
+
617
+ Each period INVO works out what the period is worth in coins (card: price × the currency's coins-per-USD rate, 10 per USD by default; Steam: what the price buys through Steam for the member's country) and splits it between INVO's platform fee and your revenue. Every figure is reported on the `subscription.renewed` event.
613
618
 
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.
619
+ - **Card rail: card only (since 2026-09-17).** The card is charged the full price every period, whatever the member's coin wallet holds. The coins that charge buys are minted and spent in the same step, so **the wallet never pays for a card subscription and never moves**. There is no shortfall, no rounding and no minimum top-up. INVO's fee is 10% by default plus $0.30, on the full price ($9.99 pays INVO $1.30 and you $8.69).
620
+ - **Steam rail: unchanged.** INVO spends the member's wallet first and tops up from Steam for the shortfall only.
621
+ - **Save a card before `subscriptions.create`.** A member with coins but no saved card is still subscribed (the create succeeds), but the first charge fails with `failureCode: "no_payment_method"` and the subscription enters dunning. Coins never pay it.
622
+ - **`walletOnly` is deprecated.** It is still accepted and returned, but a `walletOnly: true` card subscription never charges a card and so can never be paid: every charge fails with `failure_code: "wallet_only"` and it lapses to `expired`. Do not send it on new integrations.
615
623
 
616
624
  **Three rules to carry through everything below.**
617
625
 
@@ -621,12 +629,65 @@ Each period INVO works out what the period is worth in coins (card: price × the
621
629
 
622
630
  **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
631
 
624
- ### The card road
632
+ ### Cards for subscriptions
633
+
634
+ A card subscription needs a card saved for later, off-session use. **The recommended way to save one is the INVO-hosted card page:** two server-to-server calls and one redirect, **no browser code**, and nothing in your integration references a card processor or loads its script, so INVO can change processor without you changing anything. Your PCI scope does not change: the subscription endpoints never receive card data and neither does this SDK.
635
+
636
+ **1. Mint a card-setup session on your server.** The member must already exist in your title; this call never creates players.
637
+
638
+ ```ts
639
+ const session = await server.cards.createSetupSession({
640
+ playerEmail: "member@example.com",
641
+ successUrl: "https://your.game/billing/card-saved?member=7", // optional: where the page sends the member after the save; put your own correlation id here
642
+ });
643
+ // session.sessionId, session.cardSetupUrl, session.expiresAt (10 minutes from now)
644
+ ```
645
+
646
+ **2. Send the member to `session.cardSetupUrl`.** Open it as a top-level page (a redirect or a new tab); **do not frame it**. The page says in words that no money moves. The member enters the card, authenticates with their issuer if the issuer asks, and INVO saves the card and then redirects to your `successUrl` (or shows "Card saved, you can close this window" when you gave none). You write no browser code for this step and you never see a client secret, a publishable key or a processor name.
647
+
648
+ **3. Read the card back and subscribe.** A card saved this way **appears in `cards.list` immediately**, carries the off-session consent a subscription needs, and is indistinguishable from one saved any other way. The `id` is the only handle INVO returns for a card.
649
+
650
+ ```ts
651
+ const { cards } = await server.cards.list("member@example.com"); // unexpired, newest first
652
+ const r = await server.subscriptions.create({
653
+ clientRequestId: "guild-42-member-7",
654
+ playerEmail: "member@example.com",
655
+ playerName: "Member",
656
+ itemId: "guild-42-membership",
657
+ amountUsd: "9.99",
658
+ playerCardId: cards[0].id, // or omit it: INVO attaches the member's newest unexpired saved card
659
+ });
660
+ ```
661
+
662
+ **A brand-new member (no player in your title yet).** The card page needs an existing player and there is no create-player call, so bring the member into your title first. Two ways that move no money: `subscriptions.create` with `trialDays` creates the player and a `trialing` subscription (`firstCharge.status: "skipped_trial"`); or a card-less `subscriptions.create` (no `playerCardId`, no saved card yet) creates the player and the subscription, and its first charge is recorded as failed with `failureCode: "no_payment_method"` (outcome `insufficient_funds`), so the subscription sits in dunning with access retained. Then mint the card session and send the member to the page. After the save either call `subscriptions.setPaymentMethod(id, { playerCardId })` or do nothing: INVO adopts the member's newest saved card at the next attempt and attaches it. A currency purchase also creates the player, and with `save_card: true` saves the card in the same step.
663
+
664
+ **What to expect.**
665
+
666
+ - **The session lives 10 minutes.** Entering a card is one sitting. Mint the link when the member is about to use it, not ahead of time. An expired link shows the member a message asking for a new one; a new `createSetupSession` call is all it takes.
667
+ - **The link may be reloaded freely before the card is saved.** A reload after the issuer has authorised the card opens directly on the final "finish saving" step rather than asking for the card again.
668
+ - **Once the card is saved the link is spent.** Reopening it returns the same saved card and redirects to `successUrl` again; nothing is saved twice.
669
+ - **If saving fails after the issuer authorised the card,** the page tells the member to try again and the same link keeps working; nothing is recorded until the save succeeds. If what the member entered is not a card (a bank account, for instance) the page stops with a terminal message and a new link is needed.
670
+ - **There is no webhook for a saved card.** `cards.list` is the signal: read it when the member lands on `successUrl`, or right before the next `subscriptions.create`.
671
+ - **`createSetupSession` is never auto-retried.** Each call mints a fresh link, so on a timeout or 5xx just call it again.
672
+ - **`successUrl` is redirected to verbatim**, with nothing appended, and `metadata` is stored on the session and not returned anywhere today (no read returns the session). Put your own correlation id in `successUrl`. `cancelUrl` is carried on the session but not used by the page today.
625
673
 
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):
674
+ **Errors from `createSetupSession`.** Match on `err.code`, never on the message.
675
+
676
+ | Helper / code | HTTP | Meaning |
677
+ |---|---|---|
678
+ | `.isInvalidPlayerEmail` (`INVALID_PLAYER_EMAIL`) | 400 | `playerEmail` is not an email address (INVO checks for an `@`). A missing or blank `playerEmail` never reaches INVO: the SDK throws `INVALID_INPUT` with `.status === 0` first |
679
+ | `.isPlayerNotFound` (`PLAYER_NOT_FOUND`) | 404 | the member does not exist in this title yet. Create the player first (any call that creates players, for example a currency purchase); the card page never creates one |
680
+ | `.isInvalidInput` (`INVALID_INPUT`) | 400 | `successUrl` or `cancelUrl` uses a script scheme (`javascript:`, `data:`, `vbscript:`). http(s) and app deep-link schemes are fine. The SDK refuses the same values before the network with `.status === 0` |
681
+ | no code, `err.status === 401` | 401 | the game key is missing or wrong for this environment (body is `{ message }`) |
682
+ | no code, `err.status === 403` | 403 | the game is not `live` or `testing` |
683
+ | `err.status === 503` (the `error_code` names the cause) | 503 | card setup is not available right now; retry shortly |
684
+
685
+ Rate limit: 2000 per minute per game key with a per-IP floor; on a 429 honour `err.retryAfter`.
686
+
687
+ **The processor-bound alternative: `cards.beginSetup` / `cards.confirmSetup`.** Use these only if you already run a card form in your own client against INVO's current card processor. `beginSetup` hands back a `clientSecret` that only that processor's client library can consume, so the browser code you write for it is bound to the processor of the day and will need rework when INVO changes processor. `createSetupSession` does not have that problem, which is why it is the recommended path.
627
688
 
628
689
  ```ts
629
- // Option A: the setup flow (charges nothing). The player must already exist in this game.
690
+ // The processor-bound alternative (charges nothing). The player must already exist in this game.
630
691
  const setup = await server.cards.beginSetup({
631
692
  playerEmail: "member@example.com",
632
693
  setupReference: "setup-guild-42-member-7", // idempotency anchor: resend the same value on a retry
@@ -643,10 +704,15 @@ switch (setup.status) {
643
704
  // saved.card.id (a 400 with body.status === "still_requires_action" means the client hasn't finished)
644
705
  break;
645
706
  }
707
+ ```
708
+
709
+ **Saving the card during a purchase** also works: `purchaseCurrency(...)` with a new `paymentMethodId` and `save_card: true` in the body saves it with the off-session consent as a side effect; the purchase response carries `card_saved: true` and you read the `id` from `cards.list`.
646
710
 
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.
711
+ ### The card road
712
+
713
+ **1. Capture a card (off-session).** Three 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): the INVO-hosted card page through `cards.createSetupSession` (recommended; see [Cards for subscriptions](#cards-for-subscriptions) above), the processor-bound `cards.beginSetup` / `cards.confirmSetup` pair, or a purchase with `save_card: true`. Whichever you use, the card's `id` comes from `cards.list`:
649
714
 
715
+ ```ts
650
716
  const { cards } = await server.cards.list("member@example.com"); // unexpired, newest first; `id` is the only handle
651
717
  ```
652
718
 
@@ -664,7 +730,7 @@ const r = await server.subscriptions.create({
664
730
  // intervalCount: 3, // quarterly; 1..36
665
731
  // trialDays: 7, // or trialEnd: "2026-10-01T00:00:00Z"
666
732
  // 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
733
+ // walletOnly: true, // DEPRECATED: never charges a card, so it can never be paid ("wallet_only")
668
734
  metadata: { guild_id: "42" }, // echoed on every read and event (`_invo` is reserved)
669
735
  consent: { // send it: INVO is merchant of record and a dispute is argued from this
670
736
  consentAt: new Date().toISOString(),
@@ -692,6 +758,7 @@ switch (r.firstCharge.status) {
692
758
  grantTrialUntil(r.subscription.trialEnd!);
693
759
  break;
694
760
  case "failed": // status is past_due, in dunning; INVO retries at nextRetryAt
761
+ // failureCode: "no_payment_method" (save a card; coins never pay), "card_declined", "wallet_negative", ...
695
762
  tellMemberToFixCard(r.firstCharge.failureCode);
696
763
  break;
697
764
  case "pending": // an ambiguous processor answer; INVO resolves it within ~30 minutes
@@ -744,7 +811,7 @@ try {
744
811
 
745
812
  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
813
 
747
- ### Renewals, dunning and the seven events
814
+ ### Renewals, dunning and the events
748
815
 
749
816
  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
817
 
@@ -759,13 +826,19 @@ export const POST = createWebhookHandler({
759
826
  case "subscription.renewed": { // THE source of truth for entitlement (event.data is typed)
760
827
  const d = event.data; // d.period_seq is the period JUST PAID; d.period_end is the new paid_through
761
828
  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)
829
+ // d.funding.rail ("card" | "steam"). Card: d.funding.card_charged_usd is the full price and
830
+ // d.funding.balance_applied_coins is always "0.00". Steam: d.funding.steam_charged_usd is the shortfall only.
763
831
  // d.split.basis: "price" on card; "steam_net" on Steam, where d.split.total_usd is what the coins are worth,
764
832
  // not the price (the price is d.amount_usd). d.split.partner_revenue_usd is what you earned.
765
833
  // d.revenue_share_attribution?.attributed_amount_usd: what to pay your recipient yourself (settled_by_invo: false)
766
834
  break;
767
835
  }
836
+ case "purchase.completed": // a paid CARD RENEWAL also sends this, for the coins its charge minted
837
+ if (event.data.metadata?.["source"] === "subscription_renewal") break; // grant NOTHING here; subscription.renewed is the signal
838
+ await grantCurrency(event.data); // (its order_id is the renewal's mint_order_id)
839
+ break;
768
840
  case "subscription.payment_failed": // every failed attempt; access RETAINED. Do not revoke.
841
+ // failure_code: "no_payment_method" (no saved card), "wallet_negative" (coin balance below zero), "card_declined", ...
769
842
  await notifyCardProblem(event.data.subscription_id, event.data.failure_code, event.data.retry_at);
770
843
  break;
771
844
  case "subscription.past_due": // once, on ENTERING past_due. Access retained.
@@ -775,12 +848,22 @@ export const POST = createWebhookHandler({
775
848
  break;
776
849
  case "subscription.canceled": // once, at request time, both modes. Revoke at access_until.
777
850
  await revokeAt(event.data.subscription_id, event.data.access_until); // event.data.canceled_by: "partner" | "steam"
778
- break;
851
+ break; // event.data.cancel_cause === "full_refund" when a full refund ended it
779
852
  case "subscription.expired": // the retry budget ran out (or a Steam row was never authorised)
780
853
  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);
854
+ break; // failure_code "steam_containment" is no longer sent (spending is not restricted by origin)
855
+ case "subscription.refunded": { // your revenue is reversed, plus the processor fee on a card refund
856
+ const r = event.data.refund; // older events carry no partner_total_reversed_usd
857
+ await recordReversal(event.data.subscription_id, r.partner_total_reversed_usd ?? r.partner_revenue_reversed_usd);
858
+ break; // event.data.subscription_canceled: a full refund cancels (subscription.canceled is sent with it)
859
+ }
860
+ case "subscription.refund_requested": // a refund over your daily limit is waiting for INVO; nothing moved
861
+ await markRefundPending(event.data.request_id, event.data.client_request_id);
862
+ break;
863
+ case "subscription.refund_approved": // INVO approved it; subscription.refunded is sent with it, in any order
864
+ break;
865
+ case "subscription.refund_rejected": // INVO rejected it; nothing moved. A new clientRequestId can try again
866
+ await markRefundRejected(event.data.request_id, event.data.decision_reason);
784
867
  break;
785
868
  }
786
869
  },
@@ -791,9 +874,13 @@ export const POST = createWebhookHandler({
791
874
  |---|---|
792
875
  | Has the member paid for the period they are in? | `subscription.renewed` for that period, or `paidThrough` on `get` |
793
876
  | 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` |
877
+ | What did I earn? | `split.partner_revenue_usd` on `subscription.renewed`, minus `refund.partner_total_reversed_usd` (revenue reversed plus the card processor fee you bear) on any `subscription.refunded`; on refunds before 2026-09-17, which carry no such field, `refund.partner_revenue_reversed_usd` |
878
+ | Should I grant anything on a renewal's `purchase.completed`? | **No.** Every paid card renewal also sends `purchase.completed` (`data.metadata.source === "subscription_renewal"`) for the coins its charge minted, and the renewal spends them in the same step. Act on `subscription.renewed`. The two share the mint order id: `order_id` there is `mint_order_id` here |
879
+ | Did a refund end the subscription? | `subscription_canceled` on `subscription.refunded`, and the `subscription.canceled` sent with it (`cancel_cause: "full_refund"`; the two are sent together and may arrive in any order) |
880
+
881
+ If a card renewal's charge succeeds but INVO cannot finish the renewal in the same step, you may see `subscription.payment_failed` with a settlement `failure_code` (for example `settlement_error`); the retry then completes the period **without charging the card again**, and `subscription.renewed` follows.
795
882
 
796
- A few renewal outcomes are **deferrals**, not failures, with no event and no retry consumed (a price above the 25000.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.
883
+ A few renewal outcomes are **deferrals**, not failures, with no event and no retry consumed (a price above the 25000.00 per-charge ceiling; 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. There used to be a third: a wallet holding currency bought through Steam, in a title that was not on Steam. **That deferral is gone.** A balance is spendable in any title whatever rail bought it, so a renewal spends the whole wallet.
797
884
 
798
885
  ### Reading, cancelling, repricing, changing the card
799
886
 
@@ -812,27 +899,53 @@ const a = await server.subscriptions.changeAmount(id, "14.99");
812
899
  // Sending the current price clears a staged change. More than double, or above 25000.00, stays pending forever.
813
900
 
814
901
  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
902
+ await server.subscriptions.setPaymentMethod(id, { playerCardId: 43, walletOnly: false }); // convert a wallet-only subscription back (do this for any you have)
903
+ // setPaymentMethod(id, { walletOnly: true }) still works but is DEPRECATED: the subscription can then never be paid
817
904
  ```
818
905
 
819
906
  ### Refunds
820
907
 
821
908
  ```ts
822
- const receipt = await server.subscriptions.refund(id, {
909
+ import { isRefundPendingApproval } from "@invonetwork/web-sdk/server";
910
+
911
+ const r = await server.subscriptions.refund(id, {
823
912
  clientRequestId: "refund-2026-11-guild-42-member-7", // one per refund; reuse it on retries (the receipt replays)
824
913
  // periodSeq: 2, // default: the most recent billed period
825
914
  // amountUsd: "4.00", // default: the full remaining refundable amount
826
- reason: "member request",
915
+ reason: "member request", // recommended now, required after a notice period
827
916
  });
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.
917
+ if (isRefundPendingApproval(r)) { // narrows r; status === "pending_approval"
918
+ // Over the game's daily self-serve limit: NOTHING moved. INVO reviews request r.requestId.
919
+ // Wait for subscription.refund_approved (sent with subscription.refunded) or subscription.refund_rejected.
920
+ await markRefundPending(r.requestId, r.requestedAmountUsd);
921
+ } else {
922
+ // r.status === "refunded". r.isFullRefund, r.fundingShape ("card" for every card period since 2026-09-17),
923
+ // r.cardRefundedUsd (card-only periods: equals the amount, partial included), r.balanceDeltaCoins,
924
+ // r.partnerRevenueReversedUsd (your revenue reversed; INVO's fee is retained),
925
+ // r.processingFeeUsd (the card processor fee you bear), r.partnerTotalReversedUsd (the two together),
926
+ // r.subscriptionCanceled (a full refund cancels the subscription), r.idempotentReplay on a repeat,
927
+ // r.revenueShareAttribution?.netAttributedAmountUsd (the corrected figure to pay your recipient).
928
+ }
929
+ for (const w of r.warnings ?? []) log(w.code); // "REASON_RECOMMENDED" | "REASON_TRUNCATED"
833
930
  ```
834
931
 
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.
932
+ **What is refunded.** A card subscription is card only (since 2026-09-17), so its period is refunded **in cash, full or partial**: the amount goes back to the card (`cardRefundedUsd` equals the amount, `balanceDeltaCoins` is `"0.00"`), and partials plus the refund that completes them add up to exactly the card charge. A period charged **before** 2026-09-17, or a Steam period the wallet covered, keeps the earlier rule: a full refund returns the whole card charge and reclaims the coins that charge minted (`balanceDeltaCoins` is signed and can go negative), a partial refund credits coins at the currency's rate (10 coins per USD by default). A fully refunded period no longer counts toward `paidThrough`.
933
+
934
+ **What else happens.**
935
+
936
+ - **A full refund cancels the subscription** immediately (`subscriptionCanceled: true`, `subscriptionStatus: "canceled"`), and you receive `subscription.canceled` (`canceled_by: "partner"`, `cancel_cause: "full_refund"`) together with `subscription.refunded`; the two are sent together and may arrive in any order. A partial refund leaves it live. Before 2026-09-17 a full refund did not cancel.
937
+ - **You bear the card processor fee** on any refund that returns money to a card: `processingFeeUsd` (`processingFeeBasis` `actual` or `estimated`, `processingFeeBorneBy: "partner"`) is deducted from your revenue as its own line. `partnerTotalReversedUsd` is your revenue reversed plus that fee. A coin refund has no fee.
938
+ - **INVO emails the member** when a refund executes (the amount, where it went, and whether the subscription ended). Your `reason` is not in that email.
939
+ - **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.
940
+
941
+ **Limits.** Self-serve refunds run inside four limits:
942
+
943
+ 1. **Enabled per game.** On by default for every game; INVO can turn them off for a game (`403 REFUNDS_NOT_ENABLED`, `err.isRefundsNotEnabled`).
944
+ 2. **30 days.** A period can be refunded for 30 days after it was charged (`409 REFUND_WINDOW_CLOSED`, `err.isRefundWindowClosed`, with `err.periodChargedAt`, `err.refundWindowDays`, `err.refundWindowClosedAt`). A retry of a refund that already ran still returns its receipt.
945
+ 3. **A daily limit per game** (per UTC day; $500 by default in sandbox and production, adjustable by INVO). A refund that would exceed it does **not** run: the call answers HTTP 202 with `status: "pending_approval"` and `requestId` (check with `isRefundPendingApproval(r)`), carrying every receipt field with nothing moved, and INVO reviews the request. Approved: the refund runs as if your call had (the 30 days count from when you asked), you receive `subscription.refunded`, `subscription.refund_approved` and, for a full refund, `subscription.canceled`, sent together and may arrive in any order, and a retry of your key returns the receipt. Rejected: you receive `subscription.refund_rejected` with `decision_reason`, and your key throws `409 REFUND_REQUEST_REJECTED` (`err.isRefundRequestRejected`); use a new key to try again. While a request is pending, other refunds of that period throw `409 REFUND_REQUEST_PENDING` (`err.isRefundRequestPending`, the id on `err.refundRequestId`). The same key returns the same 202 with `idempotentReplay: true`.
946
+ 4. **A reason.** Recommended now, required after a notice period. Without it the refund still runs (`reason: null`) and `warnings` carries `REASON_RECOMMENDED`; a reason longer than 500 characters is cut, with `REASON_TRUNCATED` (the SDK refuses one over 500 before the network).
947
+
948
+ Your developer console session can list your refund requests (`GET /api/dev/subscriptions/refund-requests?status=pending|approved|rejected|all`); that console read is not wrapped by this SDK, which authenticates with the game key.
836
949
 
837
950
  ### Sandbox: the clock tools
838
951
 
@@ -857,7 +970,7 @@ await sb.forceAuthChallenge(id); // moves it to awaiting_authenticati
857
970
  >
858
971
  > **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
972
 
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.
973
+ **Card recipe.** Make the sandbox game live and register a webhook. Save a card with `cards.createSetupSession` (open `cardSetupUrl` in a browser; the sandbox page runs against the test-mode card processor, so enter a test card there, never a real one; the sandbox recipe on the public docs site is at https://docs.invo.network/docs/subscriptions-sandbox), or, on the processor-bound path, 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 (a full refund cancels the subscription, so refund a partial amount first if you want to keep testing it; the $500 daily limit applies in sandbox too, and a refund over it answers `pending_approval`); and create one with `trialDays: 7` to see `skipped_trial` convert.
861
974
 
862
975
  **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
976
 
@@ -879,13 +992,20 @@ Match on `err.code` (and on `body.status` where the body carries one), never on
879
992
  | `.isNotAuthorized` | (409) `steamFinalize` before the member authorised. The normal wait state: call it again |
880
993
  | `.isSteamRefundNotSupported` | (409) `refund` on a period charged through Steam |
881
994
  | `.isAlreadyRefunded` | (409) the period was already refunded; treat as done |
995
+ | `.isRefundsNotEnabled` | (403) refunds are turned off for this game; contact INVO |
996
+ | `.isRefundWindowClosed` + `.periodChargedAt` / `.refundWindowDays` / `.refundWindowClosedAt` | (409) the period was charged more than 30 days ago |
997
+ | `.isRefundRequestPending` + `.refundRequestId` | (409) a refund request for this period is waiting for INVO's review |
998
+ | `.isRefundRequestRejected` + `.refundRequestId` / `.decisionReason` | (409) this key was a refund request INVO rejected; use a new key to try again |
999
+ | `.isConcurrentRequest` | (409) two requests collided (two creates for a new player, or two refund requests for one period); retry with the **same** key |
1000
+ | `.isRefundMismatch` | (502) a card refund needs manual reconciliation; contact INVO, do not retry-loop |
882
1001
  | `.isSandboxClockUnauthorized` | (401) missing/wrong `X-Sandbox-Clock-Key`; reveal it in the sandbox console |
883
1002
  | `.isPhoneShareApprovalRequired` | (409) the supplied `playerPhone` belongs to another identity; run the phone-share flow, then retry |
884
1003
  | `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 |
1004
+ | `WALLET_ONLY_SUBSCRIPTION` / `WALLET_ONLY_CONFLICT` | `walletOnly: true` with a card; or a wallet-only subscription needs `walletOnly: false` beside the new card (`walletOnly` is deprecated: such a subscription can never be paid) |
886
1005
  | `NO_PAID_PERIOD` / `PERIOD_NOT_REFUNDABLE` / `AMOUNT_EXCEEDS_REMAINING` | refund refusals (the last carries `remaining_refundable_usd`) |
887
1006
  | `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` |
1007
+ | `.isPlayerNotFound` / `.isInvalidPlayerEmail` / `.isInvalidInput` | (404 / 400 / 400) `cards.createSetupSession`: the member does not exist yet (the card page never creates players); `playerEmail` is not an email; `successUrl`/`cancelUrl` uses a script scheme (`isInvalidInput` is also the SDK's own pre-network guard code, at `.status === 0`) |
1008
+ | `SETUP_REFERENCE_REUSED` / `PLAYER_NOT_FOUND` / `CARD_DECLINED` / `RAW_CARD_NOT_SUPPORTED` / `CARD_PERSIST_FAILED` | the processor-bound card capture (`beginSetup`/`confirmSetup`); on `CARD_PERSIST_FAILED` (500) retry `confirmSetup` with the same `setupIntentId` |
889
1009
 
890
1010
  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
1011
 
@@ -896,11 +1016,14 @@ Client-side guards (missing key, a `sub_`-prefixed key, a bad amount, a non-E.16
896
1016
  3. **`pending` is not `failed`.** Wait for the event; INVO resolves it.
897
1017
  4. **`currentPeriodEnd` is not entitlement.** Use `paidThrough`.
898
1018
  5. **`payment_failed` and `past_due` do not revoke access.** Only `expired` (at `final_period_end`) and `canceled` (at `access_until`) do.
1019
+ 6. **Coins never pay a card subscription.** Save a card before `create`; a member without one fails with `no_payment_method` whatever their balance.
1020
+ 7. **A renewal's `purchase.completed` is not a purchase.** Skip it when `data.metadata.source === "subscription_renewal"`; grant on `subscription.renewed`.
1021
+ 8. **`pending_approval` is not `refunded`.** Nothing moved (`isRefundPendingApproval(r)`); wait for `subscription.refund_approved` or `subscription.refund_rejected`.
899
1022
  6. **`authentication_required` is not a failure.** Send the link, not a "payment failed" message.
900
1023
  7. **Do not poll for renewals.** Handle `subscription.renewed`.
901
1024
  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
1025
  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.
1026
+ 10. **A card saved without off-session consent cannot back a subscription.** Hosted checkout and `savedCardId` purchases do not save one; use `cards.createSetupSession` (the INVO-hosted card page), the processor-bound `cards.beginSetup`, or a `save_card: true` purchase.
904
1027
  11. **`walletOnly` is absolute.** A card attached later is ignored until you pass `walletOnly: false` on `setPaymentMethod`.
905
1028
  12. **Price changes apply next period, and big jumps never apply.** More than double, or above 25000.00, stays pending.
906
1029
  13. **`sub_` is reserved** as a prefix for every idempotency key on the platform.
@@ -1027,7 +1150,7 @@ try {
1027
1150
  `transfer.refunded` remain the source of truth — reconcile off those, not the messages.
1028
1151
  - **`err.isPhoneShareApprovalRequired` on `confirmReceipt*` / `claimTransfer` / `claimCurrency`** (409): the receiver phone is contested, so INVO **holds the money** and texts the phone owner to approve. Not a failure — show `err.message` verbatim (`err.phoneShareLast4` names the phone), then **retry the same call** once approved (it succeeds idempotently); on denial/expiry the sender is refunded. Same handling as the initiate-time phone-share 409.
1029
1152
  - **Both games must be Live.** `initiateSend`/`initiateTransfer` throw `403` if either side is still in testing, and the two cases are **deliberately separate** because the fix differs: `err.isSourceGameNotLive` is **your** game (self-serve — switch it to Live in the console under Game Settings → Status), `err.isTargetGameNotLive` is the **destination** game, usually owned by another developer, so you can't flip it — show `err.message` and steer the player elsewhere via `getDestinations`. `err.gameStatus` carries the current state. Don't merge these into one "not live" branch; it produces a "go fix it" button that leads nowhere half the time.
1030
- - **Steam titles** (dark until a title is Steam-distributed): `initiateSend`/`initiateTransfer` can throw `err.isSteamValueNonTransferable` (moving more than the non-Steam balance to a non-Steam destination — show `err.message`, cap the amount at `err.steamTransferableMax`; `err.steamOriginAmount` is the Steam-locked portion) or `err.isNonSteamValueIntoSteamBlocked` (non-Steam value into a Steam title). Prevent both up front: `getDestinations` rows carry **`acceptsSteamOriginValue`** — disable non-Steam destinations for a player holding Steam-purchased currency.
1153
+ - **Steam titles** (dark until a title is Steam-distributed): `initiateSend`/`initiateTransfer` can throw `err.isSteamValueNonTransferable` (moving more than the non-Steam balance to a non-Steam destination — show `err.message`, cap the amount at `err.steamTransferableMax`; `err.steamOriginAmount` is the Steam-locked portion) or `err.isNonSteamValueIntoSteamBlocked` (non-Steam value into a Steam title). Prevent both up front: `getDestinations` rows carry **`acceptsSteamOriginValue`** — disable non-Steam destinations for a player holding Steam-purchased currency. **This is a rule about currency moving between titles, not about spending.** A player can spend any balance on items in any title, Steam-distributed or not, including currency bought through Steam, so an item purchase never fails on origin and there is nothing to branch on there.
1031
1154
  - Transfer self-claim may be disabled for your tenant; if it is, surface the claim-code path instead.
1032
1155
  - **Holds:** an approve/claim can return an HTTP 202 hold instead of success — inspect `result.holdReason` (`"RISK_HOLD"`, `"GUARDIAN_APPROVAL_PENDING"`, and on confirm-receipt `"RECIPIENT_IDENTITY_PENDING"`); success has no `holdReason` (and `next: "pending_claim"`). Terminal guardian outcomes throw (`GUARDIAN_APPROVAL_REJECTED`/`_EXPIRED`).
1033
1156
  - **Guardian approval goes by email first.** When a minor's initiate returns the 202, the guardian gets a
@@ -1446,7 +1569,7 @@ Each settle call takes the body `{"device_code": "..."}` and the player's bearer
1446
1569
  the same token that began the grant.
1447
1570
 
1448
1571
  **Available to every title, with nothing to configure.** The constraint is a property of
1449
- the *device*, not your game: a title with a website *and* a console build uses the normal
1572
+ the *device*, not your title: a title with a website *and* a console build uses the normal
1450
1573
  ceremony in the browser and this one on the console.
1451
1574
 
1452
1575
  **Native Steam and desktop game clients (Mac & Windows) belong here too.** Even though the
@@ -1721,7 +1844,7 @@ export const POST = createWebhookHandler({
1721
1844
 
1722
1845
  | Event | Fires for | Use it to |
1723
1846
  |---|---|---|
1724
- | `purchase.completed` | every currency-purchase rail | grant currency (payload: `transaction_id, order_id, player_email, identity_id, usd_amount, currency_amount, currency_name, new_balance, rail`, `metadata`) — `metadata` echoes what you passed to `createCheckout`/`purchaseCurrency` (all rails); `order_id` is also on every webhook as a secondary reconciliation key (`getOrderDetails`). |
1847
+ | `purchase.completed` | every currency-purchase rail, **and every paid card subscription renewal** | grant currency (payload: `transaction_id, order_id, player_email, identity_id, usd_amount, currency_amount, currency_name, new_balance, rail`, `metadata`) — `metadata` echoes what you passed to `createCheckout`/`purchaseCurrency` (all rails); `order_id` is also on every webhook as a secondary reconciliation key (`getOrderDetails`). **Skip it when `metadata.source` is `"subscription_renewal"`**: those coins are spent by the renewal itself; grant on `subscription.renewed`. |
1725
1848
  | `purchase.failed` / `purchase.disputed` | `platform` rail only | handle failures/disputes |
1726
1849
  | `purchase.refunded` | `game` / `steam` rails | handle refunds |
1727
1850
  | `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`) |
@@ -1730,9 +1853,10 @@ export const POST = createWebhookHandler({
1730
1853
  | `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
1854
  | `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
1855
  | `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`) |
1856
+ | `subscription.canceled` | a cancel request (yours, or the member's from Steam: `canceled_by`), or a full refund (`cancel_cause: "full_refund"`) | revoke at `access_until` |
1857
+ | `subscription.expired` | the retry budget ran out, or a Steam row was never authorised (`steam_authorization_abandoned`). `steam_containment` is **no longer returned**: spending is not restricted by which rail bought the currency | **revoke at `final_period_end`** (not `ended_at`; `null` if nothing was ever paid) |
1858
+ | `subscription.refunded` | a period refund | record the reversal (`refund.partner_total_reversed_usd` = revenue reversed plus the card processor fee you bear, `refund.partner_revenue_reversed_usd`, `refund.processing_fee_usd`, `is_full_refund`, `subscription_canceled`, `initiation`, `refund_request_id`, `revenue_share_attribution`) |
1859
+ | `subscription.refund_requested` / `subscription.refund_approved` / `subscription.refund_rejected` | a refund over the game's daily self-serve limit became a request / INVO approved it (sent together with `subscription.refunded`, and `subscription.canceled` on a full refund, in any order) / INVO rejected it | track the request (`request_id, status, subscription_id, item_id, period_seq, client_request_id, amount_usd, reason, requested_at, daily_cap_usd, executed_today_usd, player_email, identity_id, metadata`; approved adds `decided_at, transaction_id`; rejected adds `decided_at, decision_reason`) |
1736
1860
  | `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 |
1737
1861
 
1738
1862
  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.
@@ -1825,7 +1949,7 @@ Helpers:
1825
1949
  | `.isPhoneShareAlreadyApproved` | phone-share was already approved (e.g. from a `/reject`) |
1826
1950
  | `.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 |
1827
1951
  | `.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) |
1952
+ | `.isActiveSubscriptionExists` / `.isIdempotentReplayMismatch` / `.isSubscriptionTerminal` / `.isSteamReauthorizationRequired` / `.isNotACardSubscription` / `.isSteamChannelRequired` / `.isNotAuthorized` / `.isSteamRefundNotSupported` / `.isRefundsNotEnabled` / `.isRefundWindowClosed` / `.isRefundRequestPending` / `.isRefundRequestRejected` / `.isConcurrentRequest` / `.isRefundMismatch` / `.isSandboxClockUnauthorized` / `.isFlowPaused` / `.isGameNotLive` | the subscription refusals — see [Subscriptions → Errors](#subscription-errors) |
1829
1953
  | `.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) |
1830
1954
 
1831
1955
  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`.
@@ -1863,16 +1987,17 @@ try {
1863
1987
  | `platformCommerce.getStatus(orderId)` | `{ orderId, status, gameCurrencyAmount?, usdAmount?, paymentMethod?, createdAt?, raw }` |
1864
1988
  | `platformCommerce.refund({ orderId? \| clientRequestId?, reason? })` | `{ status, orderId?, fundingSource?, refundedAmount?, amountUnit?, feeRetained?, raw }` — pass **exactly one** id; INVO keeps its fee |
1865
1989
  | `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 |
1990
+ | `subscriptions.get(id, { includePlayer? })` | `{ subscription, player?, raw }`: `subscription.paidThrough` is the entitlement boundary; `currentPeriodEnd` is only the billing window; `includePlayer: true` adds `subscription.playerEmail` / `subscription.playerName` (INVO puts them on the object; `player` is derived from them) |
1867
1991
  | `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
1992
  | `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
1993
  | `subscriptions.changeAmount(id, amountUsd)` | `ChangeAmountResult` — `{ oldAmountUsd, newAmountUsd, pendingAmountUsd, changeQueued, appliesFrom, appliesFromPeriodSeq, prorated, subscription, raw }`; staged for the next renewal (Steam: increases throw `isSteamReauthorizationRequired`) |
1870
1994
  | `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` |
1995
+ | `subscriptions.refund(id, { clientRequestId, periodSeq?, amountUsd?, reason? })` | `RefundResult` (one interface; branch with `isRefundPendingApproval(r)`): `status: "refunded"` (the receipt: `isFullRefund, fundingShape, balanceDeltaCoins, cardRefundedUsd, partnerRevenueReversedUsd, revenueShareAttribution, idempotentReplay`, plus `subscriptionCanceled, subscriptionStatus, processingFeeUsd, processingFeeBasis, partnerTotalReversedUsd, initiation, refundRequestId, warnings?, raw`) or `"pending_approval"` (HTTP 202, over the daily limit, nothing moved: the same fields plus `requestId, requestStatus, requestedAmountUsd, requestedAt, dailyCapUsd, executedTodayUsd, message`, required on the narrowed `RefundPendingApproval`); idempotent on `clientRequestId` (a replay, `idempotentReplay: true`, never carries `newBalance` or `revenueShareAttribution`); a full refund cancels the subscription; Steam-charged periods throw `isSteamRefundNotSupported` |
1872
1996
  | `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
1997
  | `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 |
1998
+ | `cards.createSetupSession({ playerEmail, successUrl?, cancelUrl?, metadata? })` | `CardSetupSessionResult`: `{ sessionId, cardSetupUrl, expiresAt, raw }`. **The recommended card capture for subscriptions**: mint a 10-minute link to the INVO-hosted card page, send the member to `cardSetupUrl` (top-level), then read the card's `id` from `cards.list`; no browser code, no processor named; never auto-retried; `isPlayerNotFound` / `isInvalidPlayerEmail` / `isInvalidInput` |
1999
+ | `cards.beginSetup({ playerEmail, setupReference, paymentMethodId? })` | `CardSetupResult`: `{ status, setupIntentId, clientSecret?, publishableKey?, card, alreadySaved, raw }`; the **processor-bound** card capture (you run the card form; charges nothing; idempotent on `setupReference`) |
2000
+ | `cards.confirmSetup({ setupIntentId })` | `{ status, setupIntentId, card, alreadySaved, raw }`: finish a client-confirmed setup on the processor-bound path |
1876
2001
  | `cards.list(playerEmail)` | `{ cards: SavedCard[], raw }` — unexpired cards, newest first; `card.id` is the `playerCardId` |
1877
2002
  | `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 |
1878
2003
  | `getPlayerBalance({ playerEmail })` | `{ player, balances, summary, raw }` — **by email only** (no by-id route; use `InvoClient.getBalance()` client-side) |