The return button isn't a receipt: building a "waiting for your crypto" page on your own site
DEV Community

The return button isn't a receipt: building a "waiting for your crypto" page on your own site

With a card payment, the customer comes back to your site and the result comes with them. The redirect says "succeeded" or "declined", and your thank-you page more or less writes itself.

Crypto doesn't work like that. The customer might send the money and close the tab. They might pay from an exchange twenty minutes later. They might come back to your site while the transaction is still collecting confirmations, or open the order email the next morning. Your order page has to make sense in every one of those cases, and none of them hand you a result in the URL.

I work on Coldtill, a self-hosted crypto payment gateway, and this is the page I'd build on top of it. The shape carries over to most gateways with a hosted checkout and webhooks; the field names are Coldtill's.

What the hosted checkout already does

When your backend creates a payment, you get back a url like https://pay.example.com/pay/{reference_id}. That page lets the customer pick a network and coin, shows the address as text and a QR code with the exact amount, counts down to expiry and updates live as deposits arrive and confirm.

Two things it deliberately doesn't do:

  • It never sends the customer back by itself. Once the payment is complete it shows a Return to {store} button, if you've given it somewhere to return to. That's it.
  • It can't be embedded. It sets a strict content security policy and refuses to load in a frame. Link to it; don't try to iframe it into your order page.

So "the customer is back on my site" happens in three ways: they clicked the button after paying, they came back early by themselves (back button, a new tab, the email link), or they never come back. Build for all three.

Give each payment its own return URL

Every payment stores its own returnURL, set when you create it. Without one, it takes the project's Return URL as it is at that moment, and if neither exists the checkout just tells the customer they can close the page. Send a per-order URL so the button lands on this order:

// server side only: the API key never goes near the browser
async function createCryptoPayment ( order ) {
  const res = await fetch ( `${process.env.COLDTILL_URL}/api/v1/payment` , {
    method : "POST" ,
    headers : {
      "API-Key" : process.env.COLDTILL_API_KEY , // a payments-only key is enough
      "Content-Type" : "application/json" ,
    } ,
    body : JSON.stringify ( {
      customerID : String ( order.customerId ) ,
      amountInUSD : order.totalUsd , // e.g. "149.00"
      invoiceID : order.number ,
      returnURL : `https://shop.example.com/orders/${order.publicToken}` ,
    } ) ,
  } ) ;
  if ( res.status === 409 ) {
    // the customer's previous payment has a deposit still confirming
    throw new PreviousPaymentConfirming ( ) ;
  }
  if ( ! res.ok ) throw new Error ( `create payment failed: ${res.status}` ) ;
  const { reference_id , url } = await res.json ( ) ;
  await db.orders.update ( order.id , { coldtillRef : reference_id , checkoutUrl : url } ) ;
  return url ; // redirect the customer here
}

The rules are strict and worth knowing before they bite: an absolute https:// URL, at most 2,048 characters, no username or password in it, or the request gets a 400. A project admin can also set Allowed return hosts, and then any returnURL on another host is refused. If you run shop.example.com and www.example.com, list both; names have to match exactly.

Now the important bit. The docs put it plainly: opening the return URL tells Coldtill nothing, and anyone can open it. So:

  • publicToken is just an unguessable handle for the order, so customers can't browse each other's orders. It proves nothing about payment.
  • Never put ?paid=1, an amount, or a status in the return URL and believe it later.
  • The page reads the order's status from your database. It doesn't decide anything from how the customer got there.

Let webhooks write the state, and let the page read it

The page is only as good as what's stored. Coldtill sends a signed webhook as deposits are seen, gain confirmations and close the payment, so that handler is where the state comes from:

import express from "express" ;
import { verifyWebhookRequest } from "@coldtill/sdk" ;
const FINAL = new Set ( [ "FILLED" , "OVER_FILLED" , "CANCELLED" , "REPLACED" ] ) ;
app.post ( "/coldtill/webhook" , express.raw ( { type : "application/json" } ) , async ( req , res ) => {
  let ev ;
  try {
    ev = await verifyWebhookRequest ( req.body , req.headers , process.env.COLDTILL_WEBHOOK_SECRET ) ;
  } catch {
    return res.sendStatus ( 401 ) ;
  }
  if ( ! ev.event.startsWith ( "payment." ) ) return res.sendStatus ( 200 ) ;
  const p = ev.data ;
  const order = await db.orders.findByNumber ( p.invoice_id ) ;
  // an old payment must not touch a newer order
  if ( ! order || order.coldtillRef !== p.reference_id ) return res.sendStatus ( 200 ) ;
  // ordering isn't guaranteed: never let an older event overwrite a newer one,
  // and never move a closed payment back to an open state
  const stale = order.lastEventMs && p.timestamp_ms < order.lastEventMs ;
  if ( ! stale && ! FINAL.has ( order.paymentStatus ) ) {
    await db.orders.update ( order.id , {
      paymentStatus : p.status ,
      filledUsd : p.filled_amount_in_usd ,
      confirmations : p.confirmation_current ?? null ,
      confirmationsNeeded : p.confirmation_required ?? null ,
      lastEventMs : p.timestamp_ms ,
    } ) ;
  }
  if ( ! stale && FINAL.has ( order.paymentStatus ) && ! FINAL.has ( p.status ) ) {
    // a deposit after the payment closed: Coldtill sends a progress event with the new
    // filled_amount and leaves the payment closed. Flag it for a person.
    await db.orders.flagLateDeposit ( order.id , p.filled_amount_in_usd ) ;
  }
  res.sendStatus ( 200 ) ; // reply fast; send emails and fulfil after this
} ) ;

