@konfiqo/storefront-sdk 0.6.1 → 0.8.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,7 +1,7 @@
1
1
  # @konfiqo/storefront-sdk
2
2
 
3
3
  Typed client for the Storefront API: catalog, carts, checkout, buyer order
4
- status and catalog images — plus helpers to present payment, format money
4
+ status and catalog images, plus helpers to present payment, format money
5
5
  and remember the buyer's cart.
6
6
 
7
7
  - Works in browsers and in Node ≥ 20 (global `fetch`). ESM + CJS + `.d.ts`.
@@ -79,7 +79,7 @@ export default async function Page({
79
79
  ```
80
80
 
81
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
82
+ **and your server's IP**, about **120 reads per minute** for all your
83
83
  buyers together (and a page often makes two or three reads: store,
84
84
  categories, products). Uncached server rendering starts failing with
85
85
  `rate_limited` at a few dozen page views per minute. With the cache above,
@@ -147,27 +147,29 @@ right** (N = the number of your proxies that append to it). Never the first
147
147
  (leftmost) `X-Forwarded-For` entry: the client writes that one, so any
148
148
  buyer could pose as any IP and dodge throttling.
149
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).
150
+ Sends `x-konfiqo-storefront-key`, `x-konfiqo-buyer-ip` and
151
+ `x-konfiqo-buyer-user-agent` so throttling and the payment provider see the
152
+ buyer instead of your server. Create one client per incoming request. Without
153
+ `trustedStorefrontKey` or `serverKey`, none of these headers is ever sent
154
+ (`buyerIp` and `buyerUserAgent` are ignored).
154
155
 
155
156
  The constructor **throws** when `trustedStorefrontKey` is given in a
156
157
  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.
158
+ that define `window` on the server (jsdom, Electron renderers, React
159
+ Native) are refused too; keep the trusted key in a plain server process.
159
160
 
160
161
  ## Client options
161
162
 
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` |
163
+ | Option | Default | |
164
+ | ---------------------- | -------------- | -------------------------------------------------------------- |
165
+ | `baseUrl` | none | `https://<store domain>/api`, or `/api` on the same origin |
166
+ | `publishableKey` | none | `pk_live_…` / `pk_test_…` |
167
+ | `fetch` | global `fetch` | any `fetch`-compatible function |
168
+ | `timeoutMs` | `15000` | per request; on expiry the request is aborted → `timeout` |
169
+ | `trustedStorefrontKey` | none | server only, see above |
170
+ | `serverKey` | none | server only, see Server usage |
171
+ | `buyerIp` | none | required with `serverKey` or `trustedStorefrontKey` |
172
+ | `buyerUserAgent` | none | optional; sent only with `serverKey` or `trustedStorefrontKey` |
171
173
 
172
174
  **`pk_test_` is not a test mode**: it places real orders against the
173
175
  tenant's payment connection. Test against a store whose payments are in the
@@ -181,31 +183,34 @@ with the response body or rejects with a [`StorefrontError`](#errors).
181
183
  Path arguments (slugs, ids) that are empty, `.` or `..` reject with a
182
184
  `TypeError` (`invalid_path_segment`) without a request.
183
185
 
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, personalization? })` | `POST /v1/carts/:id/lines` | `Cart` |
193
- | `carts.updateLine(cartId, lineId, { quantity })` | `PATCH /v1/carts/:id/lines/:lineId` | `Cart` |
194
- | `carts.removeLine(cartId, lineId)` | `DELETE /v1/carts/:id/lines/:lineId` | `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) |
186
+ | Method | Route | Resolves with |
187
+ | ----------------------------------------------------------------------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
188
+ | `store.get()` | `GET /v1/store` | `Store`: name, `defaultLanguage`, `currency`, `logo`/`logoUrl`, `theme` (`ThemeV1`, as stored), contact, `company`, shipping rules |
189
+ | `categories.list()` | `GET /v1/categories` | `{ items: Category[] }` (active tree, sorted) |
190
+ | `products.list({ category?, q?, page?, pageSize? })` | `GET /v1/products` | `{ items: Product[], pagination }` (`pageSize` 1–100, default 20) |
191
+ | `products.get(slug)` | `GET /v1/products/:slug` | `Product` |
192
+ | `blog.list({ page?, pageSize? })` | `GET /v1/blog` | `{ items: BlogPostSummary[], pagination }` (newest first, `pageSize` 1–50, default 12) |
193
+ | `blog.get(slug)` | `GET /v1/blog/:slug` | `BlogPost`: the summary fields, `metaDescription` and the body `tree` |
194
+ | `carts.create()` | `POST /v1/carts` | `Cart` |
195
+ | `carts.get(cartId)` | `GET /v1/carts/:id` | `Cart` |
196
+ | `carts.addLine(cartId, { variantId, quantity, personalization? })` | `POST /v1/carts/:id/lines` | `Cart` |
197
+ | `carts.updateLine(cartId, lineId, { quantity })` | `PATCH /v1/carts/:id/lines/:lineId` | `Cart` |
198
+ | `carts.removeLine(cartId, lineId)` | `DELETE /v1/carts/:id/lines/:lineId` | `Cart` |
199
+ | `carts.setCustomer(cartId, { email, name, surname, phone, identityNumber? })` | `PUT /v1/carts/:id/customer` | `Cart` |
200
+ | `carts.setAddress(cartId, { shipping, billing? })` | `PUT /v1/carts/:id/address` | `Cart` |
201
+ | `carts.shippingOptions(cartId)` | `GET /v1/carts/:id/shipping-options` | `{ items: { id, priceMinor }[] }` |
202
+ | `carts.setShippingOption(cartId, optionId)` | `PUT /v1/carts/:id/shipping-option` | `Cart` |
203
+ | `carts.agreements(cartId)` | `POST /v1/carts/:id/agreements` | `CartAgreements` (see [Legal texts and agreements](#legal-texts-and-agreements)) |
204
+ | `carts.checkout(cartId, { agreementsHash, turnstileToken? })` | `POST /v1/carts/:id/checkout` | `CheckoutResult` (see [Checkout challenge](#checkout-challenge)) |
205
+ | `orders.get(orderId, token)` | `GET /v1/orders/:id?token=` | `Order` |
206
+ | `carts.recover(token)` | `POST /v1/carts/recover` | `{ cartId }`: a **new** cart with the abandoned cart's lines (see [Accounts](#accounts-and-cart-recovery)) |
207
+ | `account.requestCode(email, { turnstileToken? })` | `POST /v1/account/code` | nothing (202 for any address) |
208
+ | `account.signIn(email, code)` | `POST /v1/account/session` | `{ customer: { email } }`; sets the session cookie |
209
+ | `account.signOut()` | `DELETE /v1/account/session` | nothing |
210
+ | `account.get(page?)` | `GET /v1/account` | `Account`: profile, `savedAddresses`, one page of `orders` (20, newest first) |
211
+ | `account.updateProfile({ name, surname, phone })` | `PUT /v1/account/profile` | nothing |
212
+ | `account.saveAddresses(list)` | `PUT /v1/account/addresses` | `SavedAddress[]` as stored (max 5, one default) |
213
+ | `media.url(key)` | none | absolute image URL (synchronous) |
209
214
 
210
215
  ### Accounts and cart recovery
211
216
 
@@ -253,7 +258,7 @@ are ignored; every cart response is priced by the server.
253
258
 
254
259
  **Images.** `image`, `logo` and the theme's `logo` / `favicon` / section
255
260
  `image` are storage keys. `imageUrl` / `logoUrl` in responses are
256
- **relative** (`/v1/media/<key>?pk=…`) — prefix `baseUrl`, or call
261
+ **relative** (`/v1/media/<key>?pk=…`); prefix `baseUrl`, or call
257
262
  `sf.media.url(key)`, which returns
258
263
  `${baseUrl}/v1/media/<each segment encoded>?pk=<publishable key>` (a key
259
264
  with an empty, `.` or `..` segment throws `invalid_path_segment`). The key
@@ -301,7 +306,7 @@ without a response), `message` (for logs, not for logic) and `details`
301
306
  import { isStorefrontError } from '@konfiqo/storefront-sdk';
302
307
 
303
308
  try {
304
- const result = await sf.carts.checkout(cartId);
309
+ const result = await sf.carts.checkout(cartId, { agreementsHash });
305
310
  } catch (e) {
306
311
  if (!isStorefrontError(e)) throw e;
307
312
  switch (e.code) {
@@ -317,6 +322,12 @@ try {
317
322
  case 'checkout_incomplete':
318
323
  ask(e.details.missing);
319
324
  break;
325
+ case 'agreements_changed':
326
+ reloadAgreements(); // carts.agreements again, show, then checkout
327
+ break;
328
+ case 'legal_not_confirmed':
329
+ showNotTakingOrders();
330
+ break;
320
331
  case 'invalid_buyer_details':
321
332
  focusField(e.details.field);
322
333
  break;
@@ -348,9 +359,12 @@ try {
348
359
  | `too_many_lines` | 400 | | a cart holds at most 50 lines |
349
360
  | `line_not_found` | 404 | | no line with that id |
350
361
  | `invalid_shipping_option` | 400 | | the option is not offered for this cart |
351
- | `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 |
362
+ | `cart_read_only` | 409 | `{ status: 'ordered' \| 'expired' }` | the cart can no longer change: `expired` → start a new cart; `ordered` → show the order, or re-open payment with `REOPEN_AGREEMENTS_HASH` (step 9) |
352
363
  | `checkout_in_progress` | 409 | | another checkout of this cart is running: retry in a few seconds |
353
364
  | `checkout_incomplete` | 400 | `{ missing: ('lines' \| 'customer' \| 'identityNumber' \| 'shippingAddress' \| 'shippingOption')[] }` | collect what is missing |
365
+ | `legal_not_confirmed` | 409 | | the store has not confirmed its legal texts and takes no orders yet: show a clear "not taking orders" message |
366
+ | `agreements_changed` | 409 | | the cart or a legal text changed after `carts.agreements`: load the agreements again, show them, then check out with the new hash |
367
+ | `cart_incomplete` | 409 | `{ missing }` (as `checkout_incomplete`) | `carts.agreements` on a cart without lines, customer or address: collect what is missing, then load the agreements |
354
368
  | `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. |
355
369
  | `out_of_stock` | 409 | `{ variantIds }` | remove / reduce those lines |
356
370
  | `invalid_personalization` | 400, 409 | `{ lineIds? }` (409 at checkout) | 400: the text breaks the product's rule (or the product asks for none). 409: those lines' stored text is no longer valid: remove each line and add it again with a valid text |
@@ -397,9 +411,9 @@ not be reached at all, or the page's origin is in **no** store's
397
411
  `allowedOrigins` (the browser then hides the response). Treat a
398
412
  `network_error` on checkout as "try again in a moment", not as a decline.
399
413
 
400
- **No retries.** The SDK never retries. Writes are not safely repeatable —
401
- in particular, checking out a cart whose payment failed places a **new**
402
- order — so retrying is your decision, per code (`checkout_in_progress`,
414
+ **No retries.** The SDK never retries. Writes are not safely repeatable. In
415
+ particular, checking out a cart whose payment failed places a **new**
416
+ order, so retrying is your decision, per code (`checkout_in_progress`,
403
417
  `checkout_unavailable`, `catalog_unavailable`, `rate_limited`).
404
418
 
405
419
  ## Payment
@@ -417,7 +431,7 @@ order — so retrying is your decision, per code (`checkout_in_progress`,
417
431
  ```ts
418
432
  import { mountPayment } from '@konfiqo/storefront-sdk';
419
433
 
420
- const result = await sf.carts.checkout(cartId);
434
+ const result = await sf.carts.checkout(cartId, { agreementsHash });
421
435
  if (result.token) saveOrderToken(result.orderId, result.token); // returned ONCE
422
436
  const token = result.token ?? loadOrderToken(result.orderId);
423
437
 
@@ -431,11 +445,11 @@ const mount = mountPayment(document.getElementById('payment')!, result, {
431
445
 
432
446
  - **embedded** (`iyzico-checkout-form`): puts the provider's HTML into the
433
447
  element and re-creates every `<script>` (attributes + text) so it
434
- executes — `innerHTML` alone never runs scripts. Mounting the same form
448
+ executes; `innerHTML` alone never runs scripts. Mounting the same form
435
449
  into the same element again does nothing; a different form replaces the
436
450
  old one. Scripts are never injected twice (safe with React Strict Mode).
437
- Pass `mountPayment` only the **unmodified result of `checkout()`** —
438
- never build a presentation, `embed` or redirect `url` from user input,
451
+ Pass `mountPayment` only the **unmodified result of `checkout()`**.
452
+ Never build a presentation, `embed` or redirect `url` from user input,
439
453
  URL parameters or storage: the embedded content is executed as script.
440
454
  This is the provider's own form: card data goes from it to the provider
441
455
  and never through your code. If you use a Content Security Policy, allow
@@ -443,6 +457,66 @@ const mount = mountPayment(document.getElementById('payment')!, result, {
443
457
  - **redirect**: `window.location.assign(url)`; only `http(s)` URLs.
444
458
  - **closed**: calls `onClosed(page)` and returns `{ kind: 'closed', page }`.
445
459
 
460
+ ## Blog
461
+
462
+ `blog.list` pages through the published posts, newest first. A post
463
+ carries `slug`, `title`, `summary`, `coverImage`, `coverImageUrl`,
464
+ `publishedAt` and `updatedAt`. `blog.get(slug)` adds `metaDescription`
465
+ (the summary when the seller wrote none) and `tree`, the body as a Markdoc
466
+ tree you render like store content. An unknown, draft or not yet published
467
+ post rejects with `blog_post_not_found`.
468
+
469
+ `coverImageUrl` is relative (`/v1/media/<key>?pk=<key>`): prefix the API
470
+ origin, or use `client.media.url(post.coverImage)`.
471
+
472
+ ```ts
473
+ const { items, pagination } = await sf.blog.list({ page: 1, pageSize: 12 });
474
+ const post = await sf.blog.get(items[0].slug);
475
+ ```
476
+
477
+ ## Legal texts and agreements
478
+
479
+ `Store.legal` is gone. The six legal texts are store content under fixed
480
+ keys, listed in `LEGAL_KEYS` (type `LegalKey`): `legal.kvkk`,
481
+ `legal.privacy`, `legal.preliminary-information`, `legal.distance-sales`,
482
+ `legal.returns` and `legal.cookies`. Build each public legal page with
483
+ `getContent`; the answer is a Markdoc tree you render (`<Content>` in the
484
+ React package). A text the seller has not written is answered with
485
+ `content_not_found`: show a "missing" notice on that page.
486
+
487
+ ```ts
488
+ import { LEGAL_KEYS } from '@konfiqo/storefront-sdk';
489
+
490
+ const pages = await Promise.all(
491
+ LEGAL_KEYS.map((key) => sf.getContent(key).catch(() => null)),
492
+ );
493
+ ```
494
+
495
+ `store.company` holds the seller's title, address, tax office, tax number,
496
+ MERSIS number and KEP address (each `string | null`) for an imprint or
497
+ footer.
498
+
499
+ Two of the texts are order documents: the preliminary information and the
500
+ distance sales agreement. They contain the buyer's name, address and
501
+ items, so they must be shown **filled in for the cart** before payment:
502
+
503
+ 1. Once the cart has lines, a customer and an address, call
504
+ `carts.agreements(cartId)`. It answers `{ orderNumber, documents,
505
+ agreementsHash }`. The `documents` are `{ key, title, tree }`.
506
+ 2. Show the documents and ask the buyer to accept them. Call
507
+ `carts.agreements` again after every change to the cart.
508
+ 3. Check out with the hash:
509
+ `carts.checkout(cartId, { agreementsHash, turnstileToken? })`.
510
+ 4. If the cart or a legal text changed in between, checkout fails with
511
+ `agreements_changed` and creates no order. Load the agreements again,
512
+ show the new texts and let the buyer accept them. Never reuse the old
513
+ hash.
514
+ 5. A store that has not confirmed its legal texts refuses both calls with
515
+ `legal_not_confirmed`: tell the buyer the store is not taking orders.
516
+
517
+ The order the buyer opens later (`orders.get`) carries `agreements`, the
518
+ documents exactly as the buyer accepted them.
519
+
446
520
  ## Checkout challenge
447
521
 
448
522
  A store can require a bot challenge (Cloudflare Turnstile) on checkout.
@@ -468,6 +542,7 @@ const widget = challenge
468
542
  async function pay() {
469
543
  try {
470
544
  return await sf.carts.checkout(cartId, {
545
+ agreementsHash,
471
546
  turnstileToken: token ?? undefined,
472
547
  });
473
548
  } finally {
@@ -501,36 +576,38 @@ store's language, `durationDays`). It is empty when the store uses no
501
576
  optional cookie: then nothing needs the shopper's consent.
502
577
  `store.consentVersion` identifies the set of optional cookies ('' when
503
578
  none); a consent given for another version should be asked again.
504
- `store.legal.cookies` is the cookie policy text. All three are absent from
505
- API versions before cookie consent: treat them as `[]`, `''` and no text.
579
+ The cookie policy text is the content `legal.cookies` (see
580
+ [Legal texts and agreements](#legal-texts-and-agreements)). `cookies` and
581
+ `consentVersion` are absent from API versions before cookie consent: treat
582
+ them as `[]` and `''`.
506
583
 
507
584
  Server-safe helpers for a store's own host (no browser API, so they run in
508
585
  server components):
509
586
 
510
- - `onDefaultDomain(host, suffix)` — whether `host` is the default store
587
+ - `onDefaultDomain(host, suffix)` tells whether `host` is the default store
511
588
  domain suffix or a subdomain of it (case-insensitive; `false` without a
512
589
  suffix).
513
- - `pixelsForHost(adPixels, defaultDomain)` — on a default domain only
514
- Google is kept: Meta and TikTok write their cookies to the registrable
590
+ - `pixelsForHost(adPixels, defaultDomain)` keeps only Google on a default
591
+ domain: Meta and TikTok write their cookies to the registrable
515
592
  domain, which every default store domain shares.
516
- - `cookiesForHost(cookies, defaultDomain)` — on a default domain the
517
- `customDomainOnly` cookies are dropped, and the list is empty when no
518
- optional cookie is left (then no consent is needed).
593
+ - `cookiesForHost(cookies, defaultDomain)` drops the `customDomainOnly`
594
+ cookies on a default domain, and returns an empty list when no optional
595
+ cookie is left (then no consent is needed).
519
596
 
520
597
  `@konfiqo/storefront-react` has the consent state, store analytics and
521
598
  the ad-pixel loader that use them.
522
599
 
523
600
  ## Helpers
524
601
 
525
- - `formatMoney(minor, currency, locale?)` — `Intl.NumberFormat` with the
526
- currency's own minor digits: `formatMoney(14990, 'TRY', 'tr-TR')` →
602
+ - `formatMoney(minor, currency, locale?)` formats with `Intl.NumberFormat`
603
+ and the currency's own minor digits: `formatMoney(14990, 'TRY', 'tr-TR')` →
527
604
  `₺149,90`.
528
- - `loadCartId(storage, storeId)`, `saveCartId(storage, storeId, cartId)`,
529
- `clearCartId(storage, storeId)` — remember the cart per store in
605
+ - `loadCartId(storage, storeId)`, `saveCartId(storage, storeId, cartId)` and
606
+ `clearCartId(storage, storeId)` remember the cart per store in
530
607
  `localStorage` (or any `{ getItem, setItem, removeItem }`). Key
531
608
  `storefront:cart:<storeId>`. They never throw: no storage (SSR), a
532
609
  throwing storage (private mode) → `null` / `false`.
533
- - `cookieCartStorage()` — the same interface over the first-party
610
+ - `cookieCartStorage()` offers the same interface over the first-party
534
611
  `__Host-konfiqo_cart` cookie, which the hosted checkout on a store domain
535
612
  reads too.
536
613
  - **Clearing a cart on a store domain.** A frontend served on the store's
@@ -559,7 +636,7 @@ the ad-pixel loader that use them.
559
636
  `allowedOrigins` (not as a store _domain_: store domains are routed
560
637
  to the hosted storefront);
561
638
  - set the store's `orderStatusUrl` to **your** order page, e.g.
562
- `https://shop.example.com/orders/{orderId}?token={token}` (step 7);
639
+ `https://shop.example.com/orders/{orderId}?token={token}` (step 8);
563
640
  - add your origin to the tenant's payments connection **allowed return
564
641
  addresses** (`allowedReturnOrigins`), else checkout fails with
565
642
  `payment_unavailable`;
@@ -575,59 +652,76 @@ the ad-pixel loader that use them.
575
652
  checkout) `x-konfiqo-turnstile-token` request headers cross-origin. Server-side requests (no `Origin`) are always
576
653
  allowed.
577
654
 
578
- 3. **Catalog.** `store.get()` for name, currency, language, theme, legal
579
- texts (show KVKK, distance-sales and returns texts at checkout);
655
+ 3. **Catalog.** `store.get()` for name, currency, language, theme and company
656
+ details; legal pages through `getContent(LEGAL_KEYS…)`;
580
657
  `categories.list()`, `products.list()`, `products.get(slug)`. Build
581
658
  variant pickers from `variant.optionValues`; disable variants with
582
659
  `available === 0`.
583
660
 
584
661
  4. **Cart.** `carts.create()` once, `saveCartId(localStorage, storeId, cart.id)`.
585
- The cart id is a bearer capability — keep it in the buyer's browser
662
+ The cart id is a bearer capability; keep it in the buyer's browser
586
663
  only. On `cart_not_found` or `cart_read_only` with `status: 'expired'`,
587
664
  `clearCartId` and create a new cart (on a store domain, through the
588
665
  React package's storage: see "Clearing a cart on a store domain").
589
666
  Carts live 7 days.
590
667
 
591
668
  5. **Checkout form.** `setCustomer` (Turkish mobile number; the **identity
592
- number** — TC kimlik no, 11 digits — is required by the payment
669
+ number** (TC kimlik no, 11 digits) is required by the payment
593
670
  provider, is stored sealed, is never returned (`identityNumberProvided`
594
671
  tells you one is on file) and can be omitted on later calls to keep the
595
672
  one on file; show a KVKK notice next to the field), `setAddress`,
596
673
  `shippingOptions` + `setShippingOption`.
597
674
 
598
- 6. **Pay.** If `store.checkoutChallenge` is set, render the challenge
599
- widget first ([below](#checkout-challenge)). `carts.checkout(cartId, { turnstileToken })`. Store the returned `token` with the
600
- `orderId` — it is returned only once and is the buyer's only key to the
675
+ 6. **Agreements.** Call `carts.agreements(cartId)`, show its `documents`
676
+ next to a confirmation checkbox, and keep its `agreementsHash`. Call it
677
+ again after any cart change. `legal_not_confirmed` means the store takes
678
+ no orders yet.
679
+
680
+ 7. **Pay.** If `store.checkoutChallenge` is set, render the challenge
681
+ widget first ([below](#checkout-challenge)). `carts.checkout(cartId, { agreementsHash, turnstileToken })`. Handle
682
+ `agreements_changed` by loading the agreements again. Store the returned `token` with the
683
+ `orderId`; it is returned only once and is the buyer's only key to the
601
684
  order page. Then `mountPayment`. Handle `cart_changed` by showing the
602
685
  new totals and asking the buyer to confirm before calling checkout
603
686
  again; never charge silently.
604
687
 
605
- 7. **Return URL.** The store's `orderStatusUrl`
688
+ 8. **Return URL.** The store's `orderStatusUrl`
606
689
  (`https://shop.example.com/orders/{orderId}?token={token}`) is where the
607
690
  payment provider sends the buyer back. Serve that page: read
608
691
  `orders.get(orderId, token)` and poll with backoff until the order is
609
692
  settled: `status` is anything past `pendingPayment` (`paid`,
610
693
  `fulfilling`, `shipped`, `delivered`, `cancelled`, `refunded`, …), or it
611
694
  is still `pendingPayment` but `paymentStatus` is `failed` or `expired`
612
- (offer to check out again, step 8). `paymentStatus: 'processing'` means
695
+ (offer to check out again, step 9). `paymentStatus: 'processing'` means
613
696
  the payment succeeded and the order is being updated: keep polling.
614
697
  `isOrderSettled(order)` in `@konfiqo/storefront-react` implements this
615
698
  rule. Do not send the token to analytics or logs.
616
699
 
617
- 8. **Failed payments.** A declined, failed or expired payment cancels the
700
+ 9. **Failed payments.** A declined, failed or expired payment cancels the
618
701
  order, but the cart is **not** lost: the next `carts.get` or
619
- `carts.checkout` reopens it (`status: 'open'`) and checkout places a new
620
- order (new `orderId`, new `token`) with the same lines, buyer and
621
- addresses — the buyer re-enters nothing, including the identity number,
622
- which stays sealed on the cart until the order is paid or the cart
623
- expires. Calling checkout on an `ordered` cart whose payment is still
624
- pending re-opens the same payment (no new order). Stock is reserved for
625
- a pending order for up to 24 h.
626
-
627
- 9. **Secrets.** The publishable key is the only key that belongs in client
628
- code. The tenant API key, the operator key and the trusted storefront
629
- key are server secrets: never put them in a browser bundle, a mobile
630
- app or a public repository.
631
-
632
- 10. **Errors.** Map every code in the [table](#api-error-codes) to copy in
702
+ `carts.checkout` reopens it (`status: 'open'`). The buyer re-enters
703
+ nothing, including the identity number, which stays sealed on the cart
704
+ until the order is paid or the cart expires. The new order gets a new
705
+ order number, so the agreements the buyer accepted no longer match:
706
+ checkout answers `agreements_changed`. Call `carts.agreements(cartId)`
707
+ again, show the documents, ask the buyer to accept them, and check out
708
+ with the new `agreementsHash`. That checkout places a new order (new
709
+ `orderId`, new `token`) with the same lines, buyer and addresses.
710
+
711
+ **Re-opening a pending payment.** On an `ordered` cart whose payment is
712
+ still pending, `carts.agreements` answers `cart_read_only`, so there is
713
+ no new hash. Call
714
+ `carts.checkout(cartId, { agreementsHash: REOPEN_AGREEMENTS_HASH })`
715
+ (exported by this package). Commerce re-opens the same payment (no new
716
+ order) and does not read the hash on this path. If the old order was
717
+ cancelled in the meantime, checkout answers `agreements_changed`:
718
+ handle it as above. Stock is reserved for a pending order for up to
719
+ 24 h.
720
+
721
+ 10. **Secrets.** The publishable key is the only key that belongs in client
722
+ code. The tenant API key, the operator key and the trusted storefront
723
+ key are server secrets: never put them in a browser bundle, a mobile
724
+ app or a public repository.
725
+
726
+ 11. **Errors.** Map every code in the [table](#api-error-codes) to copy in
633
727
  your languages; never show `message` to buyers.
package/dist/index.cjs CHANGED
@@ -21,8 +21,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  BUYER_IP_HEADER: () => BUYER_IP_HEADER,
24
+ BUYER_USER_AGENT_HEADER: () => BUYER_USER_AGENT_HEADER,
24
25
  DEFAULT_TIMEOUT_MS: () => DEFAULT_TIMEOUT_MS,
26
+ LEGAL_KEYS: () => LEGAL_KEYS,
25
27
  PUBLISHABLE_KEY_HEADER: () => PUBLISHABLE_KEY_HEADER,
28
+ REOPEN_AGREEMENTS_HASH: () => REOPEN_AGREEMENTS_HASH,
26
29
  SDK_VERSION: () => SDK_VERSION,
27
30
  STOREFRONT_KEY_HEADER: () => STOREFRONT_KEY_HEADER,
28
31
  StorefrontError: () => StorefrontError,
@@ -56,6 +59,7 @@ var API_CODES = /* @__PURE__ */ new Set([
56
59
  "catalog_unavailable",
57
60
  "product_not_found",
58
61
  "content_not_found",
62
+ "blog_post_not_found",
59
63
  "cart_not_found",
60
64
  "variant_not_found",
61
65
  "line_not_found",
@@ -66,6 +70,9 @@ var API_CODES = /* @__PURE__ */ new Set([
66
70
  "cart_read_only",
67
71
  "checkout_in_progress",
68
72
  "checkout_incomplete",
73
+ "legal_not_confirmed",
74
+ "agreements_changed",
75
+ "cart_incomplete",
69
76
  "cart_changed",
70
77
  "invalid_personalization",
71
78
  "out_of_stock",
@@ -181,6 +188,7 @@ function apiError(code, status, message, b) {
181
188
  return new StorefrontError(code, status, message, {
182
189
  variantIds: arr(b.variantIds)
183
190
  });
191
+ case "cart_incomplete":
184
192
  case "checkout_incomplete":
185
193
  return new StorefrontError(code, status, message, {
186
194
  missing: arr(b.missing)
@@ -218,6 +226,8 @@ var STOREFRONT_KEY_HEADER = "x-konfiqo-storefront-key";
218
226
  var SERVER_KEY_HEADER = "x-konfiqo-server-key";
219
227
  var TURNSTILE_TOKEN_HEADER = "x-konfiqo-turnstile-token";
220
228
  var BUYER_IP_HEADER = "x-konfiqo-buyer-ip";
229
+ var BUYER_USER_AGENT_HEADER = "x-konfiqo-buyer-user-agent";
230
+ var REOPEN_AGREEMENTS_HASH = "0".repeat(64);
221
231
  function seg(v) {
222
232
  if (typeof v !== "string" || v === "" || v === "." || v === "..") {
223
233
  throw new TypeError(
@@ -281,6 +291,10 @@ function createStorefrontClient(options) {
281
291
  baseHeaders[STOREFRONT_KEY_HEADER] = options.trustedStorefrontKey;
282
292
  baseHeaders[BUYER_IP_HEADER] = buyerIp;
283
293
  }
294
+ const buyerUserAgent = options.buyerUserAgent?.trim();
295
+ if (buyerUserAgent && (options.serverKey !== void 0 || options.trustedStorefrontKey !== void 0)) {
296
+ baseHeaders[BUYER_USER_AGENT_HEADER] = buyerUserAgent;
297
+ }
284
298
  async function request(method, path, body, callOptions, extraHeaders = {}, flags = {}) {
285
299
  const url = `${baseUrl}${path()}`;
286
300
  const callerSignal = callOptions?.signal;
@@ -362,6 +376,17 @@ function createStorefrontClient(options) {
362
376
  store: {
363
377
  get: (o) => get(() => "/v1/store", o)
364
378
  },
379
+ blog: {
380
+ list: (query = {}, o) => get(() => {
381
+ const params = new URLSearchParams();
382
+ if (query.page !== void 0) params.set("page", String(query.page));
383
+ if (query.pageSize !== void 0)
384
+ params.set("pageSize", String(query.pageSize));
385
+ const qs = params.toString();
386
+ return `/v1/blog${qs ? `?${qs}` : ""}`;
387
+ }, o),
388
+ get: (slug, o) => get(() => `/v1/blog/${seg(slug)}`, o)
389
+ },
365
390
  categories: {
366
391
  list: (o) => get(() => "/v1/categories", o)
367
392
  },
@@ -421,13 +446,37 @@ function createStorefrontClient(options) {
421
446
  { id: optionId },
422
447
  o
423
448
  ),
424
- checkout: (cartId, o) => request(
449
+ agreements: (cartId, o) => request(
425
450
  "POST",
426
- () => `${cart(cartId)}/checkout`,
451
+ () => `${cart(cartId)}/agreements`,
427
452
  void 0,
428
- o,
429
- o?.turnstileToken ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken } : {}
430
- )
453
+ o
454
+ ),
455
+ checkout: async (cartId, o) => {
456
+ const hash = o?.agreementsHash;
457
+ if (typeof hash !== "string" || !/^[0-9a-f]{64}$/i.test(hash)) {
458
+ throw new StorefrontError(
459
+ "invalid_request",
460
+ 0,
461
+ "carts.checkout needs the agreementsHash of carts.agreements (64 hex characters)",
462
+ {
463
+ issues: [
464
+ {
465
+ path: "agreementsHash",
466
+ message: "Must be the 64 hex characters from carts.agreements"
467
+ }
468
+ ]
469
+ }
470
+ );
471
+ }
472
+ return request(
473
+ "POST",
474
+ () => `${cart(cartId)}/checkout`,
475
+ { agreementsHash: o.agreementsHash },
476
+ o,
477
+ o.turnstileToken ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken } : {}
478
+ );
479
+ }
431
480
  },
432
481
  orders: {
433
482
  get: (orderId, token, o) => get(
@@ -506,6 +555,16 @@ function transportError(e, timedOut, timeoutMs) {
506
555
  );
507
556
  }
508
557
 
558
+ // src/legal.ts
559
+ var LEGAL_KEYS = [
560
+ "legal.kvkk",
561
+ "legal.privacy",
562
+ "legal.preliminary-information",
563
+ "legal.distance-sales",
564
+ "legal.returns",
565
+ "legal.cookies"
566
+ ];
567
+
509
568
  // src/theme.ts
510
569
  var THEME_FONTS = [
511
570
  "inter",
@@ -764,12 +823,15 @@ async function renderTurnstile(element, siteKey, options) {
764
823
  }
765
824
 
766
825
  // src/index.ts
767
- var SDK_VERSION = "0.6.1";
826
+ var SDK_VERSION = "0.8.0";
768
827
  // Annotate the CommonJS export names for ESM import in node:
769
828
  0 && (module.exports = {
770
829
  BUYER_IP_HEADER,
830
+ BUYER_USER_AGENT_HEADER,
771
831
  DEFAULT_TIMEOUT_MS,
832
+ LEGAL_KEYS,
772
833
  PUBLISHABLE_KEY_HEADER,
834
+ REOPEN_AGREEMENTS_HASH,
773
835
  SDK_VERSION,
774
836
  STOREFRONT_KEY_HEADER,
775
837
  StorefrontError,