Node.js library

The @payitgo/node package wraps the payitgo API for Node.js and TypeScript: payments, tokens, your webhook (IPN), its signature check and its events to replay, the public checkout calls, and payouts to your own clients from your payout wallet. It has no runtime dependencies and ships its own TypeScript types. Use it on your server only: it holds your secret key.

Requests and responses use the API's own field names (order_id, checkout_url, …), so the Payments, Webhooks, Checkout and Mass payouts pages describe every field this library returns.

Method HTTP Returns
payments.create(params) POST /v1/payments Payment
payments.retrieve(id) GET /v1/payments/{id} Payment
payments.list(params?) GET /v1/payments PaymentList
payments.selectToken(id, token) POST /v1/payments/{id}/token Payment
payments.simulate(id, outcome) POST /v1/payments/{id}/simulate Payment
tokens.list(params?) GET /v1/tokens TokenInfo[]
webhooks.get() GET /v1/webhook Webhook
webhooks.set(url) PUT /v1/webhook Webhook
webhooks.remove() DELETE /v1/webhook Webhook
webhooks.test() POST /v1/webhook/test WebhookDelivery
webhooks.constructEvent(body, header, secret?, tolerance?) none (local) WebhookEvent
Payitgo.webhooks.constructEvent(body, header, secret, tolerance?) none (local, no client) WebhookEvent
events.list(params?) GET /v1/events EventList
checkout.retrieve(checkoutToken) GET /checkout/{checkout_token} Payment
checkout.selectToken(checkoutToken, token) POST /checkout/{checkout_token}/token Payment
payouts.request(params) POST /v1/payouts PayoutItem
payouts.inbox(params?) GET /v1/payouts/inbox PayoutInbox
payouts.send(ids?) POST /v1/payouts/send PayoutBatch
payouts.cancel(id) DELETE /v1/payouts/{id} PayoutItem
payouts.retrieve(id) GET /v1/payouts/{id} PayoutItem
payouts.retrieveByReference(reference) GET /v1/payouts?reference= PayoutItem
payouts.list(params?) GET /v1/payouts PayoutList
payouts.quote(params) POST /v1/payout-quotes PayoutQuoteResult
payoutBatches.retrieve(id) GET /v1/payout-batches/{id} PayoutBatch
payoutWallets.list() GET /v1/payout-wallets PayoutWallet[]
payoutWallets.simulateTopUp(asset, amount) POST /v1/payout-wallets/{asset}/simulate-top-up PayoutWallet[]
isLive() GET /v1/webhook, the first time only boolean

Every method that calls the API returns a Promise.

Install

npm install @payitgo/node
Requirement
Node.js 18 or later (the library uses the built-in fetch)
Dependencies None
TypeScript Types included (dist/index.d.ts); no @types package needed
Module format CommonJS, with an ES module entry point (package.json exports)
// ES modules and TypeScript: the default export is the Payitgo class
import Payitgo, { PayitgoError, SignatureVerificationError } from "@payitgo/node";

// CommonJS
const { Payitgo, PayitgoError, SignatureVerificationError } = require("@payitgo/node");

Both entry points share one implementation, so instanceof PayitgoError holds whichever way a module imported the package. Only the package root is public: deep imports such as @payitgo/node/dist/index.js are not exported.

Quickstart

import { Payitgo } from "@payitgo/node";

const payitgo = new Payitgo(process.env.PAYITGO_KEY!);

const payment = await payitgo.payments.create({
  order_id: "ORD-1001",
  amount: "49.90",
  token: "USDT_TRC20",
});
console.log(payment.crypto_amount, payment.token, "to", payment.deposit_address);

Then set your webhook URL and fulfil the order when payment.confirmed arrives.

Configuration

new Payitgo

new Payitgo(apiKey: string, options?: PayitgoOptions)
Parameter Type Required Default Description
apiKey string yes Your secret key, test or live (Authentication). An empty key throws
options.baseUrl string no PAYITGO_BASE_URL, then https://api.payitgo.co payitgo's API, default https://api.payitgo.co (Base URL). Trailing slashes are removed
options.timeoutMs number no 30000 How long one attempt may take, in milliseconds, reading the answer included. A timeout counts as a network error, so it is retried
options.maxRetries number no 2 How many times a request is retried after a network error, a 429 or a 5xx. 0 turns retries off
options.webhookSecret string no none Your mode's signing secret. webhooks.constructEvent uses it when you pass none
options.webhookUrl string no none Sent as webhook_url with every payments.create that does not pass its own

The constructor makes no request. It throws a plain Error (not a PayitgoError) when:

Message Cause
payitgo: the API key is required apiKey is missing or empty
payitgo: baseUrl is empty: leave it out to use https://api.payitgo.co baseUrl is "", or it is left out and PAYITGO_BASE_URL is set but empty
const payitgo = new Payitgo(process.env.PAYITGO_KEY!, {
  timeoutMs: 15_000,
  maxRetries: 2,
  webhookSecret: process.env.PAYITGO_WEBHOOK_SECRET, // the signing secret of the key's mode
  webhookUrl: "https://api.yourdomain.com/payitgo/ipn",    // optional default for payments.create
});

One client can serve your whole application: it keeps no per-request state.

Properties

Property Type Description
payments object Payments
tokens object Tokens
webhooks object Webhooks
events object Events: the mode's events, to replay
checkout object Checkout
payouts object Payouts: your clients' payout requests, one by one
payoutBatches object Payout batches
payoutWallets object Payout wallets
Payitgo.webhooks object (static) constructEvent without a client

The module also exports VERSION ("0.7.1"), sent in the User-Agent: payitgo-node/0.7.1 header, and webhooks, the same object as Payitgo.webhooks.

isLive

GET /v1/webhook · API reference

payitgo.isLive(): Promise<boolean>

