@sunbay/checkout-sdk-js 0.0.5 → 0.0.7

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,14 +1,8 @@
1
1
  # @sunbay/checkout-sdk-js
2
2
 
3
- Browser JS SDK for embedding **Sunbay Checkout** into merchant web pages. It
4
- renders the payment UI inside secure, Sunbay-hosted iframes, so merchants can
5
- accept a growing range of payment methods while sensitive payment details never
6
- touch the merchant page. This keeps your integration PCI-compliant and your
7
- customers' data protected out of the box.
8
-
9
- `createCheckout` is the single entry point: you create a checkout session
10
- server-side, hand the resulting `sessionId` to the browser, mount Elements into
11
- your DOM, and confirm the payment.
3
+ Browser JS SDK for embedding **Sunbay Checkout** into merchant web pages. Payment UI
4
+ renders inside Sunbay-hosted iframes, so card data never touches your page (PCI scope
5
+ stays out of your integration).
12
6
 
13
7
  ## Install
14
8
 
@@ -16,57 +10,188 @@ your DOM, and confirm the payment.
16
10
  npm install @sunbay/checkout-sdk-js
17
11
  ```
18
12
 
19
- The protocol contract ([`@sunbay/checkout-sdk-protocol`](https://www.npmjs.com/package/@sunbay/checkout-sdk-protocol))
20
- comes in transitively — you do not need to install it separately.
13
+ The protocol types (`@sunbay/checkout-sdk-protocol`) come in transitively.
21
14
 
22
15
  ## Quick start
23
16
 
24
- A checkout session is created **server-side** by your backend (it holds the
25
- merchant API key). The browser only ever receives a `sessionId`.
17
+ Create the checkout session **server-side** (your backend holds the API key, and creates the
18
+ session with `sessionType: 'embedded'`) and pass the `sessionId` and the returned
19
+ `checkoutClientSecret` to the browser.
26
20
 
27
21
  ```ts
28
22
  import { createCheckout } from '@sunbay/checkout-sdk-js';
29
23
 
30
- // 1. Create the checkout instance from a server-created session.
31
- const checkout = await createCheckout({
32
- sessionId, // from your backend
33
- });
24
+ const checkout = await createCheckout({ sessionId, checkoutClientSecret, env: 'test' });
34
25
 
35
- // 2. Mount Elements into your DOM.
36
26
  await checkout.create('cardNumber').mount('#card-number');
37
27
  await checkout.create('cardExpiry').mount('#card-expiry');
38
28
  await checkout.create('cardCvc').mount('#card-cvc');
39
29
 
40
- // Express wallets (Apple Pay / Google Pay) render their own buttons.
41
- const express = checkout.create('expressCheckout');
42
- express.on('expressAvailabilityChange', (evt) => {
43
- console.log('available wallets:', evt.availableWallets);
44
- });
45
- await express.mount('#express');
46
-
47
- // 3. Confirm a card payment; the result arrives as a PaymentOutcome.
48
- checkout.on('paymentResult', (evt) => console.log(evt));
30
+ checkout.on('paymentResult', (evt) => console.log(evt.outcome));
49
31
  const outcome = await checkout.confirm();
