@konfiqo/storefront-sdk 0.0.0-stage → 0.5.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 +21 -0
- package/README.md +616 -2
- package/dist/index.cjs +772 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1287 -0
- package/dist/index.d.ts +1287 -0
- package/dist/index.js +725 -0
- package/dist/index.js.map +1 -0
- package/package.json +60 -4
package/README.md
CHANGED
|
@@ -1,3 +1,617 @@
|
|
|
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
|
|
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, 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) |
|
|
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
|
+
**Line personalization.** A product can ask the buyer for one short text per
|
|
267
|
+
line (an engraving, a pet's name). When it does, `product.personalization` is
|
|
268
|
+
`{ label, required, minLength, maxLength }` (absent otherwise; lengths count
|
|
269
|
+
characters). Pass the text to `carts.addLine(cartId, { variantId, quantity,
|
|
270
|
+
personalization: 'Sarı' })`; a refused text rejects with
|
|
271
|
+
`invalid_personalization` (400). The same variant with a different text is a
|
|
272
|
+
separate line, so address lines by `line.id` in `updateLine` / `removeLine`:
|
|
273
|
+
it is the variant id for a line without text and `<variantId>~<12 hex>` for a
|
|
274
|
+
line with text (a variant id still matches a line without text). Each line
|
|
275
|
+
carries `personalization: string | null` and `personalizationValid`, which is
|
|
276
|
+
false when the stored text no longer satisfies the product's current rule;
|
|
277
|
+
checkout then rejects with `invalid_personalization` and `details.lineIds`:
|
|
278
|
+
remove those lines and add them again. `id`, `personalization` and
|
|
279
|
+
`personalizationValid` are required in the types and need a Konfiqo commerce
|
|
280
|
+
API that returns them; an older server omits them, and against one treat `id`
|
|
281
|
+
as `variantId`, `personalization` as null and `personalizationValid` as true.
|
|
282
|
+
Order lines carry `personalization?: string | null`.
|
|
283
|
+
|
|
284
|
+
**Customer.** `phone` must be a Turkish mobile number (`05XX…`, `5XX…`,
|
|
285
|
+
`+90…`, `0090…`; spaces, dashes, parentheses allowed); it comes back as
|
|
286
|
+
`90XXXXXXXXXX`. Addresses use `{ name?, phone?, email?, address | line1 +
|
|
287
|
+
line2?, district, city, zipCode | postalCode, country: 'TR' }`.
|
|
288
|
+
|
|
289
|
+
**Theme.** `store.theme` is passed through as the seller stored it and is
|
|
290
|
+
not validated: every field is optional, unknown keys are kept. Narrow
|
|
291
|
+
homepage sections with `isKnownThemeSection(section)` and skip the rest;
|
|
292
|
+
render `richText` as text or sanitised markdown, never raw HTML.
|
|
293
|
+
|
|
294
|
+
## Errors
|
|
295
|
+
|
|
296
|
+
Every failure is a `StorefrontError` with `code`, `status` (HTTP status, `0`
|
|
297
|
+
without a response), `message` (for logs, not for logic) and `details`
|
|
298
|
+
(typed per code). Switch on `code`:
|
|
299
|
+
|
|
300
|
+
```ts
|
|
301
|
+
import { isStorefrontError } from '@konfiqo/storefront-sdk';
|
|
302
|
+
|
|
303
|
+
try {
|
|
304
|
+
const result = await sf.carts.checkout(cartId);
|
|
305
|
+
} catch (e) {
|
|
306
|
+
if (!isStorefrontError(e)) throw e;
|
|
307
|
+
switch (e.code) {
|
|
308
|
+
case 'cart_changed':
|
|
309
|
+
showNewTotals(e.details.totalMinor, e.details.lines);
|
|
310
|
+
break;
|
|
311
|
+
case 'out_of_stock':
|
|
312
|
+
markLines(e.details.variantIds);
|
|
313
|
+
break;
|
|
314
|
+
case 'invalid_personalization':
|
|
315
|
+
askAgain(e.details.lineIds ?? []);
|
|
316
|
+
break;
|
|
317
|
+
case 'checkout_incomplete':
|
|
318
|
+
ask(e.details.missing);
|
|
319
|
+
break;
|
|
320
|
+
case 'invalid_buyer_details':
|
|
321
|
+
focusField(e.details.field);
|
|
322
|
+
break;
|
|
323
|
+
case 'rate_limited':
|
|
324
|
+
retryIn(e.details.retryAfter ?? 5);
|
|
325
|
+
break;
|
|
326
|
+
default:
|
|
327
|
+
showGenericError();
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
`e.is('cart_changed')` narrows a single code the same way.
|
|
333
|
+
|
|
334
|
+
### API error codes
|
|
335
|
+
|
|
336
|
+
| Code | Status | `details` | Meaning / what to do |
|
|
337
|
+
| ------------------------- | -------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
338
|
+
| `store_not_found` | 404 | | bad / revoked publishable key, or the store is disabled |
|
|
339
|
+
| `origin_not_allowed` | 403 | | browser `Origin` not in the store's `allowedOrigins` |
|
|
340
|
+
| `invalid_request` | 400 | `{ issues: [{ path, message }] }` | a body or query field is invalid (e.g. `path: "phone"`) |
|
|
341
|
+
| `invalid_buyer_ip` | 400 | | trusted key sent without a valid `buyerIp` |
|
|
342
|
+
| `catalog_unavailable` | 503 | | the catalog could not be read; retry later |
|
|
343
|
+
| `product_not_found` | 404 | | no sellable product with that slug |
|
|
344
|
+
| `cart_not_found` | 404 | | unknown cart (or another store's): start a new cart |
|
|
345
|
+
| `variant_not_found` | 404 | | the variant is not sold |
|
|
346
|
+
| `insufficient_stock` | 409 | `{ available }` | only `available` units can be added |
|
|
347
|
+
| `quantity_out_of_range` | 400 | | a line holds 1–99 units |
|
|
348
|
+
| `too_many_lines` | 400 | | a cart holds at most 50 lines |
|
|
349
|
+
| `line_not_found` | 404 | | no line with that id |
|
|
350
|
+
| `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 |
|
|
352
|
+
| `checkout_in_progress` | 409 | | another checkout of this cart is running: retry in a few seconds |
|
|
353
|
+
| `checkout_incomplete` | 400 | `{ missing: ('lines' \| 'customer' \| 'identityNumber' \| 'shippingAddress' \| 'shippingOption')[] }` | collect what is missing |
|
|
354
|
+
| `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
|
+
| `out_of_stock` | 409 | `{ variantIds }` | remove / reduce those lines |
|
|
356
|
+
| `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 |
|
|
357
|
+
| `amount_out_of_range` | 400 | | total not representable |
|
|
358
|
+
| `nothing_to_pay` | 400 | | total is zero |
|
|
359
|
+
| `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 |
|
|
360
|
+
| `payment_unavailable` | 502 | | payments refused or unreachable; the order was cancelled, the cart is still open |
|
|
361
|
+
| `checkout_unavailable` | 503 | | store backend unreachable; the cart is still open, retry |
|
|
362
|
+
| `order_not_found` | 404 | | unknown order or wrong token |
|
|
363
|
+
| `order_unavailable` | 503 | | order status temporarily unavailable; poll again |
|
|
364
|
+
| `media_not_found` | 404 | | (image route) key not referenced by the catalog |
|
|
365
|
+
| `media_unavailable` | 503 | | (image route) image temporarily unavailable |
|
|
366
|
+
| `challenge_required` | 400 | | the store requires a checkout challenge and no token was sent: render the widget, check out with its token |
|
|
367
|
+
| `challenge_failed` | 403 | | the token was invalid, expired or already used: `reset()` the widget, check out with the new token |
|
|
368
|
+
| `challenge_unavailable` | 503 | | the challenge could not be verified right now: retry in a moment |
|
|
369
|
+
| `too_many_open_orders` | 429 | | too many unpaid orders from this buyer: finish or wait out a pending payment |
|
|
370
|
+
| `not_signed_in` | 401 | | no valid session cookie: sign in |
|
|
371
|
+
| `invalid_code` | 401 | | wrong, spent or expired sign-in code (5 attempts per code) |
|
|
372
|
+
| `profile_required` | 409 | | save the profile before saving addresses |
|
|
373
|
+
| `too_many_code_requests` | 429 | | too many codes requested from this address: wait |
|
|
374
|
+
| `invalid_recovery_token` | 400 | | the recovery link is malformed or not for this store |
|
|
375
|
+
| `cart_not_recoverable` | 410 | | the abandoned cart was ordered, expired or deleted: start a new cart |
|
|
376
|
+
| `unavailable` | 503 | | the account could not be read or saved right now: retry |
|
|
377
|
+
|
|
378
|
+
### Codes the SDK assigns
|
|
379
|
+
|
|
380
|
+
| Code | Status | `details` | When |
|
|
381
|
+
| ------------------ | ------ | --------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
|
382
|
+
| `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 |
|
|
383
|
+
| `unauthorized` | 401 | | a wrong `trustedStorefrontKey` |
|
|
384
|
+
| `http_error` | any | | an error response without an `error` code |
|
|
385
|
+
| `unknown_error` | any | `{ error }` | an `error` code this SDK version does not know |
|
|
386
|
+
| `invalid_response` | 2xx | | the response body is not JSON |
|
|
387
|
+
| `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) |
|
|
388
|
+
| `timeout` | 0 | `{ timeoutMs }` | no response within `timeoutMs` |
|
|
389
|
+
| `aborted` | 0 | | your `signal` aborted the request |
|
|
390
|
+
|
|
391
|
+
**In browsers.** Error responses (status ≥ 400) carry CORS headers for
|
|
392
|
+
any origin that some store allows, and expose `Retry-After` /
|
|
393
|
+
`Retry-After-ip`: a browser reads every error code, including
|
|
394
|
+
`rate_limited` with its `retryAfter`, `store_not_found` and
|
|
395
|
+
`origin_not_allowed`. A `network_error` in a browser means the API could
|
|
396
|
+
not be reached at all, or the page's origin is in **no** store's
|
|
397
|
+
`allowedOrigins` (the browser then hides the response). Treat a
|
|
398
|
+
`network_error` on checkout as "try again in a moment", not as a decline.
|
|
399
|
+
|
|
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`,
|
|
403
|
+
`checkout_unavailable`, `catalog_unavailable`, `rate_limited`).
|
|
404
|
+
|
|
405
|
+
## Payment
|
|
406
|
+
|
|
407
|
+
`carts.checkout` answers how to present payment, by `presentation`:
|
|
408
|
+
|
|
409
|
+
| `presentation` | Fields | Do |
|
|
410
|
+
| -------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
|
|
411
|
+
| `embedded` | `embed: { kind, content }` | render the provider's form in your page |
|
|
412
|
+
| `redirect` | `url` | top-level navigation to `url` (never an iframe) |
|
|
413
|
+
| `closed` | `page` (+ `orderStatus`) | payment cannot be (re)opened: show the order status page. `page` is `paid`, `cancelled`, `processing`, `expired`, `failed` or `not_found` |
|
|
414
|
+
|
|
415
|
+
`mountPayment` does each of these:
|
|
416
|
+
|
|
417
|
+
```ts
|
|
418
|
+
import { mountPayment } from '@konfiqo/storefront-sdk';
|
|
419
|
+
|
|
420
|
+
const result = await sf.carts.checkout(cartId);
|
|
421
|
+
if (result.token) saveOrderToken(result.orderId, result.token); // returned ONCE
|
|
422
|
+
const token = result.token ?? loadOrderToken(result.orderId);
|
|
423
|
+
|
|
424
|
+
const mount = mountPayment(document.getElementById('payment')!, result, {
|
|
425
|
+
onClosed: () =>
|
|
426
|
+
router.push(`/orders/${result.orderId}?token=${encodeURIComponent(token)}`),
|
|
427
|
+
});
|
|
428
|
+
// mount.kind: 'embedded' (mount.unmount()), 'redirect', 'closed', or
|
|
429
|
+
// 'unsupported' (an embed kind this SDK cannot render: show a fallback)
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
- **embedded** (`iyzico-checkout-form`): puts the provider's HTML into the
|
|
433
|
+
element and re-creates every `<script>` (attributes + text) so it
|
|
434
|
+
executes — `innerHTML` alone never runs scripts. Mounting the same form
|
|
435
|
+
into the same element again does nothing; a different form replaces the
|
|
436
|
+
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,
|
|
439
|
+
URL parameters or storage: the embedded content is executed as script.
|
|
440
|
+
This is the provider's own form: card data goes from it to the provider
|
|
441
|
+
and never through your code. If you use a Content Security Policy, allow
|
|
442
|
+
the provider's script and frame origins.
|
|
443
|
+
- **redirect**: `window.location.assign(url)`; only `http(s)` URLs.
|
|
444
|
+
- **closed**: calls `onClosed(page)` and returns `{ kind: 'closed', page }`.
|
|
445
|
+
|
|
446
|
+
## Checkout challenge
|
|
447
|
+
|
|
448
|
+
A store can require a bot challenge (Cloudflare Turnstile) on checkout.
|
|
449
|
+
`store.checkoutChallenge` is then `{ provider: 'turnstile', siteKey }`
|
|
450
|
+
(`null` or absent: no challenge).
|
|
451
|
+
|
|
452
|
+
```ts
|
|
453
|
+
import { renderTurnstile } from '@konfiqo/storefront-sdk';
|
|
454
|
+
|
|
455
|
+
let token: string | null = null;
|
|
456
|
+
const challenge = store.checkoutChallenge; // null: skip the widget
|
|
457
|
+
const widget = challenge
|
|
458
|
+
? await renderTurnstile(
|
|
459
|
+
document.getElementById('challenge')!,
|
|
460
|
+
challenge.siteKey,
|
|
461
|
+
{
|
|
462
|
+
onToken: (t) => (token = t),
|
|
463
|
+
onExpired: () => (token = null),
|
|
464
|
+
},
|
|
465
|
+
)
|
|
466
|
+
: null;
|
|
467
|
+
|
|
468
|
+
async function pay() {
|
|
469
|
+
try {
|
|
470
|
+
return await sf.carts.checkout(cartId, {
|
|
471
|
+
turnstileToken: token ?? undefined,
|
|
472
|
+
});
|
|
473
|
+
} finally {
|
|
474
|
+
token = null;
|
|
475
|
+
widget?.reset(); // tokens are single-use: every checkout call needs a new one
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
- `loadTurnstile(document)` injects Cloudflare's official script
|
|
481
|
+
(`https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit`)
|
|
482
|
+
once per document and resolves with `window.turnstile`; nothing else is
|
|
483
|
+
ever injected. `renderTurnstile` calls it for you. If the script fails to
|
|
484
|
+
load, the promise rejects and the failed tag is removed: calling again retries.
|
|
485
|
+
- Tokens are **single-use** and expire after about 5 minutes: reset the
|
|
486
|
+
widget after every checkout call, successful or not
|
|
487
|
+
(`challenge_failed` = used, expired or invalid token).
|
|
488
|
+
- On your own site, the widget only works on hostnames Cloudflare knows
|
|
489
|
+
for the store's site key: your domain must be one of the store's domains
|
|
490
|
+
/ `allowedOrigins` **and** in the widget's hostname list (ask the store
|
|
491
|
+
operator).
|
|
492
|
+
- Re-opening payment on an already ordered cart needs no token.
|
|
493
|
+
- With a Content Security Policy, allow `https://challenges.cloudflare.com`
|
|
494
|
+
in `script-src` and `frame-src`.
|
|
495
|
+
|
|
496
|
+
## Cookies
|
|
497
|
+
|
|
498
|
+
`store.cookies` lists the cookies the store uses (`CookieInfo`: `name`,
|
|
499
|
+
`category` of `'necessary' | 'analytics' | 'marketing'`, `purpose` in the
|
|
500
|
+
store's language, `durationDays`). It is empty when the store uses no
|
|
501
|
+
optional cookie: then nothing needs the shopper's consent.
|
|
502
|
+
`store.consentVersion` identifies the set of optional cookies ('' when
|
|
503
|
+
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.
|
|
506
|
+
|
|
507
|
+
## Helpers
|
|
508
|
+
|
|
509
|
+
- `formatMoney(minor, currency, locale?)` — `Intl.NumberFormat` with the
|
|
510
|
+
currency's own minor digits: `formatMoney(14990, 'TRY', 'tr-TR')` →
|
|
511
|
+
`₺149,90`.
|
|
512
|
+
- `loadCartId(storage, storeId)`, `saveCartId(storage, storeId, cartId)`,
|
|
513
|
+
`clearCartId(storage, storeId)` — remember the cart per store in
|
|
514
|
+
`localStorage` (or any `{ getItem, setItem, removeItem }`). Key
|
|
515
|
+
`storefront:cart:<storeId>`. They never throw: no storage (SSR), a
|
|
516
|
+
throwing storage (private mode) → `null` / `false`.
|
|
517
|
+
- `cookieCartStorage()` — the same interface over the first-party
|
|
518
|
+
`__Host-konfiqo_cart` cookie, which the hosted checkout on a store domain
|
|
519
|
+
reads too.
|
|
520
|
+
- **Clearing a cart on a store domain.** A frontend served on the store's
|
|
521
|
+
own domain shares both the cookie and `localStorage` with the hosted
|
|
522
|
+
storefront, which restores a cart id from `localStorage` whenever the
|
|
523
|
+
cookie is missing (Safari expires script-written cookies after 7 days).
|
|
524
|
+
`clearCartId(localStorage, …)` or `cookieCartStorage().removeItem` on
|
|
525
|
+
their own are therefore not enough: neither writes the
|
|
526
|
+
`storefront:cart:<storeId>:cleared` tombstone, so the old cart comes back.
|
|
527
|
+
Clear through `@konfiqo/storefront-react`'s `defaultCartStorage()` (or
|
|
528
|
+
`useCartStorage()`), e.g. `clearCartId(defaultCartStorage(), storeId)`,
|
|
529
|
+
which clears the cookie and `localStorage` and writes the tombstone. On
|
|
530
|
+
your own domain (not a store domain) `localStorage` alone is fine.
|
|
531
|
+
- **`storeId`** is any string that is stable for one store and different
|
|
532
|
+
between stores: it only names the storage key. The API does not return a
|
|
533
|
+
store id; use the publishable key (it is public anyway), or a string the
|
|
534
|
+
store operator gives you. Changing it later forgets carts saved under the
|
|
535
|
+
old value.
|
|
536
|
+
|
|
537
|
+
## Build your own storefront
|
|
538
|
+
|
|
539
|
+
1. **Operator setup.** Ask the store operator to:
|
|
540
|
+
- mint a `pk_live_…` publishable key for you;
|
|
541
|
+
- list your site's exact origins (`https://shop.example.com`, plus
|
|
542
|
+
`http://localhost:3000` for development) in the store's
|
|
543
|
+
`allowedOrigins` (not as a store _domain_: store domains are routed
|
|
544
|
+
to the hosted storefront);
|
|
545
|
+
- set the store's `orderStatusUrl` to **your** order page, e.g.
|
|
546
|
+
`https://shop.example.com/orders/{orderId}?token={token}` (step 7);
|
|
547
|
+
- add your origin to the tenant's payments connection **allowed return
|
|
548
|
+
addresses** (`allowedReturnOrigins`), else checkout fails with
|
|
549
|
+
`payment_unavailable`;
|
|
550
|
+
- if the store uses a checkout challenge, add your hostname to its
|
|
551
|
+
Turnstile widget's hostname list, else checkout fails with
|
|
552
|
+
`challenge_failed`.
|
|
553
|
+
|
|
554
|
+
2. **CORS and `allowedOrigins`.** <a id="cors-and-allowedorigins"></a>
|
|
555
|
+
Browser requests must come from one of those origins, else 403
|
|
556
|
+
`origin_not_allowed` (an origin that no store allows at all sees
|
|
557
|
+
`network_error` instead). The API
|
|
558
|
+
allows only the `content-type`, `x-konfiqo-publishable-key` and (on
|
|
559
|
+
checkout) `x-konfiqo-turnstile-token` request headers cross-origin. Server-side requests (no `Origin`) are always
|
|
560
|
+
allowed.
|
|
561
|
+
|
|
562
|
+
3. **Catalog.** `store.get()` for name, currency, language, theme, legal
|
|
563
|
+
texts (show KVKK, distance-sales and returns texts at checkout);
|
|
564
|
+
`categories.list()`, `products.list()`, `products.get(slug)`. Build
|
|
565
|
+
variant pickers from `variant.optionValues`; disable variants with
|
|
566
|
+
`available === 0`.
|
|
567
|
+
|
|
568
|
+
4. **Cart.** `carts.create()` once, `saveCartId(localStorage, storeId, cart.id)`.
|
|
569
|
+
The cart id is a bearer capability — keep it in the buyer's browser
|
|
570
|
+
only. On `cart_not_found` or `cart_read_only` with `status: 'expired'`,
|
|
571
|
+
`clearCartId` and create a new cart (on a store domain, through the
|
|
572
|
+
React package's storage: see "Clearing a cart on a store domain").
|
|
573
|
+
Carts live 7 days.
|
|
574
|
+
|
|
575
|
+
5. **Checkout form.** `setCustomer` (Turkish mobile number; the **identity
|
|
576
|
+
number** — TC kimlik no, 11 digits — is required by the payment
|
|
577
|
+
provider, is stored sealed, is never returned (`identityNumberProvided`
|
|
578
|
+
tells you one is on file) and can be omitted on later calls to keep the
|
|
579
|
+
one on file; show a KVKK notice next to the field), `setAddress`,
|
|
580
|
+
`shippingOptions` + `setShippingOption`.
|
|
581
|
+
|
|
582
|
+
6. **Pay.** If `store.checkoutChallenge` is set, render the challenge
|
|
583
|
+
widget first ([below](#checkout-challenge)). `carts.checkout(cartId, { turnstileToken })`. Store the returned `token` with the
|
|
584
|
+
`orderId` — it is returned only once and is the buyer's only key to the
|
|
585
|
+
order page. Then `mountPayment`. Handle `cart_changed` by showing the
|
|
586
|
+
new totals and asking the buyer to confirm before calling checkout
|
|
587
|
+
again; never charge silently.
|
|
588
|
+
|
|
589
|
+
7. **Return URL.** The store's `orderStatusUrl`
|
|
590
|
+
(`https://shop.example.com/orders/{orderId}?token={token}`) is where the
|
|
591
|
+
payment provider sends the buyer back. Serve that page: read
|
|
592
|
+
`orders.get(orderId, token)` and poll with backoff until the order is
|
|
593
|
+
settled: `status` is anything past `pendingPayment` (`paid`,
|
|
594
|
+
`fulfilling`, `shipped`, `delivered`, `cancelled`, `refunded`, …), or it
|
|
595
|
+
is still `pendingPayment` but `paymentStatus` is `failed` or `expired`
|
|
596
|
+
(offer to check out again, step 8). `paymentStatus: 'processing'` means
|
|
597
|
+
the payment succeeded and the order is being updated: keep polling.
|
|
598
|
+
`isOrderSettled(order)` in `@konfiqo/storefront-react` implements this
|
|
599
|
+
rule. Do not send the token to analytics or logs.
|
|
600
|
+
|
|
601
|
+
8. **Failed payments.** A declined, failed or expired payment cancels the
|
|
602
|
+
order, but the cart is **not** lost: the next `carts.get` or
|
|
603
|
+
`carts.checkout` reopens it (`status: 'open'`) and checkout places a new
|
|
604
|
+
order (new `orderId`, new `token`) with the same lines, buyer and
|
|
605
|
+
addresses — the buyer re-enters nothing, including the identity number,
|
|
606
|
+
which stays sealed on the cart until the order is paid or the cart
|
|
607
|
+
expires. Calling checkout on an `ordered` cart whose payment is still
|
|
608
|
+
pending re-opens the same payment (no new order). Stock is reserved for
|
|
609
|
+
a pending order for up to 24 h.
|
|
610
|
+
|
|
611
|
+
9. **Secrets.** The publishable key is the only key that belongs in client
|
|
612
|
+
code. The tenant API key, the operator key and the trusted storefront
|
|
613
|
+
key are server secrets: never put them in a browser bundle, a mobile
|
|
614
|
+
app or a public repository.
|
|
615
|
+
|
|
616
|
+
10. **Errors.** Map every code in the [table](#api-error-codes) to copy in
|
|
617
|
+
your languages; never show `message` to buyers.
|