@konfiqo/storefront-sdk 0.0.0-stage → 0.4.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Konfiqo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,595 @@
1
- # Temporary Holding Version
1
+ # @konfiqo/storefront-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
+ Typed client for the Storefront API: catalog, carts, checkout, buyer order
4
+ status and catalog images — plus helpers to present payment, format money
5
+ and remember the buyer's cart.
6
+
7
+ - Works in browsers and in Node ≥ 20 (global `fetch`). ESM + CJS + `.d.ts`.
8
+ - Zero runtime dependencies. TypeScript ≥ 5.0 for the types.
9
+ - No retries, no caching, no global state: one function call = one request.
10
+
11
+ ```bash
12
+ npm install @konfiqo/storefront-sdk
13
+ ```
14
+
15
+ ## Quick start
16
+
17
+ ### Browser
18
+
19
+ ```ts
20
+ import { createStorefrontClient, formatMoney } from '@konfiqo/storefront-sdk';
21
+
22
+ const sf = createStorefrontClient({
23
+ baseUrl: 'https://shop.example.com/api', // your store domain + /api (or '/api' on the same origin)
24
+ publishableKey: 'pk_live_…', // public: safe to ship to browsers
25
+ });
26
+
27
+ const store = await sf.store.get();
28
+ const { items } = await sf.products.list({ category: 'tshirts', pageSize: 24 });
29
+ console.log(
30
+ formatMoney(items[0].variants[0].priceMinor, store.currency, 'tr-TR'),
31
+ );
32
+ ```
33
+
34
+ The page's origin must be in the store's `allowedOrigins` (see
35
+ [CORS](#cors-and-allowedorigins)).
36
+
37
+ ### Node
38
+
39
+ ```ts
40
+ const sf = createStorefrontClient({ baseUrl, publishableKey });
41
+ const product = await sf.products.get('basic-tee');
42
+ ```
43
+
44
+ A server-side request has no `Origin`, so `allowedOrigins` does not apply.
45
+ It is throttled per publishable key **and server IP**: every buyer your
46
+ server serves shares one budget (reads: about 120 requests per minute).
47
+ For buyer traffic, call the API from the browser (cart, checkout, order
48
+ status) and cache server-side catalog reads (see Next.js below). To
49
+ report the real buyer IP from your server, use a server key (see Server
50
+ usage below). The trusted storefront key is issued only to the hosted
51
+ Konfiqo storefront.
52
+
53
+ ### Next.js (App Router)
54
+
55
+ Read the catalog in Server Components (no `Origin`) **and cache it**; run
56
+ the cart and checkout in Client Components (from the buyer's browser):
57
+
58
+ ```tsx
59
+ // lib/storefront.ts (server)
60
+ import { createStorefrontClient } from '@konfiqo/storefront-sdk';
61
+
62
+ export const sf = createStorefrontClient({
63
+ baseUrl: process.env.COMMERCE_URL!,
64
+ publishableKey: process.env.NEXT_PUBLIC_PK!,
65
+ // Next.js caches each catalog response for 60 s and shares it between
66
+ // renders and buyers.
67
+ fetch: (input, init) => fetch(input, { ...init, next: { revalidate: 60 } }),
68
+ });
69
+
70
+ // app/products/[slug]/page.tsx (server)
71
+ export default async function Page({
72
+ params,
73
+ }: {
74
+ params: Promise<{ slug: string }>;
75
+ }) {
76
+ const product = await sf.products.get((await params).slug);
77
+ return <ProductView product={product} />;
78
+ }
79
+ ```
80
+
81
+ Why the cache matters: server-side reads are throttled per publishable key
82
+ **and your server's IP** — about **120 reads per minute** for all your
83
+ buyers together (and a page often makes two or three reads: store,
84
+ categories, products). Uncached server rendering starts failing with
85
+ `rate_limited` at a few dozen page views per minute. With the cache above,
86
+ each distinct read reaches the API about once a minute. Alternatives:
87
+ wrap the calls in `unstable_cache(fn, keyParts, { revalidate: 60 })` (or
88
+ `'use cache'` with `cacheLife`). Only cache catalog reads (`store`,
89
+ `categories`, `products`): never carts, checkout or orders,
90
+ which belong in the buyer's browser anyway. Prices and stock in a cached
91
+ page can be up to a minute old; the cart and checkout always show the
92
+ server's current totals.
93
+
94
+ `@konfiqo/storefront-react` wraps the browser side in a provider and hooks.
95
+
96
+ ### Base URL
97
+
98
+ On every store domain, `/api/*` is the commerce API. Set `baseUrl` to
99
+ `https://<store domain>/api`, or to the relative `/api` in a browser app
100
+ served from the same domain. Do not add `/v1`: the client adds it, so
101
+ requests go to `/api/v1/...`.
102
+ Buyer accounts need the same-origin setup (see
103
+ [Accounts](#accounts-and-cart-recovery)).
104
+
105
+ ### Server usage (server key)
106
+
107
+ A seller's own server can report the real buyer IP with the store's server
108
+ key, which the store operator mints and revokes. Keep it in server
109
+ environment variables, never in a browser bundle.
110
+
111
+ ```ts
112
+ createStorefrontClient({
113
+ baseUrl: 'https://shop.example.com/api',
114
+ publishableKey,
115
+ serverKey: process.env.KONFIQO_SERVER_KEY, // never in a browser
116
+ buyerIp: request.headers.get('cf-connecting-ip')!, // required with serverKey
117
+ });
118
+ ```
119
+
120
+ Sends `x-konfiqo-server-key` and `x-konfiqo-buyer-ip` next to the
121
+ publishable key. Create one client per incoming request. The constructor
122
+ throws when `serverKey` has no `buyerIp`, when it is combined with
123
+ `trustedStorefrontKey`, or when it runs in a browser-like host (the same
124
+ rules as `trustedStorefrontKey` below).
125
+
126
+ ### Trusted storefront key (hosted storefront only)
127
+
128
+ The trusted storefront key is issued **only to the hosted Konfiqo
129
+ storefront**. Third-party sellers never get one: call the API from the
130
+ buyer's browser, or from your server with only the publishable key (then
131
+ throttled per key + server IP, as above).
132
+
133
+ ```ts
134
+ createStorefrontClient({
135
+ baseUrl,
136
+ publishableKey,
137
+ trustedStorefrontKey: process.env.COMMERCE_STOREFRONT_API_KEY, // never in a browser
138
+ // Required with it: the buyer's IP as written by YOUR trusted edge.
139
+ buyerIp: request.headers.get('cf-connecting-ip')!, // origin reachable only from Cloudflare
140
+ });
141
+ ```
142
+
143
+ `buyerIp` must be an address that a proxy **you control** wrote, never one
144
+ the client can choose: `CF-Connecting-IP` when the origin accepts traffic
145
+ from Cloudflare only, or the Nth `X-Forwarded-For` entry **counted from the
146
+ right** (N = the number of your proxies that append to it). Never the first
147
+ (leftmost) `X-Forwarded-For` entry: the client writes that one, so any
148
+ buyer could pose as any IP and dodge throttling.
149
+
150
+ Sends `x-konfiqo-storefront-key` and `x-konfiqo-buyer-ip` so throttling and
151
+ the payment provider see the buyer instead of your server. Create one client
152
+ per incoming request. Without `trustedStorefrontKey` or `serverKey`, neither
153
+ header is ever sent (`buyerIp` is ignored).
154
+
155
+ The constructor **throws** when `trustedStorefrontKey` is given in a
156
+ browser-like host: `window` or `document` defined, or a web worker. Hosts
157
+ that define `window` on the server — jsdom, Electron renderers, React
158
+ Native — are refused too; keep the trusted key in a plain server process.
159
+
160
+ ## Client options
161
+
162
+ | Option | Default | |
163
+ | ---------------------- | -------------- | ---------------------------------------------------------- |
164
+ | `baseUrl` | — | `https://<store domain>/api`, or `/api` on the same origin |
165
+ | `publishableKey` | — | `pk_live_…` / `pk_test_…` |
166
+ | `fetch` | global `fetch` | any `fetch`-compatible function |
167
+ | `timeoutMs` | `15000` | per request; on expiry the request is aborted → `timeout` |
168
+ | `trustedStorefrontKey` | — | server only, see above |
169
+ | `serverKey` | — | server only, see Server usage |
170
+ | `buyerIp` | — | required with `serverKey` or `trustedStorefrontKey` |
171
+
172
+ **`pk_test_` is not a test mode**: it places real orders against the
173
+ tenant's payment connection. Test against a store whose payments are in the
174
+ provider's sandbox.
175
+
176
+ ## API reference
177
+
178
+ Every method takes an optional last argument `{ signal?: AbortSignal }`
179
+ (combined with the timeout; aborting rejects with `aborted`) and resolves
180
+ with the response body or rejects with a [`StorefrontError`](#errors).
181
+ Path arguments (slugs, ids) that are empty, `.` or `..` reject with a
182
+ `TypeError` (`invalid_path_segment`) without a request.
183
+
184
+ | Method | Route | Resolves with |
185
+ | ----------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
186
+ | `store.get()` | `GET /v1/store` | `Store`: name, `defaultLanguage`, `currency`, `logo`/`logoUrl`, `theme` (`ThemeV1`, as stored), contact, legal texts, shipping rules |
187
+ | `categories.list()` | `GET /v1/categories` | `{ items: Category[] }` (active tree, sorted) |
188
+ | `products.list({ category?, q?, page?, pageSize? })` | `GET /v1/products` | `{ items: Product[], pagination }` (`pageSize` 1–100, default 20) |
189
+ | `products.get(slug)` | `GET /v1/products/:slug` | `Product` |
190
+ | `carts.create()` | `POST /v1/carts` | `Cart` |
191
+ | `carts.get(cartId)` | `GET /v1/carts/:id` | `Cart` |
192
+ | `carts.addLine(cartId, { variantId, quantity })` | `POST /v1/carts/:id/lines` | `Cart` |
193
+ | `carts.updateLine(cartId, variantId, { quantity })` | `PATCH /v1/carts/:id/lines/:variantId` | `Cart` |
194
+ | `carts.removeLine(cartId, variantId)` | `DELETE /v1/carts/:id/lines/:variantId` | `Cart` |
195
+ | `carts.setCustomer(cartId, { email, name, surname, phone, identityNumber? })` | `PUT /v1/carts/:id/customer` | `Cart` |
196
+ | `carts.setAddress(cartId, { shipping, billing? })` | `PUT /v1/carts/:id/address` | `Cart` |
197
+ | `carts.shippingOptions(cartId)` | `GET /v1/carts/:id/shipping-options` | `{ items: { id, priceMinor }[] }` |
198
+ | `carts.setShippingOption(cartId, optionId)` | `PUT /v1/carts/:id/shipping-option` | `Cart` |
199
+ | `carts.checkout(cartId, { turnstileToken? })` | `POST /v1/carts/:id/checkout` | `CheckoutResult` (see [Checkout challenge](#checkout-challenge)) |
200
+ | `orders.get(orderId, token)` | `GET /v1/orders/:id?token=` | `Order` |
201
+ | `carts.recover(token)` | `POST /v1/carts/recover` | `{ cartId }`: a **new** cart with the abandoned cart's lines (see [Accounts](#accounts-and-cart-recovery)) |
202
+ | `account.requestCode(email, { turnstileToken? })` | `POST /v1/account/code` | nothing (202 for any address) |
203
+ | `account.signIn(email, code)` | `POST /v1/account/session` | `{ customer: { email } }`; sets the session cookie |
204
+ | `account.signOut()` | `DELETE /v1/account/session` | nothing |
205
+ | `account.get(page?)` | `GET /v1/account` | `Account`: profile, `savedAddresses`, one page of `orders` (20, newest first) |
206
+ | `account.updateProfile({ name, surname, phone })` | `PUT /v1/account/profile` | nothing |
207
+ | `account.saveAddresses(list)` | `PUT /v1/account/addresses` | `SavedAddress[]` as stored (max 5, one default) |
208
+ | `media.url(key)` | — | absolute image URL (synchronous) |
209
+
210
+ ### Accounts and cart recovery
211
+
212
+ Buyers sign in with an e-mailed 6-digit code: `account.requestCode(email)`,
213
+ then `account.signIn(email, code)` (a wrong, spent or expired code rejects
214
+ `invalid_code`). The session is an **HttpOnly cookie** (`konfiqo_session`)
215
+ the API sets on the store origin, so run the storefront on the same origin
216
+ as the API (`baseUrl: '/api'`). Account calls send `credentials: 'include'`;
217
+ `account.get()` rejects `not_signed_in` (401) without a session. Save a
218
+ profile (`updateProfile`) before `saveAddresses`, else `profile_required`
219
+ (409). `phone` must be a Turkish mobile number (`invalid_request` otherwise).
220
+
221
+ **Same origin only.** Account calls (cookie sessions) work only when the
222
+ storefront is served on the store domain and calls `/api` there. A storefront
223
+ on another origin with a cross-origin `baseUrl` (for example
224
+ `https://shop.example.com/api` from `https://my-app.example.net`) can use the
225
+ catalog, carts and checkout, but not accounts: the session cookie belongs to
226
+ the store domain (`SameSite=Lax`) and the API does not allow credentialed
227
+ cross-origin requests, so the browser neither sends nor accepts the session
228
+ on those calls.
229
+
230
+ **Server-side.** A server that renders for the buyer must forward the
231
+ buyer's cookie: every method accepts `cookie` in its options.
232
+
233
+ ```ts
234
+ const sf = createStorefrontClient({ baseUrl, publishableKey });
235
+ const account = await sf.account.get(1, {
236
+ cookie: request.headers.get('cookie') ?? undefined,
237
+ });
238
+ ```
239
+
240
+ The `cookie` option is a plain request header: browsers ignore it (they send
241
+ the session cookie themselves). Forward it only from the buyer's own request,
242
+ never store it or share a client's cookie across buyers. `Set-Cookie` from
243
+ `signIn` is not exposed to you on a server: sign in from the browser.
244
+
245
+ **Cart recovery.** An abandoned-cart e-mail links to
246
+ `<store>/cart/recover?t=<token>`. Pass `t` to `carts.recover(token)`: it
247
+ answers a **new** cart id holding the same lines (no buyer data); save it as
248
+ the buyer's cart. `invalid_recovery_token` (400) = bad link,
249
+ `cart_not_recoverable` (410) = the cart was ordered, expired or deleted.
250
+
251
+ Money is always integer **minor units** (kuruş for `TRY`). Prices you send
252
+ are ignored; every cart response is priced by the server.
253
+
254
+ **Images.** `image`, `logo` and the theme's `logo` / `favicon` / section
255
+ `image` are storage keys. `imageUrl` / `logoUrl` in responses are
256
+ **relative** (`/v1/media/<key>?pk=…`) — prefix `baseUrl`, or call
257
+ `sf.media.url(key)`, which returns
258
+ `${baseUrl}/v1/media/<each segment encoded>?pk=<publishable key>` (a key
259
+ with an empty, `.` or `..` segment throws `invalid_path_segment`). The key
260
+ rides in the query because `<img>` cannot send headers; it is public.
261
+
262
+ **Cart lines** carry `purchasable` (false = no longer sold) and `inStock`
263
+ (false = fewer units left than the line asks for). Checkout refuses both:
264
+ show them and let the buyer remove or reduce.
265
+
266
+ **Customer.** `phone` must be a Turkish mobile number (`05XX…`, `5XX…`,
267
+ `+90…`, `0090…`; spaces, dashes, parentheses allowed); it comes back as
268
+ `90XXXXXXXXXX`. Addresses use `{ name?, phone?, email?, address | line1 +
269
+ line2?, district, city, zipCode | postalCode, country: 'TR' }`.
270
+
271
+ **Theme.** `store.theme` is passed through as the seller stored it and is
272
+ not validated: every field is optional, unknown keys are kept. Narrow
273
+ homepage sections with `isKnownThemeSection(section)` and skip the rest;
274
+ render `richText` as text or sanitised markdown, never raw HTML.
275
+
276
+ ## Errors
277
+
278
+ Every failure is a `StorefrontError` with `code`, `status` (HTTP status, `0`
279
+ without a response), `message` (for logs, not for logic) and `details`
280
+ (typed per code). Switch on `code`:
281
+
282
+ ```ts
283
+ import { isStorefrontError } from '@konfiqo/storefront-sdk';
284
+
285
+ try {
286
+ const result = await sf.carts.checkout(cartId);
287
+ } catch (e) {
288
+ if (!isStorefrontError(e)) throw e;
289
+ switch (e.code) {
290
+ case 'cart_changed':
291
+ showNewTotals(e.details.totalMinor, e.details.lines);
292
+ break;
293
+ case 'out_of_stock':
294
+ markLines(e.details.variantIds);
295
+ break;
296
+ case 'checkout_incomplete':
297
+ ask(e.details.missing);
298
+ break;
299
+ case 'invalid_buyer_details':
300
+ focusField(e.details.field);
301
+ break;
302
+ case 'rate_limited':
303
+ retryIn(e.details.retryAfter ?? 5);
304
+ break;
305
+ default:
306
+ showGenericError();
307
+ }
308
+ }
309
+ ```
310
+
311
+ `e.is('cart_changed')` narrows a single code the same way.
312
+
313
+ ### API error codes
314
+
315
+ | Code | Status | `details` | Meaning / what to do |
316
+ | ------------------------- | ------ | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
317
+ | `store_not_found` | 404 | | bad / revoked publishable key, or the store is disabled |
318
+ | `origin_not_allowed` | 403 | | browser `Origin` not in the store's `allowedOrigins` |
319
+ | `invalid_request` | 400 | `{ issues: [{ path, message }] }` | a body or query field is invalid (e.g. `path: "phone"`) |
320
+ | `invalid_buyer_ip` | 400 | | trusted key sent without a valid `buyerIp` |
321
+ | `catalog_unavailable` | 503 | | the catalog could not be read; retry later |
322
+ | `product_not_found` | 404 | | no sellable product with that slug |
323
+ | `cart_not_found` | 404 | | unknown cart (or another store's): start a new cart |
324
+ | `variant_not_found` | 404 | | the variant is not sold |
325
+ | `insufficient_stock` | 409 | `{ available }` | only `available` units can be added |
326
+ | `quantity_out_of_range` | 400 | | a line holds 1–99 units |
327
+ | `too_many_lines` | 400 | | a cart holds at most 50 lines |
328
+ | `line_not_found` | 404 | | no line for that variant |
329
+ | `invalid_shipping_option` | 400 | | the option is not offered for this cart |
330
+ | `cart_read_only` | 409 | `{ status: 'ordered' \| 'expired' }` | the cart can no longer change: `expired` → start a new cart; `ordered` → check out again (re-opens payment) or show the order |
331
+ | `checkout_in_progress` | 409 | | another checkout of this cart is running: retry in a few seconds |
332
+ | `checkout_incomplete` | 400 | `{ missing: ('lines' \| 'customer' \| 'identityNumber' \| 'shippingAddress' \| 'shippingOption')[] }` | collect what is missing |
333
+ | `cart_changed` | 409 | `{ lines, subtotalMinor, shippingMinor, totalMinor, shippingOptions }` | prices or shipping changed: show the new totals, let the buyer confirm, then call checkout again. Never re-submit silently. |
334
+ | `out_of_stock` | 409 | `{ variantIds }` | remove / reduce those lines |
335
+ | `amount_out_of_range` | 400 | | total not representable |
336
+ | `nothing_to_pay` | 400 | | total is zero |
337
+ | `invalid_buyer_details` | 422 | `{ field }` | the payment provider refused `name`, `surname`, `email`, `phone`, `identityNumber`, `shippingAddress.<f>` or `billingAddress.<f>`: let the buyer fix it, check out again |
338
+ | `payment_unavailable` | 502 | | payments refused or unreachable; the order was cancelled, the cart is still open |
339
+ | `checkout_unavailable` | 503 | | store backend unreachable; the cart is still open, retry |
340
+ | `order_not_found` | 404 | | unknown order or wrong token |
341
+ | `order_unavailable` | 503 | | order status temporarily unavailable; poll again |
342
+ | `media_not_found` | 404 | | (image route) key not referenced by the catalog |
343
+ | `media_unavailable` | 503 | | (image route) image temporarily unavailable |
344
+ | `challenge_required` | 400 | | the store requires a checkout challenge and no token was sent: render the widget, check out with its token |
345
+ | `challenge_failed` | 403 | | the token was invalid, expired or already used: `reset()` the widget, check out with the new token |
346
+ | `challenge_unavailable` | 503 | | the challenge could not be verified right now: retry in a moment |
347
+ | `too_many_open_orders` | 429 | | too many unpaid orders from this buyer: finish or wait out a pending payment |
348
+ | `not_signed_in` | 401 | | no valid session cookie: sign in |
349
+ | `invalid_code` | 401 | | wrong, spent or expired sign-in code (5 attempts per code) |
350
+ | `profile_required` | 409 | | save the profile before saving addresses |
351
+ | `too_many_code_requests` | 429 | | too many codes requested from this address: wait |
352
+ | `invalid_recovery_token` | 400 | | the recovery link is malformed or not for this store |
353
+ | `cart_not_recoverable` | 410 | | the abandoned cart was ordered, expired or deleted: start a new cart |
354
+ | `unavailable` | 503 | | the account could not be read or saved right now: retry |
355
+
356
+ ### Codes the SDK assigns
357
+
358
+ | Code | Status | `details` | When |
359
+ | ------------------ | ------ | --------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
360
+ | `rate_limited` | 429 | `{ retryAfter? }` (seconds) | throttled (`checkout`: 5/min per key + IP); a 429 with a known code (`too_many_open_orders`) keeps that code |
361
+ | `unauthorized` | 401 | | a wrong `trustedStorefrontKey` |
362
+ | `http_error` | any | | an error response without an `error` code |
363
+ | `unknown_error` | any | `{ error }` | an `error` code this SDK version does not know |
364
+ | `invalid_response` | 2xx | | the response body is not JSON |
365
+ | `network_error` | 0 | | the API was unreachable (DNS, TLS, offline), or the page's origin is allowed by no store (`cause` holds the original error) |
366
+ | `timeout` | 0 | `{ timeoutMs }` | no response within `timeoutMs` |
367
+ | `aborted` | 0 | | your `signal` aborted the request |
368
+
369
+ **In browsers.** Error responses (status ≥ 400) carry CORS headers for
370
+ any origin that some store allows, and expose `Retry-After` /
371
+ `Retry-After-ip`: a browser reads every error code, including
372
+ `rate_limited` with its `retryAfter`, `store_not_found` and
373
+ `origin_not_allowed`. A `network_error` in a browser means the API could
374
+ not be reached at all, or the page's origin is in **no** store's
375
+ `allowedOrigins` (the browser then hides the response). Treat a
376
+ `network_error` on checkout as "try again in a moment", not as a decline.
377
+
378
+ **No retries.** The SDK never retries. Writes are not safely repeatable —
379
+ in particular, checking out a cart whose payment failed places a **new**
380
+ order — so retrying is your decision, per code (`checkout_in_progress`,
381
+ `checkout_unavailable`, `catalog_unavailable`, `rate_limited`).
382
+
383
+ ## Payment
384
+
385
+ `carts.checkout` answers how to present payment, by `presentation`:
386
+
387
+ | `presentation` | Fields | Do |
388
+ | -------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
389
+ | `embedded` | `embed: { kind, content }` | render the provider's form in your page |
390
+ | `redirect` | `url` | top-level navigation to `url` (never an iframe) |
391
+ | `closed` | `page` (+ `orderStatus`) | payment cannot be (re)opened: show the order status page. `page` is `paid`, `cancelled`, `processing`, `expired`, `failed` or `not_found` |
392
+
393
+ `mountPayment` does each of these:
394
+
395
+ ```ts
396
+ import { mountPayment } from '@konfiqo/storefront-sdk';
397
+
398
+ const result = await sf.carts.checkout(cartId);
399
+ if (result.token) saveOrderToken(result.orderId, result.token); // returned ONCE
400
+ const token = result.token ?? loadOrderToken(result.orderId);
401
+
402
+ const mount = mountPayment(document.getElementById('payment')!, result, {
403
+ onClosed: () =>
404
+ router.push(`/orders/${result.orderId}?token=${encodeURIComponent(token)}`),
405
+ });
406
+ // mount.kind: 'embedded' (mount.unmount()), 'redirect', 'closed', or
407
+ // 'unsupported' (an embed kind this SDK cannot render: show a fallback)
408
+ ```
409
+
410
+ - **embedded** (`iyzico-checkout-form`): puts the provider's HTML into the
411
+ element and re-creates every `<script>` (attributes + text) so it
412
+ executes — `innerHTML` alone never runs scripts. Mounting the same form
413
+ into the same element again does nothing; a different form replaces the
414
+ old one. Scripts are never injected twice (safe with React Strict Mode).
415
+ Pass `mountPayment` only the **unmodified result of `checkout()`** —
416
+ never build a presentation, `embed` or redirect `url` from user input,
417
+ URL parameters or storage: the embedded content is executed as script.
418
+ This is the provider's own form: card data goes from it to the provider
419
+ and never through your code. If you use a Content Security Policy, allow
420
+ the provider's script and frame origins.
421
+ - **redirect**: `window.location.assign(url)`; only `http(s)` URLs.
422
+ - **closed**: calls `onClosed(page)` and returns `{ kind: 'closed', page }`.
423
+
424
+ ## Checkout challenge
425
+
426
+ A store can require a bot challenge (Cloudflare Turnstile) on checkout.
427
+ `store.checkoutChallenge` is then `{ provider: 'turnstile', siteKey }`
428
+ (`null` or absent: no challenge).
429
+
430
+ ```ts
431
+ import { renderTurnstile } from '@konfiqo/storefront-sdk';
432
+
433
+ let token: string | null = null;
434
+ const challenge = store.checkoutChallenge; // null: skip the widget
435
+ const widget = challenge
436
+ ? await renderTurnstile(
437
+ document.getElementById('challenge')!,
438
+ challenge.siteKey,
439
+ {
440
+ onToken: (t) => (token = t),
441
+ onExpired: () => (token = null),
442
+ },
443
+ )
444
+ : null;
445
+
446
+ async function pay() {
447
+ try {
448
+ return await sf.carts.checkout(cartId, {
449
+ turnstileToken: token ?? undefined,
450
+ });
451
+ } finally {
452
+ token = null;
453
+ widget?.reset(); // tokens are single-use: every checkout call needs a new one
454
+ }
455
+ }
456
+ ```
457
+
458
+ - `loadTurnstile(document)` injects Cloudflare's official script
459
+ (`https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit`)
460
+ once per document and resolves with `window.turnstile`; nothing else is
461
+ ever injected. `renderTurnstile` calls it for you. If the script fails to
462
+ load, the promise rejects and the failed tag is removed: calling again retries.
463
+ - Tokens are **single-use** and expire after about 5 minutes: reset the
464
+ widget after every checkout call, successful or not
465
+ (`challenge_failed` = used, expired or invalid token).
466
+ - On your own site, the widget only works on hostnames Cloudflare knows
467
+ for the store's site key: your domain must be one of the store's domains
468
+ / `allowedOrigins` **and** in the widget's hostname list (ask the store
469
+ operator).
470
+ - Re-opening payment on an already ordered cart needs no token.
471
+ - With a Content Security Policy, allow `https://challenges.cloudflare.com`
472
+ in `script-src` and `frame-src`.
473
+
474
+ ## Cookies
475
+
476
+ `store.cookies` lists the cookies the store uses (`CookieInfo`: `name`,
477
+ `category` of `'necessary' | 'analytics' | 'marketing'`, `purpose` in the
478
+ store's language, `durationDays`). It is empty when the store uses no
479
+ optional cookie: then nothing needs the shopper's consent.
480
+ `store.consentVersion` identifies the set of optional cookies ('' when
481
+ none); a consent given for another version should be asked again.
482
+ `store.legal.cookies` is the cookie policy text. All three are absent from
483
+ API versions before cookie consent: treat them as `[]`, `''` and no text.
484
+
485
+ ## Helpers
486
+
487
+ - `formatMoney(minor, currency, locale?)` — `Intl.NumberFormat` with the
488
+ currency's own minor digits: `formatMoney(14990, 'TRY', 'tr-TR')` →
489
+ `₺149,90`.
490
+ - `loadCartId(storage, storeId)`, `saveCartId(storage, storeId, cartId)`,
491
+ `clearCartId(storage, storeId)` — remember the cart per store in
492
+ `localStorage` (or any `{ getItem, setItem, removeItem }`). Key
493
+ `storefront:cart:<storeId>`. They never throw: no storage (SSR), a
494
+ throwing storage (private mode) → `null` / `false`.
495
+ - `cookieCartStorage()` — the same interface over the first-party
496
+ `__Host-konfiqo_cart` cookie, which the hosted checkout on a store domain
497
+ reads too.
498
+ - **Clearing a cart on a store domain.** A frontend served on the store's
499
+ own domain shares both the cookie and `localStorage` with the hosted
500
+ storefront, which restores a cart id from `localStorage` whenever the
501
+ cookie is missing (Safari expires script-written cookies after 7 days).
502
+ `clearCartId(localStorage, …)` or `cookieCartStorage().removeItem` on
503
+ their own are therefore not enough: neither writes the
504
+ `storefront:cart:<storeId>:cleared` tombstone, so the old cart comes back.
505
+ Clear through `@konfiqo/storefront-react`'s `defaultCartStorage()` (or
506
+ `useCartStorage()`), e.g. `clearCartId(defaultCartStorage(), storeId)`,
507
+ which clears the cookie and `localStorage` and writes the tombstone. On
508
+ your own domain (not a store domain) `localStorage` alone is fine.
509
+ - **`storeId`** is any string that is stable for one store and different
510
+ between stores: it only names the storage key. The API does not return a
511
+ store id; use the publishable key (it is public anyway), or a string the
512
+ store operator gives you. Changing it later forgets carts saved under the
513
+ old value.
514
+
515
+ ## Build your own storefront
516
+
517
+ 1. **Operator setup.** Ask the store operator to:
518
+ - mint a `pk_live_…` publishable key for you;
519
+ - list your site's exact origins (`https://shop.example.com`, plus
520
+ `http://localhost:3000` for development) in the store's
521
+ `allowedOrigins` (not as a store _domain_: store domains are routed
522
+ to the hosted storefront);
523
+ - set the store's `orderStatusUrl` to **your** order page, e.g.
524
+ `https://shop.example.com/orders/{orderId}?token={token}` (step 7);
525
+ - add your origin to the tenant's payments connection **allowed return
526
+ addresses** (`allowedReturnOrigins`), else checkout fails with
527
+ `payment_unavailable`;
528
+ - if the store uses a checkout challenge, add your hostname to its
529
+ Turnstile widget's hostname list, else checkout fails with
530
+ `challenge_failed`.
531
+
532
+ 2. **CORS and `allowedOrigins`.** <a id="cors-and-allowedorigins"></a>
533
+ Browser requests must come from one of those origins, else 403
534
+ `origin_not_allowed` (an origin that no store allows at all sees
535
+ `network_error` instead). The API
536
+ allows only the `content-type`, `x-konfiqo-publishable-key` and (on
537
+ checkout) `x-konfiqo-turnstile-token` request headers cross-origin. Server-side requests (no `Origin`) are always
538
+ allowed.
539
+
540
+ 3. **Catalog.** `store.get()` for name, currency, language, theme, legal
541
+ texts (show KVKK, distance-sales and returns texts at checkout);
542
+ `categories.list()`, `products.list()`, `products.get(slug)`. Build
543
+ variant pickers from `variant.optionValues`; disable variants with
544
+ `available === 0`.
545
+
546
+ 4. **Cart.** `carts.create()` once, `saveCartId(localStorage, storeId, cart.id)`.
547
+ The cart id is a bearer capability — keep it in the buyer's browser
548
+ only. On `cart_not_found` or `cart_read_only` with `status: 'expired'`,
549
+ `clearCartId` and create a new cart (on a store domain, through the
550
+ React package's storage: see "Clearing a cart on a store domain").
551
+ Carts live 7 days.
552
+
553
+ 5. **Checkout form.** `setCustomer` (Turkish mobile number; the **identity
554
+ number** — TC kimlik no, 11 digits — is required by the payment
555
+ provider, is stored sealed, is never returned (`identityNumberProvided`
556
+ tells you one is on file) and can be omitted on later calls to keep the
557
+ one on file; show a KVKK notice next to the field), `setAddress`,
558
+ `shippingOptions` + `setShippingOption`.
559
+
560
+ 6. **Pay.** If `store.checkoutChallenge` is set, render the challenge
561
+ widget first ([below](#checkout-challenge)). `carts.checkout(cartId, { turnstileToken })`. Store the returned `token` with the
562
+ `orderId` — it is returned only once and is the buyer's only key to the
563
+ order page. Then `mountPayment`. Handle `cart_changed` by showing the
564
+ new totals and asking the buyer to confirm before calling checkout
565
+ again; never charge silently.
566
+
567
+ 7. **Return URL.** The store's `orderStatusUrl`
568
+ (`https://shop.example.com/orders/{orderId}?token={token}`) is where the
569
+ payment provider sends the buyer back. Serve that page: read
570
+ `orders.get(orderId, token)` and poll with backoff until the order is
571
+ settled: `status` is anything past `pendingPayment` (`paid`,
572
+ `fulfilling`, `shipped`, `delivered`, `cancelled`, `refunded`, …), or it
573
+ is still `pendingPayment` but `paymentStatus` is `failed` or `expired`
574
+ (offer to check out again, step 8). `paymentStatus: 'processing'` means
575
+ the payment succeeded and the order is being updated: keep polling.
576
+ `isOrderSettled(order)` in `@konfiqo/storefront-react` implements this
577
+ rule. Do not send the token to analytics or logs.
578
+
579
+ 8. **Failed payments.** A declined, failed or expired payment cancels the
580
+ order, but the cart is **not** lost: the next `carts.get` or
581
+ `carts.checkout` reopens it (`status: 'open'`) and checkout places a new
582
+ order (new `orderId`, new `token`) with the same lines, buyer and
583
+ addresses — the buyer re-enters nothing, including the identity number,
584
+ which stays sealed on the cart until the order is paid or the cart
585
+ expires. Calling checkout on an `ordered` cart whose payment is still
586
+ pending re-opens the same payment (no new order). Stock is reserved for
587
+ a pending order for up to 24 h.
588
+
589
+ 9. **Secrets.** The publishable key is the only key that belongs in client
590
+ code. The tenant API key, the operator key and the trusted storefront
591
+ key are server secrets: never put them in a browser bundle, a mobile
592
+ app or a public repository.
593
+
594
+ 10. **Errors.** Map every code in the [table](#api-error-codes) to copy in
595
+ your languages; never show `message` to buyers.