How to verify a crypto payment in your own app
To verify a crypto payment in your own app, confirm 5 things: the right token contract on the right network, the right amount after decimals, an address tied to one order, enough confirmations that the transfer will not be undone, and a value matching your price. Doing it yourself means building each check for every network. The middle path: a gateway detects and settles the payment, and your code verifies a signed webhook and fetches the checkout's status.
The question developers keep asking
In March 2026 a developer building a SaaS that takes USDC posted "Ask HN: How do you verify crypto payments in your app?". The two options on the table were a payment processor at 0.5 to 1% per transaction, or a do-it-yourself setup with webhooks from a node provider, which had taken about 2 weeks to build and was still brittle. The question at the end: "Is there a middle ground?" In a follow-up, the poster listed the edge cases a webhook setup runs into: reorgs on Base, events missed while the webhook endpoint was down, and telling apart several payments of the same amount to the same address.
Those 3 failures are a fair map of the problem. The sections below go through each job a verifier has to do, then show what the middle path looks like in code.
What a do-it-yourself verifier has to handle
| Job | What you build | Where it breaks |
|---|---|---|
| Detect the transfer | A node, or a node provider's webhooks, per network | Events missed during downtime, so you also need a backfill that scans blocks |
| Match it to an order | A fresh address per order, or a unique amount, or a memo | Shared addresses make 2 equal payments indistinguishable |
| Check the token | An allowlist of contract addresses per network | Bridged and look-alike tokens with the same symbol |
| Read the amount | Unit conversion using each token's decimals | The same token name with different decimals on different networks |
| Wait for finality | A confirmation policy per network | Reorgs, replaced transactions, block times that change |
| Value it | A price feed and a quote timer for non-stablecoins | Payments sent after the quoted price expired |
| Decide edge cases | Rules for short, over, late and wrong-network payments | Every rule becomes a support ticket |
Matching a payment to an order
Bitcoin's own guidance is that "Bitcoin addresses should only be used once" (bitcoin.org), and the same logic holds for matching on any chain. With one address for everyone, 2 customers who each send 49 USDC within a minute look identical. Gateways give each order its own address: BTCPay Server derives each invoice's address from the merchant's xpub, and CoinStack creates a deposit address per checkout. Fresh addresses bring a second job: you hold or derive keys for every one of them, and the funds sit spread across those addresses until you sweep them.
Token contracts and decimals
A transfer of "USDC" proves nothing until you check which contract sent it. On Base, Circle's native USDC lives at 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 according to Circle's contract list, while an older bridged token, USDbC, still exists at a different address. Circle says it does not issue or back bridged versions. Anyone can deploy a token named USDC, so a verifier that trusts the symbol can be paid in a worthless copy.
Decimals vary too. Native USDC has 6. On BNB Smart Chain, where Circle does not issue USDC, the token named USD Coin at 0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d is a pegged version that uses 18. Compare amounts as integers in each token's smallest unit, never as floats:
function toSmallestUnit(amount, decimals) {
const [whole, fraction = ""] = amount.split(".");
if (fraction.length > decimals) throw new Error("Too many decimal places");
return BigInt(whole + fraction.padEnd(decimals, "0"));
}
console.log(toSmallestUnit("25.00", 6)); // 25000000n: USDC on Base
console.log(toSmallestUnit("25.00", 18)); // 25000000000000000000n: USDC on BNB Smart ChainGet the decimals wrong on one network and you either reject every payment or accept a millionth of the price. Native USDC vs bridged USDC covers the token side in more depth.
Confirmations and reorgs
There is no single right number of confirmations. For Polygon PoS, Circle Mint waits 2 to 3 blocks, the Coinbase Exchange API lists 128 for USDC, and Kraken waits 250. Each figure is that company's risk policy, collected in December 2026 from Kraken's deposit page, Coinbase's public API and Circle's confirmation table. You have to pick your own, network by network.
Reorgs are rare on modern networks, but they happen. Base's finality docs say "less than 0.00000002% of transactions have ever reorged", describe a new block every 200ms, and put full finality on Ethereum at about 20 minutes. Base moved to 200ms blocks on November 5, 2026, so a block-count rule written earlier now waits a tenth as long, and Base advises comparing timestamps instead. On Bitcoin, unconfirmed payments are not safe: since Bitcoin Core 28.0, nodes accept and pass on replacement transactions by default, whether or not the original signalled it. On TRON, a block counts as solidified once 19 of the 27 Super Representatives have built on it, which TRON's docs say typically takes about a minute. Blockchain confirmations explained for merchants goes network by network.
Price conversion and wrong amounts
For stablecoins the value is close to the face amount. For BTC, ETH or SOL you need a price at the moment you quote, a time limit on that price, and a rule for payments that arrive after it. Customers also miss the total. OpenNode's help centre notes that "Payers may accidentally send too little Bitcoin" and that "It can also happen when a user pays from an exchange" (OpenNode), because exchanges take their withdrawal fee out of the amount sent. Your code needs a tolerance, a way to accept a top-up to the same address, and a decision on overpayments. Underpaid crypto payments: why they happen, what to do covers the policy side.
What building costs against buying
Take a SaaS doing $20,000 a month in crypto payments. A gateway charging 0.8% costs $160 a month, or $1,920 a year. On the other side, the Hacker News poster spent about 2 weeks on a USDC setup that they still called brittle, before adding networks, price feeds or refunds of the wrong token. Each extra network repeats the detect, match, token and finality work with different rules.
Across several networks, that upkeep tends to cost more than the fee.
The middle path: a gateway detects, your code verifies
In the middle path the gateway does the chain work: a deposit address per order, detection, finality and conversion. Your app does the part that must be yours: proving that a notification is genuine and deciding whether this order is paid. With CoinStack that is 2 checks.
- Verify the webhook signature. Each event arrives with a
CoinStack-Signature: t=...,v1=...header. Compute an HMAC-SHA256 oft, a full stop and the raw request body, keyed with your signing secret, and compare it tov1in constant time. Reject anything older than 5 minutes. - Fetch the checkout and read its status. Do not trust the event's contents alone for fulfilment. Ask the API for the checkout and act on its current
status. The webhooks guide recommends this because events can arrive out of order, and a retried event can arrive after a newer one.
Here is the whole handler in Node.js with Express. The verify function is the one from the docs.
import crypto from "node:crypto";
import express from "express";
const app = express();
const secret = process.env.COINSTACK_WEBHOOK_SECRET;
const apiKey = process.env.COINSTACK_API_KEY;
// Your own records. A database in real code.
const orders = new Map(); // checkout_id -> { amount: "49.00", currency: "USD", paid: false }
const seenEvents = new Set();
function verify(header, body) {
const parts = Object.fromEntries(
String(header).split(",").map((part) => part.split("=")),
);
const expected = Buffer.from(
crypto.createHmac("sha256", secret).update(`${parts.t}.${body}`).digest("hex"),
);
const given = Buffer.from(String(parts.v1));
return (
given.length === expected.length &&
crypto.timingSafeEqual(given, expected) &&
Math.abs(Date.now() / 1000 - Number(parts.t)) <= 300
);
}
async function getCheckout(checkoutId) {
const response = await fetch(
`https://coinstack.net/api/v1/checkouts/${encodeURIComponent(checkoutId)}`,
{ headers: { Authorization: `Bearer ${apiKey}` } },
);
const body = await response.json();
if (!body.success) {
throw new Error(body.response);
}
return body.response.checkout;
}
async function settle(checkoutId) {
const order = orders.get(checkoutId);
if (!order || order.paid) {
return; // Not a checkout you created, or already handled.
}
const checkout = await getCheckout(checkoutId);
const paid = checkout.status === "completed" || checkout.status === "resolved";
const sameAmount =
Number(checkout.amount) === Number(order.amount) &&
checkout.currency === order.currency;
if (paid && sameAmount) {
order.paid = true; // Fulfil the order here.
}
}
app.post(
"/webhooks/coinstack",
express.raw({ type: "application/json" }),
(request, response) => {
const body = request.body.toString("utf8");
if (!verify(request.get("CoinStack-Signature"), body)) {
return response.status(400).send("Invalid signature");
}
const event = JSON.parse(body);
response.sendStatus(200);
if (seenEvents.has(event.event_id) || !event.kind.startsWith("checkout.")) {
return;
}
settle(event.data.checkout.checkout_id)
.then(() => seenEvents.add(event.event_id))
.catch((error) => console.error("Could not settle", event.event_id, error));
},
);
app.listen(3000);Why each check is there
express.rawkeeps the body as bytes. If a framework parses the JSON and you turn it back into text, the bytes can differ and the signature fails. How to verify payment webhooks explains the HMAC scheme line by line.- The quick
200. CoinStack expects a2xxwithin 10 seconds, so the handler answers first and does the API call afterwards. The cost is that a failed API call is not retried by CoinStack, which already has its200; the scheduled check described below picks those orders up. event_idstays the same when an event is retried or resent, so it is the key for skipping duplicates. Theorder.paidcheck stops a second fulfilment even if a duplicate slips through.- The order lookup confirms the checkout is one you created. The docs say to "Match
checkout_idto an order you created before you fulfil anything." completedorresolved.completedmeans paid in full, or short by less than your underpayment allowance (0.5% by default).resolvedmeans you accepted an underpayment in the dashboard. The docs say to treat both as paid. Theunderpaid,overpaidandlateflags on the checkout tell you whether a refund conversation is due.- The amount and currency match guards against a bug that attached the wrong checkout to an order. Amounts arrive as strings such as
"49.00000000", so convert both sides before comparing.
The status fetch only reads data, so it can run on a read-only API key, which can list and get checkouts, payments and tokens and gets a 403 on every other endpoint. Keep the read-and-write key for the code that creates checkouts.
Catching what the webhook misses
If your endpoint is down, CoinStack retries after 1 minute, 5 minutes, 30 minutes, 2 hours, 5 hours, 8 hours and 8 hours: 8 attempts over about a day. Add a scheduled job that takes orders still unpaid after an hour and calls getCheckout for each, and you have covered the outage case from the Hacker News thread. If you lost track of which checkout belongs to an order, you can find it by the reference you set:
curl "https://coinstack.net/api/v1/checkouts?reference=order-1042" \
-H "Authorization: Bearer $COINSTACK_API_KEY"Reliable payment webhooks: retries, duplicates and ordering covers the queue and storage side of this.
What stays with you on the middle path
- Independent checks are optional. The status is CoinStack's judgement that the payment is final. To confirm one yourself, each payment records a
deposit_tx_hashyou can look up on a block explorer, as described in how to verify a crypto payment on a block explorer. - Simple pricing. 0.8% per payment, taken before the USDC settles to your wallet. No setup or monthly fee.
- You control refunds. The USDC settles to a wallet you control, so you send refunds from it on your own timing and record them against the order in your app.
Frequently asked questions
Is watching my wallet's incoming transactions enough to verify a payment?
Only if each order has its own address and you check the token contract, the decimals and the confirmation count yourself. Watching one shared wallet tells you money arrived, not which order it was for. Two customers paying the same amount minutes apart look identical, and a token copying the USDC name would show up as a USDC deposit.
How many confirmations should my app wait for?
It depends on the network and the amount, and the companies that publish numbers disagree. For Polygon PoS, Circle waits 2 to 3 blocks and Kraken waits 250. On Base, the network's docs give about 2 minutes for a batch to reach Ethereum and about 20 minutes for full finality. On Bitcoin, treat unconfirmed payments as unpaid, because they can be replaced.
Can I trust the data inside a webhook without calling the API?
Once the signature checks out, the data did come from CoinStack, but it describes the checkout as it was when the event fired. Events can arrive late or out of order, so a retried older event could follow a newer one. Fetching the checkout and acting on its current status removes that problem.
What should my app do with an underpaid crypto payment?
With a gateway, set the tolerance once: CoinStack completes checkouts that fall short by less than your allowance, 0.5% of the total by default. A larger shortfall leaves the checkout partial while the customer sends the rest to the same address. If it expires short, resolve it to accept what arrived, or refund the customer from your wallet.