@shop2topup/sdk 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/AGENTS.md +265 -0
  2. package/CHANGELOG.md +26 -0
  3. package/FAQ.md +177 -0
  4. package/GUIDE.md +313 -0
  5. package/LICENSE +24 -0
  6. package/README.md +201 -2
  7. package/dist/cjs/client.d.ts +229 -0
  8. package/dist/cjs/client.js +696 -0
  9. package/dist/cjs/error-codes.d.ts +126 -0
  10. package/dist/cjs/error-codes.js +169 -0
  11. package/dist/cjs/errors.d.ts +96 -0
  12. package/dist/cjs/errors.js +195 -0
  13. package/dist/cjs/http.d.ts +92 -0
  14. package/dist/cjs/http.js +269 -0
  15. package/dist/cjs/index.d.ts +12 -0
  16. package/dist/cjs/index.js +21 -0
  17. package/dist/cjs/models.d.ts +182 -0
  18. package/dist/cjs/models.js +188 -0
  19. package/dist/cjs/money.d.ts +14 -0
  20. package/dist/cjs/money.js +31 -0
  21. package/dist/cjs/package.json +1 -0
  22. package/dist/cjs/version.d.ts +2 -0
  23. package/dist/cjs/version.js +5 -0
  24. package/dist/cjs/webhooks.d.ts +20 -0
  25. package/dist/cjs/webhooks.js +81 -0
  26. package/dist/esm/client.d.ts +229 -0
  27. package/dist/esm/client.js +686 -0
  28. package/dist/esm/error-codes.d.ts +126 -0
  29. package/dist/esm/error-codes.js +166 -0
  30. package/dist/esm/errors.d.ts +96 -0
  31. package/dist/esm/errors.js +187 -0
  32. package/dist/esm/http.d.ts +92 -0
  33. package/dist/esm/http.js +263 -0
  34. package/dist/esm/index.d.ts +12 -0
  35. package/dist/esm/index.js +5 -0
  36. package/dist/esm/models.d.ts +182 -0
  37. package/dist/esm/models.js +175 -0
  38. package/dist/esm/money.d.ts +14 -0
  39. package/dist/esm/money.js +27 -0
  40. package/dist/esm/package.json +1 -0
  41. package/dist/esm/version.d.ts +2 -0
  42. package/dist/esm/version.js +2 -0
  43. package/dist/esm/webhooks.d.ts +20 -0
  44. package/dist/esm/webhooks.js +78 -0
  45. package/examples/express-webhook.mjs +68 -0
  46. package/examples/nextjs-route.ts +43 -0
  47. package/examples/node-http-webhook.mjs +109 -0
  48. package/examples/quickstart.mjs +67 -0
  49. package/llms.txt +26 -0
  50. package/package.json +65 -4
