Pay-ins
A pay-in is one payment from your customer to you. You create it, the customer pays, we tell you.
Create one
POST /v1/payinsReference
- Scope:
payins:write Idempotency-Keyrequired — use your own id- SDK:
createPayin() - Success: HTTP 201
Request
| Field | Notes |
|---|---|
merchant_order_id | your order id: 1 to 64 characters of A–Z a–z 0–9 _ . : -; unique per project forever |
amount, currency | "10000.00", "INR" (USDT methods take "USDT") |
method | upi, bank_transfer, usdt_trc20, usdt_bep20, or auto (we pick) |
customer.ref | your customer's id, in the same form as an order id; name, phone and ip are optional |
return_url | optional https URL where the payment page sends the customer back. Its host must be on your project's allowlist in the portal |
expires_in | optional, seconds (60–86,400) |
metadata | optional, up to 20 keys with string values (at most 500 characters each); returned on the object and in events |
Response
201 with the pay-in, in status pending:
checkout_url— send the customer here. Only the create response carries it (a retrieved pay-in showsnull), so store it if you may need it again. Use it exactly as given; never build it yourself.instructions.type—redirect(usecheckout_url), or, when you show the payment details yourself,upi_qr,bank_detailsorcrypto_address. In test mode it issimulated: nobody pays, you move the pay-in with the simulation call.rail— which kind of rail serves it. It is our routing decision, for your information only.
Errors
| Code | When |
|---|---|
422 amount_too_small | the fees would leave you nothing of this amount |
409 duplicate_merchant_reference | a pay-in with this merchant_order_id exists; existing_id is its id |
409 invoice_already_open | this customer already has an open USDT invoice on that chain |
403 limit_exceeded | this customer has too many open pay-ins, reached the number allowed for the period, or asked again too soon; detail says which |
422 method_not_available | the method is not set up for your project |
503 rail_unavailable | nothing can take this payment right now; retry later or offer another method |
400 invalid_request | a field is wrong; errors names it |
Nothing is created when a request is refused. The idempotency errors are on the idempotency page, and every code is on the errors page.
Example
samples/ts/payins.ts// Pay-ins: create one per order exactly once, read it back, list, cancel.
// bun payins.ts DEP-48213
import { NicePay, NicePayError, type Payin } from "@nicepay/sdk-ts";
const nicepay = new NicePay({
keyId: process.env["NICEPAY_KEY_ID"] ?? "",
secret: process.env["NICEPAY_KEY_SECRET"] ?? "",
...(process.env["NICEPAY_API_BASE"] ? { baseUrl: process.env["NICEPAY_API_BASE"] } : {}),
});
/**
* The pay-in for one of your orders: created the first time, the same one every time
* after — whether you retry a second later (idempotency key) or a week later
* (merchant_order_id is unique per project forever).
*/
async function payinForOrder(orderId: string, amount: string): Promise<Payin> {
try {
return await nicepay.createPayin(
{ merchant_order_id: orderId, amount, currency: "INR", method: "upi", customer: { ref: "player-7591035" }, metadata: { cart: "c-1" } },
{ idempotencyKey: orderId },
);
} catch (error) {
if (error instanceof NicePayError && error.code === "duplicate_merchant_reference") {
return nicepay.getPayin(String(error.problem["existing_id"]));
}
throw error;
}
}
const orderId = process.argv[2] ?? `DEP-${String(Date.now())}`;
const first = await payinForOrder(orderId, "750.00");
const again = await payinForOrder(orderId, "750.00");
console.log(`order ${orderId} → ${first.id} (again: ${again.id}, same: ${String(first.id === again.id)})`);
// Read it back. checkout_url is only in the create response; store it if you need it.
const fetched = await nicepay.getPayin(first.id);
console.log(`status ${fetched.status}, amount ${fetched.amount} ${fetched.currency}, rail ${fetched.rail}`);
// Find it by your own id.
const found = await nicepay.listPayins({ merchant_order_id: orderId });
console.log(`found by merchant_order_id: ${String(found.data.length)}`);
// The customer gave up: cancel. (If money still arrives, the pay-in succeeds anyway — "late money wins".)
if (fetched.status === "pending") {
const cancelled = await nicepay.cancelPayin(first.id);
console.log(`cancelled: ${cancelled.status}`);
}Statuses
pending ──► processing ──► succeeded (final)
│ ├──► failed ──┐
│ └──► expired ──┤
├──► succeeded ├──► succeeded (money arrived late)
├──► failed ────────────────┤
├──► expired ────────────────┤
└──► cancelled ──────────────┘pending waitingprocessing in progresssucceeded finished wellfailed went wrongexpired overcancelled over
processing: a reference was submitted, the rail reported progress, or an on-chain transfer is seen but not confirmed. Not money yet.succeededis final and is the only status in which money has been credited (one exception for USDT invoices, below).feeandnet_amountare set then.- Late money always wins. If real money arrives for a pay-in that is
failed,expiredorcancelled, it becomessucceededwith"late": true, you are credited, and you getpayin.succeeded. Never close an order on your side so hard that a latepayin.succeededcannot credit it. - Reversal. If a credited pay-in turns out not to be real money, it stays
succeededbut gainsreversed_atandreversed_amount; your balance is reduced and you getpayin.reversed. amount_receivedis what actually arrived. Credit your customer that, notamount.
Cancel
POST/v1/payins/{id}/cancel while it is pending; in any other status the answer is 409 invalid_state. Cancelling is not a refusal of money: if the customer pays anyway, late money wins.
Your own payment page
If you show the UPI QR or bank details yourself (instructions.type upi_qr or bank_details), send the customer's payment reference (UTR) with POST/v1/payins/{id}/reference. A reference already used for another pay-in is refused with reference_already_used.
USDT
Each customer gets one permanent deposit address per chain (tron or bsc). Asking again returns the same address; it is never given to anyone else.
samples/ts/crypto-address.ts// USDT: each customer gets one permanent deposit address per chain. Ask as often as you
// like — it is a get-or-create and always returns the same address.
// bun crypto-address.ts player-7591035 bsc
import { NicePay, NicePayError, type Chain } from "@nicepay/sdk-ts";
const nicepay = new NicePay({
keyId: process.env["NICEPAY_KEY_ID"] ?? "",
secret: process.env["NICEPAY_KEY_SECRET"] ?? "",
...(process.env["NICEPAY_API_BASE"] ? { baseUrl: process.env["NICEPAY_API_BASE"] } : {}),
});
const customerRef = process.argv[2] ?? "player-7591035";
const chain = (process.argv[3] ?? "tron") as Chain;
async function depositAddress(): Promise<string> {
for (let attempt = 0; ; attempt += 1) {
try {
return (await nicepay.createCryptoAddress({ customer_ref: customerRef, chain })).address;
} catch (error) {
// A new address comes from a pool filled in advance; if it is momentarily empty, wait and ask again.
if (error instanceof NicePayError && error.code === "address_pool_empty" && attempt < 5) {
await new Promise((resolve) => setTimeout(resolve, 2000));
continue;
}
throw error;
}
}
}
const first = await depositAddress();
const second = await depositAddress();
console.log(`${customerRef} on ${chain}: ${first} (stable: ${String(first === second)})`);
// Every confirmed transfer to it becomes its own pay-in (payin.succeeded with the amount received).- Open deposits: every confirmed transfer to the address becomes its own pay-in (no
merchant_order_id) for the amount received, withpayin.succeeded. Three transfers are three pay-ins and three credits. - Invoices:
createPayinwithmethod: "usdt_trc20"or"usdt_bep20"and anamountopens an invoice on the customer's address. Transfers while it is open add up in that one pay-in:amount_receivedgrows, each transfer is listed intransfers[], and it succeeds when enough arrived (more is credited in full; at expiry a partly paid invoice succeeds for what arrived). Each confirmed transfer is credited to you as it confirms and raisescrypto.transfer.confirmed. Credit your customer either per confirmed transfer or once onpayin.succeededwithamount_received— pick one and key your credit on it. - One invoice per address may be open at a time (
409 invoice_already_open). - Never credit on
crypto.transfer.detected: it is seen, not confirmed.
In test mode, addresses are real-format addresses that nothing watches; simulated USDT transfers are not available yet.
Mistakes that lose money
- Crediting your customer from the event body or from the redirect back to
return_url. Always fetch the pay-in by id and checkstatus === "succeeded"— the SDKs'handlePayinEventdoes this. - Crediting
amountinstead ofamount_received(a partial or late payment). - Crediting twice: a unique key on the pay-in id in your database, inserted in the same transaction as the credit (webhooks).
- Refusing a late
payin.succeededbecause the order "expired": the money is yours and the customer paid.