DEV Community

Jonathan Azeroual
Jonathan Azeroual

Posted on

Accept USDC on four networks with one API request

Disclosure up front: I work on PYMSTR, the gateway used in this example. The pattern applies to any gateway that lets you whitelist networks per payment.

Your customers hold USDC on different networks. One has it on Base because they bought it on Coinbase, another on Arbitrum from a DeFi app, a third on Ethereum mainnet. If your checkout only takes one network, the others have to bridge first, and a lot of them will not bother.

The usual fix is four integrations: four RPC providers, four sets of contract addresses, four places to watch for confirmations. This post does it with one request.

1. Create the payment

You need an API key from the dashboard (Integration > API keys). Keys start with pk_ and belong on your server, never in the browser.

const res = await fetch('https://api.pymstr.com/v1/payments', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.PYMSTR_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    amount: '250.00',
    currency: 'USD',
    title: 'Order 1042',
    externalId: 'order-1042',
    acceptedChains: [1, 42161, 8453, 137], // Ethereum, Arbitrum, Base, Polygon
    acceptedTokens: ['USDC'],
  }),
})

const payment = await res.json()
// payment.paymentUrl -> https://pay.pymstr.com/p/<id>
Enter fullscreen mode Exit fullscreen mode

Two fields do the work:

  • acceptedChains takes chain IDs. These four are the networks where native USDC is accepted. (BNB Smart Chain, ID 56, is supported for USDT only, so it is left out here.)
  • acceptedTokens pins the coin. The customer can pick any of the four networks, but they cannot pay in anything other than USDC.

The amount is a fiat string ("250.00", currency USD). The rate to USDC is locked when the customer starts paying, so you price in dollars and never touch token decimals.

The 201 response includes the fee split up front:

{
  "id": "01234567-89ab-cdef-0123-456789abcdef",
  "status": "ACTIVE",
  "amount": "250.00",
  "currency": "USD",
  "acceptedChains": [1, 42161, 8453, 137],
  "acceptedTokens": ["USDC"],
  "pymstrFee": "1.25",
  "merchantFee": "248.75",
  "paymentUrl": "https://pay.pymstr.com/p/01234567-89ab-cdef-0123-456789abcdef",
  "expiresAt": "..."
}
Enter fullscreen mode Exit fullscreen mode

pymstrFee is the gateway's 0.5%; merchantFee is what reaches you. The link expires after an hour by default (expiresAt takes anything from 15 minutes to 30 days).

2. Send the customer to paymentUrl

Redirect or email the link. The customer picks a network, signs in with Google, Apple or email (a wallet is created for them if they do not have one) or connects their own wallet, and pays.

The money goes straight to your wallet. The gateway never holds it, so there is no gateway balance to withdraw from and nothing for a processor to freeze. (The industry calls this non-custodial.)

3. Verify the webhook

Add an HTTPS endpoint under Integration > Webhooks and save the secret, which is shown once. When the payment confirms on chain you receive payment.completed:

{
  "event": "payment.completed",
  "timestamp": "2026-02-24T10:05:00.000Z",
  "data": { "paymentId": "01234567-...", "externalId": "order-1042" }
}
Enter fullscreen mode Exit fullscreen mode

Every delivery is signed. The X-Pymstr-Signature header looks like t=<unix seconds>,v1=<hex>, and v1 is an HMAC-SHA256 of <t>.<raw body> with your webhook secret. Verify it against the raw body, before any JSON parsing:

import express from 'express'
import { createHmac, timingSafeEqual } from 'node:crypto'

const app = express()

function verify(rawBody, header, secret, toleranceSec = 300) {
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')))
  const t = Number(parts.t)
  if (!t || !parts.v1) return false
  if (Math.abs(Date.now() / 1000 - t) > toleranceSec) return false // replay window

  const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest()
  const given = Buffer.from(parts.v1, 'hex')
  return given.length === expected.length && timingSafeEqual(given, expected)
}

app.post('/webhooks/pymstr', express.raw({ type: 'application/json' }), async (req, res) => {
  const raw = req.body.toString()
  if (!verify(raw, req.get('X-Pymstr-Signature') || '', process.env.PYMSTR_WEBHOOK_SECRET)) {
    return res.status(401).send('bad signature')
  }
  const { event, data } = JSON.parse(raw)
  try {
    if (event === 'payment.completed') await fulfil(data.paymentId)
    res.sendStatus(200) // answer 2xx only after the work is done, within 10 seconds
  } catch (err) {
    console.error('fulfil failed', data.paymentId, err)
    res.sendStatus(500) // any non-2xx answer is delivered again
  }
})
Enter fullscreen mode Exit fullscreen mode

Answer with a 2xx within 10 seconds, after the work is done. A failure after a 2xx is never retried; any other answer or a timeout is, up to seven attempts in total over about 34 hours, so deduplicate on paymentId plus event. If fulfilment can take longer, store the event first and finish the work from a queue.

4. Read the authoritative state

The webhook payload is deliberately small. Events can arrive out of order, so fetch the payment before you ship anything:

async function fulfil(paymentId) {
  const res = await fetch(`https://api.pymstr.com/v1/payments/${paymentId}`, {
    headers: { Authorization: `Bearer ${process.env.PYMSTR_API_KEY}` },
  })
  const p = await res.json()
  if (p.status !== 'SUCCESSFUL') return

  // Which of the four networks did the customer use?
  console.log(p.chainId, p.token, p.txHash) // e.g. 8453 'USDC' '0x...'
  // ...mark order p.externalId as paid
}
Enter fullscreen mode Exit fullscreen mode

chainId and txHash tell you exactly where the money moved, so reconciliation is a block explorer lookup instead of a support ticket.

What you did not have to build

  • No per-network RPC, contract addresses or confirmation watchers.
  • No token decimals or price feeds: you priced in dollars, the rate was locked at payment time.
  • No refunds of the wrong coin on the wrong network: acceptedChains and acceptedTokens mean the customer can only pay the way you allowed.
  • No chargebacks: an on-chain payment is final.

Gotchas

  • Native USDC only. Bridged variants such as USDC.e are not the same token and are not accepted.
  • Base has no USDT. If you add 'USDT' to acceptedTokens, customers can pay USDT on Ethereum, Arbitrum or Polygon (add 56 to acceptedChains for BNB), never on Base.
  • externalId is unique while a payment is active, processing or successful. You can reuse it after a payment fails, expires or is cancelled.
  • A lost create response is recoverable. If the request times out, send the same request again. A 201 means the first one never landed; a 409 carries the existing payment's id, which you read with GET /v1/payments/:id to get the paymentUrl back.
  • Act on SUCCESSFUL, not on the absence of failure. Rarely, a payment marked FAILED turns out to have gone through and becomes SUCCESSFUL later ("late credit"), so you can get payment.failed and payment.completed for the same payment, in either order. Fetching the payment and checking its status, as above, handles this.

Full reference: docs.pymstr.com. If you are comparing approaches for USDC specifically, there is a longer guide at pymstr.com/accept/usdc.

Top comments (0)