@isroilov_an/paylov 0.0.1

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.
@@ -0,0 +1,46 @@
1
+ # Splits and sub-merchants
2
+
3
+ `paylov.splits` divides a paid transaction among recipients; `paylov.subMerchants` creates the child
4
+ merchants that receive shares. Paylov enables each feature per merchant (`permission_denied`
5
+ otherwise).
6
+
7
+ ## Split a paid transaction
8
+
9
+ ```ts
10
+ import { isPaylovApiError } from '@isroilov_an/paylov';
11
+
12
+ try {
13
+ await paylov.splits.create({
14
+ transactionId,
15
+ recipients: [
16
+ { recipientId: platformRecipientId, amountTiyin: 150_000 },
17
+ { recipientId: sellerRecipientId, amountTiyin: 850_000, items: sellerItems },
18
+ ],
19
+ });
20
+ } catch (error) {
21
+ if (!isPaylovApiError(error, 'split_already_done')) throw error;
22
+ }
23
+ const shares = await paylov.splits.get({ transactionId });
24
+ ```
25
+
26
+ - Splitting moves money to the recipients; amounts must add up to the transaction amount.
27
+ - A recipient's `items` ([fiscalization.md](fiscalization.md)) start OFD fiscalization of its share
28
+ in the background; Paylov does not document how the receipt is reported. `resendOfd: true` asks
29
+ Paylov to resend the split to the fiscal system; Paylov does not say when that is needed.
30
+ - Read the split back with the paid transaction's id, not the id `create` returns.
31
+ - `splits.get` throws on a miss instead of returning `null`.
32
+
33
+ ## Create a sub-merchant
34
+
35
+ ```ts
36
+ const { subMerchantId } = await paylov.subMerchants.create({
37
+ name: shop.displayName,
38
+ tin: shop.tin,
39
+ externalId: shop.id,
40
+ });
41
+ await shops.linkPaylov(shop.id, subMerchantId);
42
+ ```
43
+
44
+ - Paylov staff activate a new sub-merchant later.
45
+ - No lookup exists: after an ambiguous failure, repeat with the same data and treat
46
+ `sub_merchant_already_created` as success.
@@ -0,0 +1,132 @@
1
+ # Testing
2
+
3
+ Two doubles, imported only from tests:
4
+
5
+ - A narrow interface you fake yourself, for business logic that only needs results.
6
+ - `PaylovFakeGateway` from `@isroilov_an/paylov/testing`, for code that meets SDK behavior: errors,
7
+ `isPaylovOutcomeUnknown`, retries, timeouts, the token lifecycle and logger events.
8
+
9
+ ## Stub the client
10
+
11
+ Depend on the namespaces your code uses, not on `PaylovClient`; a `PaylovClient` satisfies the
12
+ narrowed type:
13
+
14
+ ```ts
15
+ import type { PaymentsResource, TransactionsResource } from '@isroilov_an/paylov';
16
+
17
+ export interface PaylovPort {
18
+ readonly payments: Pick<PaymentsResource, 'create' | 'pay'>;
19
+ readonly transactions: Pick<TransactionsResource, 'get'>;
20
+ }
21
+
22
+ const fake: PaylovPort = {
23
+ payments: {
24
+ create: async () => ({ transactionId: '00000000-0000-4000-8000-000000000001' }),
25
+ pay: async ({ transactionId }) => ({ transactionId }),
26
+ },
27
+ transactions: { get: async () => null },
28
+ };
29
+ ```
30
+
31
+ To test a failure branch, throw the SDK's own error, e.g.
32
+ `new PaylovApiError({ code: 'insufficient_funds', httpStatus: 400, endpoint: 'POST /merchant/receipts/pay/' })`.
33
+
34
+ ## Script the fake gateway
35
+
36
+ ```ts
37
+ import { PaylovClient, isPaylovOutcomeUnknown } from '@isroilov_an/paylov';
38
+ import { PaylovFakeGateway } from '@isroilov_an/paylov/testing';
39
+
40
+ const fake = new PaylovFakeGateway();
41
+ const paylov = new PaylovClient({ ...fake.clientConfig, timeoutMs: 100 });
42
+
43
+ fake.payments.create.reply({ transactionId: '00000000-0000-4000-8000-000000000001' });
44
+ fake.payments.pay.disconnect();
45
+
46
+ const error = await payOrder(paylov, order).catch((caught: unknown) => caught);
47
+ expect(isPaylovOutcomeUnknown(error)).toBe(true);
48
+ fake.assertDone();
49
+ ```
50
+
51
+ - Each SDK method has a script with `reply`, `fail`, `disconnect` and `hang`. Scripting a value or a
52
+ failure the gateway cannot send throws `TypeError`.
53
+ - `reply(null)` or `reply(false)` on a read sends the gateway's not-found answer.
54
+ - A status outside the SDK's vocabulary passes through; a raw gateway spelling the SDK renames, such
55
+ as a hold's `'paid'`, throws `TypeError`.
56
+ - An unscripted request fails with `fake_unscripted`, and a request the fake cannot read back into
57
+ its method's params with `fake_unreadable_request`, both HTTP 501; `assertDone()` reports each.
58
+ - `hang()` ends the call with `sdk_timeout` after `timeoutMs`, or `sdk_aborted` when its signal
59
+ aborts.
60
+ - `PaylovOnboarding` takes `fake.onboardingConfig` and is scripted through `fake.onboarding`.
61
+
62
+ ### Sent params
63
+
64
+ Each script's `requests` lists the params of every attempt it served, decoded back from the wire
65
+ into the method's own params type (whole SUM back to tiyin, wire names back to SDK names):
66
+
67
+ ```ts
68
+ fake.holds.capture.reply({ transactionId, cardId, capturedAt: new Date('2026-01-02T03:04:05Z') });
69
+ await captureOrder(paylov, order);
70
+ expect(fake.holds.capture.requests).toEqual([{ transactionId, amountTiyin: 150_000 }]);
71
+ ```
72
+
73
+ A retried GET appears once per attempt. PAN methods record the card number you passed; passwords are
74
+ never recorded.
75
+
76
+ ### One answer per attempt
77
+
78
+ - Each scripted answer serves one HTTP attempt. Retries follow
79
+ [setup.md](setup.md#runtime-behavior): a GET that meets `disconnect()`, `hang()` or HTTP
80
+ 500/502/503/504 is retried up to twice, each retry taking the next answer. Script one answer per
81
+ attempt, or pass `{ persist: true }` for a gateway that stays down:
82
+ `fake.transactions.get.fail('server_error', { httpStatus: 500 }, { persist: true })`.
83
+ - `fail('permission_denied', { httpStatus: 401 })` makes the client fetch a new token and replay the
84
+ call once against the next answer.
85
+ - Use fake timers to skip backoff waits.
86
+ - `assertDone()` flags an unscripted request that followed a retryable answer as a likely retry.
87
+
88
+ ## Logger events
89
+
90
+ Assert attempts through the logger instead of counting requests. Hooks are not awaited: assert after
91
+ the call settles.
92
+
93
+ ```ts
94
+ import type { PaylovLoggerResponseEvent } from '@isroilov_an/paylov';
95
+
96
+ const events: PaylovLoggerResponseEvent[] = [];
97
+ const paylov = new PaylovClient({
98
+ ...fake.clientConfig,
99
+ logger: { onResponse: (event) => void events.push(event) },
100
+ });
101
+ ```
102
+
103
+ ## Webhook requests
104
+
105
+ `createWebhookRequest(event, credentials)` builds the request Paylov would send, so
106
+ `receiver.receive(request)` returns that event:
107
+
108
+ ```ts
109
+ import { PaylovWebhookReceiver } from '@isroilov_an/paylov';
110
+ import { createWebhookRequest } from '@isroilov_an/paylov/testing';
111
+
112
+ const credentials = { login: 'EXAMPLE-WEBHOOK-LOGIN', password: 'EXAMPLE-WEBHOOK-PASSWORD' };
113
+ const receiver = new PaylovWebhookReceiver(credentials);
114
+
115
+ const request = createWebhookRequest(
116
+ {
117
+ kind: 'transaction.perform',
118
+ id: 2,
119
+ transactionId: '00000000-0000-4000-8000-0000000000b1',
120
+ account: { order_id: 'A-1024' },
121
+ amount: { currency: 860, amountTiyin: 50_000 },
122
+ },
123
+ credentials,
124
+ );
125
+ ```
126
+
127
+ Change the request's header, method or body to cover the `invalid` outcomes.
128
+
129
+ ## Fixtures
130
+
131
+ Fixtures never hold real tokens, card numbers, OTPs, PINFLs, phone numbers or card expiries. The SDK
132
+ does not check card number values, so pass a placeholder such as `'PAN-FROM-SECURE-INPUT'`.
@@ -0,0 +1,43 @@
1
+ # Transactions
2
+
3
+ `transactions.get` is the reconciliation read for every payment kind: saved card, PAN, hold and
4
+ checkout. `transactions.list` is a settled-sales feed.
5
+
6
+ ## Reconcile one payment
7
+
8
+ ```ts
9
+ const transaction = await paylov.transactions.get({ transactionId });
10
+ if (transaction === null) {
11
+ // Unknown to the gateway so far: read again after a delay before creating anew.
12
+ } else if (transaction.status === 'paid') {
13
+ await orders.markPaid(orderId, transaction.paidOrCreatedAt);
14
+ }
15
+ ```
16
+
17
+ - `status` is open: handle values you do not know. A refunded sale reads `refunded`. A hold reads
18
+ `held`, as in `holds.get`, until captured (`paid` here, `captured` in `holds.get`). An expired
19
+ hold Paylov released has also read `refunded`, so for a hold `refunded` means only that the
20
+ merchant keeps no money from it; read `holds.get` to tell a release from a capture.
21
+ - Recovery per method: [errors.md](errors.md#recovery-after-an-ambiguous-failure).
22
+
23
+ ## Settled sales
24
+
25
+ ```ts
26
+ import type { Transaction } from '@isroilov_an/paylov';
27
+
28
+ const sales: Transaction[] = [];
29
+ for (let page = 1; ; page += 1) {
30
+ const result = await paylov.transactions.list({
31
+ fromDate: '2026-11-01',
32
+ toDate: '2026-11-30',
33
+ page,
34
+ });
35
+ sales.push(...result.transactions);
36
+ if (result.transactions.length === 0 || sales.length >= result.total) break;
37
+ }
38
+ ```
39
+
40
+ - Only currently paid transactions appear, merchant-wide: a refunded payment disappears. Never use
41
+ the list to reconcile one payment or to find refunds.
42
+ - Page until a page is empty or you have `total` rows; the page size is undocumented.
43
+ - Dates are Tashkent calendar days; `toDate` is included.
@@ -0,0 +1,168 @@
1
+ # Webhooks
2
+
3
+ `PaylovWebhookReceiver` authenticates and decodes inbound webhooks without a `PaylovClient` or an
4
+ HTTP framework. Paylov configures the webhook URLs and their Basic credentials on request; no API
5
+ sets them.
6
+
7
+ | `kind` | Meaning | Answer | Dedupe key |
8
+ | --------------------- | ------------------------------------------------------------- | ----------------------- | --------------- |
9
+ | `transaction.check` | Checkout: validate the order before payment | `createWebhookResponse` | — |
10
+ | `transaction.perform` | Checkout: apply the payment, then answer `accept` | `createWebhookResponse` | `transactionId` |
11
+ | `transaction.cancel` | Cancelled in the Paylov business panel or by Paylov staff | any 2xx | `transactionId` |
12
+ | `merchant.deposit` | An A2C, Paynet or Munis deposit reached your merchant account | any 2xx | `depositId` |
13
+ | `card.bind` | A card was bound through a Card Bind link | any 2xx | `token` |
14
+
15
+ ## Receive
16
+
17
+ ```ts
18
+ import {
19
+ createWebhookResponse,
20
+ PaylovWebhookReceiver,
21
+ type WebhookInput,
22
+ type WebhookResponseBody,
23
+ } from '@isroilov_an/paylov';
24
+
25
+ const receiver = new PaylovWebhookReceiver({
26
+ login: webhookLoginFromSecretManager, // no ':'
27
+ password: webhookPasswordFromSecretManager,
28
+ });
29
+
30
+ export interface WebhookReply {
31
+ readonly status: number;
32
+ readonly body?: WebhookResponseBody;
33
+ }
34
+
35
+ const reply = (status: number, body?: WebhookResponseBody): WebhookReply => ({ status, body });
36
+
37
+ export async function handleWebhook(request: WebhookInput): Promise<WebhookReply> {
38
+ const event = receiver.receive(request);
39
+ switch (event.kind) {
40
+ case 'transaction.check': {
41
+ const order = await orders.findByAccount(event.account);
42
+ if (order === undefined) return reply(200, createWebhookResponse(event, 'order_not_found'));
43
+ if (!order.matches(event.amount)) {
44
+ return reply(200, createWebhookResponse(event, 'invalid_amount'));
45
+ }
46
+ return reply(200, createWebhookResponse(event, 'accept'));
47
+ }
48
+ case 'transaction.perform':
49
+ // Re-checks account and amount (currency included) before applying, once per transactionId.
50
+ await orders.applyPaymentOnce(event.transactionId, event.account, event.amount);
51
+ return reply(200, createWebhookResponse(event, 'accept'));
52
+ case 'transaction.cancel':
53
+ await orders.markCancelledOnce(event.transactionId, event.cancelledAt);
54
+ return reply(200);
55
+ case 'merchant.deposit':
56
+ await ledger.recordDepositOnce(event.depositId, event.source, event.amountTiyin);
57
+ return reply(200);
58
+ case 'card.bind':
59
+ // Never retried: store it before answering, confirm it with cards.get from a job (cards.md).
60
+ await bindEvents.saveOnce(event.token, event.userId, event.cardId);
61
+ return reply(200);
62
+ case 'invalid':
63
+ return reply(event.reason === 'unauthorized' ? 401 : 400);
64
+ }
65
+ }
66
+ ```
67
+
68
+ `orders`, `ledger` and `bindEvents` are application code. For perform, answer `accept` only after
69
+ the payment is applied; if applying fails, let the handler fail rather than answer `accept`.
70
+
71
+ Pass `body` already read: JSON text, bytes (`Uint8Array`, `Buffer` or `ArrayBuffer`), or the value a
72
+ JSON body parser produced. An unread stream, such as a Fetch `Request`'s `body`, or a `Blob` answers
73
+ `malformed_body`.
74
+
75
+ ## Cap the body size
76
+
77
+ The request is unauthenticated until `receive()` runs: read at most a fixed number of bytes
78
+ (callbacks are small; 64 KiB is ample) and answer 413 beyond it, whatever `Content-Length` says.
79
+ With a framework, set that cap on the body parser that produces the raw body.
80
+
81
+ With a Fetch-style framework (a `Request`), read the raw bytes with that cap:
82
+
83
+ ```ts
84
+ const MAX_BODY_BYTES = 64 * 1024;
85
+
86
+ async function readBody(request: Request): Promise<Uint8Array | undefined> {
87
+ const chunks: Uint8Array[] = [];
88
+ let size = 0;
89
+ for await (const chunk of request.body ?? []) {
90
+ size += chunk.byteLength;
91
+ if (size > MAX_BODY_BYTES) return undefined; // stops and cancels the upload
92
+ chunks.push(chunk);
93
+ }
94
+ return Buffer.concat(chunks);
95
+ }
96
+
97
+ export async function serveFetch(request: Request): Promise<Response> {
98
+ const body = await readBody(request);
99
+ if (body === undefined) return new Response(null, { status: 413 });
100
+ const answer = await handleWebhook({ method: request.method, headers: request.headers, body });
101
+ return answer.body === undefined
102
+ ? new Response(null, { status: answer.status })
103
+ : Response.json(answer.body, { status: answer.status });
104
+ }
105
+ ```
106
+
107
+ With plain `node:http`, do not return from a `for await` loop over the request: that destroys the
108
+ socket before the 413 is sent. Stop buffering instead, answer with `Connection: close`, and destroy
109
+ the request once the answer is written:
110
+
111
+ ```ts
112
+ import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
113
+
114
+ const MAX_BODY_BYTES = 64 * 1024;
115
+
116
+ function readBody(req: IncomingMessage, res: ServerResponse): Promise<Buffer | undefined> {
117
+ return new Promise((resolve, reject) => {
118
+ const chunks: Buffer[] = [];
119
+ let size = 0;
120
+ const tooLarge = (): void => {
121
+ res.writeHead(413, { connection: 'close' }).end(() => req.destroy());
122
+ resolve(undefined);
123
+ };
124
+ if (Number(req.headers['content-length']) > MAX_BODY_BYTES) return tooLarge();
125
+ req.on('data', (chunk: Buffer) => {
126
+ if (size > MAX_BODY_BYTES) return; // already answered
127
+ size += chunk.byteLength;
128
+ if (size > MAX_BODY_BYTES) return tooLarge();
129
+ chunks.push(chunk);
130
+ });
131
+ req.on('end', () => resolve(size > MAX_BODY_BYTES ? undefined : Buffer.concat(chunks)));
132
+ req.on('error', reject);
133
+ });
134
+ }
135
+
136
+ async function serveNode(req: IncomingMessage, res: ServerResponse): Promise<void> {
137
+ const body = await readBody(req, res);
138
+ if (body === undefined) return;
139
+ const answer = await handleWebhook({ method: req.method, headers: req.headers, body });
140
+ if (answer.body === undefined) return void res.writeHead(answer.status).end();
141
+ res.writeHead(answer.status, { 'content-type': 'application/json' });
142
+ res.end(JSON.stringify(answer.body));
143
+ }
144
+
145
+ createServer((req, res) => {
146
+ serveNode(req, res).catch(() => {
147
+ if (!res.headersSent) res.writeHead(500).end();
148
+ });
149
+ }).listen(webhookPort);
150
+ ```
151
+
152
+ ## Pitfalls
153
+
154
+ - **Check the currency.** The checkout link is unsigned, so a customer can change its currency: an
155
+ amount that matches in the wrong currency is not a match.
156
+ - **Narrow `account` yourself.** It passes through as received; keep your own order mapping
157
+ ([checkout.md](checkout.md#hosted-checkout-link)).
158
+ - **Persist `card.bind` before answering.** Paylov never retries it and it carries only `cardId`;
159
+ confirm the card with `paylov.cards.get` from a job ([cards.md](cards.md#card-bind)).
160
+ - **Deduplicate** on the keys in the table: Paylov retries `transaction.cancel` and
161
+ `merchant.deposit` up to 3 times at 60 s intervals after a non-2xx or no response. Paylov
162
+ documents no retry of check and perform, and the SDK assumes none: a perform your handler did not
163
+ answer with `accept` is not sent again.
164
+ - **Only `accept` completes a payment**, by the SDK's assumption: any other perform answer, an error
165
+ response or no response leaves the payment uncompleted, so the order stays unpaid. Paylov
166
+ documents only the `accept` answer; before treating an unpaid order as final, read
167
+ `paylov.transactions.get({ transactionId })`.
168
+ - **Invalid input** has no documented response; choose the status yourself.
package/package.json ADDED
@@ -0,0 +1,86 @@
1
+ {
2
+ "name": "@isroilov_an/paylov",
3
+ "version": "0.0.1",
4
+ "description": "Unofficial server-side TypeScript SDK for the Paylov payment gateway (Uzbekistan). Not affiliated with Paylov.",
5
+ "keywords": [
6
+ "paylov",
7
+ "payments",
8
+ "payment-gateway",
9
+ "uzbekistan",
10
+ "uzcard",
11
+ "humo",
12
+ "ofd",
13
+ "fiscalization",
14
+ "typescript",
15
+ "sdk"
16
+ ],
17
+ "homepage": "https://github.com/IsroilovA/paylov-ts-sdk#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/IsroilovA/paylov-ts-sdk/issues"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/IsroilovA/paylov-ts-sdk.git"
24
+ },
25
+ "license": "MIT",
26
+ "author": "IsroilovA",
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "engines": {
30
+ "node": ">=24.13.1"
31
+ },
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.js"
36
+ },
37
+ "./testing": {
38
+ "types": "./dist/testing.d.ts",
39
+ "import": "./dist/testing.js"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "files": [
44
+ "dist",
45
+ "docs/usage",
46
+ "README.md",
47
+ "CHANGELOG.md",
48
+ "LICENSE"
49
+ ],
50
+ "scripts": {
51
+ "build": "tsdown",
52
+ "prepack": "npm run build",
53
+ "prepublishOnly": "npm run check",
54
+ "test": "vitest run",
55
+ "test:coverage": "vitest run --coverage && node scripts/checkCoverage.mjs",
56
+ "test:live": "vitest run --config vitest.live.config.ts",
57
+ "test:watch": "vitest",
58
+ "lint": "oxlint && oxfmt --check",
59
+ "format": "oxfmt",
60
+ "typecheck": "tsc -p tsconfig.build.json && tsc -p tsconfig.json",
61
+ "check:architecture": "node scripts/checkArchitecture.mjs",
62
+ "check:dependencies": "node scripts/checkDependencies.mjs",
63
+ "check:changelog": "node scripts/checkChangelog.mjs",
64
+ "check:docs": "node scripts/checkDocSurface.mjs",
65
+ "check:secrets": "node scripts/checkSecrets.mjs",
66
+ "check:package": "node scripts/checkPackage.mjs",
67
+ "check": "npm run check:static && npm run check:runtime",
68
+ "check:static": "npm run lint && npm run check:secrets && npm run check:architecture && npm run check:dependencies && npm run check:docs && npm run check:changelog && npm run typecheck",
69
+ "check:runtime": "npm run test:coverage && npm run build && npm run check:package"
70
+ },
71
+ "devDependencies": {
72
+ "@types/node": "^26.6.6",
73
+ "@vitest/coverage-v8": "^5.1.0",
74
+ "oxc-parser": "^0.157.0",
75
+ "oxfmt": "^0.77.0",
76
+ "oxlint": "^1.92.0",
77
+ "oxlint-plugin-complexity": "^4.1.0",
78
+ "oxlint-tsgolint": "^7.0.2006",
79
+ "tsdown": "^0.23.7",
80
+ "typescript": "^7.0.2",
81
+ "vitest": "^5.1.0"
82
+ },
83
+ "publishConfig": {
84
+ "access": "public"
85
+ }
86
+ }