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