@invonetwork/web-sdk 3.7.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/CHANGELOG.md CHANGED
@@ -1,5 +1,43 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Subscriptions are a first-class server surface, on both rails, with the card capture and the
8
+ sandbox clock tools beside them.
9
+
10
+ New on `InvoServer`:
11
+
12
+ - **`invo.subscriptions`**: `create` (card rail; charges the first period before answering,
13
+ idempotent on `clientRequestId`, a repeat is a typed `idempotentReplay: true` result),
14
+ `get`, `listForPlayer`, `cancel` (an already-terminal row is a 200 `alreadyCanceled`, never
15
+ thrown), `changeAmount` (staged for the next renewal), `setPaymentMethod`, `refund`
16
+ (idempotent; the receipt replays), `steamInit` and `steamFinalize` (Steam rail;
17
+ `alreadyProcessed` is a result, not an error).
18
+ - **`invo.cards`**: `beginSetup` / `confirmSetup` / `list`: the off-session card capture a
19
+ card subscription needs. The hosted checkout does not save a card for subscriptions.
20
+ - **`invo.sandbox.subscriptions`**: `advanceClock` / `forceRenewal` / `forceFailure` /
21
+ `forceAuthChallenge`. These post to `/subscriptions/<id>/...` **relative to the sandbox
22
+ base URL, not under `/api`**, and send `X-Sandbox-Clock-Key` from the new
23
+ `sandboxClockKey` config; a missing key throws before the network.
24
+
25
+ Typed results: `SubscriptionResult` (the subscription object with its TWO clocks,
26
+ `firstCharge` with `paidPeriodSeq`, `card`, `idempotentReplay`), `FirstCharge` (`paid` |
27
+ `requires_action` | `skipped_trial` | `failed` | `pending` | `pending_authorization`),
28
+ `SteamInitResult` (`steamOrderId` for the client callback, `amountCoins`, `pendingReuse`),
29
+ `CancelResult`, `ChangeAmountResult`, `RefundResult`, `CardSetupResult`, `SandboxClockResult`
30
+ (`engineStats`), and typed `data` for all seven `subscription.*` webhook events.
31
+
32
+ Error classifiers: `isActiveSubscriptionExists` (+ `existingSubscriptionId`),
33
+ `isIdempotentReplayMismatch` (+ `mismatchedFields`), `isSteamReauthorizationRequired`,
34
+ `isNotACardSubscription`, `isSteamChannelRequired`, `isSubscriptionTerminal`,
35
+ `isNotAuthorized`, `isSandboxClockUnauthorized`, `isSteamRefundNotSupported`, `isFlowPaused`,
36
+ `isGameNotLive`; `isSteamAuthorizationPending` now also covers the subscription 409.
37
+
38
+ Also: the server `User-Agent` version now derives from the package version (it had read
39
+ `3.0.0` since 3.0.0), pinned by a test.
40
+
3
41
  ## 3.7.0
4
42
 
5
43
  ### Minor Changes
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.7.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.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.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
 