Returns true for a live key, false for a test key. A key does not say its mode, so the first call asks payitgo (the livemode of the key's webhook; a read-only key may call it) and the answer is kept for the client's life: later calls make no request.

Errors PayitgoError, as any call: 401 for a key payitgo does not know, 403 for a live key while live mode is off. An error is not kept: the next call asks again.

if (!(await payitgo.isLive())) console.log("test mode: payments are simulated");

Base URL

The client calls payitgo's API, default https://api.payitgo.co, so you need not set it. The address is taken from, in order: the baseUrl option, the PAYITGO_BASE_URL environment variable, and that default. An empty baseUrl, or an empty PAYITGO_BASE_URL without baseUrl, throws (see new Payitgo).

Test and live mode

The key decides the mode. A test key creates and reads test payments (no coins: you simulate what the customer sends) and manages the test webhook; a live key does the same for live ones. The key does not say which it is: the dashboard shows a Test or Live badge next to it, and payitgo.isLive() asks payitgo. Pair each key with the webhook secret of the same mode. See Test mode.

HTTP client

Requests go through Node's global fetch, with the headers Authorization: Bearer <key>, Accept: application/json, Content-Type: application/json (when there is a body) and User-Agent: payitgo-node/0.7.1. There is no option to pass your own HTTP client.

Errors

PayitgoError

Every call that reaches the API throws a PayitgoError when the request fails.

class PayitgoError extends Error {
  readonly status: number;
  name: "PayitgoError";
}
Field Type Description
status number The HTTP status, or 0 when no full answer came (a network error, or a timeout before or while the answer was read, after the retries)
message string The API's error message, such as minimum payment in USDT_TRC20 is $6.44 right now (network fees). HTTP <status> when the answer had no message. payitgo: request failed: <cause> for a network error

Branch on status; log message (its wording may change, see Errors and limits).

status Meaning Retried by the library
0 No full answer: DNS, connection, TLS, or a timeout (also while reading the answer) Yes
400 The request is invalid (the message says which field) No
401 missing api key or invalid api key No
403 Not allowed, for example a live key while live mode is off, a storefront key changing the account's webhook or reading its events, or a key without payouts making one No
404 No such payment, payout or payout batch in the key's mode No
409 Conflicts with the current state, such as changing a payment's coin once it can no longer change, simulating a payment whose simulation is running, or canceling a payout that was sent already No
429 Over the rate limit Yes
500 and other 5xx Something failed on payitgo's side Yes
import { PayitgoError } from "@payitgo/node";

try {
  await payitgo.payments.create({ order_id: "ORD-1", amount: 1, token: "BTC" });
} catch (err) {
  if (err instanceof PayitgoError && err.status === 400) {
    console.warn("payitgo refused:", err.message); // e.g. an amount under the coin's minimum
  } else {
    throw err;
  }
}

SignatureVerificationError

constructEvent throws a SignatureVerificationError (a subclass of Error, name "SignatureVerificationError") when a notification cannot be trusted. Answer 400.

message Cause
missing or malformed X-Webhook-Signature header No header, or no t or v1 in it
signature does not match The body, the timestamp or the secret differ from what payitgo signed (a v1 that is not 64 hex characters included)
malformed timestamp t is not a whole number of seconds (checked unless the tolerance is 0)
timestamp outside the tolerance t is further than the tolerance (by default 5 minutes) from your clock
no webhook secret: pass one, or set the client's webhookSecret The client method got no secret and the client has no webhookSecret

A body that is correctly signed but is not JSON throws a SyntaxError from JSON.parse; payitgo never sends one.

Retries

A request is retried, up to maxRetries times (default 2, so at most 3 attempts), after a network error, a timeout (before or while the answer is read), a 429 or a 5xx. It waits 0.5 s before the first retry and 1 s before the second (500 ms × 2ⁿ). Other statuses are never retried. When the last attempt fails, the call throws a PayitgoError with that attempt's status (0, 429 or 5xx).

Every call is retried the same way. What repeating each does (send a reference with every payout request, so repeats are safe):

Call Repeating it
payments.create Returns the order's open payment instead of a second one (safe retries)
payments.selectToken, checkout.selectToken Returns the payment unchanged: choosing the coin it has already changes nothing
payments.simulate If the first attempt went through, the repeat throws 409 while that simulation runs: read the payment with retrieve
webhooks.set, webhooks.remove Changes nothing the second time
webhooks.test Queues one more ping
payouts.request With a reference: returns the payment that reference names. Without one, a repeat is a second request: always send a reference
payouts.send If the first attempt went through, the repeat throws 400: those requests are no longer in the list (without ids, valid requests that arrived meanwhile are sent instead). Read the list with payouts.inbox
payouts.cancel Returns the payment canceled already, as it is
payoutWallets.simulateTopUp Adds the amount again (test wallet, on paper)
Reads Change nothing

Payments

payments.create

POST /v1/payments · API reference

payments.create(params: CreatePaymentParams): Promise<Payment>

Creates a payment for one of your orders. With a token, the payment comes back with its deposit address, amount, QR payload and a 15-minute deadline. Without one, it comes back with token_options and the customer (or your page, with selectToken) chooses the coin. While the order has an open payment, creating it again returns that payment.

Parameter Type Required Description
order_id string yes Your id for the order, 1 to 128 bytes. One open payment per order and mode
amount number or string yes The price, in currency, such as "49.90". Sent as you give it; a string avoids float rounding
currency string no The ISO 4217 code of the currency the price is in, such as "EUR", "GBP" or "NGN" (any case; any of the 154 currencies GET /currencies lists). Default USD. payitgo converts the price at the rate of the moment, and every figure on the payment is in this currency from then on, in every response and webhook (your currency)
token string no The coin, such as "USDT_TRC20" (from tokens.list). Leave it out to let the customer choose
tokens string[] no Without token: the coins to offer, such as ["USDT_TRC20", "USDT_BEP20"]. Default: every coin you accept whose minimum the amount reaches
description string no What the customer pays for, up to 500 bytes
metadata Record<string, string> no Your own data: up to 20 keys of up to 40 bytes, string values of up to 500
customer_email string no The customer's email address
success_url string no http(s) URL the hosted checkout links to once the payment is confirmed
cancel_url string no http(s) URL the hosted checkout links back to if the payment closes unpaid
webhook_url string no https:// URL that gets this payment's notifications instead of your account's webhook URL (per-payment URL). Default: the client's webhookUrl. Pass "" to give this payment no URL of its own (its events go to your account's webhook URL), even with a client default
simulate SimulationOutcome no Test keys only: the outcome to simulate. With token it starts at once; without, once the coin is chosen

Returns the Payment: the new one (201) or the order's open one (200); both resolve the same way. Fields: the payment object.

Errors PayitgoError with status 400 for an invalid request: a missing order_id, amount must be > 0, amount is worth less than a cent, currency must be the ISO 4217 code of a currency (USD, EUR, GBP, NGN…), a token you do not accept, an amount under the token's minimum (minimum payment in BTC is 4.50 EUR right now (network fees); $5.00 for a payment in dollars) or, without a token, under every coin's (amount is below the minimum of every token on offer), a webhook_url that is not public https, a simulate with a live key or an unknown outcome, and the rest of the create errors. 503 (exchange rate unavailable for currency: try again shortly) when no exchange rate can be had for currency (after the retries). Also 401, 403, 429, 500 and 0 as for every call.

// The customer pays in a coin you know:
const payment = await payitgo.payments.create({
  order_id: "ORD-1001",
  amount: "49.90",
  token: "USDT_TRC20",
  description: "2 x Acme T-shirt",
  metadata: { customer_id: "cus_42" },
  customer_email: "[email protected]",
  success_url: "https://yourdomain.com/thanks",
  cancel_url: "https://yourdomain.com/cart",
});
// payment.deposit_address, payment.crypto_amount, payment.qr_payload, payment.expires_at

// The customer chooses the coin (on the hosted page, or yours):
const open = await payitgo.payments.create({ order_id: "ORD-1002", amount: 25 });
open.token_options?.forEach((t) => console.log(t.token, t.minimum, t.amount_due ?? ""));

// This payment's notifications go to its own URL:
await payitgo.payments.create({
  order_id: "ORD-1003",
  amount: 30,
  token: "USDT_TRC20",
  webhook_url: "https://api.yourdomain.com/orders/ORD-1003/ipn",
});

// Priced in euros: every figure on the payment is in EUR, in every response and webhook.
const priced = await payitgo.payments.create({ order_id: "ORD-1004", amount: "45.50", currency: "EUR", token: "USDT_TRC20" });
// priced.currency "EUR", priced.amount "45.5", priced.crypto_amount "49.23"

payments.retrieve

GET /v1/payments/{id} · API reference

payments.retrieve(id: string): Promise<Payment>
Parameter Type Required Description
id string yes The payment's id, or your order_id for the order's open payment (the payment id is tried first). Escaped for the URL by the library

Returns the Payment.

Errors PayitgoError 404 (payment not found) for an unknown id, a payment of the other mode, or an order with no open payment. Plus the common statuses.

const byId = await payitgo.payments.retrieve("8f3a2c1e9b7d4a6f05e1c2d3");
const byOrder = await payitgo.payments.retrieve("ORD-1001"); // the order's open payment
if (byId.status === "confirmed") console.log("paid at", byId.confirmed_at);

payments.list

GET /v1/payments · API reference

payments.list(params?: ListPaymentsParams): Promise<PaymentList>

Payments of the key's mode, newest first.

Parameter Type Required Default Description
status PaymentStatus no all Only payments in this status
chain string no all Only payments on this network, such as "tron"
token string no all Only payments in this coin, such as "USDT_TRC20"
store_id string no all Only payments of this store (ignored for a storefront key, which sees its own)
limit number no 50 Page size, 1 to 200 (0 or less: 50; over 200: 200)
offset number no 0 How many to skip

Parameters that are undefined, null or "" are left out of the query.

Returns a PaymentList: payments, total (matches across all pages), and the limit and offset applied.

Errors the common statuses only. An unknown status, chain or token matches nothing.

// Every confirmed payment, page by page:
const confirmed = [];
for (let offset = 0; ; offset += 100) {
  const page = await payitgo.payments.list({ status: "confirmed", limit: 100, offset });
  confirmed.push(...page.payments);
  if (offset + page.limit >= page.total) break;
}

payments.selectToken

POST /v1/payments/{id}/token · API reference

payments.selectToken(id: string, token: string): Promise<Payment>

Sets the coin of a payment created without one, once the customer picked it on your own page, or changes it: another coin, while nothing has arrived (Changing the coin).

Parameter Type Required Description
id string yes The payment's id or your order_id
token string yes One of the payment's token_options[].token, such as "USDT_TRC20"

Returns the whole Payment, now with deposit_address, crypto_amount, rate_locked, qr_payload and an expires_at 15 minutes away.

Errors PayitgoError:

status message Cause
400 token is required Empty token
400 token is not one of this payment's options A coin not in token_options
400 minimum payment in … is $… right now (it is converted on its way to the merchant, and the exchange takes no less) The coin needs a bigger payment than this one: it is converted through the exchange on its way to the merchant, which takes no less, and the merchant pays the fees or hides such coins (hide_below_minimum). Offer the other coins
400 this payment can no longer be paid The payment has closed, or it is still pending past its expires_at (an hour to choose the coin, then 15 minutes to pay)
404 payment not found No such payment in the key's mode
409 the coin for this payment can no longer be changed The payment was created with its coin, something arrived, a test payment's simulation is running, or the coin was changed three times already
const payment = await payitgo.payments.create({ order_id: "ORD-1002", amount: 25 });
// …your page lists payment.token_options, the customer picks one…
const chosen = await payitgo.payments.selectToken(payment.id, "USDT_BEP20");
console.log(chosen.crypto_amount, chosen.token, chosen.deposit_address, chosen.expires_at);

payments.simulate

POST /v1/payments/{id}/simulate · API reference

payments.simulate(id: string, outcome: SimulationOutcome): Promise<Payment>

Plays an outcome on a test payment: payitgo sends its deposits, status changes and webhooks about 5 seconds apart, as live coins would, with no coins (Test mode). Test keys only.

Parameter Type Required Description
id string yes The payment's id or your order_id
outcome SimulationOutcome yes Such as "confirmed" (what each does)

Returns the whole Payment, with its simulation started. Simulated deposits have simulated: true; their tx_id names no transaction on any chain.

Errors PayitgoError:

status message Cause
400 outcome is required Empty outcome
400 simulate must be one of: confirmed, overpaid, … An unknown outcome
400 only test payments can be simulated: use a test key A live key
400 choose the payment's coin first wrong_asset before a coin is chosen. Any other outcome waits for the coin instead (simulation.state requested)
400 this payment is confirmed: only a pending or partially paid payment can be simulated The payment is closed or confirming
400 a BTC address only receives BTC: wrong_asset needs a coin on Tron, Ethereum or BNB Smart Chain wrong_asset on a coin that has no other
404 payment not found No such payment in the key's mode
409 a simulation is already running for this payment Wait until its state is "done"
const payment = await payitgo.payments.simulate("ORD-1002", "partially_paid");
console.log(payment.simulation); // { outcome: "partially_paid", state: "running" }
// once it is done, pay the rest:
await payitgo.payments.simulate("ORD-1002", "confirmed");

Tokens

tokens.list

GET /v1/tokens · API reference

tokens.list(params?: { amount?: string | number; currency?: string }): Promise<TokenInfo[]>

The coins your customers can pay with in the key's mode, with today's network fee and minimum, in currency (US dollars without one). With amount, only the coins a payment of that amount offers (its token_options), each with amount_due when you pass the fees on.

Parameter Type Required Description
amount string or number no The order's amount, in currency, such as "49.90"
currency string no The ISO 4217 code the amount and every figure are in, such as "EUR" (any case). Default USD

Returns an array of TokenInfo (the library unwraps the API's {"currency": "USD", "tokens": […]}).

Errors PayitgoError 400 (amount must be > 0) for an amount that is not a positive number, 400 (currency must be the ISO 4217 code of a currency (USD, EUR, GBP, NGN…)) for a code that is no currency, 503 (exchange rate unavailable for currency: try again shortly) when its exchange rate cannot be had, and the common statuses.

const options = await payitgo.tokens.list({ amount: "49.90" });
for (const t of options) {
  console.log(`${t.token} on ${t.chain}: pay $${t.amount_due ?? "49.90"}, ${t.fee_note}`);
}

Webhooks

The webhook (IPN) of the key's mode: one URL that receives every notification of that mode, and the secret that signs them (Webhooks). A test key manages the test webhook, a live key the live one. A storefront key can get and test it, but not set or remove it.

webhooks.get

GET /v1/webhook · API reference

webhooks.get(): Promise<Webhook>

Returns the Webhook: url (null when none is set) and secret, the signing secret to give the client as webhookSecret. It always succeeds for a valid key.

const { url, secret } = await payitgo.webhooks.get();

webhooks.set

PUT /v1/webhook · API reference

webhooks.set(url: string): Promise<Webhook>
Parameter Type Required Description
url string yes An absolute https:// URL on a public host that accepts POST

Returns the Webhook with its new url. The secret does not change. Setting the URL it already has changes nothing.

Errors PayitgoError 400 (url is required, url must use https, url must be an absolute http(s) URL, url host does not resolve, url must point at a public host, url must point at your own server, not payitgo's), 403 for a storefront key, 500 (could not set the webhook), and the common statuses.

await payitgo.webhooks.set("https://api.yourdomain.com/payitgo/ipn");

webhooks.remove

DELETE /v1/webhook · API reference

webhooks.remove(): Promise<Webhook>

Stops posting the mode's notifications to its URL. Payments created with their own webhook_url still get theirs, and the secret is kept.

Returns the Webhook with url: null.

Errors 403 for a storefront key, 500 (could not remove the webhook), and the common statuses.

webhooks.test

POST /v1/webhook/test · API reference

webhooks.test(): Promise<WebhookDelivery>

Queues a signed ping notification to the mode's URL; it arrives within about 5 seconds.

Returns the WebhookDelivery, with status: "pending".

Errors PayitgoError 400 (no webhook url is set for this mode: set one first), 500 (could not queue the test), and the common statuses.

const delivery = await payitgo.webhooks.test();
console.log(delivery.id, delivery.event_type, delivery.url); // 6710c3a1f2b4e5d6a7b8c9d0 ping https://…

webhooks.constructEvent

No request · how verification works

webhooks.constructEvent<T = any>(
  payload: string | Uint8Array,
  signatureHeader: string | undefined | null,
  secret?: string,
  toleranceSeconds?: number, // default 300
): WebhookEvent<T>

Verifies a notification and returns its event. It computes the HMAC-SHA256 of t + "." + payload with the secret, compares it with v1 in constant time, checks that t is within the tolerance of your clock, and only then parses the body.

Parameter Type Required Description
payload string or Uint8Array (a Buffer) yes The raw request body, exactly as received. A body parsed and serialized again will not verify (keep the raw body)
signatureHeader string, undefined or null yes The X-Webhook-Signature header
secret string no The signing secret, as payitgo gave it. Default: the client's webhookSecret. A secret passed here wins
toleranceSeconds number no How far t may be from your clock, in seconds. Default 300. 0 turns the timestamp check off (only for tests with captured bodies)

Returns a WebhookEvent<T>. Pass a type to type data: constructEvent<Payment>(…) for payment.* events.

Errors SignatureVerificationError. Answer 400.

const event = payitgo.webhooks.constructEvent<Payment>(req.body, req.get("X-Webhook-Signature"));
if (event.type === "payment.confirmed") console.log(event.data.order_id);

Payitgo.webhooks.constructEvent

Payitgo.webhooks.constructEvent<T = any>(
  payload: string | Uint8Array,
  signatureHeader: string | undefined | null,
  secret: string,
  toleranceSeconds?: number, // default 300
): WebhookEvent<T>

The same check without a client, for code that has the secret but no API key. secret is required. Also exported as webhooks:

import { webhooks } from "@payitgo/node";

const event = webhooks.constructEvent(rawBody, signatureHeader, process.env.PAYITGO_WEBHOOK_SECRET!);

Errors SignatureVerificationError, except the "no webhook secret" one.

Events

Every event of the key's mode is kept, sent or not, exactly as its notification carried it: read them to replay what your system missed (an outage, a lost delivery). Any key of the account can read them, read-only ones included; a storefront key is refused.

events.list

GET /v1/events · any account key · API reference

events.list(params?: ListEventsParams): Promise<EventList>

The mode's events, oldest first, payments' and payouts' alike. A test ping is left out, and events of the last few seconds are left for the next read, so moving forward never skips one.

Parameter Type Required Default Description
type WebhookEventType or string, or an array of them no all Exact types ("payout_item.sent") or families ("payout_item.*"), sent comma-separated
after string no An event's id: the events after it. Keep the last one you handled
created_after Date or string no The events after this time: a Date is sent as its ISO string, a string as given (RFC 3339). Ignored with after
limit number no 100 Page size, 1 to 200

Parameters that are undefined, null or "" are left out of the query.

Returns an EventList: events, each a WebhookEvent with the same id its notification had (the ones you handled already are skipped by your deduplication), and has_more. While has_more, call again with after the last event's id. A key without payouts gets claim links without their url and pin.

Errors PayitgoError:

status message Cause
400 type must be event types, such as payout_item.sent or payout_item.*
400 created_after must be an RFC 3339 time, such as 2026-10-20T09:00:00Z A string that is not one
400 limit must be 1 to 200
400 after is not an event of this mode An unknown id, or the other mode's
403 a storefront's key cannot read the account's events: use an account key
// After an outage: replay the payout events since the last one you handled.
let after = await lastHandledEventId(); // your code
for (;;) {
  const { events, has_more } = await payitgo.events.list({ type: "payout_item.*", after });
  for (const event of events) await handleEvent(event); // the same code as your webhook handler
  if (events.length) after = events[events.length - 1].id;
  if (!has_more) break;
}

Checkout

These two calls use the public checkout API: they are sent without your API key and are keyed by the payment's checkout_token. They return the payer's view of a payment. On your server you rarely need them: payments.retrieve and payments.selectToken return more. The client still needs an API key to be created, though these calls never send it.

checkout.retrieve

GET /checkout/{checkout_token} · API reference

checkout.retrieve(checkoutToken: string): Promise<Payment>
Parameter Type Required Description
checkoutToken string yes The payment's checkout_token

Returns a Payment without your private fields: merchant_id, metadata, customer_email, customer_id, webhook_url, checkout_token, checkout_url and opened_at are absent, and channel is "". Reading it from your server does not count as the customer opening the checkout page.

Errors PayitgoError 404 (payment not found), 0 and 5xx.

checkout.selectToken

POST /checkout/{checkout_token}/token · API reference

checkout.selectToken(checkoutToken: string, token: string): Promise<Payment>
Parameter Type Required Description
checkoutToken string yes The payment's checkout_token
token string yes One of the payment's token_options[].token

Returns the payer's view of the Payment with its coin, address, amount and a 15-minute deadline.

Errors the same as payments.selectToken, and 429 (rate limit exceeded) when choices come too fast from one visitor.

const view = await payitgo.checkout.retrieve("b28d4f61e9a03c75d2e8f1a6");
if (view.token === "") {
  const chosen = await payitgo.checkout.selectToken("b28d4f61e9a03c75d2e8f1a6", "USDT_TRC20");
  console.log(chosen.deposit_address);
}

Payouts

Pay your own clients (withdrawals from your platform, prizes, payroll) from your payout wallet: one address per network (Tron, BNB Smart Chain, Ethereum, Bitcoin, Litecoin, Dogecoin, XRP Ledger), yours alone, that you top up (Mass payouts). Payouts are paid in USDT_TRC20, TRX, USDT_BEP20, USDC_BEP20, ETH_BEP20, BNB, USDT_ERC20, USDC_ERC20, DAI_ERC20, ETH, BTC, LTC, DOGE and XRP, or in another coin, converted on its way. A payment can also be a claim link, whose recipient chooses where to receive it. There are two ways to send payouts, both paid from the same wallet:

How Methods
Payout requests Send each client's payout request as it comes in. payitgo checks and prices it at once and keeps it in your open list, with its costs, until you send the list (or it goes by itself, with auto-send turned on in the dashboard) payouts.*, below
Batches Make a whole list at once (payroll, prizes) in the dashboard under Pay people, typed, pasted or uploaded as a CSV file payoutBatches.retrieve reads one

The key decides the mode: a test key pays from your test wallet, on paper (simulateTopUp). Reading works with any key, read-only ones included. Every other call needs a key with payouts turned on in the dashboard (The API), and is otherwise a 403 (this api key cannot make payouts: turn payouts on for it in the dashboard). A payment or batch of the other mode is a 404.

Amounts come back as decimal strings in the payment's coin ("120", "5.748213"). The amounts you send may be strings or numbers, sent as you give them.

A payout request goes like this:

  1. payouts.request when a client asks to be paid: the payment comes back ready with its fees (fee, send_amount, debit), or invalid with its errors.
  2. payouts.inbox shows the open list and its coverage: what sending it needs of each coin against what the wallet can spend, and the top_up to send first.
  3. payouts.send moves the valid requests into a batch, priced again and submitted (a payout_item.processing notification for each): approved when your payout settings ask, then funded from the wallet.
  4. A payout_item.sent notification arrives for each payment once it is on chain, or another for how it ended otherwise (Payout webhooks).

payouts.request

POST /v1/payouts · a key with payouts on · API reference

payouts.request(params: RequestPayoutParams): Promise<PayoutItem>

Adds one of your clients' payout requests to your open list, checked and priced at once (Checking and pricing).

Parameter Type Required Description
reference string no, but send one Your id for the request (the client's withdrawal request), unique in its mode. Sending it again returns that payment instead of a second one (references)
asset string yes A payout coin, such as "USDT_TRC20" or "BTC" (any case). With conversion in your payout settings, another coin is paid from the wallet's, converted on its way
address string yes, unless a claim link The client's address on the coin's network. A claim link takes none
amount number or string yes How much of the coin, such as "120". Who pays the fees is your payout settings' fee_paid_by (Fees)
tag number no XRP's destination tag; refused on other coins
name, note string no Who it is for, and why: kept with it and shown in the dashboard
email string no The client's email. A claim link's link is emailed there; otherwise nothing is sent to it
claim boolean no true makes it a claim link: leave address out
claim_assets string[] no A claim link's other coins the client may choose, paid at the same dollar value (up to 10). Makes it a claim link too
webhook_url string no https:// URL on a public host that gets this payment's events instead of your account's webhook URL. It keeps it when it is sent into a batch. The client's webhookUrl option is not used here

Returns the PayoutItem: the new one (201) or the one its reference already names (200); both resolve the same way. An invalid request is kept too, with status: "invalid" and its errors: it is never sent and costs nothing. To correct it, cancel it (its reference is then free again) and send the corrected request.

Errors PayitgoError 400 (invalid request body: a field of the wrong type; webhook_url: url must use https, webhook_url: url host does not resolve, webhook_url: url must point at a public host, webhook_url: url must point at your own server, not payitgo's; your payout wallet cannot pay this request and those already in your list; send … first, then try again: the payout wallet cannot pay it with the requests already waiting, and nothing is added; 503 when its balance cannot be checked just now, to send again), 403 for a key without payouts, 409 (your list of payout requests is full: send or cancel some first), and the common statuses.

const item = await payitgo.payouts.request({
  reference: "wd-1042",
  asset: "USDT_TRC20",
  address: "TR7mNkucnhLZoJQLLJ6DR88jpLQufWxUJi",
  amount: "120",
  name: "Ana Silva",
});
if (item.status === "invalid") {
  console.log(item.errors.map((e) => `${e.code}: ${e.message}`)); // wrong_network: this address is for …
} else {
  console.log(`the client receives ${item.send_amount}, the wallet gives ${item.debit} ${item.ticker}`);
}

payouts.inbox

GET /v1/payouts/inbox · any key · API reference

payouts.inbox(params?: ListPayoutItemsParams): Promise<PayoutInbox>

Your open list of payout requests, and what sending it takes.

Parameter Type Required Default Description
status PayoutItemStatus, or an array of them no all Only the requests in this status, or in these (sent comma-separated)
limit number no 50 Page size, 1 to 200 (0 or less: 50; over 200: 200)
offset number no 0 How many to skip

Returns the whole PayoutInbox: inbox, the list itself (a PayoutBatch with inbox and open true: its totals per coin, total_usd and counts); coverage, one entry per coin of its valid requests (needed, spendable, and the top_up to send to address first, "0" when the wallet covers it); and a page of the requests (items, total, limit, offset).

Errors the common statuses only.

const { inbox, coverage } = await payitgo.payouts.inbox({ status: "ready" });
console.log(`${inbox.counts.ready} ready to send, $${inbox.total_usd} in all`);
for (const c of coverage) {
  if (Number(c.top_up) > 0) console.log(`top up ${c.top_up} ${c.asset} on ${c.network}: ${c.address}`);
}

payouts.send

POST /v1/payouts/send · a key with payouts on · API reference

payouts.send(ids?: string[]): Promise<PayoutBatch>

Sends your open payout requests: every valid (ready) one, or those of ids. They move into a batch of their own, priced again at today's fees and submitted: it waits for approvals when your payout settings ask, then for funds when the wallet falls short (waiting.shortfall says what to send where), or starts at once (A batch's life). The other requests stay in the list.

Parameter Type Required Description
ids string[] no The requests to send, each ready in your list. Leave it out to send every valid one. An empty array is refused by the library (400, no request made) rather than read as "every request"

Returns the new PayoutBatch (source: "requests"): pending_approval, awaiting_funds or processing. More than 100 requests are priced in the background: the batch comes back validating, and is submitted once quoted (payout_batch.quoted, then the next event). If the batch cannot be submitted (none of its requests is valid any more at today's prices, or it is over your limit per batch), the requests go back to your list, each saying why, that batch is canceled, and send throws the error. A batch priced in the background is canceled the same way, and your team gets a "Payout requests not sent" notification.

Errors PayitgoError:

status message Cause
400 no valid payout request to send · no payout request to send Nothing ready in the list
400 payout request … is not a valid request waiting in your list An id that is not ready in your list
400 payitgo: ids is empty: leave it out to send every valid request ids is [] (thrown by the library)
400 none of the requests is valid any more: they are back in your list, each saying why Priced again, none can be paid
400 this batch takes $…, over your limit of $… per batch Over your payout settings' batch_max_usd: the requests are back in the list
403 this api key cannot make payouts: … The key's payouts is off
const batch = await payitgo.payouts.send();
if (batch.waiting?.reason === "funds") {
  for (const s of batch.waiting.shortfall ?? []) console.log(`send ${s.amount} ${s.asset} to ${s.address}`);
}

payouts.cancel

DELETE /v1/payouts/{id} · a key with payouts on · API reference

payouts.cancel(id: string): Promise<PayoutItem>

Takes a payment out. A request still in your open list is removed (cancel_reason: "removed"): its reference is free again (it moves to released_reference), it no longer has a batch_id, and its record stays, so retrieve keeps answering it. Any other payment not on its way yet is canceled (cancel_reason: "canceled"), its reference given back too:

Either way a payout_item.canceled notification is sent. A payment canceled already is returned as it is: safe to retry.

Parameter Type Required Description
id string yes The payment's id. Escaped for the URL by the library

Returns the PayoutItem, with status: "canceled" and its cancel_reason, canceled_by and canceled_at.

Errors 404 (not found), 409 (the payment is sent, or failed, expired) once it ended, and the common statuses.

const item = await payitgo.payouts.cancel("4e6a8c0b2d4f6a1c3e5b7d9a");
console.log(item.cancel_reason, item.released_reference); // "removed" "wd-1042"

payouts.retrieve

GET /v1/payouts/{id} · any key · API reference

payouts.retrieve(id: string): Promise<PayoutItem>

A payment by its id: a payout request, or a row of any batch.

Returns the PayoutItem.

Errors 404 (not found) for an unknown id or a payment of the other mode, and the common statuses.

payouts.retrieveByReference

GET /v1/payouts?reference= · any key · API reference

payouts.retrieveByReference(reference: string): Promise<PayoutItem>

A payment by your reference: the payout request or batch row that carries it now; if none does, the latest payment that gave it back (canceled, failed or expired, with it as released_reference): what became of a request sent with it. Escaped for the URL by the library.

Returns the PayoutItem.

Errors 400 (payitgo: reference is required, thrown by the library, no request made) for an empty reference, 404 (not found) when no payment carries it or gave it back, and the common statuses.

const item = await payitgo.payouts.retrieveByReference("wd-1042");
if (item.status === "sent") console.log(item.tx_id, item.explorer_url);
else if (item.status === "canceled") console.log(item.cancel_reason); // its reference is free again

payouts.list

GET /v1/payouts · any key · API reference

payouts.list(params?: ListPayoutsParams): Promise<PayoutList>

Every payment of the key's mode, whatever its batch (requests in your list, removed ones, every batch's), oldest change first: to bring your system back in sync after it was down, or to check it is. Changes of the last few seconds are left for the next read, so a cursor never skips one.

Parameter Type Required Default Description
status PayoutItemStatus, or an array of them no all One status, or several (sent comma-separated): ["sent", "failed", "canceled", "expired"] for the ended ones
updated_since Date or string no The payments changed at or after this time: a Date is sent as its ISO string, a string as given (RFC 3339)
cursor string no The next_cursor of the page before
limit number no 50 Page size, 1 to 200

Parameters that are undefined, null or "" are left out of the query.

Returns a PayoutList: items, has_more, and next_cursor (absent when the page is empty). Read with updated_since the first time, then with cursor while has_more; keep the last next_cursor and call again with it later to get what changed since.

Errors PayitgoError:

status message Cause
400 updated_since must be an RFC 3339 time, such as 2026-10-20T09:00:00Z A string that is not one
400 limit must be 1 to 200
400 cursor is not one this API gave
let cursor = await savedCursor(); // your code: undefined the first time
let page;
do {
  page = await payitgo.payouts.list(cursor ? { cursor } : { updated_since: new Date(Date.now() - 86_400_000) });
  for (const item of page.items) await syncWithdrawal(item); // act on item.status
  cursor = page.next_cursor ?? cursor;
} while (page.has_more);
await saveCursor(cursor);

payouts.quote

POST /v1/payout-quotes · a key with payouts on · API reference

payouts.quote(params: PayoutQuoteParams): Promise<PayoutQuoteResult>

What up to 100 payments would cost, checked and priced exactly as in a batch, without keeping anything: use it to show a client the fee before they confirm.

Parameter Type Required Description
fee_paid_by "merchant" or "recipient" no Who pays the fees: on top of each amount, or out of it. Default: your payout settings'
convert "same_network" or "convert" no same_network pays each payment from the wallet's balance of its own coin. convert pays every payment in another coin than convert_from from convert_from, converted on its way. Default: your payout settings'
convert_from string no With convert, the wallet's coin that pays, such as "USDT_TRC20". Default: your payout settings'
items PayoutItemInput[] yes 1 to 100 payments

Returns a PayoutQuoteResult: quote, the totals a batch of them would have (livemode, fee_paid_by, totals, total_usd, counts), and items, the payments as they would be, each with its fees and issues and no id, merchant_id, batch_id or times.

Errors 400 (quote between 1 and 100 payments, fee_paid_by must be merchant or recipient), 403 for a key without payouts, and the common statuses.

const { quote, items } = await payitgo.payouts.quote({
  fee_paid_by: "recipient",
  items: [{ asset: "USDT_BEP20", address: "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", amount: "120" }],
});
console.log(`fee ${items[0].fee}, the client receives ${items[0].send_amount} ${items[0].ticker}`);

API reference

A payment whose recipient chooses where to receive it: the coin (its own, or one of claim_assets, at the same dollar value) and the address. Make one in a payout request, a batch or a quote alike, with claim: true or claim_assets, and no address:

An email alone does not make a claim link: a payment with no address and neither claim nor claim_assets is invalid, like any missing address.

const item = await payitgo.payouts.request({
  reference: "prize-cup-1",
  asset: "USDT_TRC20",
  amount: "120",
  claim: true,
  email: "[email protected]",
  claim_assets: ["USDT_BEP20", "BTC"],
});
console.log(item.claim?.url); // the link, also emailed

Its life, in the payment's status and claim:

When status What to read
Its batch is funded: the money is kept for it claimable claim.expires_at: the link works until then
The recipient claims it queued, then sending and sent asset, address and amount are what they chose; claim.claimed_at; claim.funded_asset and claim.funded_amount when they chose another coin than it was funded with. A payout_item.claimed notification
The link ends unclaimed expired Its money is free again in the wallet and its reference is in released_reference. A payout_item.claim_expired notification

claim.emailed and claim.extended count the emails sent and the times the link was extended: resending and extending are done in the dashboard. A claim link with an address, or an email that is not valid (invalid_email), is invalid. A claimable payment can be canceled.

Converted payments

API reference

Pay a recipient in a coin your wallet does not hold. With convert: "convert" (on payouts.quote, or in your payout settings, which payout requests follow), every payment in another coin than convert_from is paid from convert_from, converted on its way. Both default to your payout settings.

const { items: [item] } = await payitgo.payouts.quote({
  convert: "convert",
  convert_from: "USDT_TRC20",
  items: [{ asset: "BTC", address: "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", amount: "0.002" }],
});
console.log(item.convert?.to, item.convert?.estimate); // "BTC", about what arrives
console.log(item.asset, item.fee, item.debit); // "USDT_TRC20", converting included, what the wallet gives

A converted payment's asset, amount, fee (converting included) and debit are in the wallet's coin (convert_from); its address is the recipient's on the network of convert.to. convert says what the recipient receives: to_amount (what you asked), estimate (about what arrives) and, once sent, amount_out (what did). The prices of a batch with converted payments hold for 15 minutes. A coin that cannot be converted right now is an invalid payment (conversion_unavailable). Claim links are never converted.

Payout batches

A whole list of payments at once (payroll, prizes), checked and priced when made, then submitted, approved (when your payout settings ask) and funded from your payout wallet (A batch's life). Make them in the dashboard under Pay people, typed, pasted or uploaded as a CSV file. payouts.send makes one from your open list of payout requests, and retrieve reads any of them. A batch of the other mode than the key's is a 404.

payoutBatches.retrieve

GET /v1/payout-batches/{id} · any key · API reference

payoutBatches.retrieve(id: string): Promise<PayoutBatch>

Returns the PayoutBatch.

Errors 404 (not found), and the common statuses.

Payout wallets

Your payout wallet in the key's mode: one address per network (tron, bsc, ethereum, bitcoin, litecoin, dogecoin, xrp), made the first time it is asked for, and never changing (The payout wallet). Send each address only its network's payout coins, as listed in its assets: for example USDT_TRC20 and TRX to the Tron address. Withdrawals back to your own payout addresses are made in the dashboard, by the owner (Withdrawals): no key can send the wallet's money anywhere but to your payments' recipients.

payoutWallets.list

GET /v1/payout-wallets · any key · API reference

payoutWallets.list(): Promise<PayoutWallet[]>

Returns an array of PayoutWallet (the library unwraps the API's {"wallets": […]}): per chain, its address and, per coin, balance, reserved, spendable, and needed, what batches waiting for funds lack: the top-up to send now.

for (const w of await payitgo.payoutWallets.list()) {
  for (const a of w.assets) {
    if (Number(a.needed) > 0) console.log(`send ${a.needed} ${a.asset} to ${w.address} (${w.network})`);
  }
}

payoutWallets.simulateTopUp

POST /v1/payout-wallets/{asset}/simulate-top-up · a test key with payouts on · API reference

payoutWallets.simulateTopUp(asset: string, amount: number | string): Promise<PayoutWallet[]>

Adds amount of asset to your test wallet's balance, on paper, and funds any test batch waiting for it. In test mode, payments are then sent on paper within seconds, each with a made-up tx_id (on no chain, with no explorer_url), and their notifications arrive as live ones do.

Parameter Type Required Description
asset string yes A payout coin, such as "USDT_TRC20"
amount number or string yes Over 0 and up to 10,000,000

Returns the test wallets, as list does.

Errors 400 (only a test wallet is topped up on paper: use a test key, payouts in … are not available yet for a coin payouts do not pay in, amount must be over 0 and at most 10000000), 403 for a key without payouts, and the common statuses.

await payitgo.payoutWallets.simulateTopUp("USDT_TRC20", "1000");

Payout webhooks

Each step of a batch, and of each payment, raises a notification, signed like every other with the secret of its mode (events). Where they go:

Verify them with webhooks.constructEvent, typing data:

Event data Sent when
payout_batch.quoted PayoutBatch Checked and priced: made, payments added, quoted again
payout_batch.pending_approval PayoutBatch Submitted; it waits for approvals
payout_batch.approved PayoutBatch Its last approval came: it is funded next, or waits
payout_batch.rejected PayoutBatch An approver refused it (rejection.reason)
payout_batch.awaiting_funds PayoutBatch It cannot be funded yet: waiting says why. Sent again whenever the reason changes
payout_batch.processing PayoutBatch Funded: its payments are being sent
payout_batch.completed PayoutBatch Every payment is sent, failed, canceled or expired (counts)
payout_batch.canceled PayoutBatch Canceled before it was funded: by your team or a key, or by payitgo (canceled_by: "system": a send of requests that could not be submitted, or nothing left that could be paid)
payout_item.processing PayoutItem A payout request left your list for a batch (sent from the dashboard, by payouts.send or by auto-send): status ready, batch_id the new batch
payout_item.returned PayoutItem A sent payout request came back to your list: its batch could not be submitted, or it was no longer valid when priced again (status invalid, errors say why). Not final
payout_item.sent PayoutItem A payment is on chain (tx_id)
payout_item.failed PayoutItem A payment was given up (fail_reason); its money stays in the wallet
payout_item.canceled PayoutItem A payment was canceled before it was sent, whatever canceled it: cancel_reason (removed, canceled, batch_canceled, rejected with cancel_note, invalid) and canceled_by say why and who
payout_item.claimed PayoutItem A claim link's recipient claimed it: it is queued, with their coin and address
payout_item.claim_expired PayoutItem A claim link ended unclaimed: it is expired, its money free again
payout_wallet.withdrawn PayoutWithdrawal A withdrawal reached your payout address (tx_id)
payout_wallet.withdrawal_failed PayoutWithdrawal A withdrawal could not be sent (fail_reason); its money stays in the wallet
payout_schedule.run PayoutSchedule, a summary without its rows A schedule ran: last_batch_id is the batch it made (source: "schedule"), last_error why it made none
payout_schedule.funding_needed PayoutScheduleFunding remind_days before a run, the wallet cannot cover it: {schedule, shortfall}, what to send where

Schedules make the same batch again and again (payroll); they are made and changed in the dashboard (Schedules), so the library only receives their events.

A payment never sent (failed, canceled or expired) gives its reference back: its reference is then empty and the one it had is in released_reference, so the same request can be paid again. See Paying your clients' withdrawals.

Staying in sync

API reference

Every payment, a payout request or a batch row, ends sent, failed, canceled or expired, and each end has one event (payout_item.sent, payout_item.failed, payout_item.canceled, payout_item.claim_expired), whoever acted on it: your system, your team in the dashboard, or payitgo. Each is delivered at least once:

Types

All types are exported from @payitgo/node. Amounts are decimal strings ("49.9") and times are RFC 3339 strings ("2026-10-10T09:15:00.112Z"): parse amounts with a decimal library and times with new Date(…). Optional fields are absent from the object when they have no value.

Payment

A payment, as payments.*, checkout.* and payment.* events return it. Every field is described in the payment object.

interface Payment {
  id: string;
  merchant_id?: string;
  store_id?: string;
  order_id: string;
  status: PaymentStatus;
  livemode: boolean;
  simulation?: Simulation;     // a test payment's simulated outcome
  token: string;               // "" until the coin is chosen
  chain: string;               // "" until the coin is chosen
  token_options?: TokenInfo[]; // while the coin can be chosen or changed
  previous_coins?: PreviousCoin[]; // coins chosen before token: token, chain, deposit_address, destination_tag, crypto_amount, rate_locked
  deposit_address: string;     // "" until the coin is chosen
  destination_tag?: number;    // XRP only
  crypto_amount: string;       // what the customer sends, in the coin
  crypto_received: string;     // what arrived, in the coin
  confirmations: number;       // the latest deposit's, out of confirmations_required: "12 of 20" while detecting
  confirmations_required: number; // what makes a deposit final on the payment's network
  detected_at?: string;        // when the first deposit was seen
  currency: string;            // what the payment is priced in: an ISO 4217 code ("USD" unless you gave one), or a payment link's coin
  amount: string;              // the price, in currency
  amount_due: string;          // what the customer pays, in currency: the price, plus the fees when you pass them on
  amount_received: string;     // what arrived so far, in currency
  amount_extra?: string;       // what of amount_due only reaches the exchange's minimum: you receive it
  fees_paid_by_customer: boolean;
  settlement: "custodial" | "direct";
  rate_locked: string;         // the coin's price in currency, locked when the coin was chosen
  tx_id?: string;
  overpaid?: boolean;
  paid_late?: boolean;
  deposits: Deposit[];
  expires_at: string;
  created_at: string;
  confirmed_at?: string;
  network_fee_note: string;
  qr_payload: string;
  checkout_token?: string;
  checkout_url?: string;
  description?: string;
  metadata?: Record<string, string>;
  customer_email?: string;
  success_url?: string;
  cancel_url?: string;
  webhook_url?: string;
}

PaymentStatus

type PaymentStatus =
  | "pending" | "partially_paid" | "detecting" | "confirmed"
  | "underpaid" | "expired" | "failed";

See the lifecycle. Only confirmed means you have been paid.

Simulation

A test payment's simulated outcome. Absent when it has none.

interface Simulation {
  outcome: SimulationOutcome;
  state: "requested" | "running" | "done"; // requested: asked for on create, waiting for the coin
}

type SimulationOutcome =
  | "confirmed" | "overpaid" | "partially_paid" | "underpaid"
  | "expired" | "failed" | "wrong_asset" | "paid_late" | "paid_twice";

Deposit

One transfer to the payment's address (the deposit object).

interface Deposit {
  tx_id: string;
  token: string;     // the asset that arrived
  chain: string;
  amount: string;
  value: string;     // its worth in the payment's currency
  counted: boolean;  // counts toward the payment
  late?: boolean;    // arrived after the payment had closed
  status: "pending" | "confirmed" | "failed";
  seen_at: string;
  confirmed_at?: string;
  from?: string;        // the sender, when the network reports it: where a refund would go
  to?: string;          // the address it was sent to: the payment's, or a previous coin's
  block?: number;       // the block (XRP: the ledger) that holds it
  made_at?: string;     // that block's time
  failed_at?: string;   // when it failed
  fail_reason?: string; // "transaction not found on chain" or "confirmation timeout"
  simulated?: boolean;  // played by a test payment's simulation: its tx_id is on no chain
}

CreatePaymentParams

The parameters of payments.create.

interface CreatePaymentParams {
  order_id: string;
  amount: number | string;          // the price, in currency
  currency?: string;                // its ISO 4217 code ("EUR"); "USD" when left out
  token?: string;
  tokens?: string[];
  description?: string;
  metadata?: Record<string, string>;
  customer_email?: string;
  success_url?: string;
  cancel_url?: string;
  webhook_url?: string;
  simulate?: SimulationOutcome; // test keys only
}

ListPaymentsParams

The parameters of payments.list.

interface ListPaymentsParams {
  status?: PaymentStatus;
  chain?: string;
  token?: string;
  store_id?: string;
  limit?: number;
  offset?: number;
}

PaymentList

interface PaymentList {
  payments: Payment[];
  total: number;  // matches across all pages
  limit: number;  // the page size applied
  offset: number; // the offset applied
}

TokenInfo

A coin the customer can pay with (the TokenInfo object).

interface TokenInfo {
  token: string;            // "USDT_TRC20"
  chain: string;            // "tron"
  minimum: string;          // the smallest amount accepted right now, in the listing's currency like every figure here
  network_fee: string;      // the network fee right now
  network_fee_bps?: number; // for a coin that is converted: the share the network fee adds on top
  amount_due?: string;      // with an amount, when you pass the fees on
  amount_extra?: string;    // what of amount_due only reaches the exchange's minimum: you receive it
  fee_note: string;
}

Webhook

The webhook of the key's mode (the webhook object).

interface Webhook {
  livemode: boolean;
  url: string | null; // null when none is set
  secret: string;     // signs the mode's notifications
  created_at: string;
  updated_at: string;
}

WebhookDelivery

One notification on its way to one URL (the delivery object).

interface WebhookDelivery {
  id: string;                      // the X-Webhook-Id header
  merchant_id: string;
  target: "account" | "payment";   // the mode's URL, or the payment's own webhook_url
  url: string;
  event_id: string;                // the event's id
  event_type: string;
  payload: string;                 // the exact body posted
  status: "pending" | "sending" | "delivered" | "failed" | "resolved";
  attempts: number;
  max_attempts: number;            // 7
  next_attempt_at: string;
  last_status_code?: number;
  last_error?: string;
  last_attempt_at?: string;
  delivered_at?: string;
  resolved_at?: string;
  resolution_note?: string;
  created_at: string;
  history?: WebhookDeliveryAttempt[];
}

interface WebhookDeliveryAttempt {
  at: string;
  url?: string;
  signed?: string;      // the t of the attempt's signature
  status_code?: number;
  error?: string;
  response?: string;    // the start of your server's answer
  millis?: number;
  note?: string;        // a redelivery or resolution, and by whom
}

WebhookEvent

A verified notification (the body).

interface WebhookEvent<T = any> {
  id: string;         // the same on every retry: deduplicate on it
  type: string;       // one of WebhookEventType
  livemode: boolean;
  created_at: string;
  data: T;            // the payment, settlement, payout, payout batch, payout payment, withdrawal, schedule, or {message: "pong"}
}

type WebhookEventType =
  | "payment.partially_paid" | "payment.detecting" | "payment.confirmed"
  | "payment.underpaid" | "payment.expired" | "payment.failed"
  | "payment.wrong_asset" | "payment.late_deposit"
  | "payout.approved" | "payout.rejected" | "payout.sent"
  | "settlement.completed" | "settlement.failed"
  | "payout_batch.quoted" | "payout_batch.pending_approval" | "payout_batch.approved"
  | "payout_batch.rejected" | "payout_batch.awaiting_funds" | "payout_batch.processing"
  | "payout_batch.completed" | "payout_batch.canceled"
  | "payout_item.processing" | "payout_item.returned"
  | "payout_item.sent" | "payout_item.failed" | "payout_item.canceled"
  | "payout_item.claimed" | "payout_item.claim_expired"
  | "payout_wallet.withdrawn" | "payout_wallet.withdrawal_failed"
  | "payout_schedule.run" | "payout_schedule.funding_needed"
  | "ping";

data is a Payment for payment.* events, a settlement for settlement.*, a payout for payout.*, a PayoutBatch for payout_batch.*, a PayoutItem for payout_item.*, a PayoutWithdrawal for payout_wallet.*, a PayoutSchedule for payout_schedule.run and a PayoutScheduleFunding for payout_schedule.funding_needed (Payout webhooks), and { message: "pong" } for ping. See the events.

EventList

What events.list returns.

interface EventList {
  events: WebhookEvent[];  // oldest first, each as its notification carried it
  has_more: boolean;       // more follow: call again with after = the last event's id
}

interface ListEventsParams {
  type?: WebhookEventType | string | (WebhookEventType | string)[]; // "payout_item.sent", or a family: "payout_item.*"
  after?: string;                // an event's id: the events after it
  created_after?: Date | string; // a Date is sent as its ISO string; ignored with after
  limit?: number;                // 1 to 200; 100 by default
}

PayitgoOptions

The constructor's options.

interface PayitgoOptions {
  baseUrl?: string;
  timeoutMs?: number;
  maxRetries?: number;
  webhookSecret?: string;
  webhookUrl?: string;
}

PayoutItem

One payment to a recipient: a payout request, or a row of a batch, as payouts.* and payout_item.* events return it. Every field is described in the payment object.

interface PayoutItem {
  id: string;
  merchant_id: string;
  livemode: boolean;
  batch_id?: string;           // its batch; while it waits in your open list, the list's id; absent once removed from it
  reference?: string;          // your id for it, unique in its mode
  refused_reference?: string;  // a reference another payment carries: it keeps none, and is invalid
  released_reference?: string; // canceled or failed (never sent): its reference, free again
  row: number;                 // its place in its batch, from 1
  recipient: { name?: string; email?: string; note?: string };
  asset: string;               // the coin the wallet pays it in: "USDT_TRC20", "BTC", …
  ticker?: string;             // "USDT"
  icon_url?: string;
  chain: string;               // "tron", "bsc", "ethereum", "bitcoin", "litecoin", "dogecoin" or "xrp"
  address: string;             // "" for a claim link until it is claimed
  tag?: number;                // XRP's destination tag
  amount: string;              // what you asked to pay (converted: its worth in the wallet's coin)
  send_amount: string;         // what reaches the recipient (converted: what is sent to be converted)
  fee: string;                 // the whole fee (converted: converting included)
  debit: string;               // what it takes from the wallet
  usd_rate: string;            // the coin's dollar price when it was priced
  amount_usd: string;
  status: PayoutItemStatus;
  errors: PayoutIssue[];       // [] when none: why it is invalid
  warnings: PayoutIssue[];     // [] when none: worth knowing, and it still goes
  cooling_until?: string;      // a new recipient's payment waits until then
  tx_id?: string;              // once sent (made up in test mode)
  explorer_url?: string;       // live only
  fail_reason?: string;
  cancel_reason?: PayoutCancelReason; // once canceled: why
  cancel_note?: string;        // with "rejected": the approver's reason
  canceled_by?: string;        // a team member's id, an API key's id, or "system" (payitgo itself)
  canceled_at?: string;
  members?: Record<string, string>; // the email of the team member in canceled_by, by id
  webhook_url?: string;        // where its events go instead of its batch's webhook_url or your account's URL
  claim?: PayoutClaim;         // a claim link's state
  convert?: PayoutConversion;  // a payment converted on its way
  fee_credit?: string;         // the fee given back for a payment never sent
  sent_at?: string;
  created_at: string;
  updated_at: string;
}

// A payment as payouts.quote prices it: nothing is kept.
type PayoutQuoteItem = Omit<PayoutItem, "id" | "merchant_id" | "batch_id" | "created_at" | "updated_at">;

Before it is checked (validating) and when it is invalid, its fees and dollar figures are "0".

PayoutItemStatus

type PayoutItemStatus =
  | "validating" | "ready" | "invalid" | "cooling" | "queued"
  | "claimable" | "sending" | "sent" | "failed" | "canceled" | "expired";

See the payments. Only sent means it is on chain. claimable and expired are a claim link's: funded and waiting for its recipient, or never claimed (its money free again).

PayoutCancelReason

Why a payment was canceled, in its cancel_reason.

type PayoutCancelReason = "removed" | "canceled" | "batch_canceled" | "rejected" | "invalid";
Value Meaning
removed Taken out of your list of payout requests (cancel, or the dashboard)
canceled That payment alone, by your team or a key
batch_canceled Its batch was canceled
rejected Its batch was rejected: cancel_note is the approver's reason
invalid No longer payable when its batch was submitted or funded: errors say why

PayoutClaim

A claim link's state, in a payment's claim (Claim links).

interface PayoutClaim {
  email?: string;          // where the link is emailed
  assets: string[];        // the other coins the recipient may choose; [] when only its own
  expires_at?: string;     // set when it is funded: the link works until then
  claimed_at?: string;
  emailed: number;         // emails sent
  last_email_at?: string;
  extended: number;        // times it was extended
  url?: string;            // the link (absent in a quote)
  pin?: string;            // no email: the 6 digits the recipient enters, given apart from the link
  pin_locked?: boolean;    // 5 wrong PINs: locked until a new PIN is made in the dashboard
  funded_asset?: string;   // when the recipient chose another coin: what it was funded with
  funded_amount?: string;
}

PayoutConversion

A payment converted on its way, in a payment's convert (Converted payments).

interface PayoutConversion {
  to: string;           // the coin the recipient receives: "BTC"
  ticker: string;
  network: string;
  to_amount: string;    // what you asked to pay, in to
  estimate: string;     // about what arrives
  amount_out?: string;  // what arrived, once sent
}

PayoutIssue

Something wrong with a payment (in errors: it is left out) or worth knowing (in warnings). The codes are listed in Checking and pricing; codes may be added, so treat an unknown one by the list it is in and show its message.

interface PayoutIssue {
  code: string;     // "wrong_network", "below_minimum", "new_recipient", …
  field?: string;   // asset, amount, address, tag or reference
  message: string;  // for people: what is wrong
  hint?: string;    // for people: what to do
}

PayoutBatch

A set of payments, checked, priced, approved and funded together; also your open list of payout requests (inbox and open true). Every field is described in the batch object.

interface PayoutBatch {
  id: string;
  merchant_id: string;
  livemode: boolean;
  reference?: string;              // your id for it, unique in its mode
  name: string;                    // "" when none
  source: "api" | "dashboard" | "csv" | "requests" | "schedule"; // payout requests sent together; a schedule's run
  inbox: boolean;                  // made of payout requests
  open: boolean;                   // your open list itself: never submitted
  created_by: string;              // a team member's id, or the API key's
  by_api_key: boolean;
  fee_paid_by: "merchant" | "recipient";
  convert: "same_network" | "convert"; // how it pays coins the wallet does not hold
  convert_from?: string;           // with convert: the wallet's coin that pays them
  webhook_url?: string;
  status: PayoutBatchStatus;
  waiting?: PayoutWaiting;         // while awaiting_funds
  totals: PayoutAssetTotal[];      // its valid payments, per coin
  counts: PayoutCounts;
  total_usd: string;               // what it takes from the wallet, in dollars
  quote_expires_at?: string;       // its prices hold until then
  approvals_needed: number;
  approvals: { user_id: string; at: string }[];
  rejection?: { by: string; at: string; reason: string };
  submitted_by?: string;
  submitted_at?: string;
  funded_at?: string;
  completed_at?: string;
  canceled_by?: string;
  canceled_at?: string;
  created_at: string;
  updated_at: string;
}

approvals and rejection are exported as PayoutApproval and PayoutDecision.

PayoutBatchStatus

type PayoutBatchStatus =
  | "validating" | "quoted" | "pending_approval" | "awaiting_funds"
  | "processing" | "completed" | "canceled" | "rejected";

See a batch's life.

PayoutAssetTotal

A batch's valid payments in one coin.

interface PayoutAssetTotal {
  asset: string;
  ticker: string;
  icon_url: string;
  chain: string;
  network: string;      // "Tron (TRC-20)"
  items: number;        // how many payments
  amount: string;
  send_amount: string;
  fee: string;
  debit: string;        // what the wallet gives
  debit_usd: string;
  saved_usd: string;    // what sending them together saves in network fees
}

PayoutCounts

A batch's payments by status.

interface PayoutCounts {
  total: number;
  invalid: number;
  ready: number;
  cooling: number;
  queued: number;
  sending: number;
  sent: number;
  failed: number;
  canceled: number;
  claimable: number;
  expired: number;
}

PayoutWaiting

Why a batch awaiting funds waits (why a batch waits).

interface PayoutWaiting {
  reason: "funds" | "daily_limit" | "paused";
  note: string;                  // the same, for people
  since: string;
  shortfall?: PayoutShortfall[]; // for funds: what to send where
}

interface PayoutShortfall {
  asset: string;
  network: string;
  amount: string;
  address: string;  // your payout wallet's address on that network
}

PayoutInbox

Your open payout requests, as payouts.inbox returns them.

interface PayoutInbox {
  inbox: PayoutBatch;          // the list itself: totals, counts, total_usd
  coverage: PayoutCoverage[];  // one per coin of its valid requests
  items: PayoutItem[];         // a page of the requests
  total: number;
  limit: number;
  offset: number;
}

interface PayoutCoverage {
  asset: string;
  ticker: string;
  network: string;
  needed: string;     // what sending the valid requests in this coin takes
  spendable: string;  // what the wallet can spend of it
  top_up: string;     // what to send to address first; "0" when covered
  address: string;
}

PayoutWallet

Your payout wallet on one chain (the wallet object).

interface PayoutWallet {
  chain: string;          // "tron", "bsc", "ethereum", "bitcoin", "litecoin", "dogecoin" or "xrp"
  network: string;        // "Tron", "BNB Smart Chain", …
  address: string;        // where to send that network's payout coins
  explorer_url?: string;  // live only
  livemode: boolean;
  assets: PayoutWalletAsset[];
  error?: string;         // its balances could not be read just now (they are then "0")
}

interface PayoutWalletAsset {
  asset: string;
  ticker: string;
  icon_url: string;
  balance: string;    // on chain (on paper in test mode)
  reserved: string;   // promised to payments, fees and withdrawals not sent yet
  spendable: string;  // balance - reserved
  needed: string;     // what batches waiting for funds lack: the top-up to send now
}

PayoutWithdrawal

A payout wallet's funds sent back to one of your payout addresses, as the payout_wallet.withdrawn and payout_wallet.withdrawal_failed events carry it (Withdrawals).

interface PayoutWithdrawal {
  id: string;
  merchant_id: string;
  livemode: boolean;
  asset: string;
  chain: string;
  amount: string;       // what left the wallet
  fee: string;
  send_amount: string;  // what reached your address
  address_id: string;
  address: string;
  tag?: number;
  status: "requested" | "sending" | "sent" | "failed";
  tx_id?: string;
  explorer_url?: string;
  fail_reason?: string; // why a failed one failed: its money stays in the wallet
  requested_by: string;
  created_at: string;
  updated_at: string;
  sent_at?: string;
}

PayoutQuoteResult

What payouts.quote returns.

interface PayoutQuoteResult {
  quote: PayoutQuote;
  items: PayoutQuoteItem[];  // each payment as it would be: no id, merchant_id, batch_id or times
}

interface PayoutQuote {
  livemode: boolean;
  fee_paid_by: "merchant" | "recipient";
  totals: PayoutAssetTotal[];
  total_usd: string;
  counts: PayoutCounts;
}

PayoutSchedule

A payout schedule, made in the dashboard (Schedules), as its events carry it: a summary, without its rows (they stay in the dashboard). payout_schedule.run carries a PayoutSchedule; payout_schedule.funding_needed a PayoutScheduleFunding.

interface PayoutSchedule {
  id: string;
  livemode: boolean;
  name: string;
  status: "active" | "paused";
  cadence: "weekly" | "biweekly" | "monthly";
  weekday: number;            // weekly, biweekly: 0 (Sunday) to 6 (Saturday)
  day: number;                // monthly: 1 to 28, or -1 for the month's last day
  at: string;                 // "09:00", in timezone
  timezone: string;           // "Africa/Harare"
  fee_paid_by: "merchant" | "recipient";
  auto_submit: boolean;       // each run's batch is submitted by itself
  remind_days: number;        // funding_needed comes this many days before a run
  totals: PayoutScheduleTotal[]; // per coin, each run: asset, ticker, items, amount
  next_run_at: string | null; // null while paused
  last_run_at: string | null; // null before its first run
  last_batch_id: string;      // the batch its last run made; "" when none
  last_error: string;         // why its last run made none; "" when it made one
  runs: number;
}

interface PayoutScheduleFunding {
  schedule: PayoutSchedule;
  shortfall: PayoutShortfall[];  // what the wallet lacks for the next run, and where to send it
}

PayoutItemInput

A payment to make, as payouts.quote takes it. payouts.request takes the same fields as RequestPayoutParams, where a reference used already returns that payment. A payment's webhook_url wins over its batch's and your account's URL, and a request keeps it when it is sent into a batch; a quote ignores it.

interface PayoutItemInput {
  asset: string;             // a payout coin: "USDT_TRC20", "BTC", …
  address?: string;          // required, except for a claim link (which takes none)
  amount: number | string;   // a string avoids float rounding
  reference?: string;        // unique in its mode: a row whose reference is taken is invalid
  tag?: number;              // XRP's destination tag
  name?: string;
  email?: string;            // a claim link's link is emailed there
  note?: string;
  claim?: boolean;           // makes it a claim link
  claim_assets?: string[];   // a claim link's other coins (makes it one too)
  webhook_url?: string;      // https: this payment's events go there; at most 10 different ones per call
}

interface RequestPayoutParams extends PayoutItemInput {}

PayoutQuoteParams

The parameters of payouts.quote.

interface PayoutQuoteParams {
  fee_paid_by?: "merchant" | "recipient";
  convert?: "same_network" | "convert";
  convert_from?: string;
  items: PayoutItemInput[];  // 1 to 100
}

ListPayoutItemsParams

interface ListPayoutItemsParams {    // payouts.inbox
  status?: PayoutItemStatus | PayoutItemStatus[];
  limit?: number;
  offset?: number;
}

interface ListPayoutsParams {        // payouts.list
  status?: PayoutItemStatus | PayoutItemStatus[];
  updated_since?: Date | string;     // a Date is sent as its ISO string
  cursor?: string;                   // the next_cursor of the page before
  limit?: number;                    // 1 to 200; 50 by default
}

PayoutList

What payouts.list returns.

interface PayoutList {
  items: PayoutItem[];   // oldest change first
  has_more: boolean;     // more follow: call again with cursor = next_cursor
  next_cursor?: string;  // keep it to read what changed since; absent when the page is empty
}

Examples

Your own payment page

Show the coins on your own site, create the payment in the coin the customer picks, and render the amount, address, QR code and deadline from the payment itself (what to show). Express, with the qrcode package for the QR code:

// npm install @payitgo/node express qrcode
import express from "express";
import QRCode from "qrcode";
import { Payitgo, PayitgoError, type Payment } from "@payitgo/node";

const payitgo = new Payitgo(process.env.PAYITGO_KEY!);
const app = express();
app.use(express.urlencoded({ extended: false }));

const NETWORKS: Record<string, string> = {
  tron: "Tron (TRC-20)", ethereum: "Ethereum (ERC-20)", bsc: "BNB Smart Chain (BEP-20)",
  bitcoin: "Bitcoin", litecoin: "Litecoin", dogecoin: "Dogecoin", xrp: "XRP Ledger",
};
const esc = (s: unknown) =>
  String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

// 1. The coins this order can be paid with, and what each costs the customer.
app.get("/orders/:id/pay", async (req, res) => {
  const order = await findOrder(req.params.id); // your code: { id, total: "49.90" }
  const tokens = await payitgo.tokens.list({ amount: order.total });
  res.send(`<form method="post">${tokens
    .map((t) => `<button name="token" value="${esc(t.token)}">
        ${esc(t.token)} on ${esc(NETWORKS[t.chain] ?? t.chain)}: $${esc(t.amount_due ?? order.total)}
      </button>`)
    .join("")}</form>`);
});

// 2. The customer picked one: create the payment in it and show it.
app.post("/orders/:id/pay", async (req, res) => {
  const order = await findOrder(req.params.id);
  try {
    const payment = await payitgo.payments.create({
      order_id: order.id,          // the same order again returns its open payment
      amount: order.total,
      token: String(req.body.token),
    });
    res.send(await renderPayment(payment));
  } catch (err) {
    // Log the API's message (err.status, err.message); do not show it to the customer.
    console.error(err instanceof PayitgoError ? `payitgo ${err.status}: ${err.message}` : err);
    res.status(502).send("We could not start this payment. Please try again.");
  }
});

async function renderPayment(p: Payment): Promise<string> {
  const qr = await QRCode.toDataURL(p.qr_payload);
  return `
    ${p.livemode ? "" : "<p><b>Test payment:</b> do not send coins to this address.</p>"}
    <p>Send exactly <b>${esc(p.crypto_amount)} ${esc(p.token.split("_")[0])}</b>
       on <b>${esc(NETWORKS[p.chain] ?? p.chain)}</b> to</p>
    <p><code>${esc(p.deposit_address)}</code></p>
    ${p.destination_tag !== undefined ? `<p>Destination tag (required): <b>${p.destination_tag}</b></p>` : ""}
    <img src="${qr}" width="220" height="220" alt="QR code">
    <p>Pay before <time datetime="${esc(p.expires_at)}">${esc(new Date(p.expires_at).toUTCString())}</time></p>`;
}

A payment keeps its coin while it is open: if the customer goes back and picks another coin, payments.create for the same order returns the first payment unchanged. To let the customer choose on your page after the payment exists, create it without token and set the coin with selectToken:

const payment = await payitgo.payments.create({ order_id: order.id, amount: order.total });
// render payment.token_options (each with token, chain, minimum, amount_due, fee_note)…
// …and when the customer picks one:
const chosen = await payitgo.payments.selectToken(payment.id, pickedToken);
res.send(await renderPayment(chosen));

To follow the payment live on the page, connect the page's script to the socket's default namespace (/) and subscribe with payment.checkout_token (with an acknowledgement): every payment:update then carries the whole payment (follow it live). No polling. Fulfil the order from the webhook, never from the page.

A webhook (IPN) handler with Express

Read the raw body, verify it, handle each event once, and answer 2xx within 10 seconds (answering and retries):

import express from "express";
import { Payitgo, type Payment } from "@payitgo/node";

const payitgo = new Payitgo(process.env.PAYITGO_KEY!, {
  webhookSecret: process.env.PAYITGO_WEBHOOK_SECRET, // the signing secret of the key's mode
});
const app = express();

// express.raw keeps the body as a Buffer. Register this route before any
// app.use(express.json()), or the body is parsed and will not verify.
app.post("/payitgo/ipn", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = payitgo.webhooks.constructEvent<Payment>(req.body, req.get("X-Webhook-Signature"));
  } catch {
    return res.sendStatus(400); // not from payitgo, changed, or too old
  }

  if (await isProcessed(event.id)) return res.sendStatus(200); // a retry or redelivery

  if (event.livemode === (await payitgo.isLive())) { // ignore the other mode's events
    switch (event.type) {
      case "payment.confirmed":                // final: fulfil
        await markOrderPaid(event.data.order_id, event.data.id); // idempotent
        break;
      case "payment.expired":                  // nothing arrived in time
        await releaseOrder(event.data.order_id);
        break;
    }
  }

  await markProcessed(event.id);
  res.sendStatus(200);
});

app.listen(3000);

isProcessed, markProcessed, markOrderPaid and releaseOrder are your own code: store processed event ids in a table with a unique key, and make fulfilment safe to run twice. If your code throws, Express answers 500 and payitgo retries the notification. More in handle events safely.

Paying your clients' withdrawals

A platform paying its users' withdrawal requests: each request goes to payitgo as it comes in, a job sends the open list, and the webhook marks each withdrawal paid (Payouts). Express, with a key that has payouts on:

import express from "express";
import { Payitgo, PayitgoError, type PayoutItem } from "@payitgo/node";

const payitgo = new Payitgo(process.env.PAYITGO_KEY!, {
  webhookSecret: process.env.PAYITGO_WEBHOOK_SECRET,
});
const app = express();

// 1. A user asks to withdraw: hand the request to payitgo, with your id for it.
app.post("/withdrawals", express.json(), async (req, res) => {
  const w = await createWithdrawal(req.body); // your code: { id, asset, address, amount }
  try {
    const item = await payitgo.payouts.request({
      reference: w.id,                        // a retry returns the same payment
      asset: w.asset,
      address: w.address,
      amount: w.amount,
    });
    if (item.status === "invalid") {
      await payitgo.payouts.cancel(item.id);  // frees the reference for a corrected request
      return res.status(422).json({ errors: item.errors.map((e) => e.message) });
    }
    res.json({ fee: item.fee, receive: item.send_amount });
  } catch (err) {
    console.error(err instanceof PayitgoError ? `payitgo ${err.status}: ${err.message}` : err);
    res.status(502).json({ error: "We could not take this withdrawal. Please try again." });
  }
});

// 2. Every hour (or turn auto-send on in the dashboard): send the open list.
async function sendWithdrawals() {
  const { inbox, coverage } = await payitgo.payouts.inbox({ limit: 1 });
  if (inbox.counts.ready === 0) return;
  const short = coverage.filter((c) => Number(c.top_up) > 0);
  if (short.length) await alertTreasury(short); // your code: send c.top_up of c.asset to c.address
  await payitgo.payouts.send(); // a batch short of funds waits, and starts by itself once they arrive
}

// 3. The webhook: mark each withdrawal paid, or reopen it.
app.post("/payitgo/ipn", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = payitgo.webhooks.constructEvent<PayoutItem>(req.body, req.get("X-Webhook-Signature"));
  } catch {
    return res.sendStatus(400);
  }
  if (await isProcessed(event.id)) return res.sendStatus(200);
  switch (event.type) {
    case "payout_item.sent":                  // on chain
      await markWithdrawalPaid(event.data.reference!, event.data.tx_id!);
      break;
    case "payout_item.failed":                // never sent: the money stays in the wallet,
    case "payout_item.canceled":              // and the reference moved to released_reference
      await reopenWithdrawal(event.data.released_reference!, event.data.fail_reason);
      break;
  }
  await markProcessed(event.id);
  res.sendStatus(200);
});

createWithdrawal, alertTreasury, isProcessed, markProcessed, markWithdrawalPaid and reopenWithdrawal are your own code. A batch's payout_batch.* events go to the same URL (their data is a PayoutBatch): payout_batch.awaiting_funds carries the waiting.shortfall to send.

Test mode

Build everything with your test key: the same calls, simulated payments instead of coins, and the test webhook with its own secret (Test mode).

const payitgo = new Payitgo(process.env.PAYITGO_TEST_KEY!); // your test key
console.log(await payitgo.isLive()); // false

// Point the TEST webhook at your development server and read its secret.
const hook = await payitgo.webhooks.set("https://dev.yourdomain.com/payitgo/ipn");
console.log(hook.secret);    // test mode's signing secret: your dev PAYITGO_WEBHOOK_SECRET

// A signed ping arrives within seconds.
await payitgo.webhooks.test();

// A test payment that pays itself: payment.detecting, then payment.confirmed,
// arrive at the test webhook within half a minute.
const payment = await payitgo.payments.create({
  order_id: "TEST-1", amount: 10, token: "USDT_TRC20", simulate: "confirmed",
});
console.log(payment.livemode, payment.simulation?.state); // false "running"

// Another outcome on a payment you already have:
await payitgo.payments.simulate("TEST-2", "underpaid");

// Payouts on paper: top the test wallet up, then request and send. With no
// approvals in your payout settings, payout_batch.processing and then
// payout_item.sent arrive within seconds, with a made-up tx_id.
await payitgo.payoutWallets.simulateTopUp("USDT_TRC20", "1000");
await payitgo.payouts.request({
  reference: "TEST-WD-1", asset: "USDT_TRC20", address: "TR7mNkucnhLZoJQLLJ6DR88jpLQufWxUJi", amount: "50",
});
await payitgo.payouts.send();

Never send real coins to a test address: nothing watches it (why).

Check your verification against the example in the recipe (tolerance 0, because the example is old):

const body = '{"created_at":"2026-10-10T09:12:44.512837Z","data":{"message":"pong"},"id":"5c0e1f9a2b7d4e3c8a6f1b2d","livemode":false,"type":"ping"}';
const event = Payitgo.webhooks.constructEvent(
  body,
  "t=1791623565,v1=1af0ba31872e3152c422edaf9442c9f0eb4ebd202beebafbaaba14f77336194b",
  "a3858862701d1ce11ab06cb5dd9bb941d4849283f81fc0c3f0db0d99a2b82d48",
  0,
);
console.log(event.type); // "ping"

To test your handler without the network, sign a body yourself:

import { createHmac } from "node:crypto";

function sign(body: string, secret: string, t = Math.floor(Date.now() / 1000)): string {
  return `t=${t},v1=${createHmac("sha256", secret).update(`${t}.${body}`).digest("hex")}`;
}
// POST body to your handler with the header X-Webhook-Signature: sign(body, secret)

Going live: put the live key and the live webhook secret in your production environment, set the live webhook URL with the live key, and keep the event.livemode check in your handler (going live).