@flopay/js 1.20.15 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @flopay/js
2
2
 
3
- Browser-side FloPay SDK. `loadFloPay()` initializes a `FloPay` instance for hosted card capture and session access, `PaymentAPI` is the billing API client, and `createCheckoutSession()` creates a checkout session and redirects to the hosted checkout page.
3
+ Browser-side FloPay SDK. `loadCheckoutRuntime()` loads the Flo-hosted checkout runtime, which renders the checkout and runs the payment, and `createCheckoutSession()` creates a checkout session and redirects to the hosted checkout page.
4
4
 
5
- Providers sit behind the `PaymentProviderAdapter` interface (implemented today by `StripeAdapter`), so checkout code does not change when a session is routed to a different gateway.
5
+ The package holds no checkout UI, no business rules, no buyer-facing wording and no payment processor SDK. Which payment methods a buyer sees, and which processor takes the payment, is decided by the billing API and carried out by the hosted runtime, so checkout code does not change when a session is routed to a different gateway.
6
6
 
7
7
  ## Installation
8
8
 
@@ -10,9 +10,9 @@ Providers sit behind the `PaymentProviderAdapter` interface (implemented today b
10
10
  pnpm add @flopay/js
11
11
  ```
12
12
 
13
- `@stripe/stripe-js` and `@flopay/shared` install automatically as dependencies; you do not need to add them. Choose the billing API environment once at startup with `configureFlopay()` from `@flopay/shared`, or the `NEXT_PUBLIC_FLOPAY_ENV` environment variable.
13
+ `@flopay/shared` installs automatically as a dependency; you do not need to add it. No payment processor SDK is installed or loaded by this package. Choose the billing API environment once at startup with `configureFlopay()` from `@flopay/shared`, or the `NEXT_PUBLIC_FLOPAY_ENV` environment variable.
14
14
 
15
- For React applications, `@flopay/react` builds on this package and renders the complete checkout.
15
+ For React and Vue applications, `@flopay/react` and `@flopay/vue` build on this package: their components mount the same hosted runtime.
16
16
 
17
17
  ### Choosing and upgrading a release
18
18
 
@@ -25,38 +25,48 @@ Confirm that the chosen version is available on npm for every package you are up
25
25
  GitHub pull request alone does not mean publication has finished. If that exact version is not yet
26
26
  available, wait for publication rather than mixing versions or installing a repository branch.
27
27
 
28
+ Upgrading from 1.x? See **Breaking changes in 2.0.0** under Public API below.
29
+
28
30
  ## Usage
29
31
 
30
32
  ### Initialize the SDK
31
33
 
34
+ `@flopay/js` 2.0 loads the Flo-hosted checkout runtime; it holds no checkout UI and no payment processor SDK. Load the runtime once per page and mount it for a session:
35
+
32
36
  ```ts
33
- import { loadFloPay } from '@flopay/js';
37
+ import { loadCheckoutRuntime } from '@flopay/js';
34
38
 
35
- const flopay = await loadFloPay('pk_test_...', {
36
- billingApiUrl: 'https://billing.example.com', // enables retrieveSession() and retrieveUnifiedSession()
37
- });
39
+ const runtime = await loadCheckoutRuntime({ runtimeUrl: 'https://<flo-runtime-host>/2/entry.js' });
38
40
  ```
39
41
 
40
- The optional second argument accepts every `FloPayConfig` field except `publishableKey`: `billingApiUrl`, `locale`, `appearance`, and `telemetry`. `loadFloPay` caches by publishable key and behavior-affecting options: concurrent calls with the same key and options share one in-flight provider initialization and resolve to the same `FloPay` instance. A failed initialization is evicted, so a later call can retry.
42
+ Concurrent loads of the same `runtimeUrl` share one script. The runtime has `timeoutMs` (10 seconds by default) to register itself; a script that fails to load rejects with `runtime_load_failed`, and one that does not register in time rejects with `runtime_load_timeout`.
43
+
44
+ ### Mount the checkout
45
+
46
+ `runtime.mount(container, options)` renders the checkout for one session inside `container` and returns a handle with `update(options)` and `unmount()`. Pass either a session your server created (`sessionId` and its `nonce`) or `createSession`, the body of a `POST /v1/checkouts/sessions` request the runtime sends for you. The runtime reads the session, renders the payment methods it offers, hosts the card fields, and runs the payment, including any card authentication challenge.
47
+
48
+ - **Payment methods.** The session's `paymentMethods` says which of `card`, `paypal`, `wallets` and `apms` it offers. The runtime renders only those; the SDK never adds, chooses or filters a gateway.
49
+ - **Hiding methods.** `hiddenPaymentMethods` lists methods the runtime does not show, by method or group name, never by processor: `card` (the card form), `paypal`, `apple_pay`, `google_pay` and `apms` (the other payment methods). An offered method is left out when its method or its group is listed. The runtime only removes methods the session offers; it never adds one, and a name that matches nothing hides nothing. Left out or empty, nothing is hidden. A new list is a new mount.
50
+ - **Presentation.** `appearance`, `strings`, `paymentMethodLayout` and `layout` are passed to the runtime unchanged; `update()` applies new `appearance`, `strings` or `paymentMethodLayout` without remounting.
51
+ - **Saved payments.** `automaticPayment` runs an automatic or confirm saved payment when the buyer clicks the pay control.
52
+
53
+ ### Runtime events
41
54
 
42
- ### Retrieve a session
55
+ `onEvent` receives every runtime event as `{ name, payload }`, with the payloads the 1.x checkout emitted:
43
56
 
44
- `flopay.retrieveSession(sessionId)` returns the normalized `CheckoutSession` (amount, currency, status, customer). `flopay.retrieveUnifiedSession(sessionId)` returns a `NormalizedCheckoutSession`: every gateway the session advertises is listed in `providers`, and gateway data such as the Stripe client secret is under `data`. Both use the `billingApiUrl` from `loadFloPay`, or a URL you pass as the second argument.
57
+ - `complete`, `decline` and `error` are the payment outcomes. Declines use FloPay's decline taxonomy, never a raw processor code. An ambiguous submission stays pending until the billing API reconciles it and is reported as an `error`, never a success.
58
+ - `cancel` is the buyer closing a payment method's approval without paying.
59
+ - `instruments` is the merchant instrument feed.
60
+ - `cardFieldsReady` and `cardFieldsFailed` are the card-field lifecycle, described below.
45
61
 
46
- `retrieveUnifiedSession()` exposes provider-specific session data without
47
- mounting provider UI. Use `FloPayCheckout` or `SplitCardForm` from
48
- `@flopay/react` for hosted-vault card, wallet, and APM rendering.
62
+ ### Card-field lifecycle
49
63
 
50
- ### Call the billing API directly
64
+ The runtime reports when its card fields became usable and when they failed to load, so you can measure card-field loading per buyer:
51
65
 
52
- `PaymentAPI` wraps the billing API routes the checkout uses. Session reads and continuation calls take the session **nonce**, the session-bound checkout token returned when the session was created, and send it as `x-checkout-session-token`.
66
+ - `cardFieldsReady` carries `{ type: 'card_fields_ready', elapsedMs }`. It fires once per card form, when the card fields are on screen and the buyer can type in them. `elapsedMs` is the time since that card form mounted; a re-mounted form is a new card form.
67
+ - `cardFieldsFailed` carries `{ type: 'card_fields_failed', reason, elapsedMs }`. It fires at most once per card form when the card fields fail to load, or are not ready within the timeout. If they become ready after a `timeout`, `cardFieldsReady` still follows. `reason` is always one of `load_error`, `timeout`, `blocked` (a content-security policy blocked the form) or `other`.
53
68
 
54
- - `getUnifiedCheckoutSession(sessionId, nonce)` reads and normalizes a session.
55
- - `createSessionIntent(sessionId, nonce, request)` creates a Stripe wallet/APM or direct-PayPal intent. The request is a discriminated union of provider, payment-method category, type, and id, and intent kind; direct-card requests are not representable. If the session is still processing an earlier payment (for example a PayPal capture under review), the billing API answers `202 checkout_processing`. The SDK then polls the session status within the same time limit `processPayment` uses. It resolves to a settled result, `{ settled: true, response }`, instead of an intent. `response` is the `Response` `processPayment` would give for that outcome: `204` succeeded, `200` authorized, `400` declined. Check for it with `isSettledSessionIntent` from `@flopay/shared`. If the time limit runs out first, it rejects with `checkout_processing_timeout`, `statusCode: 202` and the `sessionId`.
56
- - `reportSessionIntentDecline(sessionId, nonce, request)` reports a client-observed non-card decline using a classification code only. Messages, identifiers, card data, credentials, and personal data are rejected before sending.
57
- - `resolvePaymentMethodLayout(sessionId, nonce, rules)` sends the merchant's `PaymentMethodLayoutRules` and returns the `PaymentMethodLayout` the billing API resolved for this buyer: the order of `'card'`, `'paypal'`, `'wallets'` and `'apms'`, where the buyer's country came from (`'session'`, `'ip'` or `'none'`), and warnings about invalid rules. The SDK sends no country, and the IP country is never returned. It resolves `null` when the billing API predates the route.
58
- - `processPayment(userId, params)` submits a saved or approved non-card payment to the session's `/process` route. When the billing API answers `202`, the SDK follows its authenticated status endpoint until the latest transaction attempt succeeds, authorizes, declines, requires buyer action, fails, or times out.
59
- - `getPaymentsByEmail(email)` looks up prior payments for a saved-payment experience.
69
+ A card-field failure is not a declined or failed payment: it never emits `decline`. The payload types are `CardFieldsEvent`, `CardFieldsReadyEvent`, `CardFieldsFailedEvent` and `CardFieldsFailureReason`.
60
70
 
61
71
  ### Create a hosted checkout session
62
72
 
@@ -67,13 +77,15 @@ mounting provider UI. Use `FloPayCheckout` or `SplitCardForm` from
67
77
 
68
78
  `createCheckoutSessionWithRetries(options)` adds automatic retry with jittered exponential backoff on transient transport, timeout, and idempotency-in-progress failures: at most two retries (three attempts), all inside one 12-second total deadline you can change with `timeoutMs`.
69
79
 
80
+ A create with no `checkoutMode` sends `'full'`; an explicit `'confirm'`, `'auto'` or `'full'` is sent unchanged.
81
+
70
82
  ### Checkout metadata
71
83
 
72
- Pass `checkoutMetadata?: Record<string, string> | null` to redirect, retrying, one-shot inline, or detached creation. A present map, an explicit `null`, and `{}` are sent unchanged; omitting the field leaves the request body unchanged. Session reads expose a returned snapshot as `normalized.checkoutMetadata` and `normalized.data.session.checkoutMetadata`; an omitted or `null` create value is absent from reads, while `{}` is returned as `{}`. The SDK performs no duplicate size validation: billing API rejections keep their `code`, message, and HTTP `statusCode`.
84
+ Pass `checkoutMetadata?: Record<string, string> | null` to `createCheckoutSession` or `createCheckoutSessionWithRetries`. A present map, an explicit `null`, and `{}` are sent unchanged; omitting the field leaves the request body unchanged. The SDK performs no duplicate size validation: billing API rejections keep their `code`, message, and HTTP `statusCode`.
73
85
 
74
86
  ### Authorise now, capture later
75
87
 
76
- For an item-only card checkout that should place a hold instead of capturing immediately, add `captureMethod: 'manual'` to `createCheckoutSession`, `createCheckoutSessionWithRetries`, `PaymentAPI.createAndFetchSession`, or `PaymentAPI.createDetachedSession`. An accepted hold surfaces as `status: 'authorized'` on normalized sessions and payment results, with `paymentId`, `sessionId`, and `authorizationExpiresAt`. Treat it as checkout-terminal but not paid. Capture is a merchant-authenticated REST operation, never available to browser code; see the [payments and authorisations reference](https://flopay.com/docs/technical-reference/rest/payments).
88
+ For an item-only card checkout that should place a hold instead of capturing immediately, add `captureMethod: 'manual'` to `createCheckoutSession` or `createCheckoutSessionWithRetries`. An accepted hold surfaces as `status: 'authorized'` on the session and in the runtime's `complete` payload. Treat it as checkout-terminal but not paid. Capture is a merchant-authenticated REST operation, never available to browser code; see the [payments and authorisations reference](https://flopay.com/docs/technical-reference/rest/payments).
77
89
 
78
90
  ### Idempotent checkout creation
79
91
 
@@ -82,121 +94,15 @@ Every checkout-session create sends a stable `Idempotency-Key` header when a sec
82
94
  - **Automatic (default):** the SDK generates one cryptographically random key per logical `createCheckoutSession` call and reuses it for every retry of that operation. Independent calls get different keys even when their bodies are identical. The key is never derived from customer data and is never logged or returned. Without `crypto.randomUUID` or `crypto.getRandomValues` the header is omitted; supply your own key to stay idempotent there.
83
95
  - **Merchant-supplied:** pass `idempotencyKey` to keep the key stable across remounts, SDK instances, or your own server retries. It identifies exactly one logical checkout and must never be reused for a new purchase.
84
96
 
85
- `createCheckoutSessionWithRetries` resolves the key once, before its retry loop, so timeouts, lost responses, and in-progress replies all replay the same key; a `409` payload conflict is surfaced without retrying. `PaymentAPI.createAndFetchSession` (used by `@flopay/react`) follows the same rules, with one shared three-attempt budget across network failures and in-progress replies.
86
-
87
- ### Detached session creation (default)
88
-
89
- Inline session creation is detached by default. Instead of one request that resolves buyer identity and the catalog together, the SDK issues two:
90
-
91
- 1. `POST /v1/checkouts/sessions` with `deferDataAttachment: true` returns a lightweight **shell**. It runs no catalog validation and takes none of the buyer-identity locks that serialise concurrent checkouts for the same customer, yet already carries `gateways` and the hosted `vault` block: **the card form can mount from it.** Checkout metadata is sent on this request.
92
- 2. `PATCH /v1/checkouts/sessions/{id}/claim` attaches products and coupons in the background. When the draft has an email it also attaches the buyer; an email-less draft omits the buyer, and the returned session has its full catalog, totals, and methods while `buyerIdentified` stays `false`.
93
-
94
- `PaymentAPI.createDetachedSession(params)` exposes both phases as `{ shell, sessionId, nonce, claimed, claim }`. `claimed` settles when the catalog is attached; `claim(account)` attaches a buyer identity later. Both are independently replay-safe: repeated valid `claim(account)` calls return the same promise, and a local invalid-email rejection does not consume the operation. `createAndFetchSession` also accepts an email-less draft and resolves with the catalog-attached anonymous session.
95
-
96
- Nothing may be charged before `claimed` settles: the billing API rejects process, intent, and decline calls on an unclaimed session with `409 checkout_session_data_attachment_required`, and holds an unclaimed hosted card charge with a retryable `503`. `@flopay/react` gates the card form's submit button for exactly this window.
97
-
98
- For detached creation, `timeoutMs` is a fresh per-phase budget: the shell POST gets the full value, and after it succeeds the initial claim PATCH gets the full value again under a different `AbortSignal` (12 seconds each by default), so time spent creating a usable shell never starves its catalog claim. Detached creation requires billing API v1.7.12 or newer and `checkoutMode: 'full'`, and is skipped when `tokenizedData` is supplied. There is no fallback to the one-shot create; pass `deferDataAttachment: false` to force it. Because catalog validation moves to the claim, an invalid product or coupon surfaces as the same `422`, later in the flow. The claim body is fingerprinted by the billing API, so the SDK replays a byte-identical payload across retries, and a materially different claim for an already-claimed session returns `409` without retrying.
99
-
100
- **Stripe account routing.** The shell also carries the cart's distinct catalogue product codes as `routingProducts: [{ code }]`, one entry per code, resolved the way the claim's lines resolve them. It is a routing hint only: the billing API uses it to advertise the cart's Stripe account on the first response, never stores it, and still treats the claim as the authority. An empty cart, a cart without product codes, and a one-shot create send no `routingProducts` key, so their request is unchanged. When the claim nevertheless changes the advertised Stripe account, the billing API hides Apple Pay and Google Pay from the claimed session unless the client declared `stripe-account-switch-v1`. `new PaymentAPI(billingApiUrl, { stripeAccountSwitch: true })` adds that token in `x-flo-sdk-capabilities` to the shell POST and to every claim. Set it only when your integration loads Stripe.js for the claimed account and re-mounts its wallet buttons there, as `@flopay/react`'s `FloPayCheckout` does; the default `PaymentAPI` never declares it.
101
-
102
- ### Server-side card gateways (Worldpay)
103
-
104
- The billing API can process hosted-vault and eligible saved cards through an approved Worldpay Corporate Gateway entirely server-side. Whether a session can use it is the billing API's decision, made from the merchant's active gateways and the saved method's eligibility. `PaymentAPI` sends no gateway hint, provider selection, eligibility assertion, merchant code, or scheme reference. Everything stays provider-neutral, so existing integrations change nothing:
105
-
106
- - Cards still go through the hosted card form, from the embedded `vault` block or `getVaultCapture()`. There is no Worldpay browser SDK, key, or credential: `gateways.worldpayCorporateGateway` has a `null` publishable key and no enabled methods, and it never appears in the normalized `providers` list.
107
- - Outcomes arrive as the same `complete`, `decline`, and `error` events. Declines use FloPay's decline taxonomy, never a raw processor code. An ambiguous submission stays pending until the billing API reconciles it; the hosted form reports that as an `error`, never a success, and a later session read returns the reconciled status.
108
- - Cardholder authentication (3DS) resumes through the same provider-neutral continuation as every other card gateway. The hosted form reports `action_required` with a Flo-hosted challenge URL, the adapter renders that URL in its own modal overlay, and the outcome is resolved server-side before the hosted form reports the terminal `complete`, `decline`, or `error`. No Worldpay or authentication-provider script, merchant code, ACS URL, or token reaches the browser.
109
- - Eligible saved-card Auto, Confirm, returning-buyer, and subscription checkouts call the same provider-neutral `/process` route without `tokenizedData`. Immediate success and authorization use the existing Flo shapes; a `202 checkout_processing` response is reconciled through its nonce-protected status URL, including decline, buyer action, and terminal error states.
110
- - When a saved method cannot be used, `stored_payment_method_unsupported` is preserved as an actionable Flo error with the instruction to choose another payment method. The SDK never silently switches to a different charging behavior. Scheduled subscription rebills, retries, dunning, and stored-credential eligibility remain billing-API responsibilities.
111
-
112
- `PaymentAPI` Auto creates advertise only the generic `async-auto-checkout-v1` response capability so the billing API may return the asynchronous status envelope. It is not a Worldpay capability or routing request; Confirm and Full creates send no capability header unless the `PaymentAPI` opted into the Stripe account switch (below). Do not add gateway selection or provider-specific branches to a create request, whether through this SDK or a request you build yourself: the billing API owns that decision.
113
-
114
- ### Hosted card capture
115
-
116
- `flopay.cardCapture()` returns a `CardCaptureAdapter` that injects the billing API's self-contained hosted card form. The form owns the PCI card fields, its own submit button, tokenization, the charge (created and confirmed server-side), 3DS, and the result, so **no Stripe.js runs on the card path** and card numbers never enter the SDK runtime. The SDK injects the form and relays its terminal outcome.
117
-
118
- - Use the session's embedded `vault` block when present. Otherwise fetch one with `PaymentAPI.getVaultCapture(sessionId, nonce)` for a session whose Stripe `enabledPaymentMethods` explicitly includes `card`, or that advertises `gateways.worldpayCorporateGateway`. `getVaultCapture()` shares one active request between concurrent callers, aborts a stalled attempt after ten seconds, and retries transient network failures on the idempotent `POST /v1/checkouts/sessions/{id}/vault/capture` route.
119
- - Outcome events are `ready`, `complete`, `decline`, and `error`; `challenge_dismissed` is a non-terminal notification that the buyer closed the authentication challenge. The form is injected same-window, so the adapter rejects terminal outcomes that are not bound to the mounted session, that mismatch the block's `messageToken`, or that arrive from a different `expectedOrigin`. Pass both from the vault block to `mount()`.
120
- - When the buyer's bank asks for authentication, the hosted form hands the challenge up to the adapter, which renders the provider-hosted URL in a full-page modal overlay (`role="dialog"`, `aria-modal`, focus moved into the challenge and restored on teardown) above any processing backdrop. The challenge is not an outcome: it reaches no listener, and the challenge URL never appears in an event or in telemetry. The hosted form resolves the outcome and reports it as the usual `complete`, `decline`, or `error`; if nothing comes back at all, the overlay closes itself after the hosted form's own authentication window and reports an `error`. Closing the overlay abandons the challenge and reports the non-terminal `challenge_dismissed` event, so the host can take down its processing state and leave the form retryable straight away; it is not an outcome, and a late `complete`, `decline`, or `error` from the hosted form still reaches your listeners.
121
- - A `complete` event's `intentId` is the processing gateway's own reference. It is a Stripe PaymentIntent (or SetupIntent) id only when Stripe took the card; for a server-side card gateway it may be an opaque order reference. Reconcile by `paymentId` and the session instead.
122
- - For a merchant-server-created no-charge setup session, create the adapter with `operation: 'card_setup'`. A `complete` event may then carry a display-only `paymentMethod` (FloPay id, brand, last four, expiry, and status).
123
- - `capture.applyTheme(theme)` re-skins the mounted form without remounting; `applyTheme(null)` is the explicit classic reset. Theming is cosmetic and never blocks capture.
124
- - `capture.setSubmitLabel(label)` sets the hosted submit button's wording live (billing API v1.9.35+), without remounting or clearing entered card data. Pass final, already-localized plain text; the hosted form shows its session default (`CONFIRM PAYMENT`, or `ADD CARD` for card setup) for blank or invalid text. `capture.setSubmitLabel(null)` is the explicit reset to that default, and a `submitLabel` mount option sets the initial wording.
125
-
126
- The adapter retains the latest label and replays it
127
- every time the widget reports an authenticated `ready`, so a late or remounted
128
- form still receives it. Because the directive carries merchant text, it is
129
- posted only when the vault block supplied both `messageToken` and
130
- `expectedOrigin`, bound to the mounted `sessionId`, with the exact
131
- `expectedOrigin` as the `postMessage` target — never `'*'`:
132
-
133
- ```ts
134
- { source: 'flopay-vault-host', type: 'submitLabel', sessionId, messageToken, label }
135
- ```
136
-
137
- A form mounted without those fields (an older billing API) keeps its default. The label is never added to telemetry. The card field labels message follows the same rule: it carries the same session and message-token binding, goes only to the exact `expectedOrigin`, and is not sent at all to a form mounted without them. The other host directives (theme, submit gate, field order and card brand icons) also target the exact `expectedOrigin` when one was supplied, falling back to `'*'` only for a widget mounted without it. There is no host directive for authentication: the hosted form accepts no completion signal from the page, because the outcome of a challenge is resolved server-side.
138
-
139
- `capture.setCardBrandIcons(show)` shows or hides the Visa, Mastercard, Amex and Discover icons in the hosted card number field, live and without remounting. Only `true` turns them on; the default is `false`, so a form whose host never calls it is unchanged. The adapter posts the setting with the initial directives at mount and replays the latest value on every `ready`:
140
-
141
- ```ts
142
- { source: 'flopay-vault-host', type: 'cardBrandIcons', show }
143
- ```
144
-
145
- The hosted form narrows the icons to the brand the buyer types; no brand is reported back to the page. A hosted form that predates the icons ignores the directive.
146
-
147
- `capture.setShowCardFieldLabels(show)` shows or hides the visible labels above the hosted card fields, and `capture.setCardFieldLabels(labels)` replaces their text. Both apply live, without remounting. `labels` takes optional `number`, `expiry`, `cvv` and `name` text; only the string fields you set are sent, exactly as given, because the hosted form shows the text literally. `setCardFieldLabels(null)` clears the text, so the hosted form falls back to its default wording. The adapter sends one message, and only once the host has called either method, so a form whose host never calls them is unchanged. It posts the latest settings with the initial directives at mount and replays them on every `ready`:
148
-
149
- ```ts
150
- { source: 'flopay-vault-host', type: 'cardFieldLabels', sessionId, messageToken, show?, labels? }
151
- ```
152
-
153
- `show` is present once `setShowCardFieldLabels` was called and `labels` once `setCardFieldLabels` was called. Label text is merchant text drawn inside the card form, so, like the submit label, the message is bound to the session and the vault block's `messageToken` and is posted only to the exact `expectedOrigin`, never to `'*'`. A form mounted without a message token, an expected origin or a session id (an older billing API) receives no label message and keeps its default. The labels' look travels in the theme, not here: `applyTheme` forwards the theme's `labels` member (colour, font size, font weight, letter spacing, text transform and the gap below the label), which the browser packages map from `appearance.rules['.Label']`.
154
-
155
- ```ts
156
- capture.setShowCardFieldLabels(true);
157
- capture.setCardFieldLabels({ number: 'Card number', cvv: 'Security code' });
158
- ```
159
-
160
- `capture.setCardFieldPlaceholders(placeholders)` sets the placeholder text of the hosted card fields, live and without remounting. Every field is optional: `number`, `expiry`, `cvv` and `name`. Only the fields given are sent; the rest keep the hosted form's wording, and an empty string (`''`) shows no placeholder. The text is forwarded verbatim, with no trimming, validation or length check: the hosted form enforces its own limits and shows the text literally. A later call replaces the earlier one.
161
-
162
- ```ts
163
- capture.setCardFieldPlaceholders({ number: 'Card number', expiry: 'MM / YY', cvv: 'CVC', name: 'Name on card' });
164
- ```
165
-
166
- A value set before `mount()` is posted once at mount; the adapter keeps the latest value and replays it on every `ready`, so a reloaded form shows it again. Until it is called, or when it is called with `undefined`, nothing is posted and the form keeps its own wording; `undefined` after text was set posts one empty set so the mounted form returns to that wording. Like the submit label it carries merchant text, so it is posted only when the vault block supplied `messageToken` and `expectedOrigin`, bound to the mounted `sessionId`, to the exact `expectedOrigin` — never `'*'`:
167
-
168
- ```ts
169
- { source: 'flopay-vault-host', type: 'cardFieldPlaceholders', sessionId, messageToken, placeholders }
170
- ```
171
-
172
- ### Card-field lifecycle
173
-
174
- The card-capture adapter reports when its card fields became usable and when they failed to load, so you can measure card-field loading per buyer. Subscribe with `onCardFields(handler)`, which returns an unsubscribe function:
175
-
176
- - `{ type: 'card_fields_ready', elapsedMs }` fires once per card form, when the card fields are on screen and the buyer can type in them (not when the markup is inserted, which is the adapter's `ready`). `elapsedMs` is the time since that card form mounted; a re-mounted form is a new card form.
177
- - `{ type: 'card_fields_failed', reason, elapsedMs }` fires at most once per card form when the card fields fail to load, or are not ready within the timeout. If they become ready after a `timeout`, `card_fields_ready` still follows. `reason` is always one of `load_error` (the form failed to load, for example its script request failed), `timeout` (not interactive in time), `blocked` (a content-security policy blocked the form's own script or frame) or `other` (any other failure, such as `mount()` throwing).
178
-
179
- A card-field failure is not a declined or failed payment: it never emits `decline`, and the existing `ready`, `complete`, `decline` and `error` events are unchanged. The timeout is `cardFieldsTimeoutMs`, on `new PciVaultCardCapture({ ... })` and `flopay.cardCapture({ ... })`; the default is 15 000 ms on every device, and a value that is not a positive number keeps the default. Both events also reach Flo's SDK telemetry (`vault.fields.ready`, `vault.fields.failed`) with the checkout session id, and never carry card data. A throwing handler does not affect the card form.
180
-
181
- The `error` event still fires, as before, when the hosted form itself reports that it failed to load. A timeout, a blocked form or any other failure the adapter detects is reported only as `card_fields_failed`. An older hosted form that does not report when its fields become interactive gets `card_fields_ready` when it reports its own ready instead.
182
-
183
- ```ts
184
- const capture = flopay.cardCapture({ sessionId, cardFieldsTimeoutMs: 20_000 });
185
- const off = capture.onCardFields?.((event) => {
186
- if (event.type === 'card_fields_ready') track('card_fields_ready', { elapsedMs: event.elapsedMs });
187
- else track('card_fields_failed', { reason: event.reason, elapsedMs: event.elapsedMs });
188
- });
189
- ```
97
+ `createCheckoutSessionWithRetries` resolves the key once, before its retry loop, so timeouts, lost responses, and in-progress replies all replay the same key; a `409` payload conflict is surfaced without retrying.
190
98
 
191
99
  ### Privacy-safe operational telemetry
192
100
 
193
- Browser telemetry is on by default and best-effort. It reports only the closed SDK error, lifecycle, and performance taxonomy to a FloPay-owned API; it never bundles Sentry, reads Resource Timing, persists a queue, or transmits payment, customer, or form data, credentials, URLs, provider payloads, arbitrary messages, or stacks. Opt out with `telemetry: false` on `loadFloPay`, `PaymentAPI`, `PciVaultCardCapture`, `createCheckoutSession`, and `createCheckoutSessionWithRetries`. Merchant callbacks keep their arguments and invocation order; exceptions they throw are contained and logged only to your console.
194
-
195
- Genuine technical failures carry one bounded category: `server_error` for billing API 5xx responses, `transport_error` when no usable response arrives, `invalid_response` for malformed responses, and `provider_runtime` for provider SDK or hosted-form runtime failures. Payment declines and request validation failures are reported as non-error `payment_declined` and `validation_rejected` outcomes.
101
+ Browser telemetry is on by default and best-effort. It reports only the closed SDK error, lifecycle, and performance taxonomy to a FloPay-owned API; it never bundles Sentry, reads Resource Timing, persists a queue, or transmits payment, customer, or form data, credentials, URLs, provider payloads, arbitrary messages, or stacks. Opt out with `telemetry: false` on `createCheckoutSession` and `createCheckoutSessionWithRetries`. Merchant callbacks keep their arguments and invocation order; exceptions they throw are contained and logged only to your console.
196
102
 
197
- When telemetry is enabled, a Stripe loader rejection is reported only with the bounded `provider_runtime` category, while a null Stripe loader result uses the distinct `invalid_response` category. Neither changes the thrown error or the failed-load retry behavior, and neither transmits the publishable key, rejection, provider message, stack, URL, or provider payload.
103
+ Genuine technical failures carry one bounded category: `server_error` for billing API 5xx responses, `transport_error` when no usable response arrives, `invalid_response` for malformed responses, and `provider_runtime` for hosted-runtime failures. Payment declines and request validation failures are reported as non-error `payment_declined` and `validation_rejected` outcomes.
198
104
 
199
- `FloPayCheckout` in `@flopay/react` also classifies failures around the session and provider boundary without exposing raw errors. An existing session-read transport failure uses `transport_error`; malformed JSON uses `invalid_response`.
105
+ `FloPayCheckout` in `@flopay/react` also classifies failures around the session boundary without exposing raw errors. An existing session-read transport failure uses `transport_error`; malformed JSON uses `invalid_response`.
200
106
 
201
107
  ### Filter third-party errors in your own Sentry client
202
108
 
@@ -211,219 +117,90 @@ This pure predicate drops only complete exception stacks with no app or `@flopay
211
117
 
212
118
  ## Examples
213
119
 
214
- Initialize the SDK and read a session's gateways:
215
-
216
- ```ts
217
- import { loadFloPay } from '@flopay/js';
218
-
219
- const flopay = await loadFloPay('pk_test_...', { billingApiUrl: 'https://billing.example.com' });
220
-
221
- const session = await flopay.retrieveSession('session_uuid');
222
- console.log(session.amount, session.currency, session.status);
223
-
224
- const unified = await flopay.retrieveUnifiedSession('session_uuid');
225
- if (unified.providers.includes('stripe')) {
226
- console.log('Stripe publishable key:', unified.data.stripe?.publishableKey);
227
- }
228
- ```
229
-
230
- Create a hosted checkout session with metadata and a merchant-controlled idempotency key:
231
-
232
- ```ts
233
- import { createCheckoutSessionWithRetries } from '@flopay/js';
234
- import { FloPayError } from '@flopay/shared';
235
-
236
- try {
237
- const result = await createCheckoutSessionWithRetries({
238
- billingApiUrl: 'https://billing.example.com',
239
- checkoutBaseUrl: 'https://checkout.example.com',
240
- clientId: 'client_123',
241
- currency: 'USD',
242
- items: [{ providerItemId: 'prod_abc', providerItemName: 'Pro Plan', totalAmount: 49.99 }],
243
- account: { userId: 'user_1', email: 'user@example.com' },
244
- successUrl: '/success',
245
- cancelUrl: '/cancel',
246
- couponCodes: ['SAVE10'],
247
- checkoutMetadata: { merchantOrderId: 'order-123', campaign: 'summer' },
248
- idempotencyKey: 'checkout:order-123',
249
- });
250
- console.log('Checkout session created with status', result.status);
251
- } catch (error) {
252
- if (error instanceof FloPayError && error.code === 'CouponLimitExceeded') {
253
- console.warn('Too many coupon codes.');
254
- } else if (error instanceof FloPayError && error.code === 'CouponCurrencyUnsupported') {
255
- console.warn('A coupon is not valid for this currency.');
256
- } else {
257
- throw error;
258
- }
259
- }
260
- ```
261
-
262
- Create a detached session, mount the card form from the shell, and identify the buyer later:
120
+ Load the Flo-hosted runtime and mount the checkout for a session your server created, without Apple Pay:
263
121
 
264
122
  ```ts
265
- import { PaymentAPI } from '@flopay/js';
266
-
267
- const api = new PaymentAPI('https://billing.example.com');
268
-
269
- const detached = await api.createDetachedSession({
270
- clientId: 'client_123',
271
- currency: 'EUR',
272
- items: [{ providerItemId: 'prod_abc', providerItemName: 'Widget', totalAmount: 29.99 }],
273
- account: { userId: 'buyer_123' },
274
- successUrl: '/success',
275
- cancelUrl: '/cancel',
276
- });
277
-
278
- console.log('Card form can mount from', detached.shell.data.session?.vault);
279
- const anonymous = await detached.claimed; // catalog, totals, and methods; buyerIdentified is false
280
- const identified = await detached.claim({ email: 'buyer@example.com', firstName: 'Jane', lastName: 'Doe' });
281
- console.log(anonymous.data.session?.buyerIdentified, identified.data.session?.buyerIdentified);
282
- ```
283
-
284
- Mount the hosted card form and relay its outcome:
285
-
286
- ```ts
287
- import { loadFloPay, PaymentAPI } from '@flopay/js';
288
- import type { PaymentResult } from '@flopay/shared';
289
-
290
- const billingApiUrl = 'https://billing.example.com';
291
- const sessionId = 'session_uuid';
292
- const nonce = 'session_nonce';
293
-
294
- function onComplete(result: PaymentResult) {
295
- console.log('Checkout finished:', result.status, result.paymentId);
296
- }
297
-
298
- const flopay = await loadFloPay('pk_test_...', { billingApiUrl });
299
- const session = await flopay.retrieveSession(sessionId);
300
- const vault = session.vault ?? (await new PaymentAPI(billingApiUrl).getVaultCapture(sessionId, nonce));
301
-
302
- const capture = flopay.cardCapture({ sessionId, captureMethod: session.captureMethod });
303
- capture.on('complete', (e) => {
304
- if (e.outcome === 'authorized' || session.captureMethod === 'manual') {
305
- onComplete({
306
- status: 'authorized',
307
- paymentId: e.paymentId,
308
- sessionId: e.sessionId,
309
- authorizationExpiresAt: e.authorizationExpiresAt,
310
- });
311
- return;
312
- }
313
- onComplete({ status: 'succeeded', paymentId: e.paymentId, sessionId: e.sessionId });
314
- });
315
- capture.on('decline', (e) => console.warn('Card declined:', e.declineReason));
316
- capture.on('error', (e) => console.error('Card form failed:', e.message));
317
-
318
- const container = document.getElementById('card-form');
319
- if (container && vault.html) {
320
- await capture.mount(container, {
321
- html: vault.html,
322
- messageToken: vault.messageToken,
323
- expectedOrigin: vault.expectedOrigin,
324
- submitLabel: 'Pay €29.99',
123
+ import { loadCheckoutRuntime } from '@flopay/js';
124
+
125
+ declare const publishableKey: string;
126
+ declare const runtimeUrl: string; // the Flo-hosted runtime entry for your environment
127
+
128
+ const container = document.getElementById('checkout');
129
+ if (container) {
130
+ const runtime = await loadCheckoutRuntime({ runtimeUrl });
131
+ const checkout = runtime.mount(container, {
132
+ publishableKey,
133
+ sessionId: 'sess_123',
134
+ nonce: 'nonce_123',
135
+ hiddenPaymentMethods: ['apple_pay'],
136
+ onEvent: (event) => {
137
+ if (event.name === 'complete') checkout.unmount();
138
+ },
325
139
  });
326
140
  }
327
141
  ```
328
142
 
329
- Create a wallet intent and report a client-observed decline:
330
-
331
- ```ts
332
- import { PaymentAPI } from '@flopay/js';
333
- import { isSettledSessionIntent } from '@flopay/shared';
334
-
335
- const api = new PaymentAPI('https://billing.example.com', { telemetry: false });
336
-
337
- const intent = await api.createSessionIntent('session_uuid', 'session_nonce', {
338
- provider: 'stripe',
339
- paymentMethodCategory: 'wallet',
340
- paymentMethodType: 'apple_pay',
341
- paymentMethodId: null,
342
- intentKind: 'payment',
343
- });
344
- if (isSettledSessionIntent(intent)) {
345
- // An earlier payment on this session already reached its outcome: there is nothing to confirm.
346
- console.log('Session settled with', intent.response.status);
347
- } else if (intent.provider === 'stripe') {
348
- console.log('Confirm the wallet payment with', intent.clientSecret);
349
- }
350
-
351
- await api.reportSessionIntentDecline('session_uuid', 'session_nonce', {
352
- provider: 'stripe',
353
- paymentMethodCategory: 'wallet',
354
- paymentMethodType: 'apple_pay',
355
- providerDeclineReason: 'payment_failed',
356
- });
357
- ```
358
-
359
143
  ## Public API
360
144
 
361
145
  ### Exports
362
146
 
363
147
  | Export | Description |
364
148
  |--------|-------------|
365
- | `loadFloPay(publishableKey, options?)` | Initializes the SDK and resolves a `FloPay`. Shares successful and in-flight work by key and options; failed work stays retryable. |
366
- | `FloPay` | Main SDK class, created by `loadFloPay()` |
367
- | `PaymentAPI` | Billing API client: `new PaymentAPI(billingApiUrl, { telemetry, stripeAccountSwitch })`; `stripeAccountSwitch` (default `false`) declares `stripe-account-switch-v1` on detached creates and claims |
149
+ | `loadCheckoutRuntime(options)` | Loads the Flo-hosted checkout runtime script once per runtime URL and resolves the runtime to mount |
368
150
  | `createCheckoutSession(options)` | Creates a checkout session and redirects. Resolves a `CheckoutSessionResult`. |
369
151
  | `createCheckoutSessionWithRetries(options)` | Like `createCheckoutSession`, with up to two retries (three attempts) inside one total deadline, using jittered exponential backoff |
370
- | `PciVaultCardCapture` | `CardCaptureAdapter` implementation that injects the billing API's hosted card form |
371
- | `CardCaptureOperation` | `'checkout'` / `'card_setup'` |
372
- | `PciVaultCardCaptureConfig` | Adapter configuration: `sessionId?`, `captureMethod?`, `operation?`, `expectedOrigin?`, `telemetry?` |
373
- | `StripeAdapter` | `PaymentProviderAdapter` implementation for Stripe |
374
- | `toStripeAppearance(appearance)` | Converts a `FloPayAppearance` into a `StripeSafeAppearance`, mapping FloPay's `theme` token (`'default'`, `'flat'`, `'night'`, `'none'`) onto Stripe's accepted set. Use it wherever you hand an appearance to Stripe Elements yourself. |
375
- | `toStripeAppearanceTheme(theme)` | Lower-level helper that maps a single FloPay `theme` token to Stripe's |
376
- | `StripeSafeAppearance` | An appearance Stripe Elements accepts |
377
152
  | `cacheSessionDisplayData(sessionId, data, options?)` | Stashes display-only session data client-side so it survives the redirect to a checkout page |
378
153
  | `getSessionDisplayData(sessionId)` | Reads cached display data, or `null` when none is cached or it expired |
379
154
  | `clearSessionDisplayData(sessionId)` | Drops cached display data, for example on the success page |
380
155
  | `SessionDisplayCacheData` | Display-only data stored by `cacheSessionDisplayData()` |
381
156
  | `dropThirdPartyOnlyError(event)` | Sentry `beforeSend` predicate that drops recognized third-party-only exception stacks and otherwise returns the original event |
382
157
 
383
- ### FloPay methods
384
-
385
- | Method | Returns | Description |
386
- |--------|---------|-------------|
387
- | `cardCapture(options?)` | `CardCaptureAdapter` | Creates a hosted card-form adapter bound to `sessionId` and `captureMethod` |
388
- | `retrieveSession(sessionId, billingApiUrl?)` | `Promise<CheckoutSession>` | Reads a session through `GET /v1/checkouts/sessions/{id}` |
389
- | `retrieveUnifiedSession(sessionId, billingApiUrl?)` | `Promise<NormalizedCheckoutSession>` | Reads and normalizes a session, including gateway data |
390
- | `getRawProvider()` | `unknown` | The underlying provider instance, such as the Stripe object |
391
- | `destroy()` | `void` | Tears down telemetry and the provider |
392
-
393
- ### PaymentAPI methods
394
-
395
- | Method | Returns | Description |
396
- |--------|---------|-------------|
397
- | `getUnifiedCheckoutSession(sessionId, nonce?)` | `Promise<NormalizedCheckoutSession>` | Reads and normalizes a session |
398
- | `getVaultCapture(sessionId, nonce?)` | `Promise<VaultCaptureBlock>` | Fetches the hosted card form when the session has no embedded `vault` block |
399
- | `createAndFetchSession(params)` | `Promise<NormalizedCheckoutSession>` | Creates an inline session and resolves once its catalog (and any supplied buyer) is attached |
400
- | `createDetachedSession(params)` | `Promise<DetachedCheckoutSession>` | Creates an inline session in two phases and exposes both |
401
- | `claimCheckoutSession(sessionId, nonce, payload)` | `Promise<NormalizedCheckoutSession>` | Sends a `PATCH /v1/checkouts/sessions/{id}/claim` |
402
- | `createSessionIntent(sessionId, nonce, request, options?)` | `Promise<SessionIntentResult>` | Creates a Stripe wallet/APM or direct-PayPal intent. If the session is still processing an earlier payment, resolves to `{ settled: true, response }` with that payment's outcome. |
403
- | `reportSessionIntentDecline(sessionId, nonce, request, options?)` | `Promise<void>` | Reports a non-card decline classification |
404
- | `resolvePaymentMethodLayout(sessionId, nonce, rules, options?)` | `Promise<PaymentMethodLayout \| null>` | Applies the merchant's layout rules to this buyer; `null` on a billing API without the route |
405
- | `processPayment(userId, params, options?)` | `Promise<Response>` | Submits a saved or approved non-card payment to `/process`; a `202` follows the advertised authenticated status endpoint and maps terminal attempt outcomes back to the existing process response shapes |
406
- | `waitForCheckoutSessionCompletion(sessionId, options?)` | `Promise<NormalizedCheckoutSession>` | Waits for terminal state; pass the session `nonce` and a processing response's `statusUrl` to reconcile attempt-level success, authorization, decline, buyer action, and failure. `timeoutMs` (15 seconds by default) stops normal polling. A read already in flight may still land during a grace of up to 15 more seconds; if it returns a terminal status, the SDK may start one follow-up session read to normalize the result. The entire operation remains capped by that grace |
407
- | `reportThreeDsAbandoned(sessionId)` | `void` | Records a saved-card 3DS challenge the buyer never finished as a buyer-abandonment outcome in Flo's privacy-safe telemetry, not as a technical failure. No-op when telemetry is off. The automatic payment button calls it for you |
408
- | `getPaymentsByEmail(email, options?)` | `Promise<{ data, total, page, limit }>` | Lists prior payments for an email |
409
- | `destroy()` | `void` | Tears down the client's telemetry |
410
-
411
- ### PciVaultCardCapture methods
412
-
413
- | Method | Description |
158
+ ### Types
159
+
160
+ | Type | Description |
161
+ |------|-------------|
162
+ | `LoadCheckoutRuntimeOptions` | Options for `loadCheckoutRuntime()`: the runtime script URL and how long it has to register |
163
+ | `CheckoutRuntime` | The loaded runtime; mount a checkout with it |
164
+ | `CheckoutRuntimeMountOptions` | What a checkout mount takes; see the table below |
165
+ | `CheckoutRuntimeHandle` | A mounted checkout: `update` and `unmount` |
166
+ | `CheckoutRuntimeUpdateOptions` | The options a mounted checkout accepts later |
167
+ | `CheckoutRuntimeEvent` | One runtime event, with its name and payload |
168
+ | `CheckoutRuntimeEventName` | The runtime event names |
169
+ | `CheckoutRuntimeLayout` | The checkout layouts a merchant chooses from |
170
+ | `CheckoutRuntimeAutomaticPayment` | The saved-payment mount option |
171
+ | `CardFieldsEvent` | The card-field lifecycle payload |
172
+
173
+ ### `CheckoutRuntimeMountOptions` options
174
+
175
+ | Option | Description |
414
176
  |--------|-------------|
415
- | `mount(container, { html, messageToken?, expectedOrigin?, submitLabel? })` | Injects the hosted card form |
416
- | `on(event, handler)` | Subscribes to `ready`, `complete`, `decline`, or `error` |
417
- | `onCardFields(handler)` | Subscribes to the card-field lifecycle (`card_fields_ready`, `card_fields_failed`); returns an unsubscribe function |
418
- | `unmount()` | Removes the form and its listeners |
419
- | `applyTheme(theme)` | Re-skins the mounted form; `null` is the classic reset |
420
- | `setSubmitGate(blocked)` | While `blocked`, the hosted form cancels its next submit and emits `blocked` so the host can validate its own fields (such as AVS) first |
421
- | `setCardFieldOrder(order, autoFocus)` | Reorders the hosted card rows (`name`, `number`, `expiry`); the first row is focused unless `autoFocus` is false |
422
- | `setCardBrandIcons(show)` | Shows the Visa, Mastercard, Amex and Discover icons in the hosted card number field when `show` is `true`; off by default |
423
- | `setShowCardFieldLabels(show)` | Shows the visible labels above the hosted card fields when `show` is `true`, live; nothing is sent until the host calls it |
424
- | `setCardFieldLabels(labels)` | Replaces the label text (`number`, `expiry`, `cvv`, `name`) live, sending only the string fields that were set; `null` restores the hosted defaults |
425
- | `setCardFieldPlaceholders(placeholders)` | Sets the hosted card fields' placeholder text live (`number`, `expiry`, `cvv`, `name`, each optional; `''` shows none); replayed on every `ready`; `undefined` sends nothing |
426
- | `setSubmitLabel(label)` | Sets the hosted submit wording live; `null` restores the session default |
177
+ | `publishableKey` | Your FloPay publishable key |
178
+ | `sessionId` | A session your server created |
179
+ | `nonce` | The session-bound token for that session |
180
+ | `createSession` | An inline-created session, used when no session id is given: the billing API's create body, sent as given |
181
+ | `appearance` | Theme settings, passed to the runtime unchanged |
182
+ | `strings` | Merchant wording overrides, applied over the wording the billing API returns |
183
+ | `onEvent` | Receives every runtime event |
184
+ | `paymentMethodLayout` | The merchant's payment method layout rules, resolved by the billing API for this buyer |
185
+ | `layout` | The checkout layout; left out, the runtime uses the default layout |
186
+ | `automaticPayment` | Runs an automatic or confirm saved payment on the buyer's click |
187
+ | `hiddenPaymentMethods` | Payment methods the runtime does not show, by method or group name, never by processor |
188
+ | `contractVersion` | The runtime contract version a wrapper was built against; wrappers set it |
189
+
190
+ ### Breaking changes in 2.0.0
191
+
192
+ `@flopay/js` 2.0.0 is the loader for the hosted checkout runtime. It runs no checkout inside the package, holds no business rules or buyer-facing wording, and depends on no payment processor SDK. Its public surface is `loadCheckoutRuntime()`, `createCheckoutSession()` and the re-exported public types. `@flopay/js`, `@flopay/react`, `@flopay/vue`, `@flopay/node` and `@flopay/shared` are released together as 2.0.0.
193
+
194
+ - PaymentAPI: `loadCheckoutRuntime()`, then `runtime.mount(...)`: the hosted runtime reads and creates sessions, claims them, and runs the payment. Its session reads (`getUnifiedCheckoutSession`, `retrieveUnifiedSession`), inline and detached creation (`createAndFetchSession`, `createDetachedSession`, `claimCheckoutSession`), intents and declines (`createSessionIntent`, `reportSessionIntentDecline`), layout resolution, `processPayment`, `waitForCheckoutSessionCompletion`, `getVaultCapture` and `getPaymentsByEmail` have no browser replacement. Its `stripeAccountSwitch` option is gone with it.
195
+ - PciVaultCardCapture: `loadCheckoutRuntime()`: the hosted runtime hosts the card fields. Its controls `setSubmitLabel(label)`, `setCardBrandIcons(show)`, `setShowCardFieldLabels(show)`, `setCardFieldLabels(labels)`, `setCardFieldPlaceholders(placeholders)`, `setCardFieldOrder(order, autoFocus)`, `setSubmitGate(blocked)` and `applyTheme(theme)` have no `@flopay/js` replacement: the runtime owns the card form, and `appearance` and `strings` on the mount style and word it. Its `onCardFields(handler)` lifecycle is the runtime's `cardFieldsReady` and `cardFieldsFailed` events.
196
+ - `StripeAdapter`: No replacement: the hosted runtime loads whatever processor it needs.
197
+ - `toStripeAppearance`, `toStripeAppearanceTheme`: Pass `appearance` and `theme` to the runtime mount unchanged; the runtime resolves them.
198
+ - `FloPay`, `loadFloPay`: `loadCheckoutRuntime()` for the payment surface and `createCheckoutSession()` for the session.
199
+ - runSavedCardChallenge, completeSavedCardNextAction, beginSavedCardChallengeTelemetry, `createSavedCardActionAbortedError`: No replacement: the hosted runtime runs saved-card challenges and reports them as runtime events.
200
+ - CheckoutGateways (`gateways.stripe`, `gateways.paypal`): `paymentMethods`: availability of `card`, `paypal`, `wallets` and `apms`, with no processor key and no processor publishable key. `gateways.stripe` becomes `card`, `wallets` and `apms`; `gateways.paypal` becomes `paypal`.
201
+ - `@stripe/stripe-js` is no longer a dependency, and the Stripe loader rejection telemetry that went with it is gone.
202
+
203
+ **Default checkout mode.** `createCheckoutSession()` with no `checkoutMode` now defaults to `'full'` (it was `'confirm'` in 1.x). An explicit `'confirm'`, `'auto'` or `'full'` is sent unchanged. Merchants who want the old default must set `checkoutMode: 'confirm'` and create the session from a server with merchant credentials (`@flopay/node` `checkout.sessions.createOneClick`), because a browser cannot hold those credentials.
427
204
 
428
205
  ## Errors
429
206
 
@@ -431,25 +208,17 @@ Failures reject with `FloPayError` from `@flopay/shared`. Branch on `type` and `
431
208
 
432
209
  | Code | Type | When |
433
210
  |------|------|------|
211
+ | `runtime_load_failed` | `network_error` | `loadCheckoutRuntime()` could not load the runtime script. |
212
+ | `runtime_load_timeout` | `network_error` | The runtime script loaded but did not register itself within `timeoutMs`. |
434
213
  | `CurrencyRequired` | `validation_error` | Session creation could not resolve a currency from the session, items, subscriptions, or products. Thrown before any request. |
435
214
  | `CouponLimitExceeded` | `validation_error` or `api_error` | More than five coupon codes were supplied: a `validation_error` before the request, or an `api_error` from the billing API. |
436
215
  | `CouponCurrencyUnsupported` | `api_error` | An amount-based coupon has no price in the cart currency. |
437
216
  | `CaptureMethodUnsupportedForSubscription` | `validation_error` | Manual capture was requested for a cart with a subscription. |
438
217
  | `InvalidIdempotencyKey` | `validation_error` | A supplied `idempotencyKey` is blank or longer than 255 characters. Thrown before any request. |
439
218
  | `IdempotencyKeyInProgress` | `api_error` | The same key is still being processed. Retried automatically with the same key within the deadline. |
440
- | `MissingCheckoutSessionToken` | `validation_error` or `api_error` | A continuation call was made without the session nonce, or the billing API created a session without returning one. |
441
- | `BuyerEmailCollectionRequired` | `validation_error` | A buyer email supplied for creation or a late claim is not a valid email address. |
442
- | `checkout_session_data_attachment_required` | `api_error` | A process, intent, or decline call was made before the detached session's catalog claim settled (HTTP 409). Wait for `claimed`. |
443
- | `InvalidSessionIntentRequest` | `validation_error` | An intent request is not a supported non-card or PayPal request. |
444
- | `InvalidAuthorizationAttemptId` | `validation_error` | An intent request's authorization attempt id is not a valid UUID. |
445
- | `InvalidSessionIntentDeclineRequest` | `validation_error` | A decline report carries anything other than safe classification codes. |
446
- | `InvalidSessionIntentResponse` | `api_error` | The billing API returned an intent that does not match the request. |
447
- | `InvalidCheckoutSessionResponse` | `api_error` | The billing API returned a malformed session or no session id. |
219
+ | `MissingCheckoutSessionToken` | `validation_error` or `api_error` | The billing API created a session without returning its session token. |
448
220
  | `session_auto_completed` | `api_error` | Inline creation found a payment method already on file and completed the session without a checkout. |
449
- | `checkout_processing_timeout` | `api_error` | The SDK could not get a terminal answer in time, so the payment's outcome is not known yet and it may still complete. Do not resubmit or offer the buyer a retry: reconcile from `payment.*` webhooks or read the session again. The buyer-facing message says the payment is still being confirmed. When `createSessionIntent` raises it because the session was still processing an earlier payment, it also carries `statusCode: 202` and the `sessionId`. |
221
+ | `checkout_processing_timeout` | `api_error` | The SDK could not get a terminal answer in time, so the payment's outcome is not known yet and it may still complete. Do not resubmit or offer the buyer a retry: reconcile from `payment.*` webhooks or read the session again. The buyer-facing message says the payment is still being confirmed. |
450
222
  | `stored_payment_method_unsupported` | `api_error` | The backend-selected saved method cannot be used for this transaction. Ask the buyer to choose another payment method; the SDK does not silently change payment behavior. |
451
- | `vault_capture_timeout` | `api_error` | `getVaultCapture()` did not return the hosted card form within ten seconds. |
452
- | `card_capture_no_window` | `api_error` | `PciVaultCardCapture.mount()` ran outside a browser. |
453
- | `card_capture_no_widget_html` | `api_error` | `PciVaultCardCapture.mount()` was called without hosted form HTML. |
454
223
 
455
- Card declines are not thrown: they arrive as the card form's `decline` event with a `declineReason`, and technical failures as its `error` event. A product or coupon rejected during the detached catalog claim surfaces as the billing API's `422` error from `claimed`.
224
+ Card declines are not thrown: they arrive as the runtime's `decline` event with a `declineReason`, and technical failures as its `error` event.