@strabl-engineering/strabl-web-sdk 0.0.0-stage → 1.0.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/README.md CHANGED
@@ -1,3 +1,333 @@
1
- # Temporary Holding Version
1
+ # Strabl Web SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Accept cards, Apple Pay, Google Pay, Tabby and Tamara on your site with a secure payment form hosted by Strabl. Card number, expiry and CVC never touch your page, so no script on your site (including compromised third-party scripts) can read them. Your page only receives events such as "ready", "card brand is Visa" or "payment succeeded".
4
+
5
+ ## How the charge is decided
6
+
7
+ Your **backend** creates a session with your secret key. The browser never sets or sends an amount, so nobody can change what is charged from the page.
8
+
9
+ ```bash
10
+ curl -X POST "https://api.strabl.com/v1/api/direct/sessions" \
11
+ -H "Authorization: sk_live_…" \
12
+ -H "Content-Type: application/json" \
13
+ -H "Idempotency-Key: order-1001" \
14
+ -d '{
15
+ "amount": 125.50,
16
+ "currency": "AED",
17
+ "description": "Order 1001",
18
+ "redirectUrl": "https://shop.example/checkout",
19
+ "metadata": { "orderId": "1001" }
20
+ }'
21
+ ```
22
+
23
+ - Send the secret key as it is in `Authorization` (no `Bearer` prefix). Use `https://sandbox.api.strabl.com` with `sk_test_…` keys.
24
+ - `Idempotency-Key` is optional: a retried call with the same key returns the same session instead of creating a second one.
25
+ - `redirectUrl` must be `https://`.
26
+
27
+ The response:
28
+
29
+ ```json
30
+ {
31
+ "code": "2000",
32
+ "message": "Operation completed successfully",
33
+ "data": {
34
+ "sessionId": "dps_…",
35
+ "clientSecret": "…",
36
+ "amount": 125.5,
37
+ "currency": "AED",
38
+ "status": "CREATED",
39
+ "expiresAt": "2026-01-01T12:30:00Z"
40
+ }
41
+ }
42
+ ```
43
+
44
+ Pass `data.sessionId` and `data.clientSecret` to the page. The client secret is returned only once; never log it or put it in a URL. A session expires after 30 minutes and can be paid once. A declined card leaves it open for another card.
45
+
46
+ **Always set `redirectUrl`** to your checkout page. Cards that need 3-D Secure send the payer away and back to it (with a `key=ref_…` parameter you can ignore), and without it the payment cannot be resumed.
47
+
48
+ ## Before you start
49
+
50
+ In the Strabl dashboard, add every origin that shows the payment form (for example `https://shop.example`) to the publishable key's allowed origins. The form refuses to render anywhere else.
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ npm install @strabl-engineering/strabl-web-sdk
56
+ ```
57
+
58
+ Or with a script tag, which defines `window.StrablElements`:
59
+
60
+ ```html
61
+ <script src="https://cdn.jsdelivr.net/npm/@strabl-engineering/strabl-web-sdk@1.0.0/dist/strabl-elements.js"></script>
62
+ ```
63
+
64
+ There are two ways to use it. Both run the same UI:
65
+
66
+ - **Custom element and React**: a ready-made form that handles 3-D Secure,
67
+ Tabby and Tamara redirects for you.
68
+ - **StrablElements API**: lower level; you own the Pay button and the
69
+ redirects.
70
+
71
+ ## Custom element and React
72
+
73
+ The simplest way: a ready-made form that takes the session as props and, after
74
+ 3-D Secure, redirects and resumes the session by itself.
75
+
76
+ ```tsx
77
+ import { StrablCardPaymentForm } from "@strabl-engineering/strabl-web-sdk/react";
78
+
79
+ <StrablCardPaymentForm
80
+ apiKey="pk_live_…"
81
+ sessionId={sessionId}
82
+ clientSecret={clientSecret}
83
+ language="en"
84
+ onPaymentSuccess={(orderShortCode, tx) => {
85
+ /* confirm on your server, then fulfil */
86
+ }}
87
+ onPaymentFailed={(reason, code) => {}}
88
+ />;
89
+ ```
90
+
91
+ ```js
92
+ import { strablCardForm } from "@strabl-engineering/strabl-web-sdk";
93
+
94
+ const form = strablCardForm({
95
+ selector: "#payment",
96
+ apiKey: "pk_live_…",
97
+ sessionId,
98
+ clientSecret,
99
+ });
100
+ form.submit();
101
+ form.refresh(); // after your server re-priced the session
102
+ form.destroy();
103
+ ```
104
+
105
+ Or as an element:
106
+ `<strabl-card-form apikey="pk_live_…" sessionid="dps_…" clientsecret="…" merchantname="Demo Store" countrycode="SA">`.
107
+
108
+ HTML attributes (lowercase): `apikey`, `platformuuid`, `sessionid`, `clientsecret`, `language`, `fieldinputstyle`, `enableemailcollection`, `enablesavecard` (`"false"` turns them off), `merchantname`, `countrycode`, `elementsurl`. Arrays, objects and callbacks (`paymentMethods`, `customstyles`, `inputStyle`, `fonts`, `on…`) are set as properties.
109
+ The element and `strablCardForm`'s result both have `submit()`, `refresh()` and `update(options)`. `strablCardForm` also takes `replace: true` (replace the target's children instead of appending) and returns `destroy()`.
110
+
111
+ To resume after 3-D Secure, render the form on the session's `redirectUrl` page with the **same** `sessionId` and `clientSecret`. Your server keeps them with the order, so the page can get them again.
112
+
113
+ | Option | Type | Notes |
114
+ | -------------------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
115
+ | `apiKey` | `string` | Publishable key. Required. |
116
+ | `sessionId`, `clientSecret` | `string` | From your server's session call. Required. |
117
+ | `platformUuid` | `string` | Optional, not a secret. The form reads your dashboard SDK settings sooner; their payment methods and saving cards win over these options. See "Tabby and Tamara". |
118
+ | `language` | `"en" \| "ar"` | Arabic switches to right-to-left. |
119
+ | `fieldInputStyle` | `"outlined" \| "floating-label"` | |
120
+ | `customstyles` | object | Same keys as v1; see "Styling and fonts". |
121
+ | `inputStyle` | `{ base, focus, invalid, placeholder }` | The per-state `style` option (named so because `style` is taken on elements). |
122
+ | `fonts` | `FontSource[]` | Web fonts for the form; see "Styling and fonts". |
123
+ | `paymentMethods` | `("card" \| "applepay" \| "googlepay")[]` | Default `["card"]`. See "Amount, Apple Pay and Google Pay". With nothing payable, the card is offered. Tabby / Tamara come from your dashboard settings. |
124
+ | `enableEmailCollection` | `boolean` | Default `true`: the payer's email (and a one-time code that finds their saved cards) is asked above the methods. `false` hides it; Tabby then asks for its own email. |
125
+ | `enableSaveCard` | `boolean` | Default `true`: a new card shows "Save this card" (unticked); ticked, the email becomes required. `false` never saves a new card; saved cards are still offered. |
126
+ | `merchantName`, `countryCode` | `string` | Your name and country (ISO alpha-2) on the Apple Pay sheet. |
127
+ | `onPaymentSubmission` | `() => boolean \| Promise<boolean>` | Runs after the card fields are valid; return `false` to stop. |
128
+ | `onPaymentSuccess` | `(orderShortCode, tx) => void` | |
129
+ | `onPaymentFailed` | `(reason, code) => void` | `code` is an API status or error code; see "Errors". |
130
+ | `onReady`, `onChange`, `onError` | callbacks | `onReady` gets the methods offered. `onChange` gets brand, `complete`, `empty`, `paymentMethod` and error codes, never digits. `onError(code, message)`. |
131
+ | `elementsUrl` | `string` | Payment form origin, for local development only (e.g. `http://localhost:5173`). |
132
+ | `className`, `style` | React only | Set on the `<strabl-card-form>` element. |
133
+
134
+ DOM events (they bubble): `strablReady`, `strablChange`, `strablFocus`, `strablBlur`, `strablProcessing` (detail: `true`/`false`), `strablResult`, `strablPaymentSuccess` (detail: order short code), `strablPaymentFailed` (detail: reason), `strablError` (detail: `{ code, message }`).
135
+
136
+ ## StrablElements API
137
+
138
+ You own the Pay button and call `confirm`:
139
+
140
+ ```html
141
+ <form id="pay-form">
142
+ <div id="card"></div>
143
+ <button id="pay" disabled>Pay AED 125.50</button>
144
+ </form>
145
+
146
+ <script type="module">
147
+ const elements = StrablElements("pk_live_…");
148
+ const card = elements.create("card", {
149
+ style: { base: { color: "#0f172a", "font-size": "15px" } },
150
+ });
151
+ card.mount("#card");
152
+
153
+ const pay = document.getElementById("pay");
154
+ card.on("change", (state) => (pay.disabled = !state.complete));
155
+
156
+ document
157
+ .getElementById("pay-form")
158
+ .addEventListener("submit", async (event) => {
159
+ event.preventDefault();
160
+ try {
161
+ const tx = await card.confirm({ sessionId, clientSecret });
162
+ if (tx.status === "AUTHORIZED" && tx.threeDsUrl) {
163
+ window.location.assign(tx.threeDsUrl); // resume on return
164
+ } else {
165
+ showReceipt(tx.orderShortCode);
166
+ }
167
+ } catch (error) {
168
+ showError(error.code ?? error.message);
169
+ }
170
+ });
171
+ </script>
172
+ ```
173
+
174
+ **3-D Secure.** When the card needs it, `confirm` resolves with `status: "AUTHORIZED"` and a `threeDsUrl`: Strabl's verification page, or the gateway's. Send the payer there. (If neither exists, the form shows the bank's check over your page itself, and `confirm` resolves with the final transaction.)
175
+
176
+ After a redirect the payer lands on the session's `redirectUrl`. The page is fresh and the card is gone, but the session remembers the attempt. Mount the element again and resume:
177
+
178
+ ```js
179
+ const card = StrablElements("pk_live_…").create("card");
180
+ card.mount("#card"); // no card data needed
181
+ const tx = await card.resume({ sessionId, clientSecret });
182
+ ```
183
+
184
+ If authentication failed, `resume` rejects and the session is open again: let the payer try another card with `confirm`.
185
+
186
+ | Member | Notes |
187
+ | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
188
+ | `StrablElements(pk, { platformUuid?, language?, elementsUrl? })` | `platformUuid`: see the options table above. `language`: the default for every element. `elementsUrl` only for local development. |
189
+ | `elements.create("card", options)` | Options: `style`, `customstyles`, `fonts`, `language`, `fieldInputStyle`, `paymentMethods`, `enableEmailCollection`, `enableSaveCard`, `session`, `merchantName`, `countryCode`. |
190
+ | `mount(target)` | Selector or element. |
191
+ | `on(event, listener)` | `ready`, `change`, `focus`, `blur`, `result`, `error`. Returns `off()`. |
192
+ | `confirm({ sessionId, clientSecret })` | Resolves with the transaction; rejects with a `StrablError` (`code`). |
193
+ | `resume({ sessionId, clientSecret })` | After 3-D Secure. Same result as `confirm`. |
194
+ | `focus(field)` | `name`, `number`, `expiry`, `cvv` (or `cardHolderName`, `cardNumber`, `cvc`). |
195
+ | `clear()`, `update(options)` | `update` takes the same options as `create`. |
196
+ | `refresh()` | Reads the session again, e.g. after your server changed its amount. |
197
+ | `destroy()` | Removes the form; a pending `confirm` rejects. |
198
+
199
+ The transaction has `status`, `orderShortCode`, `paymentReference`, `amount`,
200
+ `currency` and, when the payer must authenticate, `threeDsUrl` (with
201
+ `provider: "TABBY" | "TAMARA"` when that URL is an instalment checkout). The
202
+ `change` event gives `{ complete, empty, brand, errors, paymentMethod }`, never
203
+ digits.
204
+
205
+ `create("card", options)` options:
206
+
207
+ | Option | Notes |
208
+ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |
209
+ | `style` | Per-state input styles; see "Styling and fonts". (`inputStyle` on the component.) |
210
+ | `session` | `{ sessionId, clientSecret }`. Needed up front for Apple Pay and Google Pay; cards can get it from `confirm`. |
211
+ | `language`, `fieldInputStyle`, `paymentMethods`, `customstyles`, `fonts` | As in the options table above. |
212
+ | `enableEmailCollection`, `enableSaveCard`, `merchantName`, `countryCode` | As in the options table above. |
213
+
214
+ ## Styling and fonts
215
+
216
+ **`style`** (`inputStyle` on the component) sets the inputs per state:
217
+ `base`, `focus`, `invalid`, and `placeholder` (colour only). Allowed
218
+ properties: `color`, `background-color`, `font-family`, `font-size`,
219
+ `font-weight`, `font-style`, `letter-spacing`, `line-height`, `text-align`,
220
+ `padding` (and its sides), `border`, `border-width`, `border-style`,
221
+ `border-color`, `border-radius`, `box-shadow`. Values may not contain `;`,
222
+ `{`, `}`, `@`, `url(…)` or other functions except `rgb()`/`hsl()`. Each one is
223
+ set as a single style property, never written into a stylesheet. Anything
224
+ rejected is reported on the console and ignored.
225
+
226
+ ```js
227
+ elements.create("card", {
228
+ style: {
229
+ base: {
230
+ color: "#0f172a",
231
+ "font-size": "15px",
232
+ border: "1px solid #cbd5e1",
233
+ },
234
+ focus: { "border-color": "#0ea5e9" },
235
+ invalid: { "border-color": "#dc2626" },
236
+ placeholder: { color: "#94a3b8" },
237
+ },
238
+ });
239
+ ```
240
+
241
+ **`customstyles`** themes the whole form with v1's keys:
242
+
243
+ | Key | Accepts | Applies to |
244
+ | ----------------------------------------------------- | -------------------------- | -------------------------------------------------------------------- |
245
+ | `textColor` | color | Titles, labels, typed text |
246
+ | `errorColor` | color | Error borders and messages |
247
+ | `accentColor` | color | Focused field border, Pay button |
248
+ | `backgroundColor` | color | Form, inputs, floating labels |
249
+ | `inputBorderColor`, `inputBorderWidth`, `inputRadius` | color, length, 1–4 lengths | Inputs |
250
+ | `btnRadius`, `btnPadding` | 1–4 lengths | Pay button |
251
+ | `continerMaxWidth` | length | Form width (v1 spelling kept) |
252
+ | `fontFamily` | font-family list | All text, including typed text and the button |
253
+ | `secondaryFontFamily` | font-family list | Option labels, notes, buttons (default Inter; else `fontFamily`) |
254
+ | `primaryColor` | color | Selected options, links, radios and checkbox (default `#9B03D0`) |
255
+ | `headingColor`, `mutedTextColor` | color | "Enter OTP" and alert text; notes (`#100C08`, `#8F8F8F`) |
256
+ | `labelColor`, `selectedLabelColor` | color | Option and card labels, unselected / selected (`#454545`, `#000000`) |
257
+ | `borderColor` | color | Dividers and unselected option cards (`#E4E1DE`) |
258
+ | `containerBorderColor`, `containerRadius` | color, 1–4 lengths | The border around the form (23% `#100C08`, `12px`) |
259
+ | `successColor` | color | "OTP resent" tick (`#2E7D32`) |
260
+ | `failureColor`, `failureBackgroundColor` | color | "Transaction Failed" alert (`#C00F0C`, 30% `#FDD3D0`) |
261
+ | `footerTextColor` | color | "Powered & Secured by" (`#5E5A56`) |
262
+
263
+ Colors: hex, `rgb()`/`rgba()`, `hsl()`/`hsla()` or a color name. Lengths:
264
+ `px`, `rem`, `em`, `%`, `vh`, `vw` or `0`.
265
+
266
+ **Fonts must be passed in `fonts`.** The form is hosted by Strabl, so fonts your page has loaded are not available to it:
267
+
268
+ ```js
269
+ fonts: [
270
+ { cssSrc: "https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap" },
271
+ // or your own files (HTTPS, .woff2/.woff/.ttf/.otf, served with CORS):
272
+ { family: "Brand Sans", src: "https://cdn.shop.example/brand-sans.woff2", weight: "400" },
273
+ ],
274
+ ```
275
+
276
+ Without `fonts`, a font family only works if it is installed on the payer's device. GT-America is built in. Up to 10 font sources are accepted.
277
+
278
+ ## Errors
279
+
280
+ | `code` | Meaning |
281
+ | -------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
282
+ | `invalid_card` | The fields are incomplete or invalid; nothing was charged. |
283
+ | `CR-0xx` | The API rejected the card details (e.g. `CR-013` expired). |
284
+ | `CAPTURE_FAILED`, `AUTHORIZATION_FAILED`, `CANCELLED` | Declined or not authenticated; the session is open again. |
285
+ | `PR-041` | Session not found or expired: create a new one. |
286
+ | `PR-042` | Wrong `clientSecret`. |
287
+ | `PR-043` | The session is already paid. |
288
+ | `PR-044` | Another attempt on this session is in flight; retry. |
289
+ | `PR-045` / `PR-046` | Call `resume` / `confirm` instead. |
290
+ | `APK-003` | This page's origin is not allowed for the key. |
291
+ | `APK-005` | Wrong key type: use the publishable key in the browser. |
292
+ | `unsupported_3ds` | The gateway asked for a 3DS step the SDK cannot open. |
293
+ | `amount_changed` | The session was re-priced while the Apple Pay sheet was open; nothing was charged. |
294
+ | `apple_pay_failed` | Apple Pay could not start (e.g. merchant validation failed). |
295
+ | `payment_in_progress`, `submission_cancelled`, `network_error` | As named. |
296
+
297
+ ## Amount, Apple Pay and Google Pay
298
+
299
+ The form reads the session's amount from the API and shows it on its Pay button. If your server changes it (`POST /v1/api/direct/sessions/{id}/amount` with the secret key), call `refresh()` and the form reads it again:
300
+
301
+ ```js
302
+ card.refresh(); // StrablElements
303
+ form.refresh(); // strablCardForm
304
+ document.querySelector("strabl-card-form").refresh(); // the element
305
+ cardFormRef.current?.refresh(); // React: <StrablCardPaymentForm ref={cardFormRef} />
306
+ ```
307
+
308
+ Before charging, the form checks the amount once more. If it changed since the payer saw it, nothing is charged: the payment fails with `amount_changed` and the form shows the new amount.
309
+
310
+ **Apple Pay** is offered with `paymentMethods: ["applepay", "card"]`. The button appears in Safari 17+ when the payer has a card in Wallet, your domain is registered with Apple for Strabl's merchant ID, and the session has an amount. Elsewhere the form shows cards only, and `ready` lists the methods actually offered (it fires again if that changes).
311
+
312
+ ```js
313
+ const card = elements.create("card", {
314
+ paymentMethods: ["applepay", "card"],
315
+ merchantName: "Demo Store", // on the Apple Pay sheet; default: your host name
316
+ countryCode: "SA",
317
+ session: { sessionId, clientSecret }, // Apple Pay needs it before confirm()
318
+ });
319
+ card.on("result", (result) => {
320
+ // Apple Pay starts inside the form, so its outcome arrives here.
321
+ if (result.status === "requires_action") window.location.assign(result.url);
322
+ if (result.status === "success") showReceipt(result.orderShortCode);
323
+ });
324
+ ```
325
+
326
+ **Google Pay** is offered with `"googlepay"` in `paymentMethods`, when the session has an amount and the payer's browser supports it. Like Apple Pay it starts inside the form, so its outcome arrives on `result` (or the callbacks).
327
+
328
+ The custom element and React component handle the outcome themselves:
329
+ `onPaymentSuccess` / `onPaymentFailed` fire as for a card, and 3-D Secure redirects and resumes.
330
+
331
+ ## Tabby and Tamara
332
+
333
+ Tabby and Tamara are switched on in your platform's SDK settings in the Strabl dashboard; listing them in `paymentMethods` does nothing. Pass `platformUuid` so the form reads those settings sooner. The form asks the payer for a phone (and an email for Tabby) and sends them to the provider's checkout. When the payer comes back to your `redirectUrl`, render the form again with the same session (or call `resume`): it settles the payment from the provider's return.