50
32
  ```
51
33
 
52
- ## Public API
34
+ ### `createCheckout` options
35
+
36
+ | Option | Description |
37
+ | --- | --- |
38
+ | `sessionId` | Required. Server-created session id. |
39
+ | `checkoutClientSecret` | Required. Returned by your backend's `create-session` when `sessionType` is `'embedded'`. Pass it to the browser over an authenticated HTTPS response only; never put it in a URL or write it to logs. A missing, blank or non-string value rejects with `INVALID_OPTIONS`. |
40
+ | `env` | `'dev' \| 'test' \| 'prod'` (default `'prod'`). Selects the hosted origin. |
41
+ | `hostOrigin` | Overrides the hosted origin (takes precedence over `env`), e.g. `http://localhost:3000`. |
42
+ | `locale` | UI locale, e.g. `'en-US'`, `'zh-CN'`. |
43
+ | `appearance` | `{ variables, rules, colorScheme }` (whitelisted design variables, no arbitrary CSS). |
44
+ | `paymentMethods` | `{ hide?: string[]; order?: string[] }` - subtract/sort only. |
45
+
46
+ The hosted runtime must serve `/embed/sdk/*` (SDK >= 0.0.7). Deploy the runtime before upgrading the SDK.
47
+
48
+ ## Elements
49
+
50
+ `checkout.create(type, options?)` returns a handle; call `mount(target, { timeoutMs? })`
51
+ with a CSS selector or an empty `HTMLElement`.
52
+
53
+ | Type | Options | Notes |
54
+ | --- | --- | --- |
55
+ | `card` | `showBillingAddress`, `showShippingAddress`, `showPostalCode`, `appearance` | Combined card form. Exclusive with split fields. |
56
+ | `cardNumber` / `cardExpiry` / `cardCvc` | `appearance` | Split fields. Exclusive with `card`. |
57
+ | `address` | `mode: 'billing' \| 'shipping'` (required), `appearance` | One per mode. |
58
+ | `expressCheckout` | `paymentMethods.applePay` / `googlePay` (`false` hides; or `{ buttonTheme, buttonType }`), `layout.maxColumns`, `buttonHeight` (30-64, default 40) | Singleton. Wallet buttons. |
59
+
60
+ Handle methods: `mount`, `unmount`, `update(patch)`, `destroy`, `getStatus`,
61
+ `getAvailableWallets` (express), `on`, `off`. A conflicting `create` throws `ELEMENT_CONFLICT`.
62
+
63
+ ## Events
64
+
65
+ `checkout.on(name, handler)` and `element.on(name, handler)` are typed by event name
66
+ (`EventPayloadMap`). `element.on` only receives events whose `elementId` is that
67
+ element's; payloads without an `elementId` pass through. Events are not replayed after
68
+ registration. Handler exceptions are isolated and rethrown asynchronously (they reach
69
+ `window.onerror` and never break other listeners).
70
+
71
+ | Event | Payload | Fired when |
72
+ | --- | --- | --- |
73
+ | `elementReady` | `{ elementId, availableWallets? }` | Element finished loading. |
74
+ | `ready` | `{ elementId }` | Input field is ready for input. |
75
+ | `change` | `{ elementId, empty, complete, error?, brand? }` | Field state changes (never the value). |
76
+ | `focus` / `blur` | `{ elementId }` | Field focus changes. |
77
+ | `loadError` | `{ elementId, error }` | Element failed to load. |
78
+ | `expressAvailabilityChange` | `{ availableWallets }` | Wallet availability changes. |
79
+ | `paymentStateChange` | `{ operationId, method, state, action? }` | Intermediate state, e.g. requires action. |
80
+ | `paymentResult` | `{ operationId, method, outcome }` | A payment outcome was produced. |
81
+ | `error` | `{ operationId?, method?, stage?, error }` | Asynchronous error (wallet flows etc.). |
82
+
83
+ ## Payment result semantics
84
+
85
+ `await checkout.confirm(opts?)` resolves **only** on a terminal outcome:
86
+ `succeeded`, `failed` or `canceled`. If none arrives within the watchdog (default
87
+ 120 s; per call `resultTimeoutMs`) it resolves `{ status: 'pending', operationId }`.
88
+
89
+ - `pending` or any unknown state is **not a failure**. Do **not** retry or let the user
90
+ pay again. Reconcile with `getPaymentStatus()` (`txnStatus`: `I|S|F|R`) and wait for the
91
+ terminal `paymentResult` event.
92
+ - The confirm slot stays held (`CHECKOUT_BUSY`) until a terminal result arrives, or you
93
+ call `destroy()` and create a new instance with `createCheckout`. This also applies
94
+ after the watchdog resolved `pending`.
95
+ - If the `confirm` command itself times out, the Promise rejects with
96
+ `paymentStateKnown: false`: reconcile, do not retry. Use `confirm({ onOperation })` to
97
+ capture the `operationId` early.
98
+
99
+ ### Express wallets
100
+
101
+ A wallet button click has no Promise. Listen for **both** `paymentResult` and `error`
102
+ on the instance. What is emitted depends on where the failure happens:
103
+
104
+ - Pre-submit wallet failures (merchant validation, authorization, runtime) emit **both**
105
+ `error` and a failed `paymentResult`, sharing `operationId` and `error.errorId`;
106
+ de-duplicate by `operationId`.
107
+ - Definitive backend rejections after submit emit only `paymentResult(failed)`, with
108
+ `backendCode` / `traceId` in `outcome.error`.
109
+ - Unknown states (5xx / network) emit `paymentResult(pending)` plus
110
+ `error { paymentStateKnown: false }`.
111
+ - A second authorization while another payment is in flight emits only `error`
112
+ (`CHECKOUT_BUSY`) and no failed `paymentResult`.
113
+
114
+ ```ts
115
+ const seen = new Set<string>();
116
+ checkout.on('paymentResult', (e) => {
117
+ if (seen.has(e.operationId)) return;
118
+ seen.add(e.operationId);
119
+ showOutcome(e.outcome);
120
+ });
121
+ checkout.on('error', (e) => {
122
+ if (e.operationId && seen.has(e.operationId)) return; // already handled
123
+ reportError(e.error, e.method, e.stage);
124
+ });
125
+ ```
126
+
127
+ Cancel (`outcome.status === 'canceled'`) emits only `paymentResult`, no `error`.
128
+
129
+ **Apple Pay:** when the final state is unknown the Apple Pay sheet closes as completed
130
+ while the SDK reports `pending`. Show your own "processing, do not pay again" UI.
131
+
132
+ ### Errors (`CheckoutError`)
53
133
 
54
- | Export | Description |
134
+ | Field | Meaning |
55
135
  | --- | --- |
