@invonetwork/web-sdk 2.4.1 → 2.5.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
@@ -4,6 +4,37 @@ All notable changes to `@invonetwork/web-sdk` are documented here. This project
4
4
  [Semantic Versioning](https://semver.org/). Releases are managed with
5
5
  [changesets](https://github.com/changesets/changesets).
6
6
 
7
+ ## [2.5.0] — 2026-07-20
8
+
9
+ **Platform Commerce (ecommerce).** A new flow for **platform** tenants (non-game apps: vertical
10
+ video, creator merch, marketplace) to sell items funded by **INVO balance or a real card**, with
11
+ INVO as merchant of record and full refunds. This is **distinct from item purchase** — that is a
12
+ *game* tenant spending a player's *existing game currency* on an *in-game* item (balance only, no
13
+ card, no refund). Additive; only platform tenants can call it (a game tenant gets `403
14
+ NOT_A_PLATFORM_TENANT`). (Backend handoff: BE-PIP-009 `PLATFORM_COMMERCE_SDK.md`.)
15
+
16
+ - **Server** (`InvoServer.platformCommerce`, mirrored in the Python SDK as
17
+ `server.platform_commerce`):
18
+ - `purchase(input)` — `fundingSource: "balance"` settles synchronously (`status:"success"`);
19
+ `"card"` returns `status:"requires_payment"` + a `clientSecret` and **requires a
20
+ `billingAddress`**. Idempotent on `clientRequestId`.
21
+ - `getStatus(orderId)` — `completed` | `pending_payment` | `refunded`.
22
+ - `refund({ orderId | clientRequestId, reason? })` — INVO retains its fee; a second refund
23
+ throws `409` (`err.isAlreadyRefunded`).
24
+ - **Browser** (`InvoClient.platformCommerce`):
25
+ - `confirmCardPayment(clientSecret, { mount, publishableKey?, returnUrl?, submit? })` — mounts
26
+ the card element and confirms; returns `{ status: "succeeded" | "requires_action" |
27
+ "processing" | "failed" }`. The processor JS is **lazy-loaded from its CDN — no bundled
28
+ dependency**; pass its publishable key (or set `commercePublishableKey` on the client config).
29
+ - `mountCardPayment(clientSecret, opts)` — the primitive: `{ element, confirm(), destroy() }`
30
+ to confirm from your own Pay button.
31
+ - **Webhooks:** new typed `platform_commerce.purchased` / `platform_commerce.refunded` events.
32
+ **Fulfill card orders on `platform_commerce.purchased`, never on the browser confirmation.**
33
+ - **New `InvoError` classifiers:** `isNotPlatformTenant` (403), `isAmountBelowMinimum`,
34
+ `isBelowCardMinimum` (card < $0.50), `isAlreadyRefunded` (409).
35
+ - Docs: README now leads the flow list with an explicit **item purchase vs Platform Commerce**
36
+ contrast; new "Platform Commerce (ecommerce)" section.
37
+
7
38
  ## [2.4.1] — 2026-07-10
8
39
 
9
40
  Docs only, no code change — corrects stale README prose that the 2.4.0 publish still carried:
package/README.md CHANGED
@@ -2,21 +2,26 @@
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:** `v2.4.1` — 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: **2.2.0** reconciled with the backend (`mintPlayerToken` is a session mint — `playerPhone` optional; send-by-phone-alone; email-only `getPlayerBalance`); **2.3.0** surfaces the claim-time phone-share `409` on `confirmReceipt*`/`claim*` (+ `err.phoneShareLast4`); **2.4.0** adds Steam transfer-policy handling (`isSteamValueNonTransferable`/`isNonSteamValueIntoSteamBlocked` + `DestinationGame.acceptsSteamOriginValue`). Full history in the [CHANGELOG](CHANGELOG.md).
5
+ > **Status:** `v2.5.0` — stable, published on npm. The backend it wraps is **live** on sandbox + production. The API is covered by a [stability commitment](#stability): no breaking changes without a major bump. Recent highlights: **2.5.0** adds **Platform Commerce** (ecommerce) — a platform tenant selling items funded by balance **or** card, with `invo.platformCommerce.purchase/getStatus/refund` (server), `invo.platformCommerce.confirmCardPayment` (browser), 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
- Four money flows plus passkey (WebAuthn) authentication, split across a trusted server entry and an untrusted browser entry:
10
+ Five 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
+ | **Platform Commerce** (ecommerce) | balance **or** card **→** a storefront item | card leg only | no | server creates, browser confirms the card |
16
17
  | **Send** | currency **→** another player (cross-game) | no | yes (sender approves) | server initiates, browser approves/claims |
17
18
  | **Transfer** | currency **→** another player (transfer rail) | no | yes (sender approves) | server initiates, browser approves/claims |
18
19
 
19
- The **game secret stays on your server**; the browser only ever holds a short-lived, game-scoped **player token**.
20
+ > **Item purchase vs Platform Commerce — don't mix them up.** They share a body shape (`itemId`, `unitPrice`, `totalPrice`, `clientRequestId`) but are different products:
21
+ > - **[Item purchase](#item-purchase-spend-game-currency)** — a **game** tenant. A player spends **game currency they already hold** on an **in-game** item (a sword, a skin). Always a balance debit — **never a card, never new money, no refunds**. `server.purchaseItem(...)` → `/api/item-purchases`.
22
+ > - **[Platform Commerce](#platform-commerce-ecommerce)** — a **platform** tenant (a non-game app: vertical video, creator merch, marketplace). A **storefront** sale funded by **INVO balance or a real card** (new money), with **INVO as merchant of record** and **refunds**. `server.platformCommerce.purchase(...)` → `/api/platform-commerce`. A game tenant calling it gets `403 NOT_A_PLATFORM_TENANT`.
23
+
24
+ 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 `clientSecret`).
20
25
 
21
26
  ## Contents
22
27
 
@@ -26,6 +31,7 @@ The **game secret stays on your server**; the browser only ever holds a short-li
26
31
  - [Configuration](#configuration)
27
32
  - [Currency purchase (real money in)](#currency-purchase-real-money-in)
28
33
  - [Item purchase (spend game currency)](#item-purchase-spend-game-currency)
34
+ - [Platform Commerce (ecommerce)](#platform-commerce-ecommerce)
29
35
  - [Player balance](#player-balance)
30
36
  - [Sends & transfers (move currency between players)](#sends--transfers-move-currency-between-players)
31
37
  - [Passkeys (enroll, approve, link, recover)](#passkeys-enroll-approve-link-recover)
@@ -303,6 +309,92 @@ const item = await server.purchaseItem({
303
309
 
304
310
  ---
305
311
 
312
+ ## Platform Commerce (ecommerce)
313
+
314
+ > **This is not [item purchase](#item-purchase-spend-game-currency).** Item purchase is a *game* tenant spending a player's *existing game currency* on an *in-game* item — always a balance debit, never a card, no refunds. **Platform Commerce is a _platform_ tenant (a non-game app: vertical video, creator merch, marketplace) running a storefront.** The buyer pays with **INVO balance** *or* a **real card** (new money), INVO is **merchant of record**, and **refunds** exist. Only platform tenants may call it — a game tenant gets `403` (`err.isNotPlatformTenant`).
315
+
316
+ The funding source is resolved **server-side under lock** — the client can *request* `balance` or `card`, but the backend verifies the real balance before any value moves. That's why there's a server call (holds the secret, creates the purchase/refund) **and** a browser call (confirms the card). Reached via the `platformCommerce` namespace on each entry point.
317
+
318
+ ### Balance leg — one server call, settles now
319
+
320
+ ```ts
321
+ const r = await server.platformCommerce.purchase({
322
+ clientRequestId: crypto.randomUUID(), // idempotency key, unique per tenant
323
+ fundingSource: "balance",
324
+ playerEmail: "user@example.com",
325
+ playerName: "Ada",
326
+ itemId: "sticker_pack_01",
327
+ itemName: "Sticker Pack",
328
+ itemQuantity: 1, // integer 1..1000
329
+ unitPrice: "5.00", // BALANCE leg: the tenant's network-currency amount
330
+ totalPrice: "5.00", // must equal unitPrice × itemQuantity (±0.01)
331
+ });
332
+ // r.status === "success" — settled synchronously
333
+ // r.newBalance / r.previousBalance / r.currencyName
334
+ // r.orderId / r.transactionId
335
+ // r.financialBreakdown { total_paid, developer_revenue, platform_fee } // INVO fee: 3.5% flat
336
+ ```
337
+
338
+ ### Card leg — server creates, browser confirms
339
+
340
+ The card leg is the SDK's only browser **payment** step. `totalPrice` is **USD**, and a **`billingAddress`** is required (AVS / fraud / merchant-of-record).
341
+
342
+ ```ts
343
+ // 1) server — returns a clientSecret, NOT yet paid
344
+ const r = await server.platformCommerce.purchase({
345
+ clientRequestId: crypto.randomUUID(),
346
+ fundingSource: "card",
347
+ playerEmail: "user@example.com",
348
+ playerName: "Ada",
349
+ itemId: "sticker_pack_01",
350
+ itemName: "Sticker Pack",
351
+ itemQuantity: 1,
352
+ unitPrice: "5.00", // CARD leg: USD
353
+ totalPrice: "5.00",
354
+ billingAddress: { // REQUIRED on the card leg
355
+ line1: "1 Main St", city: "Austin", postalCode: "78701", country: "US",
356
+ // optional: name, line2, state
357
+ },
358
+ });
359
+ // r.status === "requires_payment"; hand r.clientSecret to the browser
360
+ ```
361
+
362
+ ```ts
363
+ // 2) browser — mount the card element and confirm. The SDK lazy-loads the card
364
+ // processor's JS from its CDN (no bundled dependency); pass its PUBLISHABLE key.
365
+ const result = await invo.platformCommerce.confirmCardPayment(clientSecret, {
366
+ mount: "#pay", // a CSS selector or an HTMLElement
367
+ publishableKey: "pk_live_…", // or set commercePublishableKey on the InvoClient config
368
+ returnUrl: location.href, // where the bank returns after any 3-D Secure step
369
+ // optional: submit (your own Pay button, selector or element), submitLabel, appearance
370
+ });
371
+ // result.status: "succeeded" | "requires_action" | "processing" | "failed"
372
+ ```
373
+
374
+ For full control over your own Pay button, use the primitive: `const session = await invo.platformCommerce.mountCardPayment(clientSecret, { mount, publishableKey })`, then call `await session.confirm({ returnUrl })` from your button and `session.destroy()` when done.
375
+
376
+ > ⚠️ **The card sale is real only on the `platform_commerce.purchased` webhook — never on the browser confirmation** (a client can be tampered with). Treat `"succeeded"` as "show processing" and fulfill on the webhook.
377
+
378
+ ### Status & refunds
379
+
380
+ ```ts
381
+ const s = await server.platformCommerce.getStatus(r.orderId);
382
+ // s.status: "completed" (balance immediately; card after the webhook) | "pending_payment" | "refunded"
383
+
384
+ const ref = await server.platformCommerce.refund({ orderId: r.orderId, reason: "customer request" });
385
+ // or refund({ clientRequestId }). Pass EXACTLY ONE id.
386
+ // INVO retains its fee (ref.feeRetained === true); the customer is made whole minus that fee.
387
+ // A second refund of the same order throws 409 (err.isAlreadyRefunded) — treat as already done.
388
+ ```
389
+
390
+ - **Idempotent** on `clientRequestId` — a duplicate purchase throws `409` (`err.isDuplicateRequest`).
391
+ - **Lost card-purchase response?** If the network drops the card-leg response, you won't have the `clientSecret` or `orderId`, and retrying the same `clientRequestId` returns `409` (the order already exists). Reconcile via your **`platform_commerce.purchased`** webhook — don't retry to recover the `clientSecret`. (The balance leg is fully retry-safe.)
392
+ - INVO fee: **3.5% flat** (balance) · **3.5% + $0.30** (card). Below-minimum amounts throw `err.isAmountBelowMinimum`; a card charge under $0.50 throws `err.isBelowCardMinimum`.
393
+ - Client-side validation (missing fields, bad funding source, quantity outside `1..1000`, total ≠ unit×qty, missing/short billing address on the card leg) throws `INVALID_INPUT` **before** any network call.
394
+ - Fulfill on the **`platform_commerce.purchased`** webhook; handle **`platform_commerce.refunded`** for reversals.
395
+
396
+ ---
397
+
306
398
  ## Player balance
307
399
 
308
400
  Read a player's currency balances (server-side, game-secret) **by email**:
@@ -526,8 +618,10 @@ export const POST = createWebhookHandler({
526
618
  | `purchase.failed` / `purchase.disputed` | `platform` rail only | handle failures/disputes |
527
619
  | `purchase.refunded` | `game` / `steam` rails | handle refunds |
528
620
  | `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`) |
621
+ | `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`) |
622
+ | `platform_commerce.refunded` | a Platform Commerce refund | handle the reversal (payload: `order_id, funding_source, player_email, refunded_amount, amount_unit, fee_retained`) |
529
623
 
530
- Don't block waiting on `purchase.failed` for the `game`/`steam` rails — they only emit `completed`/`refunded`. Reconcile off `*.completed` + the status endpoints.
624
+ 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.
531
625
 
532
626
  ---
533
627
 
@@ -570,6 +664,9 @@ Helpers:
570
664
  | `.isReceiverNotEnrolled` | recipient has no passkey → switch to claim-code entry |
571
665
  | `.isInsufficientBalance` | item purchase failed (400); `required_amount` + `current_balance` on `.body` |
572
666
  | `.isDuplicateRequest` | idempotency-keyed request was a duplicate (409) |
667
+ | `.isNotPlatformTenant` | Platform Commerce called by a non-platform tenant (403) — use `purchaseItem`/`createCheckout` instead |
668
+ | `.isAmountBelowMinimum` / `.isBelowCardMinimum` | Platform Commerce amount too small for the fee to round up / card charge under $0.50 (400) |
669
+ | `.isAlreadyRefunded` | Platform Commerce refund of an already-refunded order (409) — treat as already done |
573
670
  | `.retryAfter` | seconds to back off on a 429 throttle |
574
671
  | `.isEnrollmentAuthorizationRequired` | first-enrollment needs the OTP grant → `enrollmentBegin`/`enrollmentVerify` |
575
672
  | `.isEnrollmentProofRequired` | another method exists → prove it via `linkDevice` |
@@ -606,9 +703,12 @@ try {
606
703
  | `purchaseCurrency(input)` | `{ status, clientSecret?, paymentIntentId?, paymentUrl?, transactionId?, orderId?, newBalance?, raw }` |
607
704
  | `confirmPayment({ paymentIntentId, orderId? })` | `{ status, transactionId?, newBalance?, raw }` |
608
705
  | `getOrderDetails({ orderId? \| transactionId? })` | `{ order, financialSummary, statusTimeline, raw }` |
609
- | `purchaseItem(input)` | `{ status, transactionId, orderId, newBalance, previousBalance, currencyName, financialBreakdown?, raw }` |
706
+ | `purchaseItem(input)` | `{ status, transactionId, orderId, newBalance, previousBalance, currencyName, financialBreakdown?, raw }` — **game** tenant spending game currency on an in-game item |
610
707
  | `getItemPurchaseHistory({ playerEmail, limit?, offset? })` | `{ history, pagination, raw }` |
611
708
  | `getItemOrderDetails({ orderId? \| transactionId? \| clientRequestId? })` | `{ order, financialSummary, statusTimeline, raw }` |
709
+ | `platformCommerce.purchase(input)` | `{ status, fundingSource, orderId, transactionId?, newBalance?, financialBreakdown?, clientSecret?, amountUsd?, raw }` — **ecommerce** (platform tenant); `balance` settles now, `card` returns a `clientSecret` |
710
+ | `platformCommerce.getStatus(orderId)` | `{ orderId, status, gameCurrencyAmount?, usdAmount?, paymentMethod?, createdAt?, raw }` |
711
+ | `platformCommerce.refund({ orderId? \| clientRequestId?, reason? })` | `{ status, orderId?, fundingSource?, refundedAmount?, amountUnit?, feeRetained?, raw }` — pass **exactly one** id; INVO keeps its fee |
612
712
  | `getPlayerBalance({ playerEmail })` | `{ player, balances, summary, raw }` — **by email only** (no by-id route; use `InvoClient.getBalance()` client-side) |
613
713
  | `getInboundPending({ playerEmail? \| playerPhone? })` | `{ inboundPending, raw }` — live unclaimed inbound sends/transfers |
614
714
  | `getLinkedIdentities({ playerEmail? \| playerPhone? })` | `{ walletUserId, primaryEmail, primaryPhone, isMinor, emails, notFound, raw }` — **server-only** (returns PII) |
@@ -638,8 +738,10 @@ Every method also accepts an optional final `{ signal }` (`AbortSignal`) for can
638
738
  | `getPendingCollect()` | `{ pending, raw }` — the player's own pending-to-collect list (player-token) |
639
739
  | `getDestinations({ direction? })` | `{ availableGames, sourceGameName, transferMode, … }` — where the player can send/transfer, metadata inline |
640
740
  | `getBalance()` | `{ gameId, gameName, balances, totalValue, currencyCount, hasFunds, raw }` — the player's balances for this game |
741
+ | `platformCommerce.confirmCardPayment(clientSecret, { mount, publishableKey?, returnUrl?, submit?, appearance? })` | `{ status: "succeeded" \| "requires_action" \| "processing" \| "failed", paymentIntentId?, error?, raw }` — mount + confirm the Platform Commerce card leg |
742
+ | `platformCommerce.mountCardPayment(clientSecret, { mount, publishableKey? })` | `{ element, confirm({ returnUrl? }), destroy() }` — the primitive: confirm from your own Pay button |
641
743
 
642
- Every method throws `InvoError` on failure and takes an optional final `{ signal }`. Full inline types ship with the package.
744
+ Every method throws `InvoError` on failure and takes an optional final `{ signal }`. Full inline types ship with the package. For the Platform Commerce card leg, set `commercePublishableKey` on the `InvoClient` config (or pass `publishableKey` per call); the processor JS is lazy-loaded from its CDN — nothing to bundle.
643
745
 
644
746
  ---
645
747
 
@@ -130,10 +130,37 @@ var InvoError = class _InvoError extends Error {
130
130
  get isPhoneShareAlreadyApproved() {
131
131
  return this.code === "PHONE_SHARE_ALREADY_APPROVED";
132
132
  }
133
- /** True if an idempotency-keyed request was a duplicate (item purchase → 409). */
133
+ /** True if an idempotency-keyed request was a duplicate (item / platform purchase → 409). */
134
134
  get isDuplicateRequest() {
135
135
  return this.code === "DUPLICATE_REQUEST" || this.status === 409 && /duplicate/i.test(this.message);
136
136
  }
137
+ /**
138
+ * True if a Platform Commerce call was rejected because the tenant isn't a platform
139
+ * tenant (`NOT_A_PLATFORM_TENANT`, 403). Platform Commerce (`invo.platformCommerce.*`)
140
+ * is only for non-game platform tenants — a game tenant should use `purchaseItem`
141
+ * (spend game currency) or `createCheckout`/`purchaseCurrency` (buy currency) instead.
142
+ */
143
+ get isNotPlatformTenant() {
144
+ return this.code === "NOT_A_PLATFORM_TENANT";
145
+ }
146
+ /** True if a Platform Commerce purchase was too small for the fee to round above zero
147
+ * (`AMOUNT_BELOW_MINIMUM`, 400) — raise the amount. */
148
+ get isAmountBelowMinimum() {
149
+ return this.code === "AMOUNT_BELOW_MINIMUM";
150
+ }
151
+ /** True if a Platform Commerce CARD purchase was below the processor's floor of $0.50
152
+ * (backend code `BELOW_STRIPE_MINIMUM`, 400). Neutral name; matches the wire code. */
153
+ get isBelowCardMinimum() {
154
+ return this.code === "BELOW_STRIPE_MINIMUM";
155
+ }
156
+ /**
157
+ * True if a Platform Commerce refund targeted an order that was already refunded
158
+ * (409). Idempotent outcome — the original refund did happen, so treat this as
159
+ * success, not a failure to retry-loop.
160
+ */
161
+ get isAlreadyRefunded() {
162
+ return this.code === "ALREADY_REFUNDED" || this.status === 409 && /already\s+refunded/i.test(this.message);
163
+ }
137
164
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
138
165
  get retryAfter() {
139
166
  const v = this.bodyObject()["retry_after"];
@@ -411,5 +438,5 @@ function toDestinationsResult(raw, direction) {
411
438
  }
412
439
 
413
440
  export { Http, InvoError, assertSecureBaseUrl, toDestinationsResult };
414
- //# sourceMappingURL=chunk-SSTZKXPC.js.map
415
- //# sourceMappingURL=chunk-SSTZKXPC.js.map
441
+ //# sourceMappingURL=chunk-ZKYUSYK5.js.map
442
+ //# sourceMappingURL=chunk-ZKYUSYK5.js.map
package/dist/index.cjs CHANGED
@@ -132,10 +132,37 @@ var InvoError = class _InvoError extends Error {
132
132
  get isPhoneShareAlreadyApproved() {
133
133
  return this.code === "PHONE_SHARE_ALREADY_APPROVED";
134
134
  }
135
- /** True if an idempotency-keyed request was a duplicate (item purchase → 409). */
135
+ /** True if an idempotency-keyed request was a duplicate (item / platform purchase → 409). */
136
136
  get isDuplicateRequest() {
137
137
  return this.code === "DUPLICATE_REQUEST" || this.status === 409 && /duplicate/i.test(this.message);
138
138
  }
139
+ /**
140
+ * True if a Platform Commerce call was rejected because the tenant isn't a platform
141
+ * tenant (`NOT_A_PLATFORM_TENANT`, 403). Platform Commerce (`invo.platformCommerce.*`)
142
+ * is only for non-game platform tenants — a game tenant should use `purchaseItem`
143
+ * (spend game currency) or `createCheckout`/`purchaseCurrency` (buy currency) instead.
144
+ */
145
+ get isNotPlatformTenant() {
146
+ return this.code === "NOT_A_PLATFORM_TENANT";
147
+ }
148
+ /** True if a Platform Commerce purchase was too small for the fee to round above zero
149
+ * (`AMOUNT_BELOW_MINIMUM`, 400) — raise the amount. */
150
+ get isAmountBelowMinimum() {
151
+ return this.code === "AMOUNT_BELOW_MINIMUM";
152
+ }
153
+ /** True if a Platform Commerce CARD purchase was below the processor's floor of $0.50
154
+ * (backend code `BELOW_STRIPE_MINIMUM`, 400). Neutral name; matches the wire code. */
155
+ get isBelowCardMinimum() {
156
+ return this.code === "BELOW_STRIPE_MINIMUM";
157
+ }
158
+ /**
159
+ * True if a Platform Commerce refund targeted an order that was already refunded
160
+ * (409). Idempotent outcome — the original refund did happen, so treat this as
161
+ * success, not a failure to retry-loop.
162
+ */
163
+ get isAlreadyRefunded() {
164
+ return this.code === "ALREADY_REFUNDED" || this.status === 409 && /already\s+refunded/i.test(this.message);
165
+ }
139
166
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
140
167
  get retryAfter() {
141
168
  const v = this.bodyObject()["retry_after"];
@@ -531,6 +558,182 @@ function toBalanceRow(row) {
531
558
  raw: row
532
559
  };
533
560
  }
561
+ var PROCESSOR_SRC = "https://js.stripe.com/v3";
562
+ var processorScriptLoad;
563
+ function loadProcessorScript() {
564
+ if (typeof document === "undefined" || typeof window === "undefined") {
565
+ return Promise.reject(
566
+ new InvoError({
567
+ message: "confirmCardPayment requires a browser DOM (window/document).",
568
+ code: "DOM_UNAVAILABLE",
569
+ status: 0
570
+ })
571
+ );
572
+ }
573
+ if (window.Stripe) return Promise.resolve();
574
+ if (processorScriptLoad) return processorScriptLoad;
575
+ processorScriptLoad = new Promise((resolve, reject) => {
576
+ const existing = document.querySelector(
577
+ `script[src="${PROCESSOR_SRC}"]`
578
+ );
579
+ const script = existing ?? document.createElement("script");
580
+ if (!existing) {
581
+ script.src = PROCESSOR_SRC;
582
+ script.async = true;
583
+ document.head.appendChild(script);
584
+ }
585
+ script.addEventListener("load", () => resolve());
586
+ script.addEventListener("error", () => {
587
+ processorScriptLoad = void 0;
588
+ reject(
589
+ new InvoError({
590
+ message: "Failed to load the card processor script.",
591
+ code: "PROCESSOR_LOAD_FAILED",
592
+ status: 0
593
+ })
594
+ );
595
+ });
596
+ });
597
+ return processorScriptLoad;
598
+ }
599
+ async function defaultLoadProcessor(publishableKey) {
600
+ await loadProcessorScript();
601
+ const factory = window.Stripe;
602
+ if (typeof factory !== "function") {
603
+ throw new InvoError({
604
+ message: "The card processor was unavailable after loading.",
605
+ code: "PROCESSOR_UNAVAILABLE",
606
+ status: 0
607
+ });
608
+ }
609
+ return factory(publishableKey);
610
+ }
611
+ function mapCardConfirm(res) {
612
+ const raw = res;
613
+ if (res.error) {
614
+ return { status: "failed", error: res.error.message ?? "Card payment failed.", raw };
615
+ }
616
+ const pi = res.paymentIntent;
617
+ const s = pi?.status;
618
+ let status;
619
+ if (s === "succeeded") status = "succeeded";
620
+ else if (s === "processing") status = "processing";
621
+ else if (s === "requires_action" || s === "requires_confirmation") status = "requires_action";
622
+ else status = "failed";
623
+ return { status, paymentIntentId: pi?.id, raw };
624
+ }
625
+ function resolveSubmit(opts) {
626
+ if (opts.submit) {
627
+ const el = typeof opts.submit === "string" ? typeof document !== "undefined" ? document.querySelector(opts.submit) : null : opts.submit;
628
+ if (!el) {
629
+ throw new InvoError({
630
+ message: `confirmCardPayment could not find the submit element "${String(opts.submit)}".`,
631
+ code: "SUBMIT_NOT_FOUND",
632
+ status: 0
633
+ });
634
+ }
635
+ return { el, created: false };
636
+ }
637
+ if (typeof document === "undefined") {
638
+ throw new InvoError({
639
+ message: "confirmCardPayment needs a submit button: pass `submit`, or use `mountCardPayment(...).confirm()` from your own button.",
640
+ code: "SUBMIT_REQUIRED",
641
+ status: 0
642
+ });
643
+ }
644
+ const container = typeof opts.mount === "string" ? document.querySelector(opts.mount) : opts.mount;
645
+ const btn = document.createElement("button");
646
+ btn.type = "button";
647
+ btn.textContent = opts.submitLabel ?? "Pay";
648
+ (container ?? document.body).appendChild(btn);
649
+ return { el: btn, created: true };
650
+ }
651
+ var PlatformCommerceClient = class {
652
+ constructor(defaultPublishableKey) {
653
+ this.defaultPublishableKey = defaultPublishableKey;
654
+ }
655
+ /**
656
+ * Mount the Payment Element and get a session you confirm from your OWN Pay button.
657
+ * This is the fully-controllable primitive (`confirmCardPayment` builds on it).
658
+ *
659
+ * ```ts
660
+ * const session = await invo.platformCommerce.mountCardPayment(clientSecret, {
661
+ * mount: "#pay", publishableKey: "pk_live_…",
662
+ * });
663
+ * // on your Pay button click:
664
+ * const r = await session.confirm({ returnUrl: location.href });
665
+ * if (r.status === "succeeded") showProcessing();
666
+ * session.destroy();
667
+ * ```
668
+ */
669
+ async mountCardPayment(clientSecret, opts) {
670
+ if (!clientSecret || !clientSecret.trim()) {
671
+ throw new Error("mountCardPayment requires a `clientSecret`.");
672
+ }
673
+ if (opts?.mount == null || typeof opts.mount === "string" && !opts.mount.trim()) {
674
+ throw new Error("mountCardPayment requires a `mount` target (selector or element).");
675
+ }
676
+ const pk = opts.publishableKey ?? this.defaultPublishableKey();
677
+ if (!pk) {
678
+ throw new InvoError({
679
+ message: "A card processor publishableKey is required \u2014 pass it in options, or set `commercePublishableKey` on the InvoClient config.",
680
+ code: "MISSING_PUBLISHABLE_KEY",
681
+ status: 0
682
+ });
683
+ }
684
+ const load = opts.loadProcessor ?? defaultLoadProcessor;
685
+ const processor = await load(pk);
686
+ const elements = processor.elements({ clientSecret, appearance: opts.appearance });
687
+ const element = elements.create("payment");
688
+ element.mount(opts.mount);
689
+ const confirm = async (confirmOpts) => {
690
+ const returnUrl = confirmOpts?.returnUrl ?? opts.returnUrl;
691
+ const res = await processor.confirmPayment({
692
+ elements,
693
+ confirmParams: returnUrl ? { return_url: returnUrl } : void 0,
694
+ // Stay in-page unless the bank forces a redirect (then return_url completes it).
695
+ redirect: "if_required"
696
+ });
697
+ return mapCardConfirm(res);
698
+ };
699
+ return {
700
+ element,
701
+ confirm,
702
+ destroy() {
703
+ try {
704
+ element.unmount?.();
705
+ } catch {
706
+ }
707
+ }
708
+ };
709
+ }
710
+ /**
711
+ * One-call mount + confirm. Mounts the Payment Element into `opts.mount` and resolves
712
+ * when the payment is confirmed via a submit trigger — either `opts.submit` (your Pay
713
+ * button, selector or element) or a minimal button the SDK renders inside `mount`. For
714
+ * full control over the button, prefer {@link mountCardPayment}.
715
+ */
716
+ async confirmCardPayment(clientSecret, opts) {
717
+ const session = await this.mountCardPayment(clientSecret, opts);
718
+ const trigger = resolveSubmit(opts);
719
+ return new Promise((resolve, reject) => {
720
+ const finish = (settle) => {
721
+ if (trigger.created) trigger.el.remove();
722
+ session.destroy();
723
+ settle();
724
+ };
725
+ const onClick = () => {
726
+ trigger.el.removeEventListener("click", onClick);
727
+ if ("disabled" in trigger.el) trigger.el.disabled = true;
728
+ session.confirm().then(
729
+ (r) => finish(() => resolve(r)),
730
+ (e) => finish(() => reject(e))
731
+ );
732
+ };
733
+ trigger.el.addEventListener("click", onClick);
734
+ });
735
+ }
736
+ };
534
737
  var InvoClient = class {
535
738
  constructor(config) {
536
739
  if (!config.token) throw new Error("InvoClient requires a player `token`.");
@@ -547,6 +750,8 @@ var InvoClient = class {
547
750
  });
548
751
  this.auth = { kind: "bearer", token: config.token };
549
752
  this.refreshToken = config.refreshToken;
753
+ this.commercePublishableKey = config.commercePublishableKey;
754
+ this.platformCommerce = new PlatformCommerceClient(() => this.commercePublishableKey);
550
755
  }
551
756
  assertWebAuthn() {
552
757
  if (typeof navigator === "undefined" || !navigator.credentials) {
@@ -889,5 +1094,6 @@ var InvoClient = class {
889
1094
 
890
1095
  exports.InvoClient = InvoClient;
891
1096
  exports.InvoError = InvoError;
1097
+ exports.PlatformCommerceClient = PlatformCommerceClient;
892
1098
  //# sourceMappingURL=index.cjs.map
893
1099
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -1,12 +1,53 @@
1
- import { C as ClientConfig, a as CallOptions, A as ApproveResult, b as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, c as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, d as EnrollmentVerifyResult, R as RecoveryBeginResult, e as RecoveryCompleteResult } from './types-7Hl0Z1Ta.cjs';
2
- export { f as BalanceRow, g as DestinationGame, I as InvoError, h as InvoErrorInfo, i as InvoHooks, j as InvoRequestInfo, k as InvoResponseInfo, l as PendingCollectItem, m as Rail, V as VerificationMethod } from './types-7Hl0Z1Ta.cjs';
1
+ import { M as MountCardPaymentOptions, C as CardPaymentSession, a as ConfirmCardPaymentOptions, b as CardPaymentResult, c as ClientConfig, d as CallOptions, A as ApproveResult, e as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, f as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, g as EnrollmentVerifyResult, R as RecoveryBeginResult, h as RecoveryCompleteResult } from './types-g1xz5GDk.cjs';
2
+ export { i as BalanceRow, j as CardPaymentStatus, k as DestinationGame, I as InvoCardConfirmResponse, l as InvoCardElement, m as InvoCardElements, n as InvoCardProcessor, o as InvoError, p as InvoErrorInfo, q as InvoHooks, r as InvoRequestInfo, s as InvoResponseInfo, t as PendingCollectItem, u as Rail, V as VerificationMethod } from './types-g1xz5GDk.cjs';
3
3
 
4
+ /**
5
+ * Platform Commerce card confirmation (browser side). The server (`InvoServer.
6
+ * platformCommerce.purchase` with `fundingSource:"card"`) returns a `clientSecret`; this
7
+ * mounts the processor's Payment Element (card / Apple Pay / Google Pay) and confirms it.
8
+ * The sale is real only on the `platform_commerce.purchased` webhook — treat a "succeeded"
9
+ * here as "show processing", never as fulfilled.
10
+ */
11
+ declare class PlatformCommerceClient {
12
+ private readonly defaultPublishableKey;
13
+ constructor(defaultPublishableKey: () => string | undefined);
14
+ /**
15
+ * Mount the Payment Element and get a session you confirm from your OWN Pay button.
16
+ * This is the fully-controllable primitive (`confirmCardPayment` builds on it).
17
+ *
18
+ * ```ts
19
+ * const session = await invo.platformCommerce.mountCardPayment(clientSecret, {
20
+ * mount: "#pay", publishableKey: "pk_live_…",
21
+ * });
22
+ * // on your Pay button click:
23
+ * const r = await session.confirm({ returnUrl: location.href });
24
+ * if (r.status === "succeeded") showProcessing();
25
+ * session.destroy();
26
+ * ```
27
+ */
28
+ mountCardPayment(clientSecret: string, opts: MountCardPaymentOptions): Promise<CardPaymentSession>;
29
+ /**
30
+ * One-call mount + confirm. Mounts the Payment Element into `opts.mount` and resolves
31
+ * when the payment is confirmed via a submit trigger — either `opts.submit` (your Pay
32
+ * button, selector or element) or a minimal button the SDK renders inside `mount`. For
33
+ * full control over the button, prefer {@link mountCardPayment}.
34
+ */
35
+ confirmCardPayment(clientSecret: string, opts: ConfirmCardPaymentOptions): Promise<CardPaymentResult>;
36
+ }
4
37
  declare class InvoClient {
5
38
  private readonly http;
6
39
  private auth;
7
40
  private readonly refreshToken;
8
41
  /** In-flight refresh, shared so concurrent expiries trigger a single re-mint. */
9
42
  private refreshInFlight;
43
+ private readonly commercePublishableKey;
44
+ /**
45
+ * Platform Commerce (ecommerce) card confirmation. Use after
46
+ * `InvoServer.platformCommerce.purchase({ fundingSource: "card" })` returns a
47
+ * `clientSecret`. The passkey/token flows never touch this. See
48
+ * {@link PlatformCommerceClient}.
49
+ */
50
+ readonly platformCommerce: PlatformCommerceClient;
10
51
  constructor(config: ClientConfig);
11
52
  private assertWebAuthn;
12
53
  /**
@@ -129,4 +170,4 @@ declare class InvoClient {
129
170
  private confirmReceipt;
130
171
  }
131
172
 
132
- export { ApproveResult, BalanceResult, CallOptions, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, PendingCollectResult, RecoveryBeginResult, RecoveryCompleteResult };
173
+ export { ApproveResult, BalanceResult, CallOptions, CardPaymentResult, CardPaymentSession, ClientConfig, ConfirmCardPaymentOptions, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, MountCardPaymentOptions, PendingCollectResult, PlatformCommerceClient, RecoveryBeginResult, RecoveryCompleteResult };
package/dist/index.d.ts CHANGED
@@ -1,12 +1,53 @@
1
- import { C as ClientConfig, a as CallOptions, A as ApproveResult, b as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, c as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, d as EnrollmentVerifyResult, R as RecoveryBeginResult, e as RecoveryCompleteResult } from './types-7Hl0Z1Ta.js';
2
- export { f as BalanceRow, g as DestinationGame, I as InvoError, h as InvoErrorInfo, i as InvoHooks, j as InvoRequestInfo, k as InvoResponseInfo, l as PendingCollectItem, m as Rail, V as VerificationMethod } from './types-7Hl0Z1Ta.js';
1
+ import { M as MountCardPaymentOptions, C as CardPaymentSession, a as ConfirmCardPaymentOptions, b as CardPaymentResult, c as ClientConfig, d as CallOptions, A as ApproveResult, e as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, f as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, g as EnrollmentVerifyResult, R as RecoveryBeginResult, h as RecoveryCompleteResult } from './types-g1xz5GDk.js';
2
+ export { i as BalanceRow, j as CardPaymentStatus, k as DestinationGame, I as InvoCardConfirmResponse, l as InvoCardElement, m as InvoCardElements, n as InvoCardProcessor, o as InvoError, p as InvoErrorInfo, q as InvoHooks, r as InvoRequestInfo, s as InvoResponseInfo, t as PendingCollectItem, u as Rail, V as VerificationMethod } from './types-g1xz5GDk.js';
3
3
 
4
+ /**
5
+ * Platform Commerce card confirmation (browser side). The server (`InvoServer.
6
+ * platformCommerce.purchase` with `fundingSource:"card"`) returns a `clientSecret`; this
7
+ * mounts the processor's Payment Element (card / Apple Pay / Google Pay) and confirms it.
8
+ * The sale is real only on the `platform_commerce.purchased` webhook — treat a "succeeded"
9
+ * here as "show processing", never as fulfilled.
10
+ */
11
+ declare class PlatformCommerceClient {
12
+ private readonly defaultPublishableKey;
13
+ constructor(defaultPublishableKey: () => string | undefined);
14
+ /**
15
+ * Mount the Payment Element and get a session you confirm from your OWN Pay button.
16
+ * This is the fully-controllable primitive (`confirmCardPayment` builds on it).
17
+ *
18
+ * ```ts
19
+ * const session = await invo.platformCommerce.mountCardPayment(clientSecret, {
20
+ * mount: "#pay", publishableKey: "pk_live_…",
21
+ * });
22
+ * // on your Pay button click:
23
+ * const r = await session.confirm({ returnUrl: location.href });
24
+ * if (r.status === "succeeded") showProcessing();
25
+ * session.destroy();
26
+ * ```
27
+ */
28
+ mountCardPayment(clientSecret: string, opts: MountCardPaymentOptions): Promise<CardPaymentSession>;
29
+ /**
30
+ * One-call mount + confirm. Mounts the Payment Element into `opts.mount` and resolves
31
+ * when the payment is confirmed via a submit trigger — either `opts.submit` (your Pay
32
+ * button, selector or element) or a minimal button the SDK renders inside `mount`. For
33
+ * full control over the button, prefer {@link mountCardPayment}.
34
+ */
35
+ confirmCardPayment(clientSecret: string, opts: ConfirmCardPaymentOptions): Promise<CardPaymentResult>;
36
+ }
4
37
  declare class InvoClient {
5
38
  private readonly http;
6
39
  private auth;
7
40
  private readonly refreshToken;
8
41
  /** In-flight refresh, shared so concurrent expiries trigger a single re-mint. */
9
42
  private refreshInFlight;
43
+ private readonly commercePublishableKey;
44
+ /**
45
+ * Platform Commerce (ecommerce) card confirmation. Use after
46
+ * `InvoServer.platformCommerce.purchase({ fundingSource: "card" })` returns a
47
+ * `clientSecret`. The passkey/token flows never touch this. See
48
+ * {@link PlatformCommerceClient}.
49
+ */
50
+ readonly platformCommerce: PlatformCommerceClient;
10
51
  constructor(config: ClientConfig);
11
52
  private assertWebAuthn;
12
53
  /**
@@ -129,4 +170,4 @@ declare class InvoClient {
129
170
  private confirmReceipt;
130
171
  }
131
172
 
132
- export { ApproveResult, BalanceResult, CallOptions, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, PendingCollectResult, RecoveryBeginResult, RecoveryCompleteResult };
173
+ export { ApproveResult, BalanceResult, CallOptions, CardPaymentResult, CardPaymentSession, ClientConfig, ConfirmCardPaymentOptions, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, MountCardPaymentOptions, PendingCollectResult, PlatformCommerceClient, RecoveryBeginResult, RecoveryCompleteResult };