@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,30 @@
1
+ # @isroilov_an/paylov usage
2
+
3
+ Guides for the server-side Paylov SDK: integration flows and pitfalls. Method contracts live in the
4
+ JSDoc, fields in the types. Start with [setup.md](setup.md).
5
+
6
+ Import from `'@isroilov_an/paylov'`, and test helpers from `'@isroilov_an/paylov/testing'`. Examples
7
+ call `paylov`, the client from [setup.md](setup.md).
8
+
9
+ ## Surface map
10
+
11
+ | Export / method | Purpose | Doc |
12
+ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | -------------------------------------- |
13
+ | `new PaylovClient(config)` — `close` | One long-lived client per credential set per process | [setup.md](setup.md) |
14
+ | `paylov.gateway` — `getStatus`, `listBanks` | Liveness probe; issuing banks | [setup.md](setup.md) |
15
+ | `config.fetch`, `config.logger` (`PaylovLogger`) | Proxy `fetch`; metadata-only observability | [setup.md](setup.md) |
16
+ | `PaylovError`, `PaylovInputError`, `PaylovClientClosedError`, `PaylovApiError`, `PaylovProtocolError`, `PaylovConnectionError`, `isPaylovError`, `isPaylovApiError`, `isPaylovOutcomeUnknown` | Branch on failures; recover after an ambiguous one | [errors.md](errors.md) |
17
+ | `sumToTiyin`, `formatSum` | Money units, wire units and time zones | [money-and-time.md](money-and-time.md) |
18
+ | `paylov.cards` — `createBindLink`, `getBindSession`, `startPanBinding`, `confirmPanBinding`, `get`, `list`, `delete`, `checkPhone` | Bind cards (hosted Card Bind or PAN + OTP), read and remove them | [cards.md](cards.md) |
19
+ | `paylov.payments` — `create`, `pay`, `refund`, `startPanPayment`, `confirmPanPayment` | Charge a saved card or a one-off card number; full refund | [payments.md](payments.md) |
20
+ | `paylov.transactions` — `get`, `list`, `getRrn` | Reconcile one transaction; settled-sales feed; RRN | [transactions.md](transactions.md) |
21
+ | `paylov.holds` — `create`, `capture`, `release`, `get` | Reserve, capture once or release, reconcile | [holds.md](holds.md) |
22
+ | `paylov.splits` — `create`, `get` | Divide a paid transaction among recipients | [splits.md](splits.md) |
23
+ | `paylov.subMerchants` — `create` | Register a sub-merchant that receives splits | [splits.md](splits.md) |
24
+ | `paylov.fiscalization` — `registerReceipt`, `getReceipt`, `attachReceipt`, `refundReceipt`, `checkActivityType` | OFD fiscal receipts and activity-type checks | [fiscalization.md](fiscalization.md) |
25
+ | `createCheckoutUrl(params)` | Hosted checkout link (pure, unsigned) | [checkout.md](checkout.md) |
26
+ | `new PaylovWebhookReceiver(config)` — `receive` | Authenticate and decode the five inbound callback kinds | [webhooks.md](webhooks.md) |
27
+ | `createWebhookResponse(event, decision)` | Answer `transaction.check` and `transaction.perform` | [webhooks.md](webhooks.md) |
28
+ | `new PaylovOnboarding(config)` — `checkToken`, `complete` | One-time operator step that issues API credentials | [onboarding.md](onboarding.md) |
29
+ | `new PaylovFakeGateway()` — `assertDone`, per-method `requests` (from `@isroilov_an/paylov/testing`) | Scripted gateway for application tests, through the real transport | [testing.md](testing.md) |
30
+ | `createWebhookRequest(event, credentials)` (from `@isroilov_an/paylov/testing`) | Authenticated webhook request for testing a receiver | [testing.md](testing.md) |
@@ -0,0 +1,69 @@
1
+ # Cards
2
+
3
+ A bound card's `cardId` is what payments and holds charge. Prefer Card Bind: the cardholder enters
4
+ the card on Paylov's page, so the card number never reaches your servers. PAN binding puts your
5
+ backend in PCI scope.
6
+
7
+ ## Card Bind
8
+
9
+ ```ts
10
+ // 1. Backend: start a session and open bindUrl in a webview.
11
+ const link = await paylov.cards.createBindLink({
12
+ userId: 'user-42',
13
+ returnUrl: 'https://app.example/wallet/cards', // close the webview on it
14
+ });
15
+ await bindSessions.save({ userId: 'user-42', token: link.token, expiresAt: link.expiresAt });
16
+
17
+ // 2. The card.bind webhook is stored (webhooks.md); a job confirms it with an authenticated read.
18
+ const card = await paylov.cards.get({ cardId: bindEvent.cardId });
19
+ if (card.userId === bindEvent.userId) await userCards.saveOnce(bindEvent.token, card.cardId);
20
+
21
+ // 3. No webhook yet: read the session instead.
22
+ const session = await paylov.cards.getBindSession({ token: storedBindToken });
23
+ if (session.isBound) await userCards.saveOnce(storedBindToken, session.card.cardId);
24
+ ```
25
+
26
+ - One link binds one card and expires after about 20 minutes; create one per card.
27
+ - Open `bindUrl` exactly as returned; its host differs between environments.
28
+ - Only the webhook or the session read carries the result, never the webview or `returnUrl`. Paylov
29
+ never retries the webhook, so when it has not arrived, read `getBindSession` after the webview
30
+ closes, then periodically until `expiresAt`.
31
+ - Deduplicate on `token`: one bind can reach you through both the webhook and the read.
32
+ - Before offering a new link after `link_expired`, compare `cards.list({ userId })` with the cards
33
+ you store: a link that bound a card also reads `link_expired` once it expires. After
34
+ `link_already_used`, never offer a new link.
35
+
36
+ ## PAN binding
37
+
38
+ ```ts
39
+ const started = await paylov.cards.startPanBinding({
40
+ userId: 'user-42',
41
+ cardNumber: panFromSecureInput,
42
+ cardExpiry: expiryFromSecureInput, // YYMM, year first
43
+ });
44
+ showOtpPrompt(`Uzcard/Humo sent a code to the phone linked to your card: ${started.otpSentPhone}`);
45
+ const card = await paylov.cards.confirmPanBinding({
46
+ cardId: started.cardId,
47
+ otp: otpFromCardholder,
48
+ });
49
+ await userCards.save('user-42', card.cardId);
50
+ ```
51
+
52
+ - The card's processing center sends the OTP by SMS, from `UZCARD` or `HUMO`, and the text may not
53
+ name your business until Paylov assigns you an SMS name. Tell the cardholder before asking for the
54
+ code.
55
+ - A card without SMS notifications receives no OTP: offer Card Bind or another card instead of
56
+ waiting.
57
+ - Store `cardId`, never the card number; keep card numbers, expiries and OTPs out of your logs.
58
+ - After a wrong code, re-prompt; after `otp_expired`, `try_new_otp` or `too_many_attempts`, start
59
+ again. Stop prompting after the third wrong code: the fourth blocks the card for about five
60
+ minutes across users, bindings and payments (`card_is_blocked`).
61
+
62
+ ## Saved cards
63
+
64
+ - Check `card.isActive` before charging, also on the card `confirmPanBinding` returns; offer another
65
+ card when it is `false`.
66
+ - After `delete`, `cards.list` and `cards.get` can still return the card for a few seconds: neither
67
+ proves the delete failed. A repeated delete answering `card_not_found` means it is gone.
68
+ - `checkPhone` is unreliable on the development gateway (`phone_not_match` for every phone); test it
69
+ on production data before relying on it.
@@ -0,0 +1,30 @@
1
+ # Checkout
2
+
3
+ `createCheckoutUrl` builds a link to Paylov's hosted payment page, where the customer enters the
4
+ card. Pure: no client, no request. Paylov then calls your `transaction.check` and
5
+ `transaction.perform` webhooks ([webhooks.md](webhooks.md)).
6
+
7
+ ## Hosted checkout link
8
+
9
+ ```ts
10
+ import { createCheckoutUrl } from '@isroilov_an/paylov';
11
+
12
+ const url = createCheckoutUrl({
13
+ merchantId: paylovMerchantId,
14
+ amount: { currency: 860, amountTiyin: 50_000 }, // USD: { currency: 840, amountCents }
15
+ account: { order_id: 'A-1001' },
16
+ returnUrl: 'https://shop.example/checkout/return',
17
+ });
18
+ await orders.saveCheckoutAccount('A-1001', { order_id: 'A-1001' });
19
+ ```
20
+
21
+ - **The link is unsigned.** Anyone who sees it can change amount, currency or account. Re-validate
22
+ all three in `transaction.check` and `transaction.perform` before answering `accept`.
23
+ - **The return carries no outcome.** Only `transaction.perform` or a status read confirms payment.
24
+ - **Production only.** No DEV checkout page is known.
25
+ - **Keep your own order mapping.** Send at least one `account` entry so `transaction.check` has a
26
+ key to match. The check and perform webhooks carry the keys you sent; `transactions.get` does not
27
+ return them.
28
+ - **`convertTo`**: the SDK assumes the webhooks then carry the converted currency and amount, not
29
+ the order's original ones. Use it only if you can accept the converted amount, and agree the
30
+ currencies and conversions with Paylov.
@@ -0,0 +1,107 @@
1
+ # Errors
2
+
3
+ Everything the SDK throws is a `PaylovError`, one class per origin:
4
+
5
+ | `kind` | Class | Means |
6
+ | ------------ | ------------------------- | ----------------------------------------------------------------------- |
7
+ | `input` | `PaylovInputError` | Rejected locally; nothing was sent. An integration bug |
8
+ | `closed` | `PaylovClientClosedError` | The client was closed; the call had no effect. Retry it on a new client |
9
+ | `api` | `PaylovApiError` | The gateway answered with an error code |
10
+ | `protocol` | `PaylovProtocolError` | The response did not match the endpoint's contract |
11
+ | `connection` | `PaylovConnectionError` | No usable response: timeout, network error or abort |
12
+
13
+ Errors carry only SDK-written messages and allowlisted metadata; `error.toJSON()` is safe to log.
14
+
15
+ ## Handle errors
16
+
17
+ ```ts
18
+ import { isPaylovError, isPaylovOutcomeUnknown } from '@isroilov_an/paylov';
19
+
20
+ export async function chargeOrder(order: Order): Promise<ChargeResult> {
21
+ try {
22
+ await paylov.payments.pay({
23
+ transactionId: order.transactionId,
24
+ cardId: order.cardId,
25
+ userId: order.userId,
26
+ });
27
+ return 'paid';
28
+ } catch (error) {
29
+ if (!isPaylovError(error)) throw error;
30
+ // The charge may have happened: reconcile before acting again.
31
+ if (isPaylovOutcomeUnknown(error)) return 'reconcile';
32
+ if (error.kind === 'api') {
33
+ if (error.code === 'insufficient_funds' || error.code === 'limit_exceeded') return 'declined';
34
+ }
35
+ console.error('paylov call failed', error.toJSON());
36
+ throw error;
37
+ }
38
+ }
39
+ ```
40
+
41
+ - Check `isPaylovOutcomeUnknown` first, then `kind`, then `code`.
42
+ - Branch on `code`, never on `httpStatus` or `message`: one code arrives under different statuses,
43
+ and Paylov's messages are display text.
44
+ - Unknown gateway codes still arrive as `PaylovApiError`; keep a default branch.
45
+ - Answer `sdk_client_closed` as a temporary unavailability, not a bad request: it arrives during
46
+ shutdown, also for a request in flight ([setup.md](setup.md#create-the-client)).
47
+ - `fields` on validation errors holds the gateway's wire names (`service_id`, `items.0.title`), not
48
+ SDK parameter names, and may be absent.
49
+
50
+ ## Code groups
51
+
52
+ Each method's JSDoc names the codes worth branching on.
53
+
54
+ | Group | Examples | Do |
55
+ | ---------------------------- | --------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
56
+ | Credentials and access | `invalid_grant`, `permission_denied`, `invalid_token` | Fix configuration or ask Paylov; never retry automatically |
57
+ | Request validation | `validation_error`, `field_required`, `field_not_valid`, `not_found` | Fix the call; `not_found` means the route does not exist |
58
+ | Infrastructure | `rate_limit_exceeded`, `server_error` | Wait `retryAfterSeconds`; a 5xx leaves the outcome unknown |
59
+ | Card | `card_not_found`, `card_not_match`, `card_exists`, `phone_not_match`, `link_expired` | Ask the end user for another card or corrected details |
60
+ | OTP and PIN | `invalid_otp`, `otp_expired`, `too_many_attempts`, `otp_code_already_sent`, `card_is_blocked` | Re-prompt or restart the flow; after `card_is_blocked`, wait `retryAfterSeconds` |
61
+ | Funds and declines | `insufficient_funds`, `invalid_amount`, `do_not_honor`, `processing_error` | Tell the user; start a new attempt only after reconciling |
62
+ | Transaction state and lookup | `transaction_not_found`, `transaction_already_payed`, `hold_not_found` | Already done or not allowed in this state: read the record |
63
+ | Fiscalization | `ofd_check_already_generated`, `ofd_error` | Fix the receipt data, or read `fiscalization.getReceipt` |
64
+ | Splits and sub-merchants | `split_already_done`, `recipient_not_found`, `sub_merchant_already_created` | Read the split or fix the recipient data |
65
+ | Merchant setup | `gateway_not_working`, `terminal_does_not_exist` | Contact Paylov |
66
+
67
+ ### Credentials and access
68
+
69
+ - `invalid_grant`: wrong username, password or consumer credentials, an account Paylov has not
70
+ activated, an IP outside the allowlist, or a locked account. The client stays locked
71
+ ([setup.md](setup.md#runtime-behavior)).
72
+ - `permission_denied`: the feature is not enabled for the merchant, or the gateway refused even a
73
+ fresh token. Ask Paylov.
74
+
75
+ ## Recovery after an ambiguous failure
76
+
77
+ `isPaylovOutcomeUnknown(error)` is true when the call may have run: a protocol error, a connection
78
+ error after a request was sent, or a gateway error with HTTP status 500 or above. Nothing that moves
79
+ money is retried automatically. Then:
80
+
81
+ - Read the record named below before acting again. Never repeat a money-moving call blindly.
82
+ - Repeat a call that takes an `externalId` or a `transactionId` with the same value, never a new
83
+ one.
84
+ - A read that finds nothing, or still shows `created`, is not proof that the call did not run: read
85
+ again with backoff before repeating.
86
+ - After `payments.pay`, keep reading while the status is `transfer`, `pending` or `held`; `failed`
87
+ needs a new transaction. A status that stays `created` across those reads means, by the SDK's
88
+ assumption, that the pay did not take effect (Paylov does not document it): pay again with the
89
+ same `transactionId`, so a pay that landed late answers `transaction_already_payed` instead of
90
+ charging twice.
91
+ - A repeated call may fail with the code in the last column; the read confirms what it means.
92
+
93
+ | Method | Read next | Code on a repeated call |
94
+ | ---------------------------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
95
+ | `payments.pay` | `transactions.get` | `transaction_already_payed`: already paid |
96
+ | `payments.refund` | `transactions.get`: `refunded` with `cancelledAt` | `transaction_not_available_for_cancel`: already cancelled, never paid, or not refundable by API |
97
+ | `payments.confirmPanPayment` | `transactions.get` | `otp_expired`: the first confirm may have succeeded |
98
+ | `holds.create` | `holds.get({ externalId })` ([holds.md](holds.md#recovery)) | `external_id_already_exists`: the hold exists, possibly already released |
99
+ | `holds.capture` | `holds.get`: `captured`, and `amountTiyin` is the captured amount | `transaction_not_available_for_payment`: already captured or released; `hold_time_expired`: the hold ran out |
100
+ | `holds.release` | `holds.get`: `released` | `hold_not_found`: already released, captured, or expired; nothing left to release, by the SDK's assumption |
101
+ | `splits.create` | `splits.get` | `split_already_done` |
102
+ | `subMerchants.create` | None exists: repeat with the same data | `sub_merchant_already_created`: it exists |
103
+ | `fiscalization.registerReceipt`, `fiscalization.attachReceipt` | `fiscalization.getReceipt`: `null` means nothing is registered yet | `ofd_check_already_generated` |
104
+ | `fiscalization.refundReceipt` | `fiscalization.getReceipt({ externalId, isRefund: true })` | None known |
105
+ | `cards.confirmPanBinding` | `cards.get` | `card_is_already_activated`: done |
106
+ | `PaylovOnboarding.complete` | `PaylovOnboarding.checkToken`: `true` means `complete` can run again | None: on `false`, ask Paylov to reissue the credentials |
107
+ | `payments.create`, `payments.startPanPayment`, `cards.startPanBinding` | Nothing: call again | None: an unpaid record or a sent OTP moves no money |
@@ -0,0 +1,62 @@
1
+ # Fiscalization
2
+
3
+ `paylov.fiscalization` registers OFD fiscal receipts and checks activity types. None of it moves
4
+ money; refund a payment with `payments.refund`.
5
+
6
+ ## Register a receipt
7
+
8
+ ```ts
9
+ import { isPaylovApiError } from '@isroilov_an/paylov';
10
+
11
+ const items = [
12
+ {
13
+ title: 'Consultation',
14
+ priceTiyin: 25_000_000,
15
+ count: 1,
16
+ code: ikpuCode,
17
+ vatPercent: 12,
18
+ packageCode,
19
+ tin: commitentTin,
20
+ },
21
+ ];
22
+
23
+ try {
24
+ const receipt = await paylov.fiscalization.registerReceipt({ transactionId, items });
25
+ await receipts.save(transactionId, receipt.receiptId, receipt.receiptUrl);
26
+ } catch (error) {
27
+ if (!isPaylovApiError(error, 'ofd_check_already_generated')) throw error;
28
+ const existing = await paylov.fiscalization.getReceipt({ transactionId, isRefund: false });
29
+ if (existing !== null) {
30
+ await receipts.save(transactionId, existing.receiptId, existing.receiptUrl);
31
+ }
32
+ }
33
+ ```
34
+
35
+ - A card payment passes its paid `transactionId`; a cash sale passes `externalId` (your receipt key)
36
+ and `phoneNumber`.
37
+ - Store every `receiptId` (a number) with its `transactionId` or `externalId`: refunds and recovery
38
+ need it.
39
+ - `priceTiyin` is the price of one unit and `discountTiyin` comes off each unit, so a line totals
40
+ `(priceTiyin - discountTiyin) * count`; the lines must add up to the transaction amount, else
41
+ `invalid_amount`. Paylov documents no formula or discount unit: this is the SDK's reading, and the
42
+ SDK sends tiyin.
43
+ - Paylov does not document which payments it fiscalizes itself; agree it with Paylov as part of your
44
+ merchant setup. `attachReceipt` needs client-side fiscalization. The SDK cannot tell which
45
+ applies: read `getReceipt` before registering.
46
+ - Pass `isRefund` explicitly to `getReceipt`; which receipt comes back without it is undocumented.
47
+ - `null` from `getReceipt` is not final: the OFD may register a receipt later.
48
+
49
+ ## Refund receipts
50
+
51
+ - `payments.refund` cancels the payment's fiscalization. Afterwards read
52
+ `getReceipt({ transactionId, isRefund: true })`, and call `refundReceipt` with the sale's
53
+ `receiptId` only when that read shows no refund receipt.
54
+ - For a cash sale, `refundReceipt({ receiptId })` reverses the stored sale receipt.
55
+
56
+ ## Activity types
57
+
58
+ `checkActivityType` may answer a negative result as `gateway_not_working` instead of
59
+ `isConfirmed: false`: treat it as not confirmed, and retry later if the tax service may have been
60
+ down.
61
+
62
+ Recovery: [errors.md](errors.md#recovery-after-an-ambiguous-failure).
@@ -0,0 +1,82 @@
1
+ # Holds
2
+
3
+ A hold reserves money on a bound card; `capture` charges it, `release` gives it back. For a booking:
4
+ reserve at booking, capture after the visit, release on cancellation.
5
+
6
+ ## Flow
7
+
8
+ ```ts
9
+ // Store the externalId, the held amount and the creation time before the call.
10
+ const externalId = `booking-${booking.id}`; // at most 64 characters, unique per merchant
11
+ await bookings.saveHoldIntent(booking.id, {
12
+ externalId,
13
+ heldTiyin: booking.priceTiyin,
14
+ createdAt: new Date(),
15
+ });
16
+
17
+ const hold = await paylov.holds.create({
18
+ userId: booking.customerId,
19
+ cardId: booking.cardId,
20
+ amountTiyin: booking.priceTiyin, // whole SUM, at least 10 SUM
21
+ durationMinutes: 3 * 24 * 60, // at most 28 days
22
+ externalId,
23
+ });
24
+
25
+ // Later, before the deadline: capture once, or release.
26
+ if (booking.visited) {
27
+ await paylov.holds.capture({
28
+ transactionId: hold.transactionId,
29
+ amountTiyin: booking.priceTiyin,
30
+ });
31
+ } else {
32
+ await paylov.holds.release({ transactionId: hold.transactionId });
33
+ }
34
+ ```
35
+
36
+ ## Rules
37
+
38
+ - **Capture once, in full unless you mean to give up the rest.** A partial capture ends the hold:
39
+ the remainder can be neither captured nor released through the API. Paylov does not document what
40
+ happens to it; the SDK assumes Paylov and the card's bank release it to the cardholder, on their
41
+ schedule.
42
+ - **Keep the held amount yourself.** `holds.get` reports the captured amount after capture.
43
+ - **Release before capture; refund after.** After a capture only `payments.refund` (full) remains,
44
+ which Paylov's test environment refuses for captured holds; the fallback is the Paylov business
45
+ panel or Paylov support. Capture only the final amount so refunds stay rare.
46
+ - **Track the deadline yourself.** An expired hold can still read `held`; capture then fails with
47
+ `hold_time_expired`, and release has been seen both to fail and to succeed. Stop capturing a hold
48
+ at creation time plus `durationMinutes`, and release every hold you will not capture, also after
49
+ it expires. Release is the only documented way to free a hold, so the SDK reads `hold_not_found`
50
+ then as nothing left to release; Paylov does not document release after expiry. For a date beyond
51
+ 28 days, create the hold when the date enters the window.
52
+ - **Poll to reconcile.** Paylov sends no hold webhook: read `holds.get({ externalId })` for every
53
+ open booking. `transactions.get` uses other words for a hold: `paid` once captured, and an expired
54
+ hold Paylov released has read `refunded` there, like a refunded sale.
55
+
56
+ ## Recovery
57
+
58
+ After an ambiguous `create`, run this from a delayed job (an immediate miss proves nothing):
59
+
60
+ ```ts
61
+ import { isPaylovApiError, type CreateHoldParams } from '@isroilov_an/paylov';
62
+
63
+ export async function reconcileHold(
64
+ bookingId: string,
65
+ holdParams: CreateHoldParams,
66
+ ): Promise<void> {
67
+ const found = await paylov.holds.get({ externalId: holdParams.externalId });
68
+ if (found !== null) return bookings.saveHold(bookingId, found.transactionId);
69
+ try {
70
+ const hold = await paylov.holds.create(holdParams); // same externalId
71
+ await bookings.saveHold(bookingId, hold.transactionId);
72
+ } catch (error) {
73
+ if (!isPaylovApiError(error, 'external_id_already_exists')) throw error;
74
+ const existing = await paylov.holds.get({ externalId: holdParams.externalId });
75
+ if (existing === null) return jobs.retryLater(bookingId); // not visible yet
76
+ await bookings.saveHold(bookingId, existing.transactionId);
77
+ }
78
+ }
79
+ ```
80
+
81
+ For `capture` and `release`, read `holds.get` first; see
82
+ [errors.md](errors.md#recovery-after-an-ambiguous-failure).
@@ -0,0 +1,45 @@
1
+ # Money and time
2
+
3
+ ## Money is tiyin
4
+
5
+ Public money is a non-negative safe integer in tiyin (1 SUM = 100 tiyin), in fields ending in
6
+ `Tiyin`; a USD hosted-checkout amount is `amountCents` ([checkout.md](checkout.md)). The SDK
7
+ converts to each endpoint's wire unit and never rounds; responses are converted back to tiyin.
8
+
9
+ ```ts
10
+ import { formatSum, sumToTiyin } from '@isroilov_an/paylov';
11
+
12
+ sumToTiyin(1000); // 100000 (whole SUM)
13
+ sumToTiyin('1250.50'); // 125050 (exact decimal text, e.g. from a form or a database)
14
+ formatSum(2_500_000); // '25 000.00', for display only; never send it
15
+ ```
16
+
17
+ Some endpoints take whole SUM on the wire, so their amounts must be multiples of 100 tiyin
18
+ (`sdk_invalid_amount` otherwise): `sumToTiyin('10.50')` is a valid fiscal item price but fails on
19
+ `payments.create`. Paylov checks the bounds itself.
20
+
21
+ | Methods | Wire unit | Pitfall |
22
+ | ------------------------------------------------------------------------ | -------------------------- | --------------------------------------------------------- |
23
+ | `payments.create`, `payments.startPanPayment` | Whole SUM | Zero is rejected by the gateway |
24
+ | `holds.create`, `holds.capture` | Whole SUM | At least 10 SUM; a capture above the held amount fails |
25
+ | `splits.create` recipients, fiscal item `priceTiyin` and `discountTiyin` | Tiyin | Amounts must add up to the transaction amount |
26
+ | `createCheckoutUrl` | Tiyin (UZS) or cents (USD) | Out-of-range amounts fail on the page, after the redirect |
27
+
28
+ ## Dates and times
29
+
30
+ Fields ending in `At` are `Date` values. Paylov sends most timestamps without a zone; the SDK
31
+ applies the zone observed on the development gateway:
32
+
33
+ | Fields | Zone applied |
34
+ | ------------------------------------------------------------------------------------------- | ------------------------- |
35
+ | Transaction times (`transactions.get`, `transactions.list`), `payments.refund` `refundedAt` | Tashkent, fixed UTC+05:00 |
36
+ | Hold `capturedAt` and `releasedAt` | UTC |
37
+ | `cards.createBindLink` `expiresAt` | The offset in the value |
38
+ | Webhook times | Unix seconds |
39
+
40
+ - One event can arrive in two zones (a hold capture in UTC, its transaction in Tashkent); as `Date`
41
+ values they compare correctly.
42
+ - Fields ending in `Raw` hold timestamps of unknown zone, verbatim. Never pass them to `new Date()`:
43
+ engines read the space-separated form in local time. Store them as text or pick a zone explicitly.
44
+ - Date filters (`fromDate`, `toDate`) are `YYYY-MM-DD` calendar days.
45
+ - A timestamp in an unexpected format fails as `sdk_malformed_response` rather than being guessed.
@@ -0,0 +1,28 @@
1
+ # Onboarding
2
+
3
+ A one-time operator step, run from a trusted machine, that turns Paylov's single-use onboarding
4
+ token into the credentials `PaylovClient` needs.
5
+
6
+ ```ts
7
+ import { PaylovOnboarding } from '@isroilov_an/paylov';
8
+
9
+ const onboarding = new PaylovOnboarding({ baseUrl: 'https://gateway.example' });
10
+
11
+ if (!(await onboarding.checkToken({ token: onboardingToken }))) {
12
+ throw new Error('onboarding token is consumed or expired; ask Paylov for a new one');
13
+ }
14
+
15
+ const credentials = await onboarding.complete({
16
+ token: onboardingToken,
17
+ username: merchantUsername,
18
+ password: merchantPassword,
19
+ });
20
+ await secretManager.store('paylov', { ...credentials, password: merchantPassword });
21
+ ```
22
+
23
+ - `consumerSecret` is shown once and the token works once: persist the result, with the password,
24
+ before anything else.
25
+ - Then ask Paylov to activate the account. Until it does, every `PaylovClient` call fails with
26
+ `invalid_grant`, the same code as wrong credentials.
27
+ - After an ambiguous failure of `complete`, call `checkToken`: `true` means `complete` can run
28
+ again; `false` means the token was used, so ask Paylov to reissue the credentials.
@@ -0,0 +1,57 @@
1
+ # Payments
2
+
3
+ `paylov.payments` charges a card without a hold and refunds. Reconcile with
4
+ [transactions.md](transactions.md); to reserve funds first, use [holds.md](holds.md).
5
+
6
+ ## Charge a saved card
7
+
8
+ ```ts
9
+ import { sumToTiyin } from '@isroilov_an/paylov';
10
+
11
+ // 1. Create: no money moves. The amount must be whole SUM.
12
+ const { transactionId } = await paylov.payments.create({
13
+ amountTiyin: sumToTiyin(25_000),
14
+ account: { order_id: 'A-1024' },
15
+ userId: 'user-42',
16
+ });
17
+ await orders.saveTransaction('A-1024', transactionId);
18
+
19
+ // 2. Pay: money moves, without an OTP. The card must be bound to the same userId.
20
+ await paylov.payments.pay({ transactionId, cardId, userId: 'user-42' });
21
+ ```
22
+
23
+ - Store the `transactionId` with your order before calling `pay`: it is the key for reconciliation
24
+ and for any repeat.
25
+ - After a decline, read the transaction: `failed` can never be paid again; `created` can be paid
26
+ with another card.
27
+
28
+ ## Pay by card number
29
+
30
+ Your server handles the full card number, which puts it in PCI scope: take it from secure input and
31
+ never log or store it.
32
+
33
+ ```ts
34
+ const started = await paylov.payments.startPanPayment({
35
+ cardNumber: cardNumberFromSecureInput,
36
+ cardExpiry: cardExpiryFromSecureInput, // YYMM
37
+ amountTiyin: sumToTiyin(1200),
38
+ account: { order_id: 'A-1025' },
39
+ });
40
+ showOtpPrompt(`Uzcard/Humo sent a code to the phone linked to your card: ${started.otpSentPhone}`);
41
+ await paylov.payments.confirmPanPayment({ transactionId: started.transactionId, otp: otpFromUser });
42
+ ```
43
+
44
+ - OTP delivery and wrong-code limits are those of PAN binding ([cards.md](cards.md#pan-binding)).
45
+ - There is no external id; keep the `transactionId`.
46
+
47
+ ## Refund
48
+
49
+ - Always the full amount; it also cancels the payment's fiscal receipt. The transaction then reads
50
+ `refunded` and drops out of `transactions.list`.
51
+ - Checkout and PAN payments cannot be refunded through the API, and Paylov's test environment
52
+ refused captured holds too: refund those from the Paylov business panel or through Paylov support,
53
+ and confirm with `transactions.get`. Before capture, release a hold instead.
54
+ - Keep refunds an admin action: Paylov documents no fee terms.
55
+
56
+ After an ambiguous failure of `pay`, `confirmPanPayment` or `refund`, follow
57
+ [errors.md](errors.md#recovery-after-an-ambiguous-failure).
@@ -0,0 +1,85 @@
1
+ # Setup
2
+
3
+ ## Requirements
4
+
5
+ - Install from npm: `npm install @isroilov_an/paylov` ([README](../../README.md#install)).
6
+ - Node >= 24.13.1, ESM only: use `import` or `await import()`, never `require`.
7
+ - TypeScript `moduleResolution` `node16`, `nodenext` or `bundler`.
8
+ - Four credentials (`consumerKey`, `consumerSecret`, `username`, `password`), issued once through
9
+ [onboarding](onboarding.md) and activated by Paylov. Keep them in a secret manager.
10
+ - Paylov allowlists source networks: ask it to allow each egress IP that calls the gateway.
11
+
12
+ ## Create the client
13
+
14
+ ```ts
15
+ import { PaylovClient } from '@isroilov_an/paylov';
16
+
17
+ function required(name: string): string {
18
+ const value = process.env[name];
19
+ if (value === undefined || value === '') throw new Error(`missing env var ${name}`);
20
+ return value;
21
+ }
22
+
23
+ export const paylov = new PaylovClient({
24
+ baseUrl: required('PAYLOV_BASE_URL'),
25
+ consumerKey: required('PAYLOV_CONSUMER_KEY'),
26
+ consumerSecret: required('PAYLOV_CONSUMER_SECRET'),
27
+ username: required('PAYLOV_USERNAME'),
28
+ password: required('PAYLOV_PASSWORD'),
29
+ });
30
+ ```
31
+
32
+ - `baseUrl` is a bare origin: development `https://dev.gw.paylov.uz`, production
33
+ `https://gw2.paylov.uz`. The `.../merchant` URL the dashboard shows is rejected. Paylov does not
34
+ document how production differs in test cards or limits.
35
+ - Keep one long-lived client per credential set per process; tokens are not shared between
36
+ processes.
37
+ - Wrong credentials surface on the first authenticated call as `invalid_grant`
38
+ ([errors.md](errors.md#credentials-and-access)).
39
+ - Call `close()` on shutdown, after your own requests have settled: it revokes the access token, and
40
+ a request still in flight may then fail with `sdk_client_closed`, without effect. On the
41
+ development gateway a revoked token keeps working. `close()` resolves even when revocation fails;
42
+ only the logger events report that, and the token then stays valid until it expires.
43
+ - `close()` does not invalidate the refresh token, which stays valid for up to 30 days. If a
44
+ credential or token leaks, notify Paylov support, which revokes the credentials.
45
+
46
+ ## Check your sandbox setup
47
+
48
+ Run once from an allowlisted network with your DEV credentials and
49
+ `PAYLOV_BASE_URL=https://dev.gw.paylov.uz`. `getStatus` proves only that the gateway answers;
50
+ `listBanks` also proves the credentials. Report the count, never tokens or bodies.
51
+
52
+ ```ts
53
+ try {
54
+ await paylov.gateway.getStatus({ signal: AbortSignal.timeout(5_000) });
55
+ const banks = await paylov.gateway.listBanks({ signal: AbortSignal.timeout(10_000) });
56
+ console.log(`paylov ok: ${banks.length} banks`);
57
+ } finally {
58
+ await paylov.close();
59
+ }
60
+ ```
61
+
62
+ ## Runtime behavior
63
+
64
+ - **Deadlines.** `timeoutMs` bounds one HTTP attempt (`sdk_timeout`). A call's `{ signal }` bounds
65
+ the whole call: attempts, backoff and the token wait (`sdk_aborted`, never retried). A GET can
66
+ make up to four attempts, so pass a `signal` for a real deadline. A timed-out POST, or one aborted
67
+ after it was sent, has an unknown outcome
68
+ ([errors.md](errors.md#recovery-after-an-ambiguous-failure)); an abort before anything was sent
69
+ reports `isSent: false`.
70
+ - **Retries.** Only GETs retry: at most twice, after a network error, a timeout or HTTP
71
+ 500/502/503/504. POST and DELETE never retry. Nothing retries a 429: wait `retryAfterSeconds`.
72
+ - **Tokens.** Acquired lazily on the first authenticated call, shared by concurrent calls and
73
+ refreshed before expiry. After a 401 `permission_denied` the client fetches a new token and
74
+ replays the call once.
75
+ - **Locked client.** An `invalid_grant` from the password grant locks the client: later calls
76
+ rethrow it without I/O, because repeated failed logins can lock the merchant account. Fix the
77
+ credentials or account, then construct a new client.
78
+ - **Token rate limit.** After an HTTP 429 from the token endpoint (about 10 grants per minute on the
79
+ development gateway), calls rethrow it without I/O until `retryAfterSeconds` (60 s if none) has
80
+ passed.
81
+ - **Redirects** are not followed.
82
+ - **Logger.** `onRequest` and `onResponse` receive metadata for every attempt, token requests
83
+ included. Hooks are not awaited and their failures are discarded.
84
+ - **`fetch`.** Inject a `fetch` to route through a proxy or for tests ([testing.md](testing.md)).
85
+ `PaylovOnboarding` takes the same `timeoutMs`, `fetch` and `logger`.