56
- | `createCheckout(options)` | Creates a `CheckoutInstance` from a server-created session. Options include `sessionId` and `env` (`'test' \| 'prod'`). |
57
- | `CheckoutInstance` | The checkout handle: `create(elementType)`, `confirm()`, `on(event, handler)`, `update(...)`, `destroy()`. |
58
- | `CheckoutElement` | A mounted UI element handle: `mount(selector)`, `update(...)`, `on(...)`, `destroy()`. |
59
- | `version` | The SDK version string. |
60
- | Protocol types | Public TS types re-exported from `@sunbay/checkout-sdk-protocol` (`PaymentOutcome`, `PublicSessionView`, `Appearance`, `ElementType`, `ElementOptions`, `CheckoutError`, …). |
136
+ | `code`, `message` | Stable SDK code and display message. |
137
+ | `category` | `configuration \| validation \| network \| runtime \| payment`. |
138
+ | `errorId` | Unique id; shared by the `error` event and failed `paymentResult`. |
139
+ | `traceId` | Backend trace id, when available (quote it to support). |
140
+ | `backendCode` | Backend business code passthrough. |
141
+ | `providerCode` | Sanitized wallet provider error name. |
142
+ | `paymentStateKnown` | `false`: outcome unknown, reconcile before any retry. |
143
+
144
+ The `error` event also carries `method` (`'card' \| 'applePay' \| 'googlePay'`) and
145
+ `stage` (`WalletErrorStage`): `merchantValidation`, `authorization`, `submit`, `poll`,
146
+ `runtime`. `availability` is reserved and not emitted yet. `stage` may also be set for
147
+ card confirms (`submit` / `poll`).
148
+
149
+ ### Runtime behavior changes (apply to all SDK versions once the hosted runtime is deployed)
150
+
151
+ - The submit lock stays held after an unknown payment state (5xx / network) until a terminal
152
+ result, so a retry gets `CHECKOUT_BUSY`. Reconcile with `getPaymentStatus()` and wait.
153
+ - Pre-submit wallet failures emit **both** `error` and a failed `paymentResult` with the same
154
+ `operationId` / `errorId`; de-duplicate by `operationId`.
155
+ - The Apple Pay sheet closes as completed when the final state is unknown (the SDK reports
156
+ `pending`). Show a "processing, do not pay again" UI.
157
+ - Polling continues past the 120 s diagnostic deadline.
158
+ - If you allowlist hosted **paths** (WAF / CSP `frame-src`) rather than the origin, allow
159
+ `/embed/sdk/*`. A block shows up as a 15 s `RUNTIME_LOAD_FAILED`. Legacy `/sdk/*` is still
160
+ served for SDK <= 0.0.5.
161
+
162
+ ### Redirect / 3DS
163
+
164
+ `paymentStateChange` may carry an `action`. The SDK **does not** perform redirects or
165
+ challenges: it only emits the event. Your page must handle the action.
166
+
167
+ ## Lifecycle
168
+
169
+ - `mount(target, { timeoutMs })` times out after 30 s by default: the iframe is removed
170
+ and it rejects `RUNTIME_LOAD_FAILED`.
171
+ - `unmount()` / `destroy()` while an element is loading rejects the in-flight `mount()`
172
+ (`RUNTIME_LOAD_FAILED` / `INSTANCE_DESTROYED`). If you call `mount()` without
173
+ `catch`/`await`, that surfaces as an **unhandled rejection**; always handle it.
174
+ - `checkout.updateCheckout({ locale?, appearance? })` hot-switches locale/appearance.
175
+ - `getSession()`, `refresh()`, `getPaymentStatus()` read session/payment state.
176
+ - `checkout.destroy()` is idempotent, removes all iframes, and later calls reject/throw
177
+ `INSTANCE_DESTROYED`. Calling `destroy()` while a `confirm()` is pending rejects that
178
+ `confirm()` with `INSTANCE_DESTROYED`.
179
+
180
+ ## Behavior changes in 0.0.7
181
+
182
+ - `confirm()` resolves only terminal outcomes or the watchdog `pending` (see above); the
183
+ slot is held until terminal or `destroy()`.
184
+ - `mount()` has a timeout (`timeoutMs`, default 30 s) and cancellation semantics.
185
+ - `on()` is typed per event name; `element.on` is scoped to its `elementId`.
186
+ - Hosted pages are loaded from `/embed/sdk/*`; deploy the runtime first.
187
+ - Listener errors are rethrown asynchronously instead of being swallowed.
188
+ - Handshake only accepts messages from the SDK's own runtime iframe.
61
189
 
62
190
  ## Security model
63
191
 
64
- Card data is entered only inside Sunbay-hosted iframes and is encrypted and sent
65
- directly to Sunbay — it is never exposed to the merchant page or passed across
66
- the SDK boundary. This keeps the merchant integration out of PCI card-data
67
- scope.
192
+ Card data is entered only in Sunbay-hosted iframes, encrypted and sent straight to
193
+ Sunbay. It never crosses the SDK boundary or reaches your page.
68
194
 
69
195
  ## Versioning
70
196
 
71
- The JS SDK and the protocol contract are released **in lockstep** and always
72
- share the same version number.
197
+ The JS SDK and the protocol contract are released in lockstep with the same version.