Dart and Flutter library
The payitgo package wraps the payitgo API for Dart. It has two clients:
| Client | Key | Where it runs | What it does |
|---|---|---|---|
Payitgo |
Your secret key | Your server (a Dart backend, Cloud Functions, a CLI) | Payments, tokens, payouts to your own clients, your webhook (IPN) and its signature check |
PayitgoCheckout |
None | Flutter apps (mobile, desktop, web) and anywhere else | Shows one payment by its checkout_token, lets the customer choose the coin, and follows the payment |
Never put a secret key in a Flutter app: anyone can extract it. Your backend
creates the payment and hands the app its checkout_token.
Models have typed getters (payment.orderId, payment.checkoutUrl, …) over
the API's fields, and raw for every field as the API sent it, so the
Payments, Webhooks,
Checkout and Mass payouts pages describe
everything this library returns.
checkout is a PayitgoCheckout, or payitgo.checkout on the
server client.
Install
dart pub add payitgo # Dart
flutter pub add payitgo # Flutter
import 'package:payitgo/payitgo.dart';
| Requirement | |
|---|---|
| Dart | 3.0 or later (Flutter 3.10 or later) |
| Dependencies | http 1.2+, crypto 3.0.3+ |
| Platforms | Every Dart platform; the library does not import dart:io |
Quickstart
On your server:
import 'dart:io';
import 'package:payitgo/payitgo.dart';
Future<void> main() async {
final payitgo = Payitgo(Platform.environment['PAYITGO_KEY']!);
final payment = await payitgo.payments.create(
orderId: 'ORD-1001',
amount: '49.90',
token: 'USDT_TRC20',
);
print('${payment.cryptoAmount} ${payment.token} to ${payment.depositAddress}');
}
Then set your webhook URL and fulfil the order when
payment.confirmed arrives. In the app,
show the payment with PayitgoCheckout.
Configuration
Payitgo
Payitgo(
String apiKey, {
String? baseUrl,
http.Client? httpClient,
int maxRetries = 2,
Duration timeout = const Duration(seconds: 30),
String? webhookSecret,
String? webhookUrl,
})
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
apiKey |
String |
yes | Your secret key, test or live (Authentication). An empty key throws | |
baseUrl |
String? |
no | https://api.payitgo.co |
payitgo's API, default https://api.payitgo.co: leave it out. Trailing slashes are removed. The library reads no environment variable |
httpClient |
http.Client? |
no | One http.Client() the library makes, shared with checkout and closed by close() |
The package:http client every request goes through: an IOClient with your own HttpClient, a MockClient in tests. You close one you pass in |
maxRetries |
int |
no | 2 |
How many times a request is retried after a network error, a 429 or a 5xx. 0 turns retries off |
timeout |
Duration |
no | 30 seconds | How long one attempt may wait for the answer to start. A timeout counts as a network error, so it is retried |
webhookSecret |
String? |
no | none | Your mode's signing secret. webhooks.constructEvent uses it when you pass none |
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 an ArgumentError when:
| Message | Cause |
|---|---|
payitgo: the API key is required |
apiKey is empty |
payitgo: baseUrl is empty: leave it out to use https://api.payitgo.co |
An empty baseUrl ('', or only slashes). Leave it out for https://api.payitgo.co |
final payitgo = Payitgo(
Platform.environment['PAYITGO_KEY']!,
timeout: const Duration(seconds: 15),
maxRetries: 2,
webhookSecret: Platform.environment['PAYITGO_WEBHOOK_SECRET'], // the signing secret of the key's mode
webhookUrl: 'https://api.yourdomain.com/payitgo/ipn', // optional default for payments.create
);
The client keeps no per-request state: create one and share it, and call
close() when you are done with it.
| Property | Type | Description |
|---|---|---|
payments |
Payments |
Payments |
tokens |
Tokens |
Tokens |
webhooks |
Webhooks |
Webhooks |
events |
Events |
Events: replay what your system missed |
payouts |
Payouts |
Payout requests |
payoutBatches |
PayoutBatches |
Payout batches |
payoutWallets |
PayoutWallets |
Payout wallets |
checkout |
PayitgoCheckout |
The key-less calls, with this client's baseUrl, http.Client, maxRetries and timeout |
PayitgoCheckout
PayitgoCheckout({String? baseUrl, http.Client? httpClient})
The key-less client for Flutter apps. It sends no key and only the headers a browser can send without a CORS preflight on reads, so it also works on Flutter web. It retries twice and waits up to 30 seconds per attempt.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
baseUrl |
String? |
no | https://api.payitgo.co |
payitgo's API, default https://api.payitgo.co: leave it out |
httpClient |
http.Client? |
no | One http.Client() the library makes, closed by close() |
The package:http client to use. You close one you pass in |
An empty baseUrl throws the same ArgumentError as Payitgo.
Methods: retrieve,
selectToken, simulate,
watch and close.
close
void close() // on Payitgo and on PayitgoCheckout
Closes the http.Client the library made for itself, when you created the
client without httpClient: a Payitgo makes one and shares it with its
checkout, a PayitgoCheckout makes its own. A client you passed in stays
open; it is yours to close. Closing a Payitgo's checkout does nothing, since
its client belongs to the Payitgo. Calls made after close() fail with a
PayitgoException of status 0.
final checkout = PayitgoCheckout();
try {
print((await checkout.retrieve(checkoutToken)).status);
} finally {
checkout.close();
}
A server that keeps one Payitgo until it stops can skip it; an app should
close its PayitgoCheckout when no screen needs it any more.
isLive
GET /v1/webhook · API reference
Future<bool> isLive() // on Payitgo
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.
Throws a PayitgoException, 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()) print('test mode: payments are simulated');
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. A PayitgoCheckout needs no mode: the
payment's livemode says which it is. See Test mode.
HTTP headers
The server client sends Authorization: Bearer <key>,
Accept: application/json, X-Payitgo-Client: payitgo-dart/0.7.1 and, with a
body, Content-Type: application/json. PayitgoCheckout sends only Accept
and, with a body, Content-Type.
Errors
PayitgoException
Every call that reaches the API throws a PayitgoException when the request
fails.
class PayitgoException implements Exception {
final String message;
final int status;
}
| Field | Type | Description |
|---|---|---|
status |
int |
The HTTP status, or 0 when no answer came (network error or timeout, 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. request failed: <cause> for a network error |
toString() is PayitgoException(<status>): <message>, or
PayitgoException: <message> when status is 0. Branch on status; log
message (its wording may change, see Errors and limits).
status |
Meaning | Retried by the library |
|---|---|---|
0 |
No answer: DNS, connection, TLS or timeout | 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 read-only key making a change, a key used from an IP address it does not allow, a storefront key changing the account's webhook or reading its events, or a key without payouts making a payout | No |
404 |
No such payment (or payout batch, or payout) in the key's mode, or no payment with this checkout token | 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 |
try {
await payitgo.payments.create(orderId: 'ORD-1', amount: '1', token: 'BTC');
} on PayitgoException catch (e) {
if (e.status != 400) rethrow;
print('payitgo refused: ${e.message}'); // e.g. an amount under the coin's minimum
}
SignatureVerificationException
constructEvent throws a
SignatureVerificationException (with a message) 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 |
timestamp outside the tolerance |
t is not a number, or is further than the tolerance (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 FormatException;
payitgo never sends one.
Retries
A request is retried, up to maxRetries times (default 2, so at most 3
attempts), after a network error or timeout, a 429 or a 5xx. It waits
0.5 s before the first retry and 1 s before the second. Other statuses are
never retried. When the last attempt fails, the call throws a
PayitgoException with that attempt's status (0, 429 or 5xx).
Every call is retried the same way, and each is safe to repeat:
| Call | Repeating it |
|---|---|
payments.create |
Returns the order's open payment instead of a second one (safe retries) |
payments.selectToken, checkout.selectToken |
The same coin again returns the payment unchanged |
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 |
Returns the payment its reference names (200) instead of a second one |
payouts.send |
If the first attempt went through, the repeat sends only requests that came in since, or throws 400 (no valid payout request to send). A sent request's batchId names its batch (payouts.retrieve) |
payouts.cancel |
Returns the payment as it is, canceled already. No second event |
payouts.quote, payoutWallets.simulateTopUp |
Price again; a repeated test top-up adds the amount twice, on paper |
| Reads | Change nothing |
Payments
payments.create
POST /v1/payments · API reference
Future<Payment> create({
required String orderId,
required Object amount,
String? currency,
String? token,
List<String>? tokens,
String? description,
Map<String, String>? metadata,
String? customerEmail,
String? successUrl,
String? cancelUrl,
String? webhookUrl,
String? simulate,
})
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 tokenOptions 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 | API field | Type | Required | Description |
|---|---|---|---|---|
orderId |
order_id |
String |
yes | Your id for the order, 1 to 128 bytes. One open payment per order and mode |
amount |
amount |
String or num |
yes | The price, in currency, such as '49.90'. Sent as amount.toString(): prefer a String to a double |
currency |
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 |
token |
String? |
no | The coin, such as 'USDT_TRC20' (from tokens.list). Leave it out to let the customer choose |
tokens |
tokens |
List<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 |
description |
String? |
no | What the customer pays for, up to 500 bytes |
metadata |
metadata |
Map<String, String>? |
no | Your own data: up to 20 keys of up to 40 bytes, values of up to 500 |
customerEmail |
customer_email |
String? |
no | The customer's email address |
successUrl |
success_url |
String? |
no | http(s) URL the hosted checkout links to once the payment is confirmed |
cancelUrl |
cancel_url |
String? |
no | http(s) URL the hosted checkout links back to if the payment closes unpaid |
webhookUrl |
webhook_url |
String? |
no | https:// URL that gets this payment's notifications instead of your account's webhook URL (per-payment URL). null: the client's webhookUrl. '': no URL of its own, even with a client default (its notifications go to your webhook's URL) |
simulate |
simulate |
String? |
no | Test keys only: the outcome to simulate, one of Payments.simulationOutcomes. With token it starts at once; without, once the coin is chosen (expired at once; wrong_asset needs token) |
Parameters left null are not sent.
Returns the Payment: the new one (201) or the order's open
one (200); both look the same. Fields: the payment
object.
Errors PayitgoException 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:
final payment = await payitgo.payments.create(
orderId: 'ORD-1001',
amount: '49.90',
token: 'USDT_TRC20',
description: '2 x Acme T-shirt',
metadata: {'customer_id': 'cus_42'},
customerEmail: '[email protected]',
successUrl: 'https://yourdomain.com/thanks',
cancelUrl: 'https://yourdomain.com/cart',
);
// payment.depositAddress, payment.cryptoAmount, payment.qrPayload, payment.expiresAt
// The customer chooses the coin (on the hosted page, in your app, or on your page):
final open = await payitgo.payments.create(orderId: 'ORD-1002', amount: '25');
for (final option in open.tokenOptions) {
print('${option.token} ${option.minimum} ${option.amountDue ?? ''}');
}
// Hand open.checkoutToken to your Flutter app, or show open.tokenOptions on your page.
// This payment's notifications go to its own URL:
await payitgo.payments.create(
orderId: 'ORD-1003',
amount: '30',
token: 'USDT_TRC20',
webhookUrl: 'https://api.yourdomain.com/orders/ORD-1003/ipn',
);
// Priced in euros: every figure on the payment is in EUR, in every response and webhook.
final priced = await payitgo.payments
.create(orderId: 'ORD-1004', amount: '45.50', currency: 'EUR', token: 'USDT_TRC20');
// priced.currency 'EUR', priced.amount '45.5', priced.cryptoAmount '49.23'
payments.retrieve
GET /v1/payments/{id} · API reference
Future<Payment> retrieve(String id)
| 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 PayitgoException 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.
final byId = await payitgo.payments.retrieve('8f3a2c1e9b7d4a6f05e1c2d3');
final byOrder = await payitgo.payments.retrieve('ORD-1001'); // the order's open payment
if (byId.isConfirmed) print('paid at ${byId.confirmedAt}, order ${byOrder.orderId}');
payments.list
GET /v1/payments · API reference
Future<PaymentList> list({String? status, String? chain, String? token, String? storeId, int? limit, int? offset})
Payments of the key's mode, newest first.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
status |
String? |
no | all | Only payments in this status, such as 'confirmed' |
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' |
storeId |
String? |
no | all | Only payments of this store (sent as store_id; ignored for a storefront key, which sees its own) |
limit |
int? |
no | 50 |
Page size, 1 to 200 (0 or less: 50; over 200: 200) |
offset |
int? |
no | 0 |
How many to skip |
Parameters left null are not sent.
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:
final confirmed = <Payment>[];
for (var offset = 0;;) {
final page = await payitgo.payments.list(status: 'confirmed', limit: 100, offset: offset);
confirmed.addAll(page.payments);
offset += page.limit;
if (offset >= page.total) break;
}
payments.selectToken
POST /v1/payments/{id}/token · API reference
Future<Payment> selectToken(String id, String token)
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). The coin it has already returns the payment unchanged.
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
String |
yes | The payment's id or your order_id |
token |
String |
yes | One of the payment's tokenOptions[].token, such as 'USDT_TRC20' |
Returns the whole Payment, now with depositAddress,
cryptoAmount, rateLocked, qrPayload and an expiresAt 15 minutes away.
Errors PayitgoException:
status |
message |
Cause |
|---|---|---|
400 |
token is required |
Empty token |
400 |
token is not one of this payment's options |
A coin not in tokenOptions |
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 is closed (confirmed, underpaid, expired or failed), or its deadline (expiresAt) has passed |
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, the coin was changed three times already, or a simulation is running |
final payment = await payitgo.payments.create(orderId: 'ORD-1002', amount: '25');
// …your page lists payment.tokenOptions, the customer picks one…
final chosen = await payitgo.payments.selectToken(payment.id, 'USDT_BEP20');
print('${chosen.cryptoAmount} ${chosen.token} to ${chosen.depositAddress} before ${chosen.expiresAt}');
payments.simulate
POST /v1/payments/{id}/simulate · API reference
Future<Payment> simulate(String id, String outcome)
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 |
String |
yes | One of Payments.simulationOutcomes, such as 'confirmed' (what each does) |
Returns the whole Payment, with its simulation started.
Simulated deposits have simulated true; their txId names no transaction on any chain.
Errors PayitgoException:
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' |
final payment = await payitgo.payments.simulate('ORD-1002', 'partially_paid');
print('${payment.simulation?.outcome} ${payment.simulation?.state}'); // partially_paid running
// once it is done, pay the rest:
await payitgo.payments.simulate('ORD-1002', 'confirmed');
Tokens
tokens.list
GET /v1/tokens · API reference
Future<List<TokenInfo>> list({Object? amount, String? currency})
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 tokenOptions), each with
amountDue when you pass the fees on.
| Parameter | Type | Required | Description |
|---|---|---|---|
amount |
String or num |
no | The order's amount, in currency, such as '49.90'. Sent as amount.toString(), as in payments.create: prefer a String to a double |
currency |
String? |
no | The ISO 4217 code the amount and every figure are in, such as 'EUR' (any case). Default USD |
Returns a List<TokenInfo> (the library unwraps the
API's {"currency": "USD", "tokens": […]}).
Errors PayitgoException 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.
for (final t in await payitgo.tokens.list(amount: '49.90')) {
print('${t.token} on ${t.chain}: pay \$${t.amountDue ?? '49.90'}, ${t.feeNote}');
}
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.events lists the event types.
webhooks.get
GET /v1/webhook · API reference
Future<WebhookSettings> get()
Returns the WebhookSettings: url (null when none
is set) and secret, the signing secret to give the client as
webhookSecret. It always succeeds for a valid key.
final webhook = await payitgo.webhooks.get();
print('${webhook.url} ${webhook.secret}');
webhooks.set
PUT /v1/webhook · API reference
Future<WebhookSettings> set(String url)
| Parameter | Type | Required | Description |
|---|---|---|---|
url |
String |
yes | An absolute https:// URL on a public host that accepts POST |
Returns the WebhookSettings with its new url. The
secret does not change. Setting the URL it already has changes nothing.
Errors PayitgoException 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
Future<WebhookSettings> remove()
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 WebhookSettings 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
Future<WebhookDelivery> test()
Queues a signed ping notification to the mode's URL; it arrives within about
5 seconds.
Returns the WebhookDelivery, with status
'pending'.
Errors PayitgoException 400 (no webhook url is set for this mode: set one first), 500 (could not queue the test), and the
common statuses.
final delivery = await payitgo.webhooks.test();
print('${delivery.id} ${delivery.eventType} ${delivery.url}'); // 6710c3a1f2b4e5d6a7b8c9d0 ping https://…
webhooks.constructEvent
No request · how verification works
WebhookEvent constructEvent(
Object payload,
String? signatureHeader, {
String? secret,
Duration tolerance = Webhook.defaultTolerance, // 5 minutes
})
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 List<int> |
yes | The raw request body, exactly as received (await request.readAsString(), or the bytes). A body decoded and encoded again will not verify (keep the raw body) |
signatureHeader |
String? |
yes | The X-Webhook-Signature header: request.headers['x-webhook-signature'] |
secret |
String? |
no | The signing secret, as payitgo gave it. Default: the client's webhookSecret. A non-empty secret passed here wins |
tolerance |
Duration |
no | How far t may be from your clock. Default 5 minutes. Duration.zero turns the timestamp check off (only for tests with captured bodies) |
Returns the WebhookEvent.
Errors SignatureVerificationException.
Answer 400.
final event = payitgo.webhooks.constructEvent(rawBody, request.headers['x-webhook-signature']);
if (event.type == 'payment.confirmed') print(Payment(event.data).orderId);
Webhook.constructEvent
static WebhookEvent constructEvent(
Object payload,
String? signatureHeader,
String secret, {
Duration tolerance = defaultTolerance, // 5 minutes
})
The same check without a client, for code that has the secret but no API key.
secret is required. Webhook.defaultTolerance is
Duration(minutes: 5).
final event = Webhook.constructEvent(rawBody, signatureHeader, Platform.environment['PAYITGO_WEBHOOK_SECRET']!);
Errors SignatureVerificationException,
except the "no webhook secret" one.
Events
payitgo.events: every event of the key's mode is kept, delivered or not
(even with no webhook URL set), each exactly as its notification carried
it. Read from the last event you handled to replay what your system missed
(Replay missed events).
events.list
GET /v1/events · API reference
Future<EventPage> list({
List<String>? types,
String? after,
DateTime? createdAfter,
int? limit,
})
The events, oldest first. Any account key reads them, read-only ones too.
| Parameter | API field | Type | Required | Description |
|---|---|---|---|---|
types |
type |
List<String>? |
no | Exact types ('payout_item.sent') or families ('payout_item.*'), sent comma-separated. null: every type |
after |
after |
String? |
no | An event's id: the events after it. Keep the last one you handled |
createdAfter |
created_after |
DateTime? |
no | The events created after it, sent in UTC as RFC 3339. Ignored with after |
limit |
limit |
int? |
no | Page size, 1 to 200. Default 100 |
Parameters left null (or empty) are not sent.
Returns an EventPage: events, each a
WebhookEvent with the same id its notification had, and
hasMore. While hasMore, call again with after the last event's id.
Events of the last few seconds are left for the next read, so reading on
never skips one; a test ping is never listed. A key that cannot make
payouts gets claim links without their url and pin.
Errors PayitgoException 400 (type must be event types, such as payout_item.sent or payout_item.*, created_after must be an RFC 3339 time, such as 2026-10-20T09:00:00Z, limit must be 1 to 200, after is not an event of this mode), 403 (a storefront's key cannot read the account's events: use an account key), and the common statuses.
var after = await lastHandledEventId(); // your code: null the first time
while (true) {
final page = await payitgo.events.list(types: ['payout_item.*'], after: after);
for (final event in page.events) {
await handle(event); // the same code as your webhook handler: skips ids it handled
after = event.id;
}
if (!page.hasMore) break;
}
Payouts
Pay your own clients (withdrawals from your platform, payroll, prizes) from
your payout wallet: one address per network that you top up, paying in
the payout coins (USDT_TRC20, USDT_BEP20, TRX, BNB, …: the
list). payitgo checks and prices every payment (the coin,
the amount, the address down to its checksum, the sanctions list, your
limits) before anything leaves the wallet, and sends each one as soon as the
wallet holds enough (Mass payouts).
| One by one | payouts.request as each client asks: payitgo keeps the request in your open list with its costs; payouts.send sends the list as a batch (or auto-send does, by itself) |
| A whole list | Made in the dashboard under Pay people, typed, pasted or uploaded as a CSV file. payoutBatches.retrieve reads it |
| No address yet | A claim link: its recipient chooses the coin and the address |
| Another coin | A converted payment: paid from your wallet's coin, converted on its way |
| The money | Your payout wallets; a test key tops up its test wallet on paper (simulateTopUp) |
| Staying in sync | Payout webhooks, one final event per payment; events.list replays them and payouts.list lists every payment by last change |
| What it costs | 0.5% of each payment, never less than $0.50, plus its network fee (Fees); feePaidBy: 'recipient' takes them out of each amount |
| Keys | Reading works with any key. Everything else needs a key with payouts turned on in the dashboard, and limited to your servers' IP addresses when your payout rules ask for it (The API): otherwise 403 |
The key decides the mode: a test key works with the test wallet, on paper,
and never reads or changes a live batch or payment (404). Payout amounts
are decimal strings, as everywhere; amounts you pass are a String or a
num, sent as toString().
final request = await payitgo.payouts.request(
reference: 'wd-7731', // your withdrawal's id: safe to retry
asset: 'USDT_TRC20',
address: 'TR7mNkucnhLZoJQLLJ6DR88jpLQufWxUJi',
amount: '120',
);
print('${request.status}: fee ${request.fee}, the wallet gives ${request.debit}');
final batch = await payitgo.payouts.send(); // every valid request, as one batch
Claim links
When you do not know where the recipient wants the money, make the payment
a claim link: a link its recipient opens to choose the coin and the address
(Claim links). Ask for one with claim: true
or claimAssets (the other coins the recipient may choose, paid at the same
dollar value), and leave address out. With an email, payitgo emails the
link there (a code sent there confirms the claim); without one, you share
the link yourself. An email alone makes no claim link: a payment without an
address is refused like any other (invalid_address). It works in
payouts.request, in quotes and in batches.
final prize = await payitgo.payouts.request(
reference: 'prize-cup-final-1',
asset: 'USDT_TRC20',
amount: '250',
claim: true, // no email: share prize.claim!.url yourself
claimAssets: ['USDT_BEP20', 'BTC'],
);
| Read | What it says |
|---|---|
item.claim |
A PayoutClaim (null for a payment to an address you gave): url (the link), pin and pinLocked for a link without an email, email, assets, expiresAt, claimedAt, emailed, lastEmailAt, extended, and fundedAsset / fundedAmount when the recipient chose another coin |
item.status |
claimable once its batch is funded: its money is kept for it until claim.expiresAt. Claimed, it is queued and sent like any payment, to the address chosen; never claimed, expired, its money free again in the wallet |
batch.counts |
claimable and expired beside the other statuses |
| Webhooks | payout_item.claimed when the recipient chose, payout_item.claim_expired when nobody did; both carry the payment |
A claim link is priced at the costliest address it could be claimed to, and
that debit is set aside while it waits; once claimed, it is priced again
for the coin and address chosen. An email that is not one makes the payment
invalid (invalid_email); so does an address given with claim: true
(invalid_address: a claim link has none). Emailing the link again and
extending it are done in the dashboard. Without an email, give the recipient
claim.url and, another way (a call, a text message), claim.pin: the link
alone pays no one. After 5 wrong PINs the link is locked (pinLocked) until
a new PIN is made in the dashboard. In test mode nothing is emailed: open
claim.url yourself, and the emailed code is always 000000.
Converted payments
To pay a recipient in a coin your wallet does not hold, give
payouts.quote convert: 'convert' and the coin to pay
from, convertFrom. Every payment in another coin is then paid from
convertFrom, converted on its way (Conversion).
Both default to your payout settings (same_network: each payment from the
wallet's own coin).
final q = await payitgo.payouts.quote(
convert: 'convert',
convertFrom: 'USDT_TRC20',
items: [PayoutItemInput(asset: 'BTC', address: 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq', amount: '0.01')],
);
final it = q.items.single;
print('${it.convert!.toAmount} ${it.convert!.to} asked, about ${it.convert!.estimate} arrives; '
'the wallet gives ${it.debit} ${it.asset} (fee ${it.fee})');
| Read | What it says |
|---|---|
item.asset, amount, fee, debit |
In the wallet's coin (convertFrom): what it takes from the wallet; fee with converting included |
item.convert |
A PayoutConversion (null when not converted): to (the coin the recipient receives), ticker, network, toAmount (what you asked), estimate (about what arrives) and, once sent, amountOut (what arrived) |
item.address |
The recipient's address, on convert.to's network |
batch.convert, batch.convertFrom |
The batch's rule |
A coin that cannot be converted to right now makes the payment invalid
(conversion_unavailable). A batch with converted payments holds its
prices 15 minutes instead of an hour, and converted payments are sent one
at a time. Claim links are never converted; payout requests follow your
payout settings' rule.
Payout webhooks
Each step of a batch and of each payment raises a notification, signed
with the secret of its mode like every other (payout
events). A payment's events go to its own
webhookUrl (given in payouts.request or a
PayoutItemInput), else to its batch's webhookUrl,
else to your webhook's URL. Withdrawals and schedules always go to your
webhook's URL.
| Event | data |
|---|---|
payout_batch.quoted, .pending_approval, .approved, .rejected, .awaiting_funds, .processing, .completed, .canceled |
The batch: PayoutBatch(event.data). payout_batch.canceled also comes when payitgo cancels a batch itself (canceledBy 'system') |
payout_item.processing |
A payout request left your list for a batch of its own (sent by you, from the dashboard, or by auto-send): PayoutItem(event.data), status 'ready', batchId the new batch |
payout_item.returned |
A sent 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, .failed, .canceled, .claimed, .claim_expired |
The payment: PayoutItem(event.data). payout_item.canceled comes for every canceled payment, whatever canceled it: cancelReason, canceledBy and canceledAt say why, who and when |
payout_wallet.withdrawn, payout_wallet.withdrawal_failed |
The withdrawal: PayoutWithdrawal(event.data). A failed one's failReason says why; its money stays in the wallet |
payout_schedule.run, payout_schedule.funding_needed |
PayoutSchedule(event.data), PayoutScheduleFunding(event.data) |
Staying in sync. Every payment, a payout request or a batch row, ends
sent, failed, canceled or expired, with one event each
(payout_item.sent, payout_item.failed, payout_item.canceled,
payout_item.claim_expired), delivered at least once: handle each event
id once (it stays the same however often it is sent). Events can arrive
out of order: act on the payment's status and its latest updatedAt,
never on the order they arrive in. To replay what you missed, call
events.list with after the last event id you handled;
to check every payment, call payouts.list and keep its
nextCursor (Staying in sync).
Payout requests
payitgo.payouts: your clients' payouts, sent one by one as they ask
(Payout requests). Each request is checked
and priced at once and waits in your open list (a batch with open
true, one per mode) with its costs, until you send the list,
or auto-send in your payout settings
(auto_send_minutes) sends it by itself once the oldest request has waited
that long. Sending moves the valid requests into a batch of their own,
priced again with today's fees and submitted: approved when your payout
settings ask for it, then funded and sent like any batch.
payouts.request
POST /v1/payouts · API reference
Future<PayoutItem> request({
required String reference,
required String asset,
required Object amount,
String? address,
int? tag,
String? name,
String? email,
String? note,
bool? claim,
List<String>? claimAssets,
String? webhookUrl,
})
| Parameter | API field | Type | Required | Description |
|---|---|---|---|---|
reference |
reference |
String |
yes | Your id for the request (the withdrawal's, say), unique in its mode. The same reference again returns the payment it names, so the call is safe to retry (references) |
asset |
asset |
String |
yes | A payout coin, such as 'USDT_TRC20' or 'USDT_BEP20' (any case) |
amount |
amount |
String or num |
yes | How much of the coin, such as '120'. Sent as amount.toString(): prefer a String to a double |
address |
address |
String? |
yes, unless a claim link | The client's address on the coin's network. Leave it out for a claim link |
tag |
tag |
int? |
no | A destination tag, for an XRP address |
name, email, note |
name, email, note |
String? |
no | Who it is for, and why: kept with it, shown in the dashboard. Only a claim link uses the email: its link is sent there |
claim |
claim |
bool? |
no | true makes it a claim link: with an email the link is emailed, without one you share it |
claimAssets |
claim_assets |
List<String>? |
no | A claim link's other coins its recipient may choose; giving them makes it a claim link too |
webhookUrl |
webhook_url |
String? |
no | An https:// URL on a public host: this payment's events go there instead of your webhook's URL (where they go). It stays with the request when it is sent in a batch. The client's webhookUrl is not used here |
Parameters left null are not sent.
Returns the PayoutItem: the new request (201), or the
payment the reference already names (200), which may be in a batch by now;
both look the same. A request with a problem is kept too, with status
'invalid' and its errors saying why
(checking and pricing): it is never
sent. Otherwise it is 'ready', with its fee, sendAmount and debit.
To send a corrected request under the same reference, cancel
the invalid one first: that frees its reference.
Errors PayitgoException 400 (invalid request body, an unusable
webhook_url: 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.
A request's own problems never fail the call: they are its errors.
final it = await payitgo.payouts.request(
reference: 'wd-7731',
asset: 'USDT_TRC20',
address: 'TR7mNkucnhLZoJQLLJ6DR88jpLQufWxUJi',
amount: '120',
name: 'Ana Silva',
);
if (it.status == 'invalid') {
for (final e in it.errors) print('${e.code}: ${e.message} (${e.hint ?? ''})');
} else {
print('${it.sendAmount} ${it.ticker} reaches the client; the wallet gives ${it.debit}');
}
payouts.retrieve
GET /v1/payouts/{id} · API reference
Future<PayoutItem> retrieve(String id)
A payment by its id: a payout request (in the open list or sent), or any
batch's row. The id is escaped for the URL. Returns the
PayoutItem. Errors 404 (not found) for an unknown id
or one of the other mode, and the common statuses.
payouts.retrieveByReference
GET /v1/payouts?reference= · API reference
Future<PayoutItem> retrieveByReference(String reference)
A payment by your reference, sent as the reference query parameter: the
payment that carries it now, or else the latest payment that gave it back
(canceled, failed or expired, with it as releasedReference): what became
of a request sent with it. An empty reference throws an ArgumentError
(payitgo: reference is required) without a request. Returns the
PayoutItem.
Errors 404 (not found) when no payment carries it or gave it back,
and the common statuses.
final it = await payitgo.payouts.retrieveByReference('wd-7731');
print('${it.status} ${it.txId ?? it.cancelReason ?? ''}');
payouts.list
GET /v1/payouts · API reference
Future<PayoutPage> list({
List<String>? status,
DateTime? updatedSince,
String? cursor,
int? limit,
})
Every payment of the key's mode, whatever its batch (payout requests in your list, removed ones, every batch's rows), oldest change first: to bring your system back in sync after it was down, or to check it is. Any key reads them.
| Parameter | API field | Type | Required | Description |
|---|---|---|---|---|
status |
status |
List<String>? |
no | The statuses to keep, sent comma-separated: ['sent', 'failed', 'canceled', 'expired'] for the ended ones. null: all |
updatedSince |
updated_since |
DateTime? |
no | The payments changed at or after it, sent in UTC as RFC 3339 |
cursor |
cursor |
String? |
no | The nextCursor of the page before: the payments changed after the last one it listed |
limit |
limit |
int? |
no | Page size, 1 to 200. Default 50 |
Parameters left null (or empty) are not sent.
Returns a PayoutPage: items, hasMore and
nextCursor. Read with updatedSince the first time, then with cursor
while hasMore; once hasMore is false, keep the last nextCursor to read
what changes next time. Changes of the last few seconds are left for the
next read, so a cursor never skips one.
Errors PayitgoException 400 (updated_since must be an RFC 3339 time, such as 2026-10-20T09:00:00Z, limit must be 1 to 200, cursor is not one this API gave), and the common statuses.
var cursor = await savedCursor(); // your code: null the first time
while (true) {
final page = await payitgo.payouts.list(
status: ['sent', 'failed', 'canceled', 'expired'],
updatedSince: cursor == null ? DateTime.utc(2026, 10, 1) : null,
cursor: cursor,
);
for (final it in page.items) {
await settleWithdrawal(it.reference ?? it.releasedReference, it.status); // your code, safe to run twice
}
cursor = page.nextCursor ?? cursor;
if (!page.hasMore) break;
}
await saveCursor(cursor); // read on from here next time
payouts.inbox
GET /v1/payouts/inbox · API reference
Future<PayoutInbox> inbox({String? status, int? limit, int? offset})
Your open payout requests: the list itself, what sending its valid requests takes of each coin against what the wallet can spend, and one page of the requests.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
status |
String? |
no | all | One status or several, comma-separated: 'ready', 'invalid', 'ready,invalid' |
limit |
int? |
no | 50 |
Page size, 1 to 200 |
offset |
int? |
no | 0 |
How many to skip |
Returns the PayoutInbox: inbox (the open list, a
PayoutBatch whose totals and counts cover every
request in it), coverage (per coin: needed, spendable, and topUp,
what to send to address before sending), items, total, limit and
offset.
final view = await payitgo.payouts.inbox(status: 'ready');
for (final c in view.coverage) {
print('${c.asset}: needs ${c.needed}, can spend ${c.spendable}'
'${c.topUp == '0' ? '' : ': send ${c.topUp} to ${c.address} first'}');
}
print('${view.inbox.counts.ready} ready, ${view.inbox.counts.invalid} invalid');
payouts.send
POST /v1/payouts/send · API reference
Future<PayoutBatch> send({List<String>? ids})
Sends your open list: every valid (ready) request, or only those of ids.
They move into a new batch, priced again with today's fees, and submitted
(at most 10,000 at a time: the rest go next time). The rest stay in the
list.
| Parameter | API field | Type | Required | Description |
|---|---|---|---|---|
ids |
ids |
List<String>? |
no | The requests to send, each a ready request of the open list. null: every valid request. An empty list throws an ArgumentError and sends nothing |
Returns the new PayoutBatch, submitted:
pending_approval when your payout settings ask for approvals,
awaiting_funds while the wallet falls short (its waiting.shortfall says
what to send where), or processing. More than 100 requests come back
validating and are submitted once checked. 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 PayitgoException 400 (no valid payout request to send,
payout request … is not a valid request waiting in your list,
none of the requests is valid any more: they are back in your list, each saying why, or a batch over your limit per batch), 403 for a key without
payouts, and the common statuses.
final batch = await payitgo.payouts.send();
switch (batch.status) {
case 'awaiting_funds':
for (final s in batch.waiting?.shortfall ?? const <PayoutShortfall>[]) {
print('top up ${s.amount} ${s.asset} at ${s.address}'); // it starts by itself
}
case 'pending_approval':
print('waiting for ${batch.approvalsNeeded} approval(s) in the dashboard');
default:
print(batch.status); // processing: its payments are being sent
}
payouts.cancel
DELETE /v1/payouts/{id} · API reference
Future<PayoutItem> cancel(String id)
Takes a request out: one still in the open list is removed (cancelReason
'removed', its reference free again in releasedReference, no
batchId); its record stays, so retrieve keeps
answering it. One already sent but not on its way yet (in a batch not
funded yet, or queued, cooling, sending or claimable) is canceled
(cancelReason 'canceled'), its money staying in the wallet and its fee
coming back. Either sends one payout_item.canceled. A payment canceled
already comes back as it is, with no second event: safe to retry.
Returns the PayoutItem, with status 'canceled'.
Errors 404 (not found) for an unknown id or one of the other mode,
409 (the payment is sent, or another status it can no longer leave),
403 for a key without payouts, and the
common statuses.
payouts.quote
POST /v1/payout-quotes · API reference
Future<PayoutQuoteResult> quote({
required List<PayoutItemInput> items,
String? feePaidBy,
String? convert,
String? convertFrom,
})
What up to 100 payments would cost, checked and priced exactly as in a batch, without keeping anything: show a client their fee before they ask.
| Parameter | API field | Type | Required | Description |
|---|---|---|---|---|
items |
items |
List<PayoutItemInput> |
yes | 1 to 100 payments |
feePaidBy |
fee_paid_by |
String? |
no | 'merchant' (fees on top) or 'recipient' (fees out of each amount). Default: your payout settings' |
convert |
convert |
String? |
no | 'same_network' (each payment from the wallet's own coin) or 'convert' (every payment in another coin than convertFrom paid from it, converted on its way). Default: your payout settings' |
convertFrom |
convert_from |
String? |
no | With convert: 'convert', the wallet's coin to pay from, such as 'USDT_TRC20'. Default: your payout settings' |
Returns a PayoutQuoteResult: quote (the totals a
batch of them would have) and items, each PayoutItem with
its fees and issues and no id.
Errors 400 (quote between 1 and 100 payments, fee_paid_by must be merchant or recipient, convert must be same_network or convert, a
convert_from payouts are not paid from), 403 for a key without payouts,
and the
common statuses.
final q = await payitgo.payouts.quote(feePaidBy: 'recipient', items: [
PayoutItemInput(asset: 'USDT_BEP20', address: '0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed', amount: '120'),
]);
print('you will receive ${q.items.single.sendAmount} USDT (fee ${q.items.single.fee})');
Payout batches
payitgo.payoutBatches: a whole list of payments at once. A batch is
checked and priced (quoted, its prices holding for an hour), submitted,
approved when your payout settings ask for it, funded from the wallet, and
sent (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.
payoutBatches.retrieve
GET /v1/payout-batches/{id} · API reference
Future<PayoutBatch> retrieve(String id)
Returns the PayoutBatch. Errors 404 (not found)
for an unknown id or another mode's batch.
Payout wallets
payitgo.payoutWallets: your payout wallet, one address per network, made
the first time it is asked for (the payout wallet).
Send it only the payout coins of its network. Withdrawing from it is done
in the dashboard, by the owner: never with a key.
payoutWallets.list
GET /v1/payout-wallets · API reference
Future<List<PayoutWallet>> list()
Returns a List<PayoutWallet> (the library unwraps
the API's {"wallets": […]}): one per network (tron, bsc, …), each with its
address and, per coin, its balance, reserved, spendable and needed
(the top-up your batches waiting for funds need).
for (final w in await payitgo.payoutWallets.list()) {
for (final a in w.assets) {
print('${a.asset} at ${w.address}: ${a.spendable} spendable'
'${a.needed == '0' ? '' : ', send ${a.needed}'}');
}
}
payoutWallets.simulateTopUp
POST /v1/payout-wallets/{asset}/simulate-top-up · API reference
Future<List<PayoutWallet>> simulateTopUp(String asset, Object amount)
Test keys only: adds amount (a String or a num, over 0 and up to
10,000,000) of asset to the test wallet's paper balance, and funds any
test batch waiting for it. Test payments are then sent on paper within
seconds, each with a made-up txId, and their webhooks follow as live.
Returns the wallets, as list. Errors 400
(only a test wallet is topped up on paper: use a test key, payouts in SHIB_ERC20 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.
await payitgo.payoutWallets.simulateTopUp('USDT_TRC20', '1000');
Checkout
The key-less calls of the public checkout API,
keyed by the payment's checkoutToken. They return the payer's view
of a payment, without your private fields: merchantId, metadata,
customerEmail, webhookUrl, checkoutToken and checkoutUrl are empty.
The first read of a payment nobody has opened yet counts as the customer
opening its checkout page, from an app or a server alike. Use them from a PayitgoCheckout in your app, or as
payitgo.checkout on the server.
checkout.retrieve
GET /checkout/{checkout_token} · API reference
Future<Payment> retrieve(String checkoutToken)
| Parameter | Type | Required | Description |
|---|---|---|---|
checkoutToken |
String |
yes | The payment's checkoutToken, from your backend |
Returns the payer's view of the Payment.
Errors PayitgoException 404 (payment not found), and 0 or 5xx as
for every call.
checkout.selectToken
POST /checkout/{checkout_token}/token · API reference
Future<Payment> selectToken(String checkoutToken, String token)
| Parameter | Type | Required | Description |
|---|---|---|---|
checkoutToken |
String |
yes | The payment's checkoutToken |
token |
String |
yes | One of the payment's tokenOptions[].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.
final checkout = PayitgoCheckout();
var payment = await checkout.retrieve(checkoutToken);
if (payment.token.isEmpty) {
payment = await checkout.selectToken(checkoutToken, payment.tokenOptions.first.token);
}
print('${payment.cryptoAmount} ${payment.token} to ${payment.depositAddress}');
checkout.simulate
POST /checkout/{checkout_token}/simulate · API reference
Future<Payment> simulate(String checkoutToken, String outcome)
payments.simulate without a key, for a test payment's
screen: put a button per outcome under its "Test payment" banner
(payment.livemode false), and follow the result with the
socket (payment.simulation events say when
it starts and ends), or with checkout.watch. Never show
them for a live payment, which answers 400.
| Parameter | Type | Required | Description |
|---|---|---|---|
checkoutToken |
String |
yes | The payment's checkoutToken |
outcome |
String |
yes | One of Payments.simulationOutcomes |
Returns the payer's view of the Payment, with its
simulation started.
Errors the same as payments.simulate, and 429
(rate limit exceeded) when requests come too fast from one visitor.
if (!payment.livemode && payment.simulation?.state != 'running') {
await checkout.simulate(checkoutToken, 'confirmed');
}
checkout.watch
GET /checkout/{checkout_token}, repeated
Stream<Payment> watch(String checkoutToken, {Duration every = const Duration(seconds: 5)})
watch polls: it reads the payment every every (5 seconds by
default). Where the app can use socket.io, follow the payment with the
socket instead: the default namespace (/),
subscribe with the checkout token and an acknowledgement, then a
payment:update with the whole payment on every change, as it happens.
watch is the fallback for apps that cannot use socket.io. With the
socket_io_client package:
import 'package:socket_io_client/socket_io_client.dart' as sio;
final socket = sio.io('https://api.payitgo.co', sio.OptionBuilder().setTransports(['websocket']).build());
socket.onConnect((_) => socket.emitWithAck('subscribe', checkoutToken, ack: (r) {
if (r['ok'] == true) show(Payment(Map<String, dynamic>.from(r['payment'])));
})); // again on every reconnect
socket.on('payment:update', (e) => show(Payment(Map<String, dynamic>.from(e['payment']))));
// socket.dispose() when the screen closes
watch emits the payment at once, then each time its status changes. It
keeps following a payment that is expired or underpaid, because money
arriving in the next 24 hours can still complete it
(late payments): the stream then emits
detecting and confirmed. The stream ends once the payment can change no
more:
| The payment | The stream |
|---|---|
confirmed or failed |
Ends after emitting it |
expired without a coin (token is '': it never had an address) |
Ends after emitting it |
expired or underpaid |
Keeps polling until 24 hours after expiresAt, then ends |
| Anything else | Keeps polling |
Cancel the subscription (or leave the await for loop) to stop sooner, for
example when the screen closes. A request that still fails after its retries
ends the stream with that PayitgoException.
| Parameter | Type | Required | Description |
|---|---|---|---|
checkoutToken |
String |
yes | The payment's checkoutToken |
every |
Duration |
no | How often to poll. Default 5 seconds |
Changes within a status (more of the amount arriving while
partially_paid) are not emitted: call retrieve for those. The
socket sends every change, confirmation
counts included.
await for (final p in checkout.watch(checkoutToken)) {
switch (p.status) {
case 'partially_paid':
print('received ${p.cryptoReceived} of ${p.cryptoAmount}');
case 'detecting':
print('payment received, confirming…');
case 'confirmed':
print('paid');
case 'expired' || 'underpaid':
print('closed unpaid (${p.status}): still listening for a late payment');
case 'failed':
print('failed');
}
}
Types
All models are exported from package:payitgo/payitgo.dart. Amounts are decimal
strings ('49.9'): parse them with a decimal package, not double. Times are
DateTime in UTC. Models that wrap a JSON object keep it in raw, for any
field without a getter.
Payment
The payment object. Payment(Map<String, dynamic> raw).
| Getter | Type | API field | When absent |
|---|---|---|---|
id |
String |
id |
|
orderId |
String |
order_id |
|
merchantId |
String? |
merchant_id |
null (the checkout view) |
storeId |
String? |
store_id |
null |
status |
String |
status |
|
livemode |
bool |
livemode |
false |
simulation |
Simulation? |
simulation |
null (no simulated outcome) |
token |
String |
token |
('' until the coin is chosen) |
tokenOptions |
List<TokenInfo> |
token_options |
[] (while the coin can be chosen or changed) |
previousCoins |
List<PreviousCoin> |
previous_coins |
[]: coins chosen before token (token, chain, depositAddress, destinationTag, cryptoAmount, rateLocked) |
chain |
String |
chain |
('' until the coin is chosen) |
depositAddress |
String |
deposit_address |
('' until the coin is chosen) |
destinationTag |
int? |
destination_tag |
null (XRP only) |
cryptoAmount |
String |
crypto_amount: what the customer sends, in the coin |
|
cryptoReceived |
String |
crypto_received: what arrived, in the coin |
|
confirmations |
int |
confirmations: the latest deposit's, out of confirmationsRequired. Show "12 of 20" while status is detecting |
0 |
confirmationsRequired |
int |
confirmations_required: what makes a deposit final on the payment's network |
0 |
detectedAt |
DateTime? |
detected_at: when the first deposit was seen |
null |
currency |
String |
currency: what the payment is priced in, an ISO 4217 code ('USD' unless you gave one) or a payment link's coin. Every figure below is in it |
|
amount |
String |
amount: the price |
|
amountDue |
String |
amount_due: what the customer pays, the price plus the fees when you pass them on |
amount |
amountReceived |
String |
amount_received: what arrived so far |
'0' |
amountExtra |
String? |
amount_extra: what of amountDue only reaches the exchange's minimum; you receive it |
null |
feesPaidByCustomer |
bool |
fees_paid_by_customer |
false |
settlement |
String |
settlement |
'custodial' |
rateLocked |
String |
rate_locked: the coin's price in currency, locked when the coin was chosen |
'0' |
txId |
String? |
tx_id |
null |
overpaid |
bool |
overpaid |
false |
paidLate |
bool |
paid_late |
false |
deposits |
List<Deposit> |
deposits |
[] |
expiresAt |
DateTime |
expires_at |
|
createdAt |
DateTime |
created_at |
|
confirmedAt |
DateTime? |
confirmed_at |
null |
networkFeeNote |
String |
network_fee_note |
'' |
qrPayload |
String |
qr_payload |
'' |
checkoutToken |
String? |
checkout_token |
null (webhooks, the checkout view) |
checkoutUrl |
String? |
checkout_url |
null (webhooks, the checkout view) |
description |
String? |
description |
null |
metadata |
Map<String, String> |
metadata |
{} |
customerEmail |
String? |
customer_email |
null |
successUrl |
String? |
success_url |
null |
cancelUrl |
String? |
cancel_url |
null |
webhookUrl |
String? |
webhook_url |
null |
isConfirmed |
bool |
status == 'confirmed': final, fulfil the order |
|
isClosed |
bool |
status is confirmed, underpaid, expired or failed |
|
raw |
Map<String, dynamic> |
The payment as the API sent it |
Deposit
The deposit object. Deposit(Map<String, dynamic> raw).
| Getter | Type | API field |
|---|---|---|
txId |
String |
tx_id |
token |
String |
token (the asset that arrived) |
chain |
String |
chain |
amount |
String |
amount |
value |
String |
value: its worth in the payment's currency |
counted |
bool |
counted (false when absent) |
late |
bool |
late (false when absent) |
status |
String |
status: pending, confirmed or failed |
seenAt |
DateTime |
seen_at |
confirmedAt |
DateTime? |
confirmed_at |
from |
String? |
from: the sender, when the network reports it (where a refund would go) |
to |
String? |
to: the address it was sent to, the payment's or a previous coin's |
block |
int? |
block: the block (on XRP, the ledger) that holds it |
madeAt |
DateTime? |
made_at: that block's time |
failedAt |
DateTime? |
failed_at |
failReason |
String? |
fail_reason: transaction not found on chain or confirmation timeout |
simulated |
bool |
simulated (false when absent): played by a test payment's simulation, its txId on no chain |
raw |
Map<String, dynamic> |
The deposit as the API sent it |
Simulation
A test payment's simulated outcome.
Simulation(Map<String, dynamic> raw).
| Getter | Type | API field |
|---|---|---|
outcome |
String |
outcome: one of Payments.simulationOutcomes |
state |
String |
state: requested (asked for on create, waiting for the coin), running or done |
raw |
Map<String, dynamic> |
The simulation as the API sent it |
PaymentList
What payments.list returns.
| Field | Type |
|---|---|
payments |
List<Payment> |
total |
int (matches across all pages) |
limit |
int (the page size applied) |
offset |
int (the offset applied) |
TokenInfo
| Field | Type | API field |
|---|---|---|
token |
String |
token |
chain |
String |
chain |
minimum |
String |
minimum: the smallest amount accepted right now, in the listing's currency like every figure here |
networkFee |
String |
network_fee ('0' when absent): the network fee right now |
networkFeeBps |
int? |
network_fee_bps: for a coin that is converted |
amountDue |
String? |
amount_due: with an amount, when you pass the fees on |
amountExtra |
String? |
amount_extra: what of amountDue only reaches the exchange's minimum; you receive it |
feeNote |
String |
fee_note ('' when absent) |
WebhookSettings
The webhook of the key's mode (the webhook object).
| Getter | Type | API field |
|---|---|---|
livemode |
bool |
livemode |
url |
String? |
url (null when none is set) |
secret |
String |
secret: signs the mode's notifications |
createdAt |
DateTime |
created_at |
updatedAt |
DateTime |
updated_at |
raw |
Map<String, dynamic> |
WebhookDelivery
One notification on its way to one URL (the delivery object).
| Getter | Type | API field |
|---|---|---|
id |
String |
id |
merchantId |
String |
merchant_id |
target |
String |
target: account or payment |
url |
String |
url |
eventId |
String |
event_id |
eventType |
String |
event_type |
payload |
String |
payload (the exact body posted) |
status |
String |
status: pending, sending, delivered, failed or resolved |
attempts |
int |
attempts |
maxAttempts |
int |
max_attempts |
nextAttemptAt |
DateTime |
next_attempt_at |
lastStatusCode |
int? |
last_status_code |
lastError |
String? |
last_error |
lastAttemptAt |
DateTime? |
last_attempt_at |
deliveredAt |
DateTime? |
delivered_at |
resolvedAt |
DateTime? |
resolved_at |
resolutionNote |
String? |
resolution_note |
createdAt |
DateTime |
created_at |
history |
List<WebhookDeliveryAttempt> |
history ([] when absent) |
raw |
Map<String, dynamic> |
WebhookDeliveryAttempt has at (DateTime), url, signed, error,
response, note (String?), statusCode, millis (int?) and raw.
WebhookEvent
A verified notification (the body), or one replayed
by events.list: the same body, with the same id.
| Getter | Type | API field |
|---|---|---|
id |
String |
id (the same on every retry: deduplicate on it) |
type |
String |
type: one of Webhooks.events |
livemode |
bool |
livemode |
createdAt |
DateTime |
created_at |
data |
Map<String, dynamic> |
data |
raw |
Map<String, dynamic> |
The whole event |
data is the payment for payment.* events (wrap it:
Payment(event.data)), the settlement
for settlement.*, the payout for
payout.*, the payout batch for payout_batch.*
(PayoutBatch(event.data)), the batch's payment for every
payout_item.* event, payout_item.processing and payout_item.returned
included (PayoutItem(event.data)), the withdrawal
for payout_wallet.withdrawn and payout_wallet.withdrawal_failed
(PayoutWithdrawal(event.data)), the schedule for
payout_schedule.run (PayoutSchedule(event.data)), the schedule and what
its next run lacks for payout_schedule.funding_needed
(PayoutScheduleFunding(event.data)), and {'message': 'pong'} for
ping.
Webhooks.events holds 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 and ping
(payout events).
EventPage
What events.list returns: events
(List<WebhookEvent>, oldest first) and hasMore
(bool): while it is true, read on with after the last event's id.
PayoutItemInput
One payment as you give it to payouts.quote.
const PayoutItemInput({
required String asset,
required Object amount, // a String or a num, sent as amount.toString()
String? address, // required unless it is a claim link
String? reference,
int? tag,
String? name,
String? email,
String? note,
bool? claim,
List<String>? claimAssets,
String? webhookUrl,
})
The fields are those of payouts.request, with
reference optional; fields left null are not sent, the others as given
(claimAssets as claim_assets, webhookUrl as webhook_url). A quote
ignores webhookUrl. Leave address out for a claim link.
In a quote that converts, a payment in another coin than its convertFrom
is converted. Give its asset, amount and
address in the coin the recipient receives.
toJson() gives the API's object.
PayoutItem
One payment to a recipient: a payout request, or a batch's row
(the payment object).
PayoutItem(Map<String, dynamic> raw). Amounts are decimal strings in the
payment's coin (for a converted payment, the
wallet's coin).
| Getter | Type | API field | When absent |
|---|---|---|---|
id |
String? |
id |
null (a quote's payments) |
merchantId |
String? |
merchant_id |
null (a quote's payments) |
livemode |
bool |
livemode |
false |
batchId |
String? |
batch_id |
null (a quote's payments, and a request removed from the list, whose record stays). A request's is the open list's id until it is sent |
reference |
String? |
reference |
null |
refusedReference |
String? |
refused_reference |
null: a reference another payment carries; this one keeps none, and is invalid |
releasedReference |
String? |
released_reference |
null: once canceled or failed (never sent), the reference it had, given back |
row |
int |
row |
0 |
recipient |
PayoutRecipient |
recipient |
name, email, note, each String? |
asset |
String |
asset |
|
ticker |
String? |
ticker |
null (a coin payouts do not know) |
iconUrl |
String? |
icon_url |
null |
chain |
String |
chain |
'' |
address |
String |
address |
'' (a claim link not claimed yet). A converted payment's is on convert.to's network |
tag |
int? |
tag |
null (XRP only) |
amount |
String |
amount |
What you asked to pay |
sendAmount |
String |
send_amount |
What reaches the recipient |
fee |
String |
fee |
The whole fee: a converted payment's converting included |
debit |
String |
debit |
What it takes from the wallet |
usdRate |
String |
usd_rate |
The coin's dollar price when it was priced |
amountUsd |
String |
amount_usd |
|
status |
String |
status |
validating, ready, invalid, cooling, queued, sending, sent, failed or canceled (the payments); a claim link's also claimable (funded, waiting for its recipient) or expired (never claimed, its money free again) |
errors |
List<PayoutIssue> |
errors |
[]: why it is invalid |
warnings |
List<PayoutIssue> |
warnings |
[]: worth knowing; it still goes |
coolingUntil |
DateTime? |
cooling_until |
null |
txId |
String? |
tx_id |
null until sent (made up in test mode) |
explorerUrl |
String? |
explorer_url |
null (test mode) |
failReason |
String? |
fail_reason |
null |
cancelReason |
String? |
cancel_reason |
null unless canceled: removed (taken out of your list of payout requests), canceled (the payment alone, by your team or a key), batch_canceled (its batch was canceled), rejected (its batch was rejected: cancelNote says why) or invalid (no longer payable when its batch was submitted or funded: errors say why) |
cancelNote |
String? |
cancel_note |
null: the rejection's reason |
canceledBy |
String? |
canceled_by |
null: a team member's id, an API key's id, or 'system' (payitgo itself) |
canceledAt |
DateTime? |
canceled_at |
null |
members |
Map<String, String> |
members |
{}: the email of the team member named in canceledBy, by id, as it was when they acted |
webhookUrl |
String? |
webhook_url |
null: where its events go instead of its batch's webhookUrl or your webhook's URL |
claim |
PayoutClaim? |
claim |
null (not a claim link) |
convert |
PayoutConversion? |
convert |
null (paid in the wallet's own coin) |
feeCredit |
String? |
fee_credit |
null: the fee given back for a payment never sent |
sentAt |
DateTime? |
sent_at |
null |
createdAt, updatedAt |
DateTime? |
created_at, updated_at |
null (a quote's payments) |
raw |
Map<String, dynamic> |
The payment as the API sent it |
Before it is checked (validating) and while invalid, its fees and dollar
figures are '0'.
PayoutClaim
A claim link's state, item.claim.
| Getter | Type | API field | When absent |
|---|---|---|---|
url |
String? |
url |
null in a quote, and for a key without payouts: the link to share |
pin |
String? |
pin |
null for a link with an email, in a quote, and for a key without payouts: the 6 digits its recipient enters, to give apart from the link |
pinLocked |
bool |
pin_locked |
false: 5 wrong PINs lock it until a new PIN is made in the dashboard |
email |
String? |
email |
null: you share the link yourself |
assets |
List<String> |
assets |
[]: the other coins its recipient may choose |
expiresAt |
DateTime? |
expires_at |
null until its batch is funded |
claimedAt |
DateTime? |
claimed_at |
null until claimed |
emailed |
int |
emailed |
0: how many times the link was emailed |
lastEmailAt |
DateTime? |
last_email_at |
null |
extended |
int |
extended |
0: how many times it was extended |
fundedAsset, fundedAmount |
String? |
funded_asset, funded_amount |
null: what funded it when its recipient chose another coin |
raw |
Map<String, dynamic> |
PayoutConversion
How a converted payment is converted, item.convert.
| Getter | Type | API field | When absent |
|---|---|---|---|
to |
String |
to |
The coin the recipient receives |
ticker, network |
String |
ticker, network |
'' |
toAmount |
String |
to_amount |
What you asked to pay, in to |
estimate |
String |
estimate |
About what arrives, in to |
amountOut |
String? |
amount_out |
null until sent: what arrived |
raw |
Map<String, dynamic> |
PayoutIssue
Something wrong with a payment (in errors) or worth knowing (in
warnings), with getters code (String: wrong_network,
below_minimum, new_recipient, invalid_email, conversion_unavailable,
… every code),
field (String?: asset, amount, address, tag, reference,
email or claim_assets),
message (String, for people), hint (String?, what to do) and raw.
Codes may be added: treat an unknown one by the list it is in, and show its
message.
PayoutBatch
A batch, or your open list of payout requests (open)
(the batch object).
PayoutBatch(Map<String, dynamic> raw).
| Getter | Type | API field | When absent |
|---|---|---|---|
id |
String |
id |
|
merchantId |
String |
merchant_id |
'' |
livemode |
bool |
livemode |
false |
reference |
String? |
reference |
null |
name |
String |
name |
'' |
source |
String |
source |
api, dashboard, csv, requests (payout requests sent together) or schedule (a schedule's run) |
inbox |
bool |
inbox |
false: made of payout requests |
open |
bool |
open |
false: your open list itself, never submitted |
createdBy |
String |
created_by |
A team member's id, or the API key's (byApiKey) |
byApiKey |
bool |
by_api_key |
false |
feePaidBy |
String |
fee_paid_by |
merchant or recipient |
convert |
String |
convert |
same_network or convert (converted payments); '' when absent |
convertFrom |
String? |
convert_from |
null: with convert, the wallet's coin it pays from |
webhookUrl |
String? |
webhook_url |
null |
status |
String |
status |
validating, quoted, pending_approval, awaiting_funds, processing, completed, canceled or rejected |
waiting |
PayoutWaiting? |
waiting |
null: while awaiting_funds, reason (funds, daily_limit, paused), note, since (DateTime) and shortfall, a List<PayoutShortfall> of asset, network, amount and address: what to send where |
totals |
List<PayoutAssetTotal> |
totals |
Per coin: asset, ticker, iconUrl, chain, network, items (int), amount, sendAmount, fee, debit, debitUsd, savedUsd |
counts |
PayoutCounts |
counts |
Its payments by status (ints): total, invalid, ready, cooling, queued, sending, sent, failed, canceled, claimable, expired |
totalUsd |
String |
total_usd |
What it takes from the wallet, in dollars |
quoteExpiresAt |
DateTime? |
quote_expires_at |
null |
approvalsNeeded |
int |
approvals_needed |
0 |
approvals |
List<PayoutApproval> |
approvals |
[]: userId, at |
rejection |
PayoutRejection? |
rejection |
null: by, at, reason once rejected |
submittedBy, canceledBy |
String? |
submitted_by, canceled_by |
null |
submittedAt, fundedAt, completedAt, canceledAt |
DateTime? |
submitted_at, funded_at, completed_at, canceled_at |
null |
createdAt, updatedAt |
DateTime |
created_at, updated_at |
|
raw |
Map<String, dynamic> |
The batch as the API sent it |
Each part (PayoutWaiting, PayoutShortfall, PayoutAssetTotal,
PayoutCounts, PayoutApproval, PayoutRejection) also has raw.
PayoutPage
What payouts.list returns: items (List<PayoutItem>,
oldest change first), hasMore (bool) and nextCursor (String?:
null when the page is empty, then keep the one you had). While hasMore,
read on with cursor: page.nextCursor.
PayoutInbox
What payouts.inbox returns.
| Field | Type | Description |
|---|---|---|
inbox |
PayoutBatch |
Your open list (open true): its totals and counts cover every request in it |
coverage |
List<PayoutCoverage> |
Per coin of its valid requests: asset, ticker, network, needed (their debits), spendable (what the wallet can spend), topUp (the difference, '0' when covered) and address (where to send it), plus raw |
items |
List<PayoutItem> |
One page of the requests |
total, limit, offset |
int |
PayoutQuoteResult
What payouts.quote returns: quote, a PayoutQuote
(livemode, feePaidBy, totals, totalUsd and counts, as on a
PayoutBatch, and raw), and items
(List<PayoutItem>), the payments as they would be. Nothing is kept.
PayoutWallet
Your payout wallet on one network (the wallet object).
| Getter | Type | API field |
|---|---|---|
chain |
String |
chain: the network, such as tron or bsc |
network |
String |
network: Tron, BNB Smart Chain |
address |
String |
address: where to send its coins |
explorerUrl |
String? |
explorer_url (live only) |
livemode |
bool |
livemode |
assets |
List<PayoutWalletAsset> |
assets: per coin, asset, ticker, iconUrl, balance, reserved, spendable and needed (decimal strings), and raw |
error |
String? |
error: why its balances could not be read just now (they are then '0') |
raw |
Map<String, dynamic> |
PayoutWithdrawal
A payout wallet's coin sent back to one of your payout addresses: the
data of a payout_wallet.withdrawn or payout_wallet.withdrawal_failed
event (withdrawals). Getters id, merchantId,
asset, chain, addressId, address, status (requested, sending,
sent or failed), requestedBy (String); amount (what left the
wallet), fee, sendAmount (what arrived) as decimal strings; livemode;
tag (int?); txId, explorerUrl (String?); failReason (String?:
why a failed withdrawal failed; its money stays in the wallet); createdAt,
updatedAt (DateTime), sentAt (DateTime?); and raw.
PayoutSchedule
A schedule, which makes the same batch again and again (a payroll): the
data of a payout_schedule.run event (Schedules).
Schedules are set up in the dashboard; each run's batch has source
'schedule'. Getters id, name, status (active or paused),
cadence (weekly, biweekly or monthly) (String); livemode;
nextRunAt, lastRunAt (DateTime?); lastBatchId (String?: the batch
its last run made) and lastError (String?: why its last run made none,
empty when it made one);
and raw for the rest of the summary the webhook carries (weekday, day,
at, timezone, totals, runs, …; never its payments).
PayoutScheduleFunding
The data of a payout_schedule.funding_needed event, sent a few days
before a run the wallet cannot cover: schedule (a
PayoutSchedule) and shortfall (a
List<PayoutShortfall>: asset, network, amount and address, what to
send where). PayoutScheduleFunding(event.data).
Examples
Your own payment page
A Dart server that shows the coins, creates the payment in the coin the
customer picks, and renders the amount, address, QR code and deadline from the
payment itself (what to show). With
shelf, and qr
for the QR code:
// dart pub add payitgo shelf qr
import 'dart:convert';
import 'dart:io';
import 'package:payitgo/payitgo.dart';
import 'package:qr/qr.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
final payitgo = Payitgo(Platform.environment['PAYITGO_KEY']!);
const networks = {
'tron': 'Tron (TRC-20)', 'ethereum': 'Ethereum (ERC-20)', 'bsc': 'BNB Smart Chain (BEP-20)',
'bitcoin': 'Bitcoin', 'litecoin': 'Litecoin', 'dogecoin': 'Dogecoin', 'xrp': 'XRP Ledger',
};
String h(Object? s) => htmlEscape.convert('$s');
Response html(String body, [int status = 200]) =>
Response(status, body: body, headers: {'content-type': 'text/html; charset=utf-8'});
// GET /pay?order=ORD-1001 lists the coins; POST creates the payment in the chosen one.
Future<Response> pay(Request request) async {
final order = await findOrder(request.url.queryParameters['order'] ?? ''); // your code: id, total ('49.90')
if (request.method != 'POST') {
final tokens = await payitgo.tokens.list(amount: order.total);
return html('<form method="post">${tokens.map((t) => '<button name="token" value="${h(t.token)}">'
'${h(t.token)} on ${h(networks[t.chain] ?? t.chain)}: \$${h(t.amountDue ?? order.total)}</button>').join()}</form>');
}
final form = Uri.splitQueryString(await request.readAsString());
try {
final payment = await payitgo.payments.create(
orderId: order.id, // the same order again returns its open payment
amount: order.total,
token: form['token'] ?? '',
);
return html(renderPayment(payment));
} on PayitgoException catch (e) {
print('payitgo ${e.status}: ${e.message}'); // log it; do not show it to the customer
return html('We could not start this payment. Please try again.', 502);
}
}
String renderPayment(Payment p) => '''
${p.livemode ? '' : '<p><b>Test payment:</b> do not send coins to this address.</p>'}
<p>Send exactly <b>${h(p.cryptoAmount)} ${h(p.token.split('_').first)}</b>
on <b>${h(networks[p.chain] ?? p.chain)}</b> to</p>
<p><code>${h(p.depositAddress)}</code></p>
${p.destinationTag == null ? '' : '<p>Destination tag (required): <b>${p.destinationTag}</b></p>'}
${qrSvg(p.qrPayload)}
<p>Pay before <time datetime="${p.expiresAt.toIso8601String()}">${h(p.expiresAt.toLocal())}</time></p>''';
String qrSvg(String data) {
final qr = QrImage(QrCode.fromData(data: data, errorCorrectLevel: QrErrorCorrectLevel.M));
final n = qr.moduleCount;
final svg = StringBuffer('<svg xmlns="http://www.w3.org/2000/svg" viewBox="-2 -2 ${n + 4} ${n + 4}" '
'width="220" height="220" shape-rendering="crispEdges"><rect x="-2" y="-2" width="${n + 4}" height="${n + 4}" fill="#fff"/>');
for (var y = 0; y < n; y++) {
for (var x = 0; x < n; x++) {
if (qr.isDark(y, x)) svg.write('<rect x="$x" y="$y" width="1" height="1"/>');
}
}
return (svg..write('</svg>')).toString();
}
Future<void> main() async {
await io.serve((Request r) async => r.url.path == 'pay' ? await pay(r) : Response.notFound(''),
InternetAddress.anyIPv4, 8080);
}
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:
final payment = await payitgo.payments.create(orderId: order.id, amount: order.total);
// render payment.tokenOptions (each with token, chain, minimum, amountDue, feeNote)…
// …and when the customer picks one:
final chosen = await payitgo.payments.selectToken(payment.id, pickedToken);
final page = 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.checkoutToken
(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 Flutter payment screen
In a Flutter app the page is a screen. Your backend creates the payment
without a token and returns its checkoutToken; the app shows the coins,
sends the customer's choice with selectToken, and follows the payment with
watch, which polls every 5 seconds. No key is involved. For updates the
moment they happen, use the socket instead of watch (the snippet under
checkout.watch: the same Payment, from each event's
payment). With qr_flutter
for the QR code:
// flutter pub add payitgo qr_flutter
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:payitgo/payitgo.dart';
import 'package:qr_flutter/qr_flutter.dart';
final checkout = PayitgoCheckout();
class PaymentScreen extends StatefulWidget {
const PaymentScreen({super.key, required this.checkoutToken}); // from your backend
final String checkoutToken;
@override
State<PaymentScreen> createState() => _PaymentScreenState();
}
class _PaymentScreenState extends State<PaymentScreen> {
Payment? payment;
String? error;
StreamSubscription<Payment>? _watching;
@override
void initState() {
super.initState();
_watching = checkout.watch(widget.checkoutToken).listen(
(p) => setState(() => payment = p),
onError: (Object e) => setState(() => error = e is PayitgoException ? e.message : '$e'),
);
}
@override
void dispose() {
_watching?.cancel(); // stop polling when the screen goes away
super.dispose();
}
Future<void> _choose(String token) async {
try {
final p = await checkout.selectToken(widget.checkoutToken, token);
if (mounted) setState(() => payment = p);
} on PayitgoException catch (e) {
if (mounted) setState(() => error = e.message);
}
}
@override
Widget build(BuildContext context) {
final p = payment;
if (error != null) return Center(child: Text('Something went wrong: $error'));
if (p == null) return const Center(child: CircularProgressIndicator());
if (p.token.isEmpty) {
return ListView(children: [
for (final t in p.tokenOptions)
ListTile(
title: Text('${t.token} on ${t.chain}'),
subtitle: Text(t.feeNote),
trailing: Text('\$${t.amountDue ?? p.amountDue}'),
onTap: () => _choose(t.token),
),
]);
}
return ListView(padding: const EdgeInsets.all(16), children: [
if (!p.livemode) const Text('Test payment: do not send coins to this address.'),
Text('Send exactly ${p.cryptoAmount} ${p.token.split('_').first} on ${p.chain}'),
SelectableText(p.depositAddress),
TextButton(
onPressed: () => Clipboard.setData(ClipboardData(text: p.depositAddress)),
child: const Text('Copy address'),
),
if (p.destinationTag != null) Text('Destination tag (required): ${p.destinationTag}'),
Center(child: QrImageView(data: p.qrPayload, size: 220)),
Text('Pay before ${TimeOfDay.fromDateTime(p.expiresAt.toLocal()).format(context)}'),
Text(switch (p.status) {
'partially_paid' => 'Received ${p.cryptoReceived}: send the rest to the same address.',
'detecting' => 'Payment received, confirming…',
'confirmed' => 'Paid. Thank you!',
'pending' => 'Waiting for your payment.',
'expired' || 'underpaid' => 'Time is up (${p.status}). Contact us if you have already paid.',
_ => 'This payment could not be completed.',
}),
]);
}
}
The app only shows progress; your backend still fulfils the order from the
payment.confirmed webhook.
A webhook (IPN) handler with shelf
Read the raw body, verify it, handle each event once, and answer 2xx within
10 seconds (answering and retries):
import 'dart:io';
import 'package:payitgo/payitgo.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
final payitgo = Payitgo(
Platform.environment['PAYITGO_KEY']!,
webhookSecret: Platform.environment['PAYITGO_WEBHOOK_SECRET'], // the signing secret of the key's mode
);
Future<Response> ipn(Request request) async {
if (request.method != 'POST') return Response(405);
final WebhookEvent event;
try {
event = payitgo.webhooks.constructEvent(
await request.readAsString(), // the raw body, before any JSON parsing
request.headers['x-webhook-signature'],
);
} on SignatureVerificationException {
return Response(400); // not from payitgo, changed, or too old
} on FormatException {
return Response(400);
}
if (await isProcessed(event.id)) return Response.ok(''); // a retry or redelivery
if (event.livemode == await payitgo.isLive()) { // ignore the other mode's events
switch (event.type) {
case 'payment.confirmed': // final: fulfil
final p = Payment(event.data);
await markOrderPaid(p.orderId, p.id); // idempotent
case 'payment.expired': // nothing arrived in time
await releaseOrder(Payment(event.data).orderId);
}
}
await markProcessed(event.id);
return Response.ok('');
}
Future<void> main() async {
await io.serve((Request r) async => r.url.path == 'payitgo/ipn' ? await ipn(r) : Response.notFound(''),
InternetAddress.anyIPv4, 8080);
}
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, shelf answers 500 and
payitgo retries the notification. More in
handle events safely.
Your clients' withdrawals
A platform whose users withdraw their balance: each withdrawal becomes a
payout request under its own id, and the webhook says when it is paid. With
shelf, and the payitgo client and
ipn handler of the example above:
// POST /withdraw: the user asks to withdraw part of their balance.
Future<Response> withdraw(Request request) async {
final w = await holdWithdrawal(request); // your code: id, wallet, amount ('120'), held from the balance
final it = await payitgo.payouts.request(
reference: w.id, // safe to retry: the same id returns the same payment
asset: 'USDT_TRC20',
address: w.wallet,
amount: w.amount,
);
if (it.status == 'invalid') {
await payitgo.payouts.cancel(it.id!); // frees the reference for a corrected request
await releaseWithdrawal(w.id); // give the balance back (safe to run twice: payout_item.canceled follows)
return Response(400, body: it.errors.first.message);
}
return Response.ok('${it.sendAmount} USDT will arrive shortly');
}
// In ipn(), beside the payment events:
switch (event.type) {
case 'payout_item.sent':
final it = PayoutItem(event.data);
await markWithdrawalPaid(it.reference!, it.txId!);
case 'payout_item.failed' || 'payout_item.canceled':
final it = PayoutItem(event.data); // never sent: its reference is given back
await releaseWithdrawal(it.releasedReference ?? it.reference!);
case 'payout_batch.awaiting_funds':
final b = PayoutBatch(event.data);
await alertTreasury(b.waiting?.note ?? ''); // what to send to the payout wallet
}
Send the list with payouts.send when you want (every
hour, say), or turn on auto-send in your payout settings and let payitgo
send it. In test mode, top up the test wallet first
(simulateTopUp); test payments are sent
on paper within seconds, and their webhooks arrive as live ones would.
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).
final payitgo = Payitgo(Platform.environment['PAYITGO_TEST_KEY']!); // your test key
print(await payitgo.isLive()); // false
// Point the TEST webhook at your development server and read its secret.
final hook = await payitgo.webhooks.set('https://dev.yourdomain.com/payitgo/ipn');
print(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.
final payment = await payitgo.payments.create(
orderId: 'TEST-1', amount: '10', token: 'USDT_TRC20', simulate: 'confirmed');
print('${payment.livemode} ${payment.simulation?.state}'); // false running
// Another outcome on a payment you already have:
await payitgo.payments.simulate('TEST-2', 'underpaid');
Never send real coins to a test address: nothing watches it (why).
Check your verification against the example in the recipe (tolerance zero, because the example is old):
const body = '{"created_at":"2026-10-10T09:12:44.512837Z","data":{"message":"pong"},"id":"5c0e1f9a2b7d4e3c8a6f1b2d","livemode":false,"type":"ping"}';
final event = Webhook.constructEvent(
body,
't=1791623565,v1=1af0ba31872e3152c422edaf9442c9f0eb4ebd202beebafbaaba14f77336194b',
'a3858862701d1ce11ab06cb5dd9bb941d4849283f81fc0c3f0db0d99a2b82d48',
tolerance: Duration.zero,
);
print(event.type); // ping
To test without the network, give the client a MockClient from
package:http/testing.dart, and sign bodies yourself with package:crypto:
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:payitgo/payitgo.dart';
String sign(String body, String secret, [DateTime? at]) {
final t = (at ?? DateTime.now()).millisecondsSinceEpoch ~/ 1000;
final v1 = Hmac(sha256, utf8.encode(secret)).convert(utf8.encode('$t.$body'));
return 't=$t,v1=$v1';
}
final fake = Payitgo(
'4f9c2a7e1b8d3f6a0c5e9b2d7a4f1c8e3b6d9a2f5c8e1b4d7a0f3c6e9b2d5a8f',
httpClient: MockClient((request) async => http.Response( // every request gets this answer
jsonEncode({'webhook': {'livemode': false, 'url': null,
'secret': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
'created_at': '2026-10-10T09:00:00Z', 'updated_at': '2026-10-10T09:00:00Z'}}),
200)),
); // await fake.isLive() is false, from this answer
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).