A few details from the webhook docs shaped that code:

  • Order by timestamp_ms, not timestamp. Two events can land in the same second.
  • Progress events are cheap and short-lived. They're retried at 2 s and 4 s and then dropped, because a later change sends a fresh one anyway. Fine for a progress bar, not something to build business logic on.
  • Final events are retried for two days (2 s, 4 s, 30 min, then 1, 2, 4, 8, 24 and 48 hours). That's what fulfilment should hang off, and why the handler has to be idempotent.
  • A deposit that's first seen already fully confirmed sends no progress event. The next thing you hear is the credit. So don't write UI that waits to see "confirming" before it will show "paid".

When the page opens and you've heard nothing yet

Webhooks can be late, your receiver can have been down, or the customer can simply beat the first event back to your site. So when the order page loads and the stored status isn't final, ask Coldtill directly, from your server:

GET /api/v1/payment/reference/{reference_id} returns paymentState, the amounts, expiresAt and a deposits array, where each deposit carries its network, currency, transactionHash, confirmations and requiredConfirmations. A payments-only key can call it.

One thing to watch: the merchant API allows 600 requests per minute per client IP, and every call comes from your backend's IP. If each open order page polls your server, and your server passes every poll straight through, a busy evening adds up. A few seconds of caching per reference fixes that:

const cache = new Map ( ) ; // reference_id -> { at, body }
async function paymentStatus ( ref ) {
  const hit = cache.get ( ref ) ;
  if ( hit && Date.now ( ) - hit.at < 5000 ) return hit.body ;
  const res = await fetch ( `${process.env.COLDTILL_URL}/api/v1/payment/reference/${ref}` , {
    headers : { "API-Key" : process.env.COLDTILL_API_KEY } ,
  } ) ;
  if ( ! res.ok ) throw new Error ( `status lookup failed: ${res.status}` ) ;
  const body = await res.json ( ) ;
  cache.set ( ref , { at : Date.now ( ) , body } ) ;
  return body ;
}

If that answer is final and your stored state isn't, treat it the same way as the webhook would: run the same idempotent "mark paid" code. Then the order page, the webhook and any background job all converge on one path.

What to say for each state

This is the part customers actually see, so it's worth writing the copy on purpose rather than printing the raw status.

  • OPEN, no deposits - Nothing seen yet - "Waiting for your payment." A link back to the checkout url and the time it expires
  • OPEN, deposit below its required confirmations - Seen, not settled - "We can see your payment. Confirming: 4 of 10." No "Pay again" button
  • PARTIALLY_FILLED - Confirmed amount is under 99% of what's owed - "We've received part of the payment." Link back to the checkout, which asks for the rest
  • FILLED or OVER_FILLED - Paid (within 1%, or more than 1% over) - Thank you, order confirmed
  • CANCELLED - Expired before it was filled - "This payment link expired." Offer a new one. If money arrived late, "we'll be in touch" instead
  • REPLACED - The customer started a newer payment - Look up the order's current reference and show that one

Two of those rows have traps.

"Pay again" while something is confirming. A customer has at most one open payment, so creating a new one replaces the previous one. Coldtill protects you here: if the previous payment has a deposit still confirming, creating a new one fails with 409 rather than stranding that deposit. Catch it and say "your last payment is still confirming, give it a few minutes", which is what the customer needs to hear anyway. Better still, hide the button while any deposit has fewer confirmations than it needs.

Expiry. Payments expire after the project's payment link expiry, 24 hours by default, or at the expire time you pass when creating one (RFC 3339, at least a minute ahead). Show the same expiresAt on your page that the checkout counts down to, so the two never disagree. And if a deposit lands after it closed, the payment stays closed. That one goes to a human, not to code.

The browser side is the boring part

Once the server does the above, the page itself just polls your endpoint and stops when the state is final:

async function watch ( orderToken ) {
  for ( ; ; ) {
    const s = await fetch ( `/orders/${orderToken}/status` ) . then ( ( r ) => r.json ( ) ) ;
    render ( s ) ; // pick the copy from the table above; the server resolves REPLACED to the current payment
    if ( [ "FILLED" , "OVER_FILLED" , "CANCELLED" ] . includes ( s.paymentStatus ) ) return ;
    await new Promise ( ( r ) => setTimeout ( r , s.confirming ? 5000 : 15000 ) ) ;
  }
}

No API key, no Coldtill URL beyond the checkout link, nothing a customer could replay. Server-sent events would work just as well; polling is easier to get right and the numbers involved are small.

Trying it locally

On a testnet install, webhook endpoints can point at http://localhost, which makes this pleasant to build: run your shop locally, pay with Sepolia ETH or Base Sepolia USDC from a faucet, and watch the page move through the states. Webhooks → Send test fires a signed test event whenever you want one. Mainnet endpoints have to be public https URLs.

If you don't have a server yet, the Free edition's installer and Docker image files are on GitHub. The one-line install starts in testnet mode unless you ask for mainnet. The merchant API reference has the full payment object and the return URL rules.

The short version: the checkout tells the customer what's happening, the webhook tells your database, and your order page reads the database. The return button is just a door back in.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.