@invonetwork/web-sdk 3.10.1 → 3.12.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 +48 -0
- package/README.md +95 -10
- package/dist/{chunk-L4A6OV54.js → chunk-5BMM5ZTW.js} +38 -4
- package/dist/index.cjs +243 -2
- package/dist/index.d.cts +146 -3
- package/dist/index.d.ts +146 -3
- package/dist/index.js +204 -3
- package/dist/server.cjs +61 -14
- package/dist/server.d.cts +7 -4
- package/dist/server.d.ts +7 -4
- package/dist/server.js +27 -14
- package/dist/{types-CBxpXgAM.d.cts → types-CT0Ksonp.d.cts} +211 -5
- package/dist/{types-CBxpXgAM.d.ts → types-CT0Ksonp.d.ts} +211 -5
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,53 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 3.12.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- The card maximum is INVO's, not the SDK's.
|
|
8
|
+
|
|
9
|
+
**INVO raised the maximum single card charge from $999.99 to $100,000.00 on 2026-09-18, and this package was refusing it.** The old limit was enforced client-side and threw before any network call, so a partner charging $50,000 failed inside the SDK and INVO never saw the request. The backend raise was invisible to every SDK user until this release. Per-customer velocity limits rose with it, to 100,000 per hour, 200,000 per day and 1,000,000 per month, all enforced by INVO.
|
|
10
|
+
|
|
11
|
+
**The design decision: the floor is a fact, the ceiling is a policy, and only facts belong in a client.**
|
|
12
|
+
|
|
13
|
+
$0.50 is the card rail's own minimum charge. Below it nothing settles in any environment, INVO holds it as a plain constant rather than a setting, and no configuration makes a smaller amount chargeable. That check stays exactly where it was and still throws before any request (`BELOW_STRIPE_MINIMUM`, `err.isBelowCardMinimum`).
|
|
14
|
+
|
|
15
|
+
The maximum is the opposite. It is a runtime setting an INVO admin edits without a deploy, and it differs between sandbox and production. Any number pinned in a published package is stale the moment somebody changes it, and the only remedy is a release, which is precisely the failure this release is repairing. So the local ceiling is **removed** rather than re-pinned at $100,000.00. It was not replaced by a fetch of the live limits either: that would turn one purchase call into two network calls, add a failure mode and a cache to a money path, and still be a snapshot rather than the truth at the moment of charge, because only the request itself is evaluated against the setting in force.
|
|
16
|
+
|
|
17
|
+
What remains is a structural bound. `usdAmount` and a card `totalPrice` must still be a positive amount with at most two decimals, and must still be at most `999999.99`, the same house ceiling every other money field in this SDK uses. That figure is deliberately **above** the largest value INVO's setting is permitted to take, so it can never refuse an amount INVO would have accepted. The invariant for anyone editing this later: the local bound must never be tighter than the server's maximum possible limit. This SDK may cost you a wasted round trip. It must never cost you a sale that a package upgrade would have allowed.
|
|
18
|
+
|
|
19
|
+
**What changed for you**
|
|
20
|
+
|
|
21
|
+
- Amounts between `999.99` and `999999.99` are now sent instead of being rejected locally. Nothing that worked before stops working; the validation only loosened.
|
|
22
|
+
- `err.isAboveCardMaximum` is unchanged and still means what it always meant, but it now arrives only from INVO (a `400`), never from the SDK. Nothing was charged.
|
|
23
|
+
- An amount above `999999.99` now throws `INVALID_INPUT` where it previously threw `ABOVE_CARD_MAXIMUM`. That range is malformed input, not a policy refusal, and INVO classifies it the same way.
|
|
24
|
+
|
|
25
|
+
**When INVO refuses an amount the SDK allowed**, catch `err.isAboveCardMaximum`. `err.message` carries the figure that was in force for that request, for example "Card purchases must be $100,000.00 or less." Do not retry it unchanged: lower the amount, split the sale, or ask INVO to raise the setting. The live figure for a tenant is also the `max_amount` of the hosted checkout's `validate-game` read, next to `min_amount`; read that if you want to show a limit in your own UI, and re-read it, because it can change under you. A velocity limit is a `429` with `err.retryAfter`, not this error.
|
|
26
|
+
|
|
27
|
+
**README: the minimum is $0.50.** The docs said only `0 < x <= 999.99` and left the floor unstated. They now state $0.50, which is what INVO advertises and what the card rail actually enforces. A $1.00 minimum was advertised by INVO's own checkout read until 2026-09-18 and was enforced nowhere; it is gone rather than enforced, because enforcing it would newly refuse charges between $0.50 and $0.99 that settle today.
|
|
28
|
+
|
|
29
|
+
No export was added, removed, renamed or retyped.
|
|
30
|
+
|
|
31
|
+
## 3.11.0
|
|
32
|
+
|
|
33
|
+
### Minor Changes
|
|
34
|
+
|
|
35
|
+
- The purchase status read, and the subscription fee is 7%.
|
|
36
|
+
|
|
37
|
+
**A buyer can always be told what happened to the money they paid.** `invo.checkout` (and the standalone `CheckoutClient`, for a page with no player token) reads `GET /api/checkout/sessions/<id>`, authenticated by the SESSION token; the id in the path is a label, not a credential. `getPurchaseStatus({ sessionId, sessionToken })` reads once; `waitForPurchase({ ..., intervalMs, timeoutMs, maxAttempts, signal, onUpdate })` polls until INVO says it is finished and returns that result. Six statuses, four of them terminal, plus `orderId`, `coinsCredited` / `transactionId` / `newBalance` on a credit, `reasonCode` + a player-safe `message` on a refusal, and both money figures (`amountChargedUsd`, `listedUsd`) so a buyer billed 206.29 for a 200 pack can be shown where the 6.29 went.
|
|
38
|
+
|
|
39
|
+
`terminal` is read off the response and is NEVER recomputed from `status`, so a status a later backend introduces cannot make this build decide a purchase finished, or finished well. A status it does not recognise is not terminal and is never a success. `paid_pending_credit` is deliberately not terminal at any age: INVO's reconciler recovers a stalled credit. A failed poll is not a failed purchase: network, timeout, 429 and 5xx are polled through; 401, 403 and 410 are raised at once (`isWrongSessionPurpose`, `isCheckoutSessionMismatch`, `isCheckoutSessionExpired`). On the cap `waitForPurchase` returns the last result it read rather than throwing, so the page keeps showing something true.
|
|
40
|
+
|
|
41
|
+
`CheckoutPurchaseStatus` is a widened union (`… | (string & {})`), not a literal one, and a tsc test pins that partner code storing or comparing an unknown status still compiles, which is the fix 3.10.0 had to make to `RefundResult` after the fact. It is named `Checkout…` because `PurchaseStatus` is already the direct `purchaseCurrency` result and is unchanged. New: `CheckoutClient`, `InvoClient.checkout`, `isPurchaseCredited` / `isPurchaseRefused` / `isPurchaseRefunded` / `isPurchaseExpired`, `nothingWasCharged` (true only where INVO said no money was taken; everything else, an unknown code included, happened after the card was charged, so never put a Try again on it), and the types `PurchaseStatusResult`, `PurchaseStatusInput`, `WaitForPurchaseInput`, `PurchaseRefusalReason`, `PurchaseCredited` / `PurchaseRefused` / `PurchaseRefunded` / `PurchaseExpired`, `CheckoutClientConfig`.
|
|
42
|
+
|
|
43
|
+
`createCheckout()` now also returns `sessionToken`, read from INVO's `session_token` field (backend commit `856fa266`) and falling back to the `checkout_url` query string only for a server that predates it, so nothing has to parse a URL to use the read. The two cannot disagree, and if a response ever carried both and they differed the field wins, because a query-key spelling is not a contract.
|
|
44
|
+
|
|
45
|
+
**Doc fix: INVO's subscription fee is 7% plus $0.30, not 10%** ($9.99 pays INVO $1.00 and you $8.99). Subscriptions became their own rate on 2026-09-17; item purchases stay at 10/90. No code change.
|
|
46
|
+
|
|
47
|
+
**Not included: withdrawals.** INVO's withdrawal request and history reads gained additive `kyc_hold`, `kyc_hold_reason` and `next_steps` fields on 2026-09-17. This package exposes no withdrawal surface at all, so there is nowhere for them to go, and adding one is a separate decision rather than part of a documentation pass.
|
|
48
|
+
|
|
49
|
+
**Fixed: the User-Agent version had drifted.** `SDK_VERSION` was left at `3.10.0` when 3.10.1 published, so every server call from 3.10.1 reported a version that was not the one running, and the test pinning it to `package.json` was failing on `main`. Back in step, and the pin is green.
|
|
50
|
+
|
|
3
51
|
## 3.10.1
|
|
4
52
|
|
|
5
53
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
First-party TypeScript SDK for integrating **INVO** into partner **web** platforms (storefronts, web games, dashboards). It wraps INVO's web money flows behind a typed, versioned API — the web analog of the Unity/Unreal plugins.
|
|
4
4
|
|
|
5
|
-
> **Status:** `v3.
|
|
5
|
+
> **Status:** `v3.11.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.11.0** adds the **[purchase status read](#did-the-purchase-go-through-the-status-read)**, where `invo.checkout.getPurchaseStatus()` / `waitForPurchase()` (and the standalone `CheckoutClient`) answer what happened to a hosted-checkout purchase in six words, four of them terminal, so a buyer is never shown a page that closes on nothing; stopping is decided by INVO's `terminal` and never re-derived from `status`, `nothingWasCharged()` says when a **Try again** is safe, `createCheckout()` now also returns `sessionToken`, and the subscription fee is corrected to **7% + $0.30** (it is its own rate; item purchases stay at 10/90); **3.10.0** documents **card-only subscriptions** (the card pays the full price every period, the coin wallet never pays; `walletOnly` deprecated; new `failure_code` `wallet_negative`; a renewal's `purchase.completed` is not a purchase) and the **[subscription refund limits](#refunds)**: `subscriptions.refund` can now return a 202 `pending_approval` refund request (`isRefundPendingApproval`), with `warnings`, the processor fee you bear, `subscriptionCanceled` (a full refund cancels), new classifiers (`isRefundsNotEnabled`, `isRefundWindowClosed`, `isRefundRequestPending`, `isRefundRequestRejected`, `isConcurrentRequest`, `isRefundMismatch`) and typed `subscription.refund_requested` / `refund_approved` / `refund_rejected` events, all additive; **3.9.0** adds the **[INVO-hosted card page for subscriptions](#cards-for-subscriptions)**, `invo.cards.createSetupSession`: mint a 10-minute link server-side, send the member to it, read the card back from `cards.list`, with no browser code and no card processor named anywhere (`beginSetup`/`confirmSetup` remain as the processor-bound alternative), plus the `isPlayerNotFound`, `isInvalidPlayerEmail` and `isInvalidInput` classifiers and a fix that makes `includePlayer` reads actually surface `playerEmail`/`playerName`; **3.8.0** adds **[Subscriptions](#subscriptions-recurring-billing)** as a first-class server surface on both rails — `invo.subscriptions.create/get/listForPlayer/cancel/changeAmount/setPaymentMethod/refund/steamInit/steamFinalize`, the off-session card capture (`invo.cards.beginSetup/confirmSetup/list`), the sandbox clock tools (`invo.sandbox.subscriptions.*`, which post to `/subscriptions/<id>/...` **relative to the sandbox base, not under `/api`**, with the new `sandboxClockKey`), typed `data` for all seven `subscription.*` webhook events, and eleven new error classifiers; **3.7.0** makes the **device approval grant a first-class SDK surface** — `beginDeviceApproval`, `pollDeviceApproval`, `confirmDeviceEnrollment` and, the step that actually moves the money, **`approveWithDeviceCode`** (plus the optional `completeDeviceApproval` loop); a grant that is polled to `approved` and left there settles **nothing**, which is the failure this release exists to make impossible, and `TRANSACTION_NOT_PENDING` now comes back as a typed `status: "not_pending"` result with `alreadySettled` rather than a thrown error you would have to string-match; **3.4.0** documents that a Steam title now bills through **its own Steam application** — the studio registers their appid + publisher Web API key and keeps a payment method on file, because Valve pays the studio and INVO settles afterwards (new `isSteamNotConfigured`, `isPartnerBillingNotSetUp`, `isPartnerSettlementUnavailable`, `isSteamAppChanged` error helpers); **3.2.3** corrects the base path and auth header in the Steam snippets (`/api/currency-purchases`, `X-Game-Secret-Key`) — 3.2.2 published both wrong, and copying them returned a 404; **3.2.x** documents **Steam currency purchases on a pack model** — INVO owns the catalogue, you pass a `pack_id` and never a price, and the currency inside a pack varies by country because Steam prices are VAT-inclusive; **3.1.0** makes the authentication guidance explicit — **[passkeys are the gold standard](#passkeys-are-the-gold-standard-dont-build-on-sms)** and the SMS-PIN completion (`verifySmsTransfer`/`verifySmsSend`) is **deprecated and being phased out** (documentation only — no behavior change, no runtime warnings); **3.0.0** moves the Platform Commerce card leg to **INVO's hosted checkout** — the server `purchase()` now returns a `checkoutUrl` and the browser just sends the buyer there (redirect or `mountCheckout` iframe); the 2.5.x card-element surface (`confirmCardPayment`/`mountCardPayment`, `billingAddress`, `commercePublishableKey`) is **removed** — see the [CHANGELOG](CHANGELOG.md) migration note; **2.5.0** added **Platform Commerce** (ecommerce) — a platform tenant selling items funded by balance **or** card, with `invo.platformCommerce.purchase/getStatus/refund` (server) and the `platform_commerce.*` webhooks; **2.4.0** adds Steam transfer-policy handling (`isSteamValueNonTransferable`/`isNonSteamValueIntoSteamBlocked` + `DestinationGame.acceptsSteamOriginValue`); **2.3.0** surfaces the claim-time phone-share `409` on `confirmReceipt*`/`claim*` (+ `err.phoneShareLast4`). Full history in the [CHANGELOG](CHANGELOG.md).
|
|
6
6
|
> Canonical partner reference: **https://docs.invo.network/docs/currency-purchase** and **https://docs.invo.network/docs/game-developer-integration**.
|
|
7
7
|
|
|
8
8
|
## What it does
|
|
@@ -96,6 +96,8 @@ The right approval method is a property of the **client the player is sitting in
|
|
|
96
96
|
- [Before you go live](#before-you-go-live)
|
|
97
97
|
- [Configuration](#configuration)
|
|
98
98
|
- [Currency purchase (real money in)](#currency-purchase-real-money-in)
|
|
99
|
+
- [The card maximum is INVO's, not the SDK's](#the-card-maximum-is-invos-not-the-sdks)
|
|
100
|
+
- [Did the purchase go through? (the status read)](#did-the-purchase-go-through-the-status-read)
|
|
99
101
|
- [Item purchase (spend game currency)](#item-purchase-spend-game-currency)
|
|
100
102
|
- [Platform Commerce (ecommerce)](#platform-commerce-ecommerce)
|
|
101
103
|
- [Subscriptions (recurring billing)](#subscriptions-recurring-billing)
|
|
@@ -283,19 +285,48 @@ const client = new InvoClient({
|
|
|
283
285
|
|
|
284
286
|
Buy game currency with real money. Authenticated by the **payment rail**, not a passkey — there's no WebAuthn step. Two paths:
|
|
285
287
|
|
|
288
|
+
### The card maximum is INVO's, not the SDK's
|
|
289
|
+
|
|
290
|
+
**Minimum: $0.50.** That is the card rail's own floor: below it a charge cannot settle at all, so this SDK checks it locally and always will.
|
|
291
|
+
|
|
292
|
+
**Maximum: an INVO setting, $100,000.00 by default.** It is changed by an INVO admin without a deploy, and it differs between sandbox and production, so **this package does not pin it and never refuses an amount for being too large.** Your amount is sent; INVO decides.
|
|
293
|
+
|
|
294
|
+
Before 3.12.0 the SDK enforced a hard-coded $999.99 and threw before any request was made, so a partner charging $50,000 failed inside the SDK and INVO never heard about it. A pinned limit is wrong by construction here: the moment anyone edits the setting, every installed copy of the SDK is stale, and the only fix is a release. Removing the local ceiling means the SDK can waste a round trip on an amount INVO refuses; keeping it meant the SDK could block a sale INVO would have taken. Only one of those is recoverable without a package upgrade.
|
|
295
|
+
|
|
296
|
+
**When INVO refuses an amount this SDK allowed**, you get a `400` and `err.isAboveCardMaximum === true`. Nothing was charged.
|
|
297
|
+
|
|
298
|
+
```ts
|
|
299
|
+
try {
|
|
300
|
+
await server.createCheckout({ playerEmail, usdAmount: "50000.00" });
|
|
301
|
+
} catch (err) {
|
|
302
|
+
if (err.isAboveCardMaximum) {
|
|
303
|
+
// err.message carries the figure in force for THIS environment, e.g.
|
|
304
|
+
// "Card purchases must be $100,000.00 or less." Do not retry it unchanged:
|
|
305
|
+
// lower the amount, split the sale, or ask INVO to raise the setting.
|
|
306
|
+
console.warn(err.message);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
The live figure for a tenant is also the `max_amount` of the hosted checkout's `validate-game` read, alongside `min_amount`. Read it if you want to show a limit in your own UI rather than hard-coding one, and re-read it, because it can change under you.
|
|
312
|
+
|
|
313
|
+
Per-customer velocity limits sit underneath the per-charge maximum (hourly, daily and monthly, per player per game) and are INVO's too. Exceeding one is a `429`; see `err.retryAfter`.
|
|
314
|
+
|
|
286
315
|
### Hosted checkout (recommended — PCI-light, you never touch card data)
|
|
287
316
|
|
|
288
317
|
```ts
|
|
289
318
|
// SERVER
|
|
290
|
-
const { checkoutUrl, sessionId, expiresAt, expiresInSeconds } = await server.createCheckout({
|
|
319
|
+
const { checkoutUrl, sessionId, sessionToken, expiresAt, expiresInSeconds } = await server.createCheckout({
|
|
291
320
|
playerEmail: "p@example.com",
|
|
292
|
-
usdAmount: "20.00", // USD
|
|
321
|
+
usdAmount: "20.00", // USD. Minimum $0.50. The maximum is an INVO setting
|
|
322
|
+
// ($100,000.00 by default) and is enforced on the request.
|
|
293
323
|
rail: "platform", // optional: "platform" (default) | "game" | "steam"
|
|
294
324
|
successUrl: "https://you/buy/ok",
|
|
295
325
|
cancelUrl: "https://you/buy/cancel",
|
|
296
326
|
metadata: { yourOrderId: "ord_42" }, // echoed on the purchase.completed webhook (all rails); order_id also reconciles
|
|
297
327
|
});
|
|
298
328
|
// → send the browser to checkoutUrl. Token TTL is expiresInSeconds (~900s / 15 min).
|
|
329
|
+
// sessionToken is the credential for the status read below (INVO's own session_token field).
|
|
299
330
|
// Reloading the URL after a completed payment is idempotent — it shows an already-complete
|
|
300
331
|
// success screen (no error), so you don't have to guard against a refresh.
|
|
301
332
|
```
|
|
@@ -321,7 +352,59 @@ window.addEventListener("message", (e) => {
|
|
|
321
352
|
});
|
|
322
353
|
```
|
|
323
354
|
|
|
324
|
-
The hosted page handles card entry, saved cards, and 3-D Secure (with a top-level break-out when framed). **Grant currency off the `purchase.completed` webhook**, not the postMessage hint.
|
|
355
|
+
The hosted page handles card entry, saved cards, and 3-D Secure (with a top-level break-out when framed). **Grant currency off the `purchase.completed` webhook**, not the postMessage hint. No browser SDK method *charges* (the browser only opens the URL), but it can now **read what happened**, below.
|
|
356
|
+
|
|
357
|
+
### Did the purchase go through? (the status read)
|
|
358
|
+
|
|
359
|
+
`invo.checkout` answers, in six words, what a checkout purchase is doing. Poll it until INVO says it is finished and the buyer always has something true on screen, **including the case where INVO has their money and they do not have their coins**. That case used to close the page on nothing: no coins, no error, no receipt.
|
|
360
|
+
|
|
361
|
+
```ts
|
|
362
|
+
// BROWSER (or Node: it needs no DOM)
|
|
363
|
+
import { CheckoutClient, isPurchaseCredited, nothingWasCharged } from "@invonetwork/web-sdk";
|
|
364
|
+
|
|
365
|
+
// `sessionId` and `sessionToken` come from the server's createCheckout(); the hosted page
|
|
366
|
+
// reads the token out of its own ?session= parameter. The token is the credential; the id
|
|
367
|
+
// in the path is only a label.
|
|
368
|
+
const checkout = new CheckoutClient({ baseUrl: "https://invo.network" });
|
|
369
|
+
|
|
370
|
+
const r = await checkout.waitForPurchase({
|
|
371
|
+
sessionId, sessionToken,
|
|
372
|
+
intervalMs: 1500, // every 1 to 2 seconds; the limit is 600 reads/min per IP
|
|
373
|
+
timeoutMs: 300_000, // the cap; on it you get the last result, never a throw
|
|
374
|
+
signal: controller.signal, // optional
|
|
375
|
+
onUpdate: (u) => render(u), // every read, terminal or not; keep the modal open
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
if (isPurchaseCredited(r)) {
|
|
379
|
+
show(`${r.coinsCredited} ${r.currencyName} added`, r.newBalance);
|
|
380
|
+
} else if (r.message) {
|
|
381
|
+
showVerbatim(r.message, r.orderId); // never paraphrase it
|
|
382
|
+
if (nothingWasCharged(r)) offerTryAgain(); // ONLY when INVO says nothing was taken
|
|
383
|
+
else offerContactSupport();
|
|
384
|
+
}
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
`invo.checkout` is the same object on an `InvoClient` you already built, if the page has a player token. Read once instead with `checkout.getPurchaseStatus({ sessionId, sessionToken })`.
|
|
388
|
+
|
|
389
|
+
| `status` | `terminal` | What it means | What to show |
|
|
390
|
+
|---|---|---|---|
|
|
391
|
+
| `pending` | no | No payment seen for this checkout yet | keep the spinner |
|
|
392
|
+
| `paid_pending_credit` | no | A charge is open, the coins are not in the balance yet, normally seconds | keep the modal open ("Finishing your payment and adding your coins"); after ~60s add the order id and a **Contact support** link, and **keep polling** |
|
|
393
|
+
| `credited` | yes | Charged and credited | `coinsCredited`, `currencyName`, `newBalance` when not null; close on the buyer's action |
|
|
394
|
+
| `refused` | yes | This purchase will not credit; `reasonCode` says why | `message` verbatim + `orderId` + **Contact support** |
|
|
395
|
+
| `refunded` | yes | The money went back | `message` verbatim + `orderId` |
|
|
396
|
+
| `expired` | yes | Never paid, can no longer be paid | `message` verbatim; offer a new checkout |
|
|
397
|
+
|
|
398
|
+
Rules worth taking literally:
|
|
399
|
+
|
|
400
|
+
- **Stop on `result.terminal`, never on `status`.** `terminal` is INVO's answer and the SDK never recomputes it, so a status a later release adds cannot make this build decide a purchase finished, or finished *well*. An unknown status is never read as a success.
|
|
401
|
+
- **`paid_pending_credit` is not a failure, however long it takes.** INVO's reconciler recovers a stalled credit. Telling a buyer they lost money they are about to receive is worse than the silence.
|
|
402
|
+
- **A failed poll is not a failed purchase.** `waitForPurchase` polls through a dropped connection, a timeout, a 429 and a 5xx; it raises a `401`, `403` or `410` at once (`err.isWrongSessionPurpose`, `err.isCheckoutSessionMismatch`, `err.isCheckoutSessionExpired`).
|
|
403
|
+
- **Render `message` verbatim and never show `reasonCode` on its own.** The six post-charge refusal codes all read the same to a buyer (they paid and the coins are not there), and the code exists for support to quote. Offer a **Try again** only where `nothingWasCharged(r)` is true (`PAYMENT_DECLINED`, `PAYMENT_CANCELLED`, `expired`); every other refusal happened *after* the card was charged.
|
|
404
|
+
- **`expired` is not declared the second the link lapses.** A payment made in the last minutes of a checkout can leave no order row until a recovery sweep finds it, so an unpaid checkout reads `pending` for about 30 minutes past expiry. Poll through it.
|
|
405
|
+
- **`amountChargedUsd` minus `listedUsd`** is the processing fee the buyer pays on the card rail. A buyer billed 206.29 for a 200 pack will ask; both numbers are here.
|
|
406
|
+
- **Storefront (in-client) purchases do not reach this read.** Those orders are keyed on your own purchase reference rather than on a checkout session, so a lookup by session id finds nothing and answers `pending`. Do not conclude the purchase never happened.
|
|
407
|
+
- `newBalance` is `null` once the session is past its expiry: the token rides in the checkout URL, so a stale link must not serve a live wallet. `coinsCredited` and `transactionId`, which are about *this* purchase, still come back.
|
|
325
408
|
|
|
326
409
|
### Payment rails (neutral names)
|
|
327
410
|
|
|
@@ -549,7 +632,7 @@ const r = await server.platformCommerce.purchase({
|
|
|
549
632
|
|
|
550
633
|
### Card leg — server creates, INVO hosts the checkout
|
|
551
634
|
|
|
552
|
-
**INVO hosts the entire card checkout** — card fields, Apple Pay / Google Pay, the international billing-address collector, and 3-D Secure all live on INVO's page. There is **no billing address in the request, no card element, no processor dependency, and no client payment code to write**: the server call returns a `checkoutUrl` and you send the buyer there. `totalPrice` is **USD
|
|
635
|
+
**INVO hosts the entire card checkout** — card fields, Apple Pay / Google Pay, the international billing-address collector, and 3-D Secure all live on INVO's page. There is **no billing address in the request, no card element, no processor dependency, and no client payment code to write**: the server call returns a `checkoutUrl` and you send the buyer there. `totalPrice` is **USD**, at least **$0.50**. The maximum is an INVO setting, **$100,000.00 by default**, so it is enforced on the request and not pinned in this package.
|
|
553
636
|
|
|
554
637
|
```ts
|
|
555
638
|
// 1) server — returns a hosted-checkout session, NOT yet paid
|
|
@@ -599,8 +682,8 @@ const ref = await server.platformCommerce.refund({ orderId: r.orderId, reason: "
|
|
|
599
682
|
```
|
|
600
683
|
|
|
601
684
|
- **Idempotency on `clientRequestId`:** a duplicate BALANCE purchase throws `409` (`err.isDuplicateRequest`); a duplicate CARD purchase **replays the same checkout session** (`r.idempotentReplay === true`, same URL — never a second charge), so a lost card-leg response is safely recovered by retrying with the *same* `clientRequestId`.
|
|
602
|
-
- INVO fee: **3.5% flat** (balance) · **3.5% + $0.30** (card). Too-small amounts throw `err.isAmountBelowMinimum` / `err.isBelowCardMinimum` (card < $0.50); a card total over
|
|
603
|
-
- Client-side validation (missing fields, bad funding source, quantity outside `1..1000`, total ≠ unit×qty, card
|
|
685
|
+
- INVO fee: **3.5% flat** (balance) · **3.5% + $0.30** (card). Too-small amounts throw `err.isAmountBelowMinimum` / `err.isBelowCardMinimum` (card < $0.50); a card total over INVO's maximum single card charge comes back as `err.isAboveCardMaximum` (400) with the live figure in `err.message`.
|
|
686
|
+
- Client-side validation (missing fields, bad funding source, quantity outside `1..1000`, total ≠ unit×qty, card total under $0.50, non-E.164 `playerPhone`) throws **before** any network call. The card **maximum** is deliberately not among them: see [The card maximum is INVO's, not the SDK's](#the-card-maximum-is-invos-not-the-sdks).
|
|
604
687
|
- Fulfill on the **`platform_commerce.purchased`** webhook; handle **`platform_commerce.refunded`** for reversals.
|
|
605
688
|
|
|
606
689
|
---
|
|
@@ -616,7 +699,7 @@ A subscription is a standing agreement, created by **your server**, under which
|
|
|
616
699
|
|
|
617
700
|
Each period INVO works out what the period is worth in coins (card: price × the currency's coins-per-USD rate, 10 per USD by default; Steam: what the price buys through Steam for the member's country) and splits it between INVO's platform fee and your revenue. Every figure is reported on the `subscription.renewed` event.
|
|
618
701
|
|
|
619
|
-
- **Card rail: card only (since 2026-09-17).** The card is charged the full price every period, whatever the member's coin wallet holds. The coins that charge buys are minted and spent in the same step, so **the wallet never pays for a card subscription and never moves**. There is no shortfall, no rounding and no minimum top-up. INVO's fee is
|
|
702
|
+
- **Card rail: card only (since 2026-09-17).** The card is charged the full price every period, whatever the member's coin wallet holds. The coins that charge buys are minted and spent in the same step, so **the wallet never pays for a card subscription and never moves**. There is no shortfall, no rounding and no minimum top-up. INVO's fee is 7% by default plus $0.30, on the full price ($9.99 pays INVO $1.00 and you $8.99). Subscriptions are their own rate: item purchases stay at 10/90.
|
|
620
703
|
- **Steam rail: unchanged.** INVO spends the member's wallet first and tops up from Steam for the shortfall only.
|
|
621
704
|
- **Save a card before `subscriptions.create`.** A member with coins but no saved card is still subscribed (the create succeeds), but the first charge fails with `failureCode: "no_payment_method"` and the subscription enters dunning. Coins never pay it.
|
|
622
705
|
- **`walletOnly` is deprecated.** It is still accepted and returned, but a `walletOnly: true` card subscription never charges a card and so can never be paid: every charge fails with `failure_code: "wallet_only"` and it lapses to `expired`. Do not send it on new integrations.
|
|
@@ -1950,7 +2033,7 @@ Helpers:
|
|
|
1950
2033
|
| `.isInsufficientBalance` | item purchase failed (400); `required_amount` + `current_balance` on `.body` |
|
|
1951
2034
|
| `.isDuplicateRequest` | idempotency-keyed request was a duplicate (409) |
|
|
1952
2035
|
| `.isNotPlatformTenant` | Platform Commerce called by a non-platform tenant (403) — use `purchaseItem`/`createCheckout` instead |
|
|
1953
|
-
| `.isAmountBelowMinimum` / `.isBelowCardMinimum` / `.isAboveCardMaximum` |
|
|
2036
|
+
| `.isAmountBelowMinimum` / `.isBelowCardMinimum` / `.isAboveCardMaximum` | amount too small for the fee to round up / card charge under $0.50 / card charge over INVO's maximum single card charge, which is a runtime setting (400) |
|
|
1954
2037
|
| `.isAlreadyRefunded` | Platform Commerce refund of an already-refunded order (409) — treat as already done |
|
|
1955
2038
|
| `.retryAfter` | seconds to back off on a 429 throttle |
|
|
1956
2039
|
| `.isEnrollmentAuthorizationRequired` | first-enrollment needs the OTP grant → `enrollmentBegin`/`enrollmentVerify` |
|
|
@@ -1988,7 +2071,7 @@ try {
|
|
|
1988
2071
|
| `mintPlayerToken({ playerEmail, playerPhone? })` | `{ token, expiresAt, identityId }` — session mint for an **existing** player (404 if unknown); `playerPhone` optional/validated-if-present (see [Player token](#player-token-session-mint-for-an-existing-player)) |
|
|
1989
2072
|
| `initiateSend(input)` | `{ transactionId, verificationMethod, guardianApproval?, raw }` |
|
|
1990
2073
|
| `initiateTransfer(input)` | `{ transactionId, verificationMethod, guardianApproval?, raw }` |
|
|
1991
|
-
| `createCheckout(input)` | `{ sessionId, checkoutUrl, expiresAt, expiresInSeconds, raw }` |
|
|
2074
|
+
| `createCheckout(input)` | `{ sessionId, checkoutUrl, sessionToken?, expiresAt, expiresInSeconds, raw }`, where `sessionToken` is INVO's own `session_token` field (falling back to the `checkoutUrl` query string on a backend that predates it) and is the credential for the [status read](#did-the-purchase-go-through-the-status-read) |
|
|
1992
2075
|
| `purchaseCurrency(input)` | `{ status, clientSecret?, paymentIntentId?, paymentUrl?, transactionId?, orderId?, newBalance?, raw }` |
|
|
1993
2076
|
| `confirmPayment({ paymentIntentId, orderId? })` | `{ status, transactionId?, newBalance?, raw }` |
|
|
1994
2077
|
| `getOrderDetails({ orderId? \| transactionId? })` | `{ order, financialSummary, statusTimeline, raw }` |
|
|
@@ -2047,6 +2130,8 @@ Every method also accepts an optional final `{ signal }` (`AbortSignal`) for can
|
|
|
2047
2130
|
| `getDestinations({ direction? })` | `{ availableGames, sourceGameName, transferMode, … }` — where the player can send/transfer, metadata inline |
|
|
2048
2131
|
| `getBalance()` | `{ gameId, gameName, balances, totalValue, currencyCount, hasFunds, raw }` — the player's balances for this game |
|
|
2049
2132
|
| `approveHosted({ transactionId, flow, platformOrigin?, onEnrollment?, renderPrompt?, popupBlocked?, popup?, signal? })` | `{ status: "approved" \| "denied" \| "expired" \| "closed" \| "blocked" \| "redirected", popupBlocked, message?, approval? }` — runs the whole RFC 8628 device-approval grant from the browser on INVO's hosted page (begin `channel:"popup"` → popup → poll → match-code prompt → confirm-enrollment → approve with the `device_code`, which the SDK holds and never exposes); `approval` is the `ApproveResult` / `ConfirmReceiptResult` of the flow's approve endpoint |
|
|
2133
|
+
| `checkout.getPurchaseStatus({ sessionId, sessionToken })` | `{ status, terminal, orderId, sessionId, coinsCredited, transactionId, newBalance, reasonCode, message, amountChargedUsd, listedUsd, currencyName, raw }`: what happened to a hosted-checkout purchase. Authenticated by the SESSION token, not the player token |
|
|
2134
|
+
| `checkout.waitForPurchase({ sessionId, sessionToken, intervalMs?, timeoutMs?, maxAttempts?, signal?, onUpdate? })` | the same result, polled until INVO's `terminal` is true (never re-derived from `status`); on the cap it returns the last result rather than throwing. Also available standalone: `new CheckoutClient({ baseUrl })` |
|
|
2050
2135
|
| `platformCommerce.mountCheckout(el, checkoutUrl, { onComplete? })` | `{ iframe, destroy() }` — optional embed of INVO's hosted checkout (or just `location.href = checkoutUrl`); `onComplete` fires on the page's origin-checked `INVO_CHECKOUT_COMPLETE` message |
|
|
2051
2136
|
|
|
2052
2137
|
Every method throws `InvoError` on failure and takes an optional final `{ signal }`. Full inline types ship with the package. The Platform Commerce card leg needs **no keys and no payment code in the browser** — INVO's hosted page owns the card form.
|
|
@@ -369,8 +369,15 @@ var InvoError = class _InvoError extends Error {
|
|
|
369
369
|
get isBelowCardMinimum() {
|
|
370
370
|
return this.code === "BELOW_CARD_MINIMUM" || this.rawCode === "BELOW_STRIPE_MINIMUM";
|
|
371
371
|
}
|
|
372
|
-
/** True if a
|
|
373
|
-
*
|
|
372
|
+
/** True if a CARD purchase exceeded INVO's maximum single card charge
|
|
373
|
+
* (`ABOVE_CARD_MAXIMUM`, 400) — split the sale or lower the amount. Do not retry it
|
|
374
|
+
* unchanged; nothing was charged.
|
|
375
|
+
*
|
|
376
|
+
* The cap is a runtime setting ($100,000.00 by default since 2026-09-18), editable by
|
|
377
|
+
* an INVO admin without a deploy and different per environment, so this SDK does not
|
|
378
|
+
* pin it and never raises this error locally. `err.message` carries the figure that was
|
|
379
|
+
* in force for the request that failed; the live figure for a tenant is also the
|
|
380
|
+
* `max_amount` of the hosted checkout's `validate-game` read. */
|
|
374
381
|
get isAboveCardMaximum() {
|
|
375
382
|
return this.code === "ABOVE_CARD_MAXIMUM";
|
|
376
383
|
}
|
|
@@ -667,6 +674,33 @@ var InvoError = class _InvoError extends Error {
|
|
|
667
674
|
get isInvalidInput() {
|
|
668
675
|
return this.code === "INVALID_INPUT";
|
|
669
676
|
}
|
|
677
|
+
// ---- Checkout session reads (the purchase status read) ----
|
|
678
|
+
/**
|
|
679
|
+
* True when a session token was refused because it belongs to a DIFFERENT checkout
|
|
680
|
+
* session than the id in the path (`SESSION_MISMATCH`, 403). The token is the
|
|
681
|
+
* credential and the id is only a label, so the two have to agree; pair a `sessionId`
|
|
682
|
+
* with the `sessionToken` minted for it.
|
|
683
|
+
*/
|
|
684
|
+
get isCheckoutSessionMismatch() {
|
|
685
|
+
return this.code === "SESSION_MISMATCH";
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* True when a token minted to SAVE A CARD was used where a purchase token belongs
|
|
689
|
+
* (`WRONG_SESSION_PURPOSE`, 401). A card setup session settles nothing and has no
|
|
690
|
+
* purchase to report on.
|
|
691
|
+
*/
|
|
692
|
+
get isWrongSessionPurpose() {
|
|
693
|
+
return this.code === "WRONG_SESSION_PURPOSE";
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* True when a checkout session token is too far past its expiry to answer with
|
|
697
|
+
* (`SESSION_EXPIRED`, 410). A lapsed token still reads its own purchase for a bounded
|
|
698
|
+
* window, because a charge outlives a 15 minute link; past that, show the buyer the
|
|
699
|
+
* order id you already hold and a Contact support link rather than a blank screen.
|
|
700
|
+
*/
|
|
701
|
+
get isCheckoutSessionExpired() {
|
|
702
|
+
return this.code === "SESSION_EXPIRED";
|
|
703
|
+
}
|
|
670
704
|
/** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
|
|
671
705
|
get retryAfter() {
|
|
672
706
|
const v = this.bodyObject()["retry_after"];
|
|
@@ -950,5 +984,5 @@ function toDestinationsResult(raw, direction) {
|
|
|
950
984
|
}
|
|
951
985
|
|
|
952
986
|
export { Http, InvoError, assertSecureBaseUrl, toDestinationsResult };
|
|
953
|
-
//# sourceMappingURL=chunk-
|
|
954
|
-
//# sourceMappingURL=chunk-
|
|
987
|
+
//# sourceMappingURL=chunk-5BMM5ZTW.js.map
|
|
988
|
+
//# sourceMappingURL=chunk-5BMM5ZTW.js.map
|
package/dist/index.cjs
CHANGED
|
@@ -371,8 +371,15 @@ var InvoError = class _InvoError extends Error {
|
|
|
371
371
|
get isBelowCardMinimum() {
|
|
372
372
|
return this.code === "BELOW_CARD_MINIMUM" || this.rawCode === "BELOW_STRIPE_MINIMUM";
|
|
373
373
|
}
|
|
374
|
-
/** True if a
|
|
375
|
-
*
|
|
374
|
+
/** True if a CARD purchase exceeded INVO's maximum single card charge
|
|
375
|
+
* (`ABOVE_CARD_MAXIMUM`, 400) — split the sale or lower the amount. Do not retry it
|
|
376
|
+
* unchanged; nothing was charged.
|
|
377
|
+
*
|
|
378
|
+
* The cap is a runtime setting ($100,000.00 by default since 2026-09-18), editable by
|
|
379
|
+
* an INVO admin without a deploy and different per environment, so this SDK does not
|
|
380
|
+
* pin it and never raises this error locally. `err.message` carries the figure that was
|
|
381
|
+
* in force for the request that failed; the live figure for a tenant is also the
|
|
382
|
+
* `max_amount` of the hosted checkout's `validate-game` read. */
|
|
376
383
|
get isAboveCardMaximum() {
|
|
377
384
|
return this.code === "ABOVE_CARD_MAXIMUM";
|
|
378
385
|
}
|
|
@@ -669,6 +676,33 @@ var InvoError = class _InvoError extends Error {
|
|
|
669
676
|
get isInvalidInput() {
|
|
670
677
|
return this.code === "INVALID_INPUT";
|
|
671
678
|
}
|
|
679
|
+
// ---- Checkout session reads (the purchase status read) ----
|
|
680
|
+
/**
|
|
681
|
+
* True when a session token was refused because it belongs to a DIFFERENT checkout
|
|
682
|
+
* session than the id in the path (`SESSION_MISMATCH`, 403). The token is the
|
|
683
|
+
* credential and the id is only a label, so the two have to agree; pair a `sessionId`
|
|
684
|
+
* with the `sessionToken` minted for it.
|
|
685
|
+
*/
|
|
686
|
+
get isCheckoutSessionMismatch() {
|
|
687
|
+
return this.code === "SESSION_MISMATCH";
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* True when a token minted to SAVE A CARD was used where a purchase token belongs
|
|
691
|
+
* (`WRONG_SESSION_PURPOSE`, 401). A card setup session settles nothing and has no
|
|
692
|
+
* purchase to report on.
|
|
693
|
+
*/
|
|
694
|
+
get isWrongSessionPurpose() {
|
|
695
|
+
return this.code === "WRONG_SESSION_PURPOSE";
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* True when a checkout session token is too far past its expiry to answer with
|
|
699
|
+
* (`SESSION_EXPIRED`, 410). A lapsed token still reads its own purchase for a bounded
|
|
700
|
+
* window, because a charge outlives a 15 minute link; past that, show the buyer the
|
|
701
|
+
* order id you already hold and a Contact support link rather than a blank screen.
|
|
702
|
+
*/
|
|
703
|
+
get isCheckoutSessionExpired() {
|
|
704
|
+
return this.code === "SESSION_EXPIRED";
|
|
705
|
+
}
|
|
672
706
|
/** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
|
|
673
707
|
get retryAfter() {
|
|
674
708
|
const v = this.bodyObject()["retry_after"];
|
|
@@ -1635,6 +1669,49 @@ async function runHostedApproval(opts, api, deps = {}) {
|
|
|
1635
1669
|
});
|
|
1636
1670
|
}
|
|
1637
1671
|
|
|
1672
|
+
// src/shared/purchase-status.ts
|
|
1673
|
+
function str(v) {
|
|
1674
|
+
return typeof v === "string" ? v : v === null || v === void 0 ? null : String(v);
|
|
1675
|
+
}
|
|
1676
|
+
function toPurchaseStatusResult(raw, sessionId) {
|
|
1677
|
+
return {
|
|
1678
|
+
status: String(raw["status"] ?? ""),
|
|
1679
|
+
// INVO SAYS, AND ONLY AN EXPLICIT `true` SAYS IT. A missing or malformed field reads
|
|
1680
|
+
// false, which keeps a poll running; the alternative, guessing terminality from
|
|
1681
|
+
// `status`, is how an old SDK declares a future status finished.
|
|
1682
|
+
terminal: raw["terminal"] === true,
|
|
1683
|
+
orderId: str(raw["order_id"]),
|
|
1684
|
+
sessionId: String(raw["session_id"] ?? sessionId),
|
|
1685
|
+
coinsCredited: str(raw["coins_credited"]),
|
|
1686
|
+
transactionId: str(raw["transaction_id"]),
|
|
1687
|
+
newBalance: str(raw["new_balance"]),
|
|
1688
|
+
reasonCode: str(raw["reason_code"]),
|
|
1689
|
+
message: str(raw["message"]),
|
|
1690
|
+
amountChargedUsd: str(raw["amount_charged_usd"]),
|
|
1691
|
+
listedUsd: str(raw["listed_usd"]),
|
|
1692
|
+
currencyName: str(raw["currency_name"]),
|
|
1693
|
+
raw
|
|
1694
|
+
};
|
|
1695
|
+
}
|
|
1696
|
+
function isPurchaseCredited(r) {
|
|
1697
|
+
return r.status === "credited";
|
|
1698
|
+
}
|
|
1699
|
+
function isPurchaseRefused(r) {
|
|
1700
|
+
return r.status === "refused";
|
|
1701
|
+
}
|
|
1702
|
+
function isPurchaseRefunded(r) {
|
|
1703
|
+
return r.status === "refunded";
|
|
1704
|
+
}
|
|
1705
|
+
function isPurchaseExpired(r) {
|
|
1706
|
+
return r.status === "expired";
|
|
1707
|
+
}
|
|
1708
|
+
var NOTHING_CHARGED_REASONS = /* @__PURE__ */ new Set(["PAYMENT_DECLINED", "PAYMENT_CANCELLED"]);
|
|
1709
|
+
function nothingWasCharged(r) {
|
|
1710
|
+
if (r.status === "expired") return true;
|
|
1711
|
+
if (r.status !== "refused") return false;
|
|
1712
|
+
return r.reasonCode !== null && NOTHING_CHARGED_REASONS.has(r.reasonCode);
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1638
1715
|
// src/index.ts
|
|
1639
1716
|
function toPendingCollectItem(row) {
|
|
1640
1717
|
return {
|
|
@@ -1766,6 +1843,163 @@ var PlatformCommerceClient = class {
|
|
|
1766
1843
|
};
|
|
1767
1844
|
}
|
|
1768
1845
|
};
|
|
1846
|
+
var DEFAULT_PURCHASE_POLL_INTERVAL_MS = 1500;
|
|
1847
|
+
var DEFAULT_PURCHASE_POLL_TIMEOUT_MS = 18e4;
|
|
1848
|
+
function pollSleep(ms, signal) {
|
|
1849
|
+
return new Promise((resolve) => {
|
|
1850
|
+
if (signal?.aborted) return resolve();
|
|
1851
|
+
const timer = setTimeout(done, ms);
|
|
1852
|
+
const onAbort = () => done();
|
|
1853
|
+
function done() {
|
|
1854
|
+
clearTimeout(timer);
|
|
1855
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1856
|
+
resolve();
|
|
1857
|
+
}
|
|
1858
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1859
|
+
});
|
|
1860
|
+
}
|
|
1861
|
+
function isTransientPollFailure(err) {
|
|
1862
|
+
if (!(err instanceof InvoError)) return false;
|
|
1863
|
+
if (err.code === "ABORTED") return false;
|
|
1864
|
+
return err.status === 0 || err.status === 429 || err.status >= 500;
|
|
1865
|
+
}
|
|
1866
|
+
var CheckoutClient = class _CheckoutClient {
|
|
1867
|
+
constructor(config) {
|
|
1868
|
+
if (!config?.baseUrl) throw new Error("CheckoutClient requires a `baseUrl`.");
|
|
1869
|
+
assertSecureBaseUrl(config.baseUrl);
|
|
1870
|
+
this.http = new Http({
|
|
1871
|
+
baseUrl: config.baseUrl,
|
|
1872
|
+
timeoutMs: config.timeoutMs,
|
|
1873
|
+
fetchImpl: config.fetch,
|
|
1874
|
+
maxRetries: config.maxRetries,
|
|
1875
|
+
retryBaseDelayMs: config.retryBaseDelayMs,
|
|
1876
|
+
hooks: config.hooks
|
|
1877
|
+
});
|
|
1878
|
+
}
|
|
1879
|
+
/**
|
|
1880
|
+
* Wrap an `Http` the owning client already built, so `invo.checkout` shares that
|
|
1881
|
+
* client's baseUrl, timeout, retry budget and observability hooks.
|
|
1882
|
+
*
|
|
1883
|
+
* @internal Not part of the public API; it takes an internal type and may change.
|
|
1884
|
+
*/
|
|
1885
|
+
static _withHttp(http) {
|
|
1886
|
+
const client = Object.create(_CheckoutClient.prototype);
|
|
1887
|
+
client.http = http;
|
|
1888
|
+
return client;
|
|
1889
|
+
}
|
|
1890
|
+
/**
|
|
1891
|
+
* Read a purchase's status once.
|
|
1892
|
+
*
|
|
1893
|
+
* Answers `200` with a {@link PurchaseStatusResult} for every state of the purchase,
|
|
1894
|
+
* including "we have your money and your coins are not there". There is no tenant gate
|
|
1895
|
+
* on it: a partner suspended after a buyer's card was charged is exactly the case it
|
|
1896
|
+
* exists for.
|
|
1897
|
+
*
|
|
1898
|
+
* Throws an {@link InvoError} on `401` (no token, bad signature, or a card-setup token:
|
|
1899
|
+
* `err.isWrongSessionPurpose`), `403` (a valid token for a DIFFERENT session:
|
|
1900
|
+
* `err.isCheckoutSessionMismatch`) and `410` (the token is more than 24 hours past its
|
|
1901
|
+
* expiry: `err.isCheckoutSessionExpired`; show the buyer the order id you already have
|
|
1902
|
+
* and a Contact support link).
|
|
1903
|
+
*
|
|
1904
|
+
* Storefront (in-client) purchases are keyed on the partner's own purchase reference
|
|
1905
|
+
* rather than on a checkout session, so a read by session id finds nothing and answers
|
|
1906
|
+
* `pending`. Do not conclude from that that such a purchase never happened.
|
|
1907
|
+
*/
|
|
1908
|
+
async getPurchaseStatus(input, opts) {
|
|
1909
|
+
const sessionId = String(input?.sessionId ?? "").trim();
|
|
1910
|
+
const sessionToken = String(input?.sessionToken ?? "").trim();
|
|
1911
|
+
if (!sessionId) {
|
|
1912
|
+
throw new InvoError({
|
|
1913
|
+
message: "getPurchaseStatus requires `sessionId` (from createCheckout).",
|
|
1914
|
+
code: "INVALID_INPUT",
|
|
1915
|
+
status: 0
|
|
1916
|
+
});
|
|
1917
|
+
}
|
|
1918
|
+
if (!sessionToken) {
|
|
1919
|
+
throw new InvoError({
|
|
1920
|
+
message: "getPurchaseStatus requires `sessionToken`. The session token is the credential; the id in the path is not.",
|
|
1921
|
+
code: "INVALID_INPUT",
|
|
1922
|
+
status: 0
|
|
1923
|
+
});
|
|
1924
|
+
}
|
|
1925
|
+
const raw = await this.http.get(
|
|
1926
|
+
`/api/checkout/sessions/${encodeURIComponent(sessionId)}`,
|
|
1927
|
+
{ kind: "bearer", token: sessionToken },
|
|
1928
|
+
{ signal: opts?.signal }
|
|
1929
|
+
);
|
|
1930
|
+
return toPurchaseStatusResult(raw, sessionId);
|
|
1931
|
+
}
|
|
1932
|
+
/**
|
|
1933
|
+
* Poll {@link getPurchaseStatus} until INVO says the purchase is finished, and return
|
|
1934
|
+
* that final result.
|
|
1935
|
+
*
|
|
1936
|
+
* ```ts
|
|
1937
|
+
* const result = await invo.checkout.waitForPurchase({
|
|
1938
|
+
* sessionId, sessionToken,
|
|
1939
|
+
* intervalMs: 1500,
|
|
1940
|
+
* timeoutMs: 300_000,
|
|
1941
|
+
* signal: controller.signal,
|
|
1942
|
+
* onUpdate: (r) => render(r), // keep the modal open on every non-terminal read
|
|
1943
|
+
* });
|
|
1944
|
+
* if (isPurchaseCredited(result)) showCoins(result.coinsCredited, result.currencyName);
|
|
1945
|
+
* else if (result.message) showMessage(result.message, result.orderId); // verbatim
|
|
1946
|
+
* ```
|
|
1947
|
+
*
|
|
1948
|
+
* IT STOPS ON `result.terminal` AND ON NOTHING ELSE. `terminal` is INVO's word, read off
|
|
1949
|
+
* the response; this loop never recomputes it from `status`, so a status a later backend
|
|
1950
|
+
* introduces cannot end a wait here as a success. `paid_pending_credit` is deliberately
|
|
1951
|
+
* not terminal and is never promoted to a failure by age: INVO's reconciler recovers a
|
|
1952
|
+
* stalled credit, and telling a buyer they lost money they are about to receive would
|
|
1953
|
+
* be a fresh lie in place of the old silence.
|
|
1954
|
+
*
|
|
1955
|
+
* A transient failure (network, timeout, 429, 5xx) is polled through rather than raised;
|
|
1956
|
+
* a `401`, `403` or `410` is raised at once. On the cap it returns the LAST result it
|
|
1957
|
+
* read, whose `terminal` is false. Nothing is guessed and nothing is thrown, so the page
|
|
1958
|
+
* keeps showing the buyer what INVO last said. If it never got a single answer, the last
|
|
1959
|
+
* transport failure is thrown.
|
|
1960
|
+
*/
|
|
1961
|
+
async waitForPurchase(input) {
|
|
1962
|
+
const intervalMs = Math.max(0, input?.intervalMs ?? DEFAULT_PURCHASE_POLL_INTERVAL_MS);
|
|
1963
|
+
const timeoutMs = Math.max(0, input?.timeoutMs ?? DEFAULT_PURCHASE_POLL_TIMEOUT_MS);
|
|
1964
|
+
const maxAttempts = input?.maxAttempts === void 0 ? Number.POSITIVE_INFINITY : Math.max(1, input.maxAttempts);
|
|
1965
|
+
const deadline = Date.now() + timeoutMs;
|
|
1966
|
+
const signal = input?.signal;
|
|
1967
|
+
let last;
|
|
1968
|
+
let lastFailure;
|
|
1969
|
+
for (let attempts = 0; ; ) {
|
|
1970
|
+
if (signal?.aborted) {
|
|
1971
|
+
throw new InvoError({
|
|
1972
|
+
message: "waitForPurchase was aborted",
|
|
1973
|
+
code: "ABORTED",
|
|
1974
|
+
status: 0
|
|
1975
|
+
});
|
|
1976
|
+
}
|
|
1977
|
+
attempts += 1;
|
|
1978
|
+
try {
|
|
1979
|
+
const result = await this.getPurchaseStatus(input, { signal });
|
|
1980
|
+
last = result;
|
|
1981
|
+
lastFailure = void 0;
|
|
1982
|
+
try {
|
|
1983
|
+
input?.onUpdate?.(result);
|
|
1984
|
+
} catch {
|
|
1985
|
+
}
|
|
1986
|
+
if (result.terminal) return result;
|
|
1987
|
+
} catch (err) {
|
|
1988
|
+
if (!isTransientPollFailure(err)) throw err;
|
|
1989
|
+
lastFailure = err;
|
|
1990
|
+
}
|
|
1991
|
+
if (attempts >= maxAttempts) break;
|
|
1992
|
+
if (Date.now() + intervalMs >= deadline) break;
|
|
1993
|
+
await pollSleep(intervalMs, signal);
|
|
1994
|
+
}
|
|
1995
|
+
if (last) return last;
|
|
1996
|
+
throw lastFailure instanceof Error ? lastFailure : new InvoError({
|
|
1997
|
+
message: "waitForPurchase could not read the purchase status before the cap.",
|
|
1998
|
+
code: "PURCHASE_STATUS_UNAVAILABLE",
|
|
1999
|
+
status: 0
|
|
2000
|
+
});
|
|
2001
|
+
}
|
|
2002
|
+
};
|
|
1769
2003
|
var InvoClient = class {
|
|
1770
2004
|
constructor(config) {
|
|
1771
2005
|
/**
|
|
@@ -1790,6 +2024,7 @@ var InvoClient = class {
|
|
|
1790
2024
|
});
|
|
1791
2025
|
this.auth = { kind: "bearer", token: config.token };
|
|
1792
2026
|
this.refreshToken = config.refreshToken;
|
|
2027
|
+
this.checkout = CheckoutClient._withHttp(this.http);
|
|
1793
2028
|
}
|
|
1794
2029
|
assertWebAuthn() {
|
|
1795
2030
|
if (typeof navigator === "undefined" || !navigator.credentials) {
|
|
@@ -2174,8 +2409,14 @@ var InvoClient = class {
|
|
|
2174
2409
|
}
|
|
2175
2410
|
};
|
|
2176
2411
|
|
|
2412
|
+
exports.CheckoutClient = CheckoutClient;
|
|
2177
2413
|
exports.InvoClient = InvoClient;
|
|
2178
2414
|
exports.InvoError = InvoError;
|
|
2179
2415
|
exports.PlatformCommerceClient = PlatformCommerceClient;
|
|
2416
|
+
exports.isPurchaseCredited = isPurchaseCredited;
|
|
2417
|
+
exports.isPurchaseExpired = isPurchaseExpired;
|
|
2418
|
+
exports.isPurchaseRefunded = isPurchaseRefunded;
|
|
2419
|
+
exports.isPurchaseRefused = isPurchaseRefused;
|
|
2420
|
+
exports.nothingWasCharged = nothingWasCharged;
|
|
2180
2421
|
//# sourceMappingURL=index.cjs.map
|
|
2181
2422
|
//# sourceMappingURL=index.cjs.map
|