@@ -95,6 +96,7 @@ The right approval method is a property of the **client the player is sitting in
95
96
  - [Currency purchase (real money in)](#currency-purchase-real-money-in)
96
97
  - [Item purchase (spend game currency)](#item-purchase-spend-game-currency)
97
98
  - [Platform Commerce (ecommerce)](#platform-commerce-ecommerce)
99
+ - [Subscriptions (recurring billing)](#subscriptions-recurring-billing)
98
100
  - [Player balance](#player-balance)
99
101
  - [Sends & transfers (move currency between players)](#sends--transfers-move-currency-between-players)
100
102
  - [Legacy fallback: the SMS PIN (being retired)](#legacy-fallback-the-sms-pin-being-retired)
@@ -235,6 +237,7 @@ INVO enables each flow for your tenant in the [console](#get-your-account--game-
235
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)).
236
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).
237
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).
238
241
 
239
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.
240
243
 
@@ -252,6 +255,7 @@ const server = new InvoServer({
252
255
  // retryBaseDelayMs: 250, // optional backoff base
253
256
  // fetch: customFetch, // optional override
254
257
  // hooks: { onRequest, onResponse, onError }, // optional observability (see below)
258
+ // sandboxClockKey: process.env.INVO_SANDBOX_CLOCK_KEY, // optional: the sandbox subscription clock tools only
255
259
  });
256
260
 
257
261
  const client = new InvoClient({
@@ -598,6 +602,314 @@ const ref = await server.platformCommerce.refund({ orderId: r.orderId, reason: "
598
602
 
599
603
  ---
600
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
+
601
913
  ## Player balance
602
914
 
603
915
  Read a player's currency balances (server-side, game-secret) **by email**:
@@ -1415,6 +1727,12 @@ export const POST = createWebhookHandler({
1415
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`) |
1416
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`) |
1417
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`) |
1418
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 |
1419
1737
 
1420
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.
@@ -1507,6 +1825,7 @@ Helpers:
1507
1825
  | `.isPhoneShareAlreadyApproved` | phone-share was already approved (e.g. from a `/reject`) |
1508
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 |
1509
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) |
1510
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) |
1511
1830
 
1512
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`.
@@ -1543,6 +1862,19 @@ try {
1543
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` |
1544
1863
  | `platformCommerce.getStatus(orderId)` | `{ orderId, status, gameCurrencyAmount?, usdAmount?, paymentMethod?, createdAt?, raw }` |
1545
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 |
1546
1878
  | `getPlayerBalance({ playerEmail })` | `{ player, balances, summary, raw }` — **by email only** (no by-id route; use `InvoClient.getBalance()` client-side) |
1547
1879
  | `getInboundPending({ playerEmail? \| playerPhone? })` | `{ inboundPending, raw }` — live unclaimed inbound sends/transfers |
1548
1880
  | `getLinkedIdentities({ playerEmail? \| playerPhone? })` | `{ walletUserId, primaryEmail, primaryPhone, isMinor, emails, notFound, raw }` — **server-only** (returns PII) |
@@ -344,6 +344,7 @@ var InvoError = class _InvoError extends Error {
344
344
  * instead of the backend's vocabulary. Only `Init` (and an absent status)
345
345
  * can mean "not yet"; every named status that is not Init is an outcome. */
346
346
  get isSteamAuthorizationPending() {
347
+ if (this.code === "STEAM_AUTHORIZATION_PENDING") return true;
347
348
  const b = this.body;
348
349
  if (!b || b["status"] !== "not_authorized") return false;
349
350
  const st = String(b["steam_status"] ?? "").toLowerCase();
@@ -466,6 +467,102 @@ var InvoError = class _InvoError extends Error {
466
467
  const v = this.bodyObject()["error_ref"];
467
468
  return typeof v === "string" && v ? v : void 0;
468
469
  }
470
+ // ---- Subscriptions ----
471
+ /**
472
+ * True when a create (`subscriptions.create` / `steamInit`) was refused because the
473
+ * player already has a LIVE subscription to this `itemId` (`ACTIVE_SUBSCRIPTION_EXISTS`,
474
+ * 409). Use `existingSubscriptionId`. This is what you hit if you regenerate
475
+ * `clientRequestId` inside a retry loop: replay the same key instead.
476
+ */
477
+ get isActiveSubscriptionExists() {
478
+ return this.code === "ACTIVE_SUBSCRIPTION_EXISTS";
479
+ }
480
+ /**
481
+ * The `subscription_id` a create refusal names: the LIVE subscription on
482
+ * `ACTIVE_SUBSCRIPTION_EXISTS`, the PENDING Steam row on `STEAM_AUTHORIZATION_PENDING`,
483
+ * or the abandoned (now `expired`) row when a Steam-side failure abandoned it after creation.
484
+ */
485
+ get existingSubscriptionId() {
486
+ const v = this.bodyObject()["subscription_id"];
487
+ return typeof v === "string" && v ? v : void 0;
488
+ }
489
+ /**
490
+ * True when the same `clientRequestId` was replayed for the same player and item but
491
+ * with DIFFERENT material terms (`IDEMPOTENT_REPLAY_MISMATCH`, 409). See
492
+ * `mismatchedFields` (any of `amount_usd`, `interval`, `interval_count`, `wallet_only`,
493
+ * `funding_rail`). To change terms use `changeAmount` / `setPaymentMethod`; to create a
494
+ * new subscription use a new key.
495
+ */
496
+ get isIdempotentReplayMismatch() {
497
+ return this.code === "IDEMPOTENT_REPLAY_MISMATCH";
498
+ }
499
+ /** The `mismatched_fields` on an `IDEMPOTENT_REPLAY_MISMATCH` 409. */
500
+ get mismatchedFields() {
501
+ const v = this.bodyObject()["mismatched_fields"];
502
+ return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
503
+ }
504
+ /**
505
+ * True when `changeAmount` tried to RAISE the price of a Steam subscription
506
+ * (`STEAM_REAUTHORIZATION_REQUIRED`, 409). The member consented to a ceiling; start a
507
+ * new Steam subscription at the new price and cancel this one. Decreases stage normally.
508
+ * The body carries `current_amount_usd` and `requested_amount_usd`.
509
+ */
510
+ get isSteamReauthorizationRequired() {
511
+ return this.code === "STEAM_REAUTHORIZATION_REQUIRED";
512
+ }
513
+ /** True when `setPaymentMethod` was called on a Steam subscription (`NOT_A_CARD_SUBSCRIPTION`, 409). A rail is fixed at creation. */
514
+ get isNotACardSubscription() {
515
+ return this.code === "NOT_A_CARD_SUBSCRIPTION";
516
+ }
517
+ /**
518
+ * True when a Steam subscription was started with a key for a non-Steam channel
519
+ * (`STEAM_CHANNEL_REQUIRED`, 409). Use the primary game key or the `steam` channel key.
520
+ */
521
+ get isSteamChannelRequired() {
522
+ return this.code === "STEAM_CHANNEL_REQUIRED";
523
+ }
524
+ /**
525
+ * True when `subscriptions.refund` targeted a period that was charged through Steam
526
+ * (`STEAM_REFUND_NOT_SUPPORTED`, 409). Refunds of Steam-charged periods are not
527
+ * supported yet; periods of a Steam subscription that the wallet covered entirely
528
+ * remain refundable in coins.
529
+ */
530
+ get isSteamRefundNotSupported() {
531
+ return this.code === "STEAM_REFUND_NOT_SUPPORTED";
532
+ }
533
+ /** True when the subscription is `canceled` or `expired` and the call cannot apply (`SUBSCRIPTION_TERMINAL`, 409). Start a new one. */
534
+ get isSubscriptionTerminal() {
535
+ return this.code === "SUBSCRIPTION_TERMINAL";
536
+ }
537
+ /**
538
+ * True when `subscriptions.steamFinalize` was called before the member completed the
539
+ * Steam authorisation (409, body `status: "not_authorized"`, with `steam_status`).
540
+ * THE NORMAL WAIT STATE: call finalize again after the overlay or checkout closes.
541
+ * The member has 24 hours; after that the row expires.
542
+ */
543
+ get isNotAuthorized() {
544
+ return this.bodyObject()["status"] === "not_authorized";
545
+ }
546
+ /**
547
+ * True when a sandbox clock call was refused for a missing, wrong or never-issued
548
+ * `X-Sandbox-Clock-Key` (`SANDBOX_CLOCK_UNAUTHORIZED`, 401). Reveal or rotate the key on
549
+ * the game's Game Settings page in the sandbox console.
550
+ */
551
+ get isSandboxClockUnauthorized() {
552
+ return this.code === "SANDBOX_CLOCK_UNAUTHORIZED";
553
+ }
554
+ /**
555
+ * True when INVO has paused this flow for maintenance (503): `flow_paused` on create /
556
+ * amount / payment-method / Steam init / card setup, `FLOW_PAUSED` on refund and the
557
+ * sandbox clock. Retry later WITH THE SAME idempotency key.
558
+ */
559
+ get isFlowPaused() {
560
+ return this.code === "flow_paused" || this.code === "FLOW_PAUSED";
561
+ }
562
+ /** True when a create was refused because the game is not `live` (`GAME_NOT_LIVE`, 403). Make it live in the console. */
563
+ get isGameNotLive() {
564
+ return this.code === "GAME_NOT_LIVE";
565
+ }
469
566
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
470
567
  get retryAfter() {
471
568
  const v = this.bodyObject()["retry_after"];
@@ -539,11 +636,11 @@ var _Http = class _Http {
539
636
  * (e.g. single-use WebAuthn assertions) are NEVER auto-retried.
540
637
  */
541
638
  async post(path, body, auth, opts) {
542
- return this.request("POST", path, body, auth, opts?.idempotent ?? false, opts?.signal);
639
+ return this.request("POST", path, body, auth, opts?.idempotent ?? false, opts?.signal, opts?.headers);
543
640
  }
544
641
  // GET is always idempotent → safe to retry.
545
642
  async get(path, auth, opts) {
546
- return this.request("GET", path, void 0, auth, true, opts?.signal);
643
+ return this.request("GET", path, void 0, auth, true, opts?.signal, opts?.headers);
547
644
  }
548
645
  authHeaders(auth) {
549
646
  switch (auth.kind) {
@@ -555,10 +652,13 @@ var _Http = class _Http {
555
652
  return {};
556
653
  }
557
654
  }
558
- async request(method, path, body, auth, idempotent, signal) {
655
+ async request(method, path, body, auth, idempotent, signal, extraHeaders) {
559
656
  const url = `${this.baseUrl}${path}`;
560
657
  const headers = {
561
658
  Accept: "application/json",
659
+ ...this.authHeaders(auth),
660
+ // Per-call extras (e.g. the sandbox clock key) — never able to override the auth header.
661
+ ...extraHeaders ?? {},
562
662
  ...this.authHeaders(auth)
563
663
  };
564
664
  if (this.userAgent) headers["User-Agent"] = this.userAgent;
@@ -746,5 +846,5 @@ function toDestinationsResult(raw, direction) {
746
846
  }
747
847
 
748
848
  export { Http, InvoError, assertSecureBaseUrl, toDestinationsResult };
749
- //# sourceMappingURL=chunk-23TGMTII.js.map
750
- //# sourceMappingURL=chunk-23TGMTII.js.map
849
+ //# sourceMappingURL=chunk-HYGBTUEJ.js.map
850
+ //# sourceMappingURL=chunk-HYGBTUEJ.js.map