package/AGENTS.md ADDED
@@ -0,0 +1,265 @@
1
+ # AGENTS.md — @shop2topup/sdk (Node.js / TypeScript)
2
+
3
+ Instructions for AI coding tools that write code with this SDK. Follow every rule; each one prevents a real loss. The flow and every rule in full: [`GUIDE.md`](GUIDE.md) (shipped in this package); short answers: [`FAQ.md`](FAQ.md).
4
+
5
+ ## Rules
6
+
7
+ 1. **The key stays on the server.** Read it from the environment (`SHOP2TOPUP_API_KEY`); never hard-code it, never send it to a browser, mobile app or log. `new Shop2Topup()` reads the env var itself, and `SHOP2TOPUP_BASE_URL` too. Without `SHOP2TOPUP_BASE_URL` the SDK talks to **production**: real orders, real money.
8
+ 2. **Money is a string.** Prices, balances and charges are six-decimal strings (`"0.950000"`). Never `parseFloat`, `Number(...)` or `+price` them. Store as text / `NUMERIC(18,6)`; compute with integer micro-units or a decimal library.
9
+ 3. **Store your order id before `buy`.** `const orderId = newOrderId()`, save it with your own order row, then `orders.buy({ orderId, ... })`. On a timeout or any doubt, call `buy` again with the **same** `orderId`: it can never charge twice and returns the existing order (`alreadyExisted: true`). After a crash or a restart, resume with the saved order id: read it first (`orders.get(savedId)`). Found: that is your order. `ORDER_NOT_FOUND`: call `buy` again with the same saved id.
10
+ 4. **A new `orderId` only when `err.orderMayExist` is `false`.** Retrying with the same `orderId` is always safe. `orderMayExist` is `true` for a network error, `TIMEOUT`, `UNEXPECTED_RESPONSE`, any 5xx, `DUPLICATE_ORDER` and action `CHECK_ORDER`: keep the id and call `buy` again later (or `orders.get(orderId)`). It is `false` when the server refused with a 4xx (`INSUFFICIENT_BALANCE`, `PLAYER_NOT_FOUND`, `OUT_OF_STOCK`, ...) or the SDK refused before sending: this call made no order. `orderMayExist` speaks only for the call that raised it. Never switch to a new id for a purchase just because a resumed call was refused (`PRICE_INCREASED`, `OUT_OF_STOCK`…): such a refusal does not prove the earlier attempt made no order. A buyer buying the same pack again is a new purchase with a new id.
11
+ 5. **`expectedPrice` = `catalog.price(packId).price`, the exact string you showed.** Call `catalog.price` when you show the pack at checkout, keep that string with the cart line, send it unchanged. `pack.price` from the list is a browsing guide, not the value to send. Never fetch a fresh price just before `buy` to fill it (that defeats the guard). `PRICE_INCREASED` means: show the new price (`err.currentPrice`; `null` when the account cannot see prices, e.g. prices locked) and ask again.
12
+ 6. **Render fields from `catalog.fields(categoryId)`.** Never hard-code `player_id`/`zone_id` per game. Send `fields` keyed by `field.name`; for select types offer only `field.options`. A category that needs no input (every gift card) returns `[]`.
13
+ 7. **Gift cards (`pack.type === 'voucher'`): skip `players.check` and send `fields: {}`** (unless `catalog.fields` lists something). **Codes:** when an order is `completed`, all its codes are in `order.codes`. On `partial`, gift cards from stock have their delivered codes in `order.codes`; packs delivered per unit (top-ups, and some gift-card packs) have them in each unit's `codes`. Collect from both; do not decide from the pack type.
14
+ 8. **Top-ups: show the player name before payment** (`players.check(...).playerName`) when `needed` is true. `needed: false` is a pass, not an error. `PLAYER_CHECK_UNAVAILABLE` does NOT mean the id is wrong. `buy` checks the player itself; `players.check` is for the buyer's confirmation. It never creates an order: ignore `orderMayExist` on its errors. Its daily quota is per account and pack.
15
+ 9. **Waiting pattern.** After `buy`, `orders.wait(order.id, { timeout: 120 })` while the buyer is on the page (first check after 2 s, then every 20 s). `wait` makes its last read when the timeout comes, so it can end up to that one read's duration after `timeout`. On `WAIT_TIMEOUT` show "processing" and keep the order `pending` in your database: a **webhook** (top-ups and gift cards) updates it, and a **scheduled job** (every few minutes) calls `orders.getMany` for orders still `pending` (catches webhooks lost while your server was down; `getMany` takes any number of ids and sleeps through the batch limit between its calls). Never poll faster than the SDK: 3 reads a minute per order, 2 batch or list calls a minute. Do not wrap SDK calls in your own retry loop: the SDK already retries what is safe.
16
+ 10. **A failed top-up stays `pending` until refunded.** A top-up that fails at the supplier stays `pending` until it is refunded automatically; this can take from under an hour to several hours. There is no "failed" status: money is either delivered or back in your wallet. `pending` is not failure, `WAIT_TIMEOUT` is not failure: the order still exists; check it later.
17
+ 11. **Verify webhooks on the raw body.** `express.raw(...)`, `await req.arrayBuffer()` or the bytes collected from a `node:http` request stream; never `express.json()` / `req.json()` before `verifyWebhook`. **Setup check:** when the webhook URL is saved in the panel, we first send an unsigned check (header `X-Shop2Topup-Event: webhook.test`, body `{"event":"webhook.test","timestamp":"…"}`, no signature header): answer it with any 2xx within 10 s and do nothing else, or the panel refuses the URL (the secret is created only after this check passes; every new save makes a new secret). Every other message is signed: verify it. **Save before 2xx:** save the new status first (one quick write, safe to run twice), then answer 2xx within 10 s, then do slow work (emails, delivery). A 2xx ends the tries; an error answer makes us try again. **Retries:** a delivery without a 2xx within 10 s is sent again 30 s later and then 1 minute after that (3 tries in all, each with the order's current status, a fresh timestamp and a new signature); a message still waiting 1 hour after it was queued is dropped. So the same message can arrive more than once, and a message can be lost: keep the scheduled `orders.getMany`. **Events:** top-up orders send one message per unit delivered (`order.completed`) or refunded (`order.refunded`); gift-card orders send one message when the order settles (`order.completed` when every code is delivered, `order.refunded` when it is refunded or partly delivered: status `partial`, the delivered codes in `event.order.codes`). Always update your order from `event.order.status` (the whole order's status), forward only (`pending` → final). A message can arrive before `buy` returned.
18
+ 12. **`tolerance: 0` / `now` only to replay recorded messages in tests.** Production keeps the default 5 minutes.
19
+ 13. **Branch on `err.action` (or `err.code`), never on `err.message`.** Unknown codes still carry a valid `action`; `NONE` means nothing to do. `SIGN_IN` is not sent by the API today: a wrong or revoked key is `INVALID_API_KEY` (HTTP 401, action `FIX_INPUT`).
20
+ 14. All durations in options are **seconds** (`timeout`, `firstPollDelay`, `pollInterval`, `maxRetryWait`, `tolerance`); `err.retryAfter` is seconds.
21
+
22
+ ## Methods
23
+
24
+ ```ts
25
+ import { Shop2Topup, Shop2TopupError, ErrorCode, verifyWebhook, newOrderId } from '@shop2topup/sdk';
26
+
27
+ new Shop2Topup(options?: {
28
+ apiKey?: string; baseUrl?: string; timeout?: number; maxRetries?: number; maxRetryWait?: number;
29
+ webhookSecret?: string; userAgent?: string; fetch?: FetchLike; clock?: () => number; sleep?: (ms: number) => Promise<void>;
30
+ })
31
+ Shop2Topup.newOrderId(): string // same as newOrderId(): crypto.randomUUID()
32
+
33
+ s2t.account.get(): Promise<Account> // { email, balance: Money }
34
+
35
+ s2t.catalog.games({ locale?, withImages? }?): Promise<Game[]>
36
+ s2t.catalog.categories({ gameId?, locale?, withImages? }?): Promise<Category[]> // locale has no effect here today
37
+ s2t.catalog.packs({ categoryId?, locale?, withImages? }?): Promise<Pack[]> // withImages and locale have no effect today: imageUrl null, descriptions not translated
38
+ s2t.catalog.price(packId: number): Promise<PackPrice> // .price is the exact Money to show + send as expectedPrice
39
+ s2t.catalog.fields(categoryId: number): Promise<Field[]> // [] when the category needs no input (gift cards)
40
+ s2t.catalog.find(text: string, { type?: 'topup' | 'voucher' }?): Promise<Pack[]>
41
+
42
+ s2t.players.check({ packId, playerId, fields? }): Promise<PlayerCheck> // top-ups: { needed, playerId, playerName, region, zoneId }
43
+
44
+ s2t.orders.buy({ packId, quantity = 1, expectedPrice, fields, orderId? }): Promise<Order>
45
+ s2t.orders.get(orderId: string): Promise<Order>
46
+ s2t.orders.getMany(orderIds: string[]): Promise<{ orders: Order[]; notFound: string[] }> // any number of ids: 50 per call; a 429 between calls is slept through
47
+ s2t.orders.list({ status?, from?, to?, page?, limit? }?): Promise<{ orders, page, limit, total, totalPages }> // rows without an order id (prepaid codes) left out; total is the server's
48
+ s2t.orders.listAll(filters?): AsyncGenerator<Order> // for await (const o of s2t.orders.listAll({ status: 'completed' }))
49
+ s2t.orders.wait(orderId, { timeout = 600, firstPollDelay = 2, pollInterval = 20, onUpdate? }?): Promise<Order> // throws WAIT_TIMEOUT (err.order); may end one read after timeout
50
+ s2t.orders.waitMany(orderIds, { timeout = 600, firstPollDelay = 2, pollInterval = 30, onUpdate? }?):
51
+ Promise<{ finished: Order[]; pending: Order[]; notFound: string[]; unchecked: string[] }> // never throws on timeout
52
+
53
+ s2t.webhooks.verify(rawBody, signatureHeader, { secret?, tolerance = 300, now? }?): WebhookEvent
54
+ verifyWebhook(rawBody, signatureHeader, { secret, tolerance = 300, now? }): WebhookEvent // no client needed
55
+ ```
56
+
57
+ Models (every one also has `raw`, the server object):
58
+
59
+ - `Pack { id, name, description, imageUrl, categoryId, categoryName, type: 'topup'|'voucher', inStock, price: Money|null, pricesLocked }`
60
+ - `PackPrice { packId, packName, price, listPrice, discount, inStock, at }`
61
+ - `Field { name, type: 'text'|'number'|'single_select'|'multi_select', placeholder, options: string[] }`
62
+ - `Order { id, status: 'pending'|'completed'|'refunded'|'partial', isFinished, playerId, playerName, packName, quantity, charged, currency, createdAt, finishedAt, codes: Code[], units: Unit[], summary: {total, completed, pending, refunded} | null, alreadyExisted }` — gift cards from stock have no units (`units` empty, `summary` null); packs delivered per unit (top-ups, some gift-card packs) have units. `charged` stays the amount charged at creation, also after a refund. Refunded on `partial`: for orders with units, the sum of `amount` of the units with status `refunded`; gift-card orders without units: the codes not delivered (`quantity` minus delivered codes) were refunded to your wallet, no itemised amount.
63
+ - `Code { code, serial, expiresAt }` — gift-card codes are cash: store encrypted, show only to the buyer.
64
+ - `Unit { n, status, playerId, playerName, amount, createdAt, finishedAt, codes }`
65
+ - `WebhookEvent { type, sentAt, order: Order|null, message, raw }` — `type` is `order.completed`, `order.refunded` (a top-up unit, or a settled gift-card order) or `webhook.test`; `order` is null for `webhook.test`.
66
+
67
+ Errors: `Shop2TopupError { code, message, action, retryable, retryAfter, status, details, availableQuantity, orderId, order, orderMayExist, raw }` with `is(code)`, `isInsufficientBalance()`, `isPlayerNotFound()`, `isOutOfStock()`, `isPriceIncreased()` (`currentPrice`, `expectedPrice`), `isRateLimited()`. `status` is the HTTP status, 0 when no answer came back (network) or the SDK refused before sending. Actions: `FIX_INPUT`, `RETRY_SOON`, `RETRY_LATER`, `TOP_UP`, `CHOOSE_OTHER`, `CONTACT_SUPPORT`, `CHECK_ORDER`, `SIGN_IN` (not sent by the API today), `NONE`, or a newer value passed through unchanged.
68
+
69
+ Common codes: `INSUFFICIENT_BALANCE` (TOP_UP) · `PRICE_INCREASED` (FIX_INPUT) · `OUT_OF_STOCK` (not enough stock for this quantity right now, there may be fewer: try fewer, later, or another pack) / `INSUFFICIENT_STOCK` (some packs only: fewer left than asked, `err.availableQuantity` says how many) · `INVALID_API_KEY` / `MISSING_API_KEY` (401, FIX_INPUT: the key is wrong or was replaced) · `PLAYER_NOT_FOUND` · `REGION_MISMATCH` (CHOOSE_OTHER, `details.player_region`) · `MISSING_REQUIRED_FIELD` (`details.field`) · `RELOAD_REQUIRED` (TOP_UP, prices locked) · `PLAYER_CHECK_UNAVAILABLE` (retry later; the id was not rejected) · `RATE_LIMIT_EXCEEDED` · `WAIT_TIMEOUT` (CHECK_ORDER) · `NO_REQUIREMENTS_FOUND` (NONE; `catalog.fields` returns `[]` for it) · SDK-made: `CONNECTION_ERROR`, `TIMEOUT`, `UNEXPECTED_RESPONSE`, `MISSING_EXPECTED_PRICE`, `INVALID_UUID_FORMAT`, `INVALID_QUANTITY`, `INVALID_API_KEY_FORMAT`, `WEBHOOK_*`.
70
+
71
+ ## Webhook messages
72
+
73
+ ```
74
+ POST /your/webhook/path
75
+ Content-Type: application/json
76
+ X-Shop2Topup-Signature: sha256=<64 hex chars: HMAC-SHA256 of the raw body with your webhook secret>
77
+ X-Shop2Topup-Event: order.completed
78
+ User-Agent: shop2topup-webhook/1.0
79
+
80
+ {"event":"order.completed","timestamp":"2026-12-02T10:00:00.000Z","data":{"order_id":"0b6f3c2e-…","status":"completed","player_id":"123456789","player_name":"PlayerOne","subcategory_name":"FF 100 Diamonds","quantity":1,"charged_amount":"0.950000","currency":"USD","created_at":"…","completed_at":"…","sub_transaction_summary":{"total":1,"completed":1,"pending":0,"refunded":0,"failed":0,"retrying":0,"processing":0}}}
81
+ ```
82
+
83
+ The summary's `failed`, `retrying` and `processing` counts are old fields (always 0); `event.order.summary` keeps `total`, `completed`, `pending`, `refunded`, and `raw` keeps everything. Gift-card orders carry no summary; their delivered codes are in `data.vouchers` (`event.order.codes`).
84
+
85
+ The setup check sent when the URL is saved in the panel has no signature header and no `data`:
86
+
87
+ ```
88
+ POST /your/webhook/path
89
+ Content-Type: application/json
90
+ X-Shop2Topup-Event: webhook.test
91
+
92
+ {"event":"webhook.test","timestamp":"2026-12-02T10:00:00.000Z"}
93
+ ```
94
+
95
+ Header names are case-insensitive (Node lower-cases them: `req.headers['x-shop2topup-signature']`). `verifyWebhook` maps `data` to `event.order` (the same `Order` model as `orders.get`, without `units`): use `event.order.id` and `event.order.status`, not `data.order_id` by hand.
96
+
97
+ ## Recipes
98
+
99
+ ### Express webhook receiver
100
+
101
+ ```js
102
+ import express from 'express';
103
+ import { verifyWebhook, Shop2TopupError } from '@shop2topup/sdk';
104
+
105
+ const app = express();
106
+ app.post('/webhooks/shop2topup', express.raw({ type: '*/*' }), async (req, res) => {
107
+ // Setup check (unsigned webhook.test when the URL is saved in the panel): 2xx, nothing else.
108
+ if (req.get('X-Shop2Topup-Event') === 'webhook.test' && !req.get('X-Shop2Topup-Signature')) return res.sendStatus(200);
109
+ let event;
110
+ try {
111
+ event = verifyWebhook(req.body, req.get('X-Shop2Topup-Signature'), { secret: process.env.SHOP2TOPUP_WEBHOOK_SECRET });
112
+ } catch (err) {
113
+ if (err instanceof Shop2TopupError) return res.status(400).send(err.code);
114
+ throw err;
115
+ }
116
+ if (event.order) await db.moveForward(event.order.id, event.order.status); // 1. quick save: idempotent, pending → final only
117
+ res.sendStatus(200); // 2. answer within 10 s (an error answer is tried again)
118
+ if (event.order) queueBuyerEmail(event.order.id); // 3. slow work only after answering
119
+ });
120
+ app.use(express.json()); // other routes may parse JSON; register it AFTER the webhook route
121
+ ```
122
+
123
+ ### Plain `node:http` webhook receiver (no framework)
124
+
125
+ ```js
126
+ import { createServer } from 'node:http';
127
+ import { verifyWebhook, Shop2TopupError } from '@shop2topup/sdk';
128
+
129
+ createServer((req, res) => {
130
+ if (req.method !== 'POST' || req.url !== '/webhooks/shop2topup') return res.writeHead(404).end();
131
+ const chunks = [];
132
+ req.on('data', (c) => chunks.push(c)); // collect the RAW bytes
133
+ req.on('end', async () => {
134
+ // Setup check (unsigned webhook.test when the URL is saved in the panel): 2xx, nothing else.
135
+ if (req.headers['x-shop2topup-event'] === 'webhook.test' && !req.headers['x-shop2topup-signature']) return res.writeHead(200).end('ok');
136
+ let event;
137
+ try {
138
+ event = verifyWebhook(Buffer.concat(chunks), req.headers['x-shop2topup-signature'],
139
+ { secret: process.env.SHOP2TOPUP_WEBHOOK_SECRET });
140
+ } catch (err) {
141
+ return res.writeHead(err instanceof Shop2TopupError ? 400 : 500).end();
142
+ }
143
+ if (event.order) await db.moveForward(event.order.id, event.order.status); // 1. quick save
144
+ res.writeHead(200).end('ok'); // 2. answer within 10 s
145
+ if (event.order) queueBuyerEmail(event.order.id); // 3. slow work only after answering
146
+ });
147
+ }).listen(3000);
148
+ ```
149
+
150
+ Full file with a body-size limit: [`examples/node-http-webhook.mjs`](examples/node-http-webhook.mjs).
151
+
152
+ ### Next.js App Router route (`app/api/webhooks/shop2topup/route.ts`)
153
+
154
+ ```ts
155
+ import { verifyWebhook, Shop2TopupError } from '@shop2topup/sdk';
156
+ export const runtime = 'nodejs';
157
+
158
+ export async function POST(req: Request) {
159
+ // Setup check (unsigned webhook.test when the URL is saved in the panel): 2xx, nothing else.
160
+ if (req.headers.get('x-shop2topup-event') === 'webhook.test' && !req.headers.get('x-shop2topup-signature')) return new Response('ok');
161
+ const raw = Buffer.from(await req.arrayBuffer());
162
+ try {
163
+ const event = verifyWebhook(raw, req.headers.get('x-shop2topup-signature'), { secret: process.env.SHOP2TOPUP_WEBHOOK_SECRET });
164
+ if (event.order) await saveStatus(event.order.id, event.order.status); // 1. quick save, then 2. answer
165
+ return new Response('ok'); // 3. slow work: after() or a queue
166
+ } catch (err) {
167
+ if (err instanceof Shop2TopupError) return new Response(err.code, { status: 400 });
168
+ throw err;
169
+ }
170
+ }
171
+ ```
172
+
173
+ ### Testing a handler with a recorded (old) message
174
+
175
+ ```js
176
+ // Test code only: a recorded message is older than 5 minutes, so turn the age check off or pin `now`.
177
+ const event = verifyWebhook(recordedBody, recordedSignature, { secret, tolerance: 0 });
178
+ const same = verifyWebhook(recordedBody, recordedSignature, { secret, now: Date.parse(recordedTimestamp) });
179
+ ```
180
+
181
+ ### Checkout: buy, then wait briefly
182
+
183
+ ```js
184
+ import { Shop2Topup, Shop2TopupError, newOrderId } from '@shop2topup/sdk';
185
+ const s2t = new Shop2Topup();
186
+
187
+ // When the buyer pays: you already stored pack.id, the catalog.price string you showed and the fields.
188
+ export async function fulfil(shopOrder) {
189
+ let order = null;
190
+ if (!shopOrder.s2tOrderId) {
191
+ shopOrder.s2tOrderId = newOrderId();
192
+ await db.save(shopOrder); // persist BEFORE buying
193
+ } else {
194
+ // A resumed run (crash, restart, job retry): read the saved id first. Found: that is the order.
195
+ try {
196
+ order = await s2t.orders.get(shopOrder.s2tOrderId);
197
+ } catch (err) {
198
+ if (!(err instanceof Shop2TopupError) || err.code !== 'ORDER_NOT_FOUND') throw err; // ORDER_NOT_FOUND: buy with the SAME id
199
+ }
200
+ }
201
+ try {
202
+ order ??= await s2t.orders.buy({
203
+ orderId: shopOrder.s2tOrderId, // same id on every run of this job, never a new one for this purchase
204
+ packId: shopOrder.packId,
205
+ quantity: shopOrder.quantity,
206
+ expectedPrice: shopOrder.shownPrice, // "0.950000": catalog.price(packId).price, exactly what the buyer saw
207
+ fields: shopOrder.fields, // { player_id: '123456789', ... }; {} for gift cards
208
+ });
209
+ const final = await s2t.orders.wait(order.id, { timeout: 120 });
210
+ await db.setStatus(shopOrder.id, mapStatus(final.status), deliveredCodes(final));
211
+ } catch (err) {
212
+ if (!(err instanceof Shop2TopupError)) throw err;
213
+ if (err.code === 'WAIT_TIMEOUT') return db.setStatus(shopOrder.id, 'processing'); // webhook + scheduled getMany finish it
214
+ if (err.orderMayExist || err.retryable) throw err; // job queue retries later with the SAME s2tOrderId
215
+ // A refusal of THIS call (orderMayExist false). Keep s2tOrderId on the row: a refusal on a resumed id does not
216
+ // prove an earlier attempt made no order, so never buy this purchase again under a new id.
217
+ await db.setStatus(shopOrder.id, 'refused', [], err.code);
218
+ }
219
+ }
220
+
221
+ // completed: every code is in order.codes. partial: packs delivered per unit have theirs in each unit's codes.
222
+ function deliveredCodes(order) {
223
+ const all = [...order.codes, ...order.units.flatMap((u) => u.codes)].map((c) => c.code);
224
+ return [...new Set(all)];
225
+ }
226
+ ```
227
+
228
+ ### Scheduled job: finish what is still pending
229
+
230
+ ```js
231
+ // Every few minutes. getMany takes 50 ids per call and allows 2 calls a minute.
232
+ export async function reconcile() {
233
+ const ids = await db.pendingS2tOrderIds({ limit: 100 }); // orders still 'processing' in your database
234
+ if (ids.length === 0) return;
235
+ const { orders } = await s2t.orders.getMany(ids);
236
+ for (const o of orders) if (o.isFinished) await db.setStatus(o.id, mapStatus(o.status), deliveredCodes(o));
237
+ }
238
+ ```
239
+
240
+ ### Map order statuses to your shop
241
+
242
+ ```js
243
+ function mapStatus(status) {
244
+ switch (status) {
245
+ case 'completed': return 'delivered'; // everything delivered (all codes in order.codes)
246
+ case 'partial': return 'partially_delivered'; // part refunded to your wallet: with units, the sum of amount of units
247
+ // with status 'refunded'; gift cards without units: the codes not
248
+ // delivered (quantity minus delivered codes). Refund the buyer for those.
249
+ case 'refunded': return 'refunded'; // nothing delivered, your wallet was refunded: refund the buyer
250
+ case 'pending': return 'processing'; // not finished; a failing top-up stays pending until its automatic
251
+ // refund (under an hour to several hours)
252
+ default: return 'processing'; // a newer status: treat as not finished
253
+ }
254
+ }
255
+ ```
256
+
257
+ ### Show a pack with its live price and form
258
+
259
+ ```js
260
+ const [{ price, inStock }, fields] = await Promise.all([s2t.catalog.price(pack.id), s2t.catalog.fields(pack.categoryId)]);
261
+ // fields is [] for gift cards. Render one input per field (select → field.options).
262
+ // Keep `price` (string) with the cart line: it is the expectedPrice.
263
+ ```
264
+
265
+ More: [`GUIDE.md`](GUIDE.md), [`FAQ.md`](FAQ.md), [`README.md`](README.md), [`llms.txt`](llms.txt), [`examples/`](examples/).
package/CHANGELOG.md ADDED
@@ -0,0 +1,26 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 — 2026-12-02
4
+
5
+ First release. Covers the 11 endpoints of the Shop2Topup Reseller API v1 (prepaid codes are not in this version).
6
+
7
+ - `new Shop2Topup({ apiKey })`: key from the option or `SHOP2TOPUP_API_KEY`, checked locally; never printed.
8
+ - `account.get()`; `catalog.games / categories / packs / price / fields / find`; `players.check`.
9
+ - `orders.buy` with a required `expectedPrice` price guard and a safe retry: one order id, the same body on every attempt, `DUPLICATE_ORDER` turned into the existing order (`alreadyExisted: true`).
10
+ - `orders.get / getMany / list / listAll / wait / waitMany`, polling inside the server's rate limits; the first check comes after `firstPollDelay` (default 2 s), then every `pollInterval`.
11
+ - `err.orderMayExist`: whether the failed call may have created an order (a new `orderId` is safe only when it is false).
12
+ - Uncertainty is sticky inside one `orders.buy` call: after an attempt with an unknown outcome (network error, timeout, unexpected answer, 5xx), a later refusal (`PRICE_INCREASED`, `OUT_OF_STOCK`, a player error, a long 429...) is checked with `orders.get`: the order found is returned with `alreadyExisted: true`; otherwise the refusal is thrown with `orderMayExist: true`. Every error from `buy` after the order id is made carries `orderId`.
13
+ - The configured `webhookSecret` is redacted from response text like the API key, only in what goes into an error (message, `details`, `raw`, the body snippet): a successful answer is parsed from the exact bytes, so an order id that happens to contain the secret comes back unchanged.
14
+ - `account.get()` without a readable `wallet` is `UNEXPECTED_RESPONSE`, never a zero balance.
15
+ - `wait` / `waitMany` stop (`WAIT_TIMEOUT` / the current result) when a server `Retry-After` reaches past the deadline, instead of reading once more at the deadline.
16
+ - `UNEXPECTED_RESPONSE` below HTTP 500 (an unclassified 4xx or any 3xx) is never retried, except a 429 with a `Retry-After` up to `maxRetryWait` (a proxy's rate limit: waited, then retried); any 3xx is `UNEXPECTED_RESPONSE` whatever its body, decided from the status before the body is read (a failed read of a 3xx body is not a retried network error).
17
+ - `catalog.fields` returns `[]` for a category that needs no input (`NO_REQUIREMENTS_FOUND`, action `NONE`).
18
+ - `orders.getMany` with more than 50 ids: the first call follows the normal retry rules; between later calls a 429 sleeps `retryAfter` (whatever its length) and sends the same ids again, like `listAll`, instead of throwing and dropping the orders already read (the batch endpoint allows 2 calls a minute).
19
+ - `orders.list` / `listAll` leave out rows without an order id (prepaid-code purchases, not orders); `total` and the page numbers stay the server's. `listAll` does not stop at a page whose rows were all left out.
20
+ - A transport error's `details.cause` goes through the same redactor as the message (API key, its secret part, the webhook secret).
21
+ - Every webhook receiver example and snippet answers the panel's unsigned setup check (`X-Shop2Topup-Event: webhook.test` without `X-Shop2Topup-Signature`) with 200 and does nothing else; everything else is verified as before. The docs describe webhook retries (3 tries, dropped after 1 h), gift-card webhooks, crash recovery with the saved order id, codes on `partial`, and refund timing.
22
+ - `GUIDE.md` and `FAQ.md` ship inside the package; plain `node:http` webhook example.
23
+ - `webhooks.verify` and the standalone `verifyWebhook` (raw-body HMAC, constant-time compare, timestamp tolerance).
24
+ - One error type, `Shop2TopupError`, with `code`, `action`, `retryable`, `retryAfter`, `details` and helpers; `ErrorCode` constants generated from the API's error catalog.
25
+ - `newOrderId()` / `Shop2Topup.newOrderId()`.
26
+ - Zero runtime dependencies; Node 18+; ESM, CommonJS and TypeScript types.
package/FAQ.md ADDED
@@ -0,0 +1,177 @@
1
+ # Shop2Topup SDK — FAQ
2
+
3
+ Short answers for developers and AI coding tools. The flow and the rules are in [GUIDE.md](GUIDE.md).
4
+
5
+ ## Money and orders
6
+
7
+ **The network died during `buy`. Was I charged?**
8
+ Maybe — so don't guess. Read the order: `orders.get(orderId)` with the **same** `orderId`. Found: that is your order, charged once. `ORDER_NOT_FOUND`: call `buy` again with the same id. (`buy` again with the same id never charges twice either: if the first call went through you get that order back, `order.alreadyExisted` = true. The SDK already does this itself for short network errors inside one `buy` call.)
9
+
10
+ **Can I make a new `orderId` when a purchase fails?**
11
+ Only when you know no order exists for the old one. `err.orderMayExist` speaks only for the call that raised it: `false` means that call made no order (a 4xx like `INSUFFICIENT_BALANCE`, `PLAYER_NOT_FOUND`, `OUT_OF_STOCK`, or the SDK refused before sending); `true` (network error, `TIMEOUT`, a 5xx, `CHECK_ORDER`) means it may have — keep the id. If that id was already sent before (an earlier run, before a crash), a refusal now proves nothing about the earlier attempt: `orders.get(orderId)` decides.
12
+
13
+ **What should I save before calling `buy`?**
14
+ The `orderId`, and with it everything you send: pack, quantity, fields, and the confirmed `expectedPrice`. On a retry send exactly the same. Keep that row until the order is final.
15
+
16
+ **After a crash, how do I find the purchase to resume?**
17
+ By your own shop's order (or cart/checkout) id: store our `orderId` on that row before calling `buy`. On restart, read every row that has an `orderId` and no final status first (`orders.get`, or `orders.getMany` for many). Only the ones that answer `ORDER_NOT_FOUND` get `buy` again, with the same `orderId`.
18
+
19
+ **I resume a purchase saved yesterday. Is the stored `expectedPrice` still used?**
20
+ Yes — it is a ceiling. If our price is now higher, the order is refused with `PRICE_INCREASED` and nothing is charged; if it is lower or equal, you are charged the current (lower or equal) price. The server checks the price before it checks the id, so read the order first (previous answer): a `PRICE_INCREASED` on a resumed id does not mean the first attempt failed.
21
+
22
+ **`CHECK_ORDER` — should I call `get` or `buy` again?**
23
+ `orders.get(orderId)` first. Found: done. `ORDER_NOT_FOUND`: `buy` again with the same `orderId`.
24
+
25
+ **The same buyer buys the same pack again.**
26
+ That's a new purchase: a new order in your shop, a new `orderId`. Reuse an id only to retry the *same* purchase.
27
+
28
+ **Where do I get `expectedPrice`?**
29
+ From `catalog.price(packId).price`, at the moment you show the price to your buyer — send that same string. (The list price `pack.price` is a browsing guide; it can be rounded.) If our price went up in between you get `PRICE_INCREASED` and nothing is charged.
30
+
31
+ **After a refund, `order.charged` still shows the amount.**
32
+ `charged` is what was charged at creation. `refunded` means all of it is back in your wallet; for `partial` with units, add up `unit.amount` of the units with status `refunded`; a gift-card order without units shows no itemised amount: the codes not delivered were refunded. `order.finishedAt` can be `null` on a refunded order.
33
+
34
+ **Why is `price` a string?**
35
+ Floats lose cents (`0.1 + 0.2 ≠ 0.3`). Amounts are six-decimal USD strings; keep them as strings or decimals. Python gives you `Decimal`.
36
+
37
+ **Why is `pack.price` null?**
38
+ Your account's prices are hidden (never reloaded and older than 7 days): `pack.pricesLocked` is true and `catalog.price` answers `RELOAD_REQUIRED`. Reload your wallet once.
39
+
40
+ **My order is `pending` for a long time. Is it stuck?**
41
+ Most top-ups finish in seconds to a few minutes. When the supplier fails, the order stays `pending` until it is refunded automatically, which can take from under an hour to several hours. It never ends in "failed": the money is either delivered or back in your wallet.
42
+
43
+ **What does `partial` mean? Where did the money go?**
44
+ Some of it was delivered and the rest refunded to your wallet. For orders with units, `order.summary` gives the counts and `order.units` lists each unit's status. Deliver what arrived to your buyer and refund them for the rest.
45
+
46
+ **Are refunds automatic?**
47
+ Yes, to your Shop2Topup wallet. You don't call anything.
48
+
49
+ **Where are the gift-card codes?**
50
+ Once the order is `completed`: all in `order.codes` (`code`, and `serial` / `expiresAt` when the card has them). On `partial`: gift cards from stock have their delivered codes in `order.codes`; packs delivered per unit (some gift-card packs, top-ups that return a code) have them in each unit (`order.units[i].codes`). Collect from both; don't decide from `pack.type`. Treat codes like cash: anyone holding one can use it.
51
+
52
+ **Can I buy several of one pack in one order?**
53
+ Yes, `quantity`. Top-ups (and per-unit packs) deliver each unit on its own, which is how an order can end `partial`.
54
+
55
+ **`OUT_OF_STOCK` or `INSUFFICIENT_STOCK`?**
56
+ `OUT_OF_STOCK`: not enough stock for this quantity right now — there may be fewer left; try fewer, later, or another pack. `INSUFFICIENT_STOCK` (some packs only): fewer than you asked, and `err.availableQuantity` says how many — order that many.
57
+
58
+ **What does `pack.inStock` promise?**
59
+ It is refreshed about once a minute. It's a guide for your shop, not a reservation: the order is checked again when you place it.
60
+
61
+ **Which ids should I store?**
62
+ Your `orderId` (UUID) with your own order. `pack.id`, `category.id`, `game.id` for your catalogue mapping. You never need our internal ids.
63
+
64
+ ## Players and fields
65
+
66
+ **How do I know which fields to ask for?**
67
+ `catalog.fields(categoryId)`. Build the form from it (text, number, select with `options`). Don't hard-code per game: fields can change.
68
+
69
+ **Do I have to call `players.check` before `buy`?**
70
+ No — `buy` checks the player itself. `players.check` is for showing the player name to your buyer before they pay, which avoids top-ups to a mistyped id.
71
+
72
+ **Does `players.check` fail the same way as `buy`?**
73
+ Yes: the same error type, codes and `action` (`PLAYER_NOT_FOUND`, `REGION_MISMATCH`, `PLAYER_CHECK_UNAVAILABLE`…). It never creates an order, so ignore `orderMayExist` there (it can read `true` on a 503 or a network error; it only matters for `buy`).
74
+
75
+ **`PLAYER_NOT_FOUND` vs `PLAYER_CHECK_UNAVAILABLE`?**
76
+ `PLAYER_NOT_FOUND`: the game confirmed the id does not exist — ask the buyer to fix it. `PLAYER_CHECK_UNAVAILABLE`: we couldn't check right now; the id was **not** rejected — try again in a few minutes.
77
+
78
+ **`REGION_MISMATCH` — what do I tell the buyer?**
79
+ Their account is in a region this pack can't serve. `err.details` carries their region; offer the pack of that region.
80
+
81
+ **`players.check` answered `needed = false`.**
82
+ This pack needs no player (most gift cards). Go straight to `buy`.
83
+
84
+ **Gift cards: what do I pass for the player and the fields?**
85
+ Nothing. Skip `players.check` for packs with `type` `voucher`; `catalog.fields` returns an empty list for their category; send `fields: {}`.
86
+
87
+ **My script only takes a player id. How do I fill `fields` without hard-coding?**
88
+ Read `catalog.fields(categoryId)`. If the only field is `player_id`, put the id there; if there are more (`zone_id`, `server`…), ask for each one — select fields list their allowed `options`.
89
+
90
+ **How do I send a select field?**
91
+ Every field value is text. For `single_select` send one of the field's `options` exactly. `multi_select` has no several-values format on the API today: send one option.
92
+
93
+ **What does action `NONE` mean?**
94
+ Nothing to do for that request. The server uses it for "this category needs no input", which `catalog.fields` already turns into an empty list.
95
+
96
+ **I hit a 429 on `players.check`.**
97
+ Player checks have a daily quota per account and pack; the error carries the quota and when it resets at midnight UTC (`err.retryAfter`, `err.details.reset_at`). Check a player once and remember the answer for the checkout.
98
+
99
+ ## Speed and limits
100
+
101
+ **How often may I check an order?**
102
+ 3 times a minute per order (`orders.get`), 2 times a minute for `getMany` / `list`. `orders.wait` and `orders.waitMany` already respect this. Never loop on `get` yourself.
103
+
104
+ **I have hundreds of pending orders.**
105
+ `orders.waitMany(ids)` or a scheduled `orders.getMany(ids)` (50 per call; past 100 ids it waits for the API's limit between calls, so 300 ids take about 2 minutes). Better: webhooks first, `getMany` as the back-up.
106
+
107
+ **Should I cache the catalogue?**
108
+ Yes, a few minutes. Prices change; take the exact one with `catalog.price` when the buyer is about to pay.
109
+
110
+ **Do packs have images or translated descriptions?**
111
+ Not yet: the server ignores `withImages` and `locale` for packs, and `locale` for categories (pack images come back empty). Only games (`catalog.games`) use `locale` today.
112
+
113
+ **Does the SDK retry by itself?**
114
+ Up to 2 more tries (`maxRetries`) for network errors, timeouts, and answers the server marks retryable: it waits the server's `retryAfter` when there is one, else a short back-off. A wait longer than `maxRetryWait` (30 s) is never slept through: the error comes to you at once with `retryAfter` (for example `PLAYER_CHECK_UNAVAILABLE`, 60 s). So a 429, a "busy" or `PRICING_UPDATING` (409, 30 s) is retried; `OUT_OF_STOCK` and any other refusal come straight to you.
115
+
116
+ ## Webhooks
117
+
118
+ **Webhook or polling?**
119
+ Both: webhook for speed, a scheduled `getMany` for orders still `pending` in your database (a message is tried 3 times over about 2 minutes, then lost if your server was down).
120
+
121
+ **Which orders send webhooks?**
122
+ Every order placed with your API key. Top-up orders (and packs delivered per unit): one message per delivered or refunded unit. Gift-card orders from stock: one message when the order settles (`order.completed`, or `order.refunded` for refunded and `partial`), with the delivered codes.
123
+
124
+ **The panel refuses my webhook URL.**
125
+ When you save the URL we first send an unsigned check (header `X-Shop2Topup-Event: webhook.test`, no signature header). Your endpoint must answer it 2xx within 10 seconds, without verifying and without doing anything. The secret is created only after that. Every other message is signed: verify those.
126
+
127
+ **Is a webhook sent again if my server fails?**
128
+ Yes: no 2xx within 10 seconds (or an error answer) and it is sent again 30 seconds later, then 1 minute after that — 3 tries, each with the order's current status, a fresh timestamp and a new signature. A message still waiting 1 hour after it was queued is dropped.
129
+
130
+ **The signature check fails.**
131
+ You must verify the **raw** body bytes as received. Frameworks that parse JSON first (Express `express.json()`, Laravel `$request->all()`) change the bytes: use `express.raw`, `$request->getContent()`, `await request.body()` (FastAPI), `request.get_data()` (Flask), `io.ReadAll(r.Body)` (Go).
132
+
133
+ **`WEBHOOK_TIMESTAMP_TOO_OLD`.**
134
+ The message is older than 5 minutes, or your server clock is wrong. Fix the clock (NTP). You can widen `tolerance`, but don't turn it off in production.
135
+
136
+ **How do I test my handler with a recorded (old) webhook?**
137
+ Verify with `tolerance: 0` (turns the age check off; in Go, `Tolerance: shop2topup.NoTimestampCheck`, because 0 means the default there) or with `now` set to the message's own time. Test code only — keep the default 5 minutes in production.
138
+
139
+ **A webhook arrived for an order I don't have yet.**
140
+ It can arrive before your `buy` call returns. If you save the `orderId` before calling `buy` (you should), you'll find it. If you really don't have it, create a row from the verified event (`event.order.id` + status) so nothing is lost, then answer 200.
141
+
142
+ **Webhook vs. polling — which wins?**
143
+ Both update the same row through the same rule: only move forward (`pending` → final). Then the order they arrive in doesn't matter.
144
+
145
+ **I got the same order twice.**
146
+ Normal: one message per unit, a message is sent again when your answer was late or not 2xx, and `event.order.status` is the whole order's status at that moment. Make the handler safe to run twice (update your order only when the status moves forward).
147
+
148
+ **How do I test my webhook endpoint?**
149
+ Panel → API Access → send a test webhook. It arrives signed, as `event.type = 'webhook.test'` with `event.order = null` and a `message`. (Different from the unsigned setup check sent when you save the URL.)
150
+
151
+ ## Keys and security
152
+
153
+ **Where do I keep the key?**
154
+ On your server only: an environment variable or a secret store. Never in browser JavaScript, a mobile app, a public repo, or logs.
155
+
156
+ **Can I call the API from a browser or mobile app?**
157
+ No. Your app talks to your server; your server talks to Shop2Topup.
158
+
159
+ **I think my key leaked.**
160
+ Panel → API Access → generate a new key (needs 2FA). The old one stops working at once. Then update your server.
161
+
162
+ **`IP_NOT_ALLOWED`.**
163
+ The call came from an address not in your key's allowlist. Add your server's outgoing IP (not your laptop's) in the panel.
164
+
165
+ **Several shops on one account?**
166
+ One key per account. Several shops can share it from the same server; keep their `orderId`s in one place so ids never collide.
167
+
168
+ **Time zones?**
169
+ All times are UTC (ISO 8601).
170
+
171
+ ## Testing
172
+
173
+ **How do I test without spending money?**
174
+ There is no test mode yet. Test with the cheapest pack you sell and a small wallet balance. Unit-test your own code with the SDK's injectable HTTP client.
175
+
176
+ **My language isn't listed.**
177
+ Use the HTTP API directly: the API reference is at https://shop2topup.com/en/reseller-api/docs and the OpenAPI file at https://shop2topup.com/openapi.json. Keep the rules of this guide in your own client: one order id per purchase, reused on every retry; the expected price you showed; waiting within the limits; webhook checks on the raw body.