Merchant Integration

Accept crypto payments on Quai in 3 steps.

Funds go straight to your wallet (the contract holds nothing), and you get a signed webhook when a payment confirms.

Overview

The flow at a glance

1

Register an order

Your backend registers the expected payment on-chain.

2

Customer pays

One contract call — ERC-20 or native QUAI.

3

We POST a webhook

Signed webhook confirms the payment; you fulfill.

Setup

Before you start

Your platform operator gives you three things at onboarding:

You receiveWhat it's for
PAYWITHQUAI_ADDRESSThe contract address you register orders on
webhookSecretSecret key to verify webhooks are really from us(shown once — store it safely)
merchantIdYour platform id, e.g. mch_ab12...

Quai mainnet (chain 9)

The platform runs on Quai mainnet, Cyprus-1 zone:RPC https://rpc.quai.network · chainId 9Deploy the PayWithQuai proxy once (see the deployment section below) and set NEXT_PUBLIC_PAYWITHQUAI_ADDRESS from contracts/deployments/cyprus1.json. Your payout wallet and the contract must be in the same zone — Cyprus-1 (0x00…).

Use the `quais` package, not ethers

All examples use quais — Quai's ethers fork. It ships usePathing (zone-aware RPC), formatQuai / parseQuai and the wallet types used below.

Same zone — this matters

Quai is sharded. Your payout wallet, your customers, and the contract must all be in the same zone (the contract address prefix tells you which, e.g. 0x00… = Cyprus-1). Value can't move between zones.

Amounts are in the token's smallest unit

Always use strings/bigint — never floats. For a 6-decimal stablecoin, $25.00 = 25000000. QUAI is token = address(0).

Currencies

Supported assets

Orders can be registered in native QUAI or any ERC-20 the contract owner has allowlisted. The platform ships with these assets built in — payment links, checkout, Blip and the dashboard balances panel all pick them up automatically:

AssetAddressDecimalsNotes
QUAIaddress(0)18Native gas asset — always accepted
USDT0x0049F7cbCa3556C2DfaE62Aafa7015F99de1b8f56Tether USD — canonical mainnet token
WQUAI0x006C3e2AaAE5DB1bCd11A1a097cE572312EADdBB18Wrapped Quai — ERC-20 form of QUAI
mUSDQ0x003fafB5126a5296c6edC7C23De55daf2E84B5036Mock stablecoin — testnet faucet only

Registry-driven frontend

Canonical addresses are compiled into frontend/src/lib/currencies.ts and can be overridden per deployment with NEXT_PUBLIC_USDT_ADDRESS / NEXT_PUBLIC_WQUAI_ADDRESS. Every surface (link builder, pay page, checkout, dashboard, analytics) reads from this one registry.

Tokens must be allowlisted on the contract

Registering an order in a token the contract hasn't accepted reverts with TokenNotAccepted. The owner enables assets once with npx hardhat run scripts/allowTokens.js --network cyprus1 (USDT + WQUAI are already enabled on mainnet). Optionally set ACCEPTED_TOKENS on the backend to mirror the same list for payment-link creation.

Blip pays every listed asset

The "Pay with Blip" flow works for native QUAI and all supported tokens alike — balance check, top-up and approve/transferFrom are handled by the app.

Step 1

Authorize the order (from your backend)

install
npm install quais   # Quai's ethers fork — usePathing, formatQuai, parseQuai

Orders are created by the customer's payment transaction, not by yours. Your backend mints an order id and signs one EIP-712 authorization for it; the contract verifies that signature and creates the order, moves the money and marks it settled — all in that single transaction. Nobody spends gas to open a checkout, and the payout wallet only has to be able to receive.

authorizeOrder.ts
// Your backend, after the customer starts checkout. NOTHING is broadcast here —
// and nothing was broadcast when they added the item to their cart.
import { Wallet } from 'quais';

const signer = new Wallet(ORDER_SIGNER_KEY);          // allowlisted on-chain: setSigner(signer, true)

// Same domain the contract was initialized with: initializeSigning('PayWithQuai', '1').
// chainId + verifyingContract are per-deployment — get both from deployments/<network>.json.
const domain = { name: 'PayWithQuai', version: '1', chainId, verifyingContract: PAYWITHQUAI_ADDRESS };

const order = {
  merchant: MERCHANT_ADDRESS,     // your payout wallet — the money lands here
  orderId,                          // random bytes32, minted per checkout
  token: TOKEN_ADDRESS,             // or address(0) for native QUAI
  amount: 25000000n,
  expiry: Math.floor(Date.now()/1000) + 1800,   // never leave this unbounded
  feeBps: await pay.feeBps(),                    // read live — don't cache a fee
  feeRecipient: await pay.feeRecipient(),
  expectedPayer: customerAddress,   // binds this authorization to ONE wallet
};

const signature = await signer.signTypedData(domain, { SignedOrder: SIGNED_ORDER_FIELDS }, order);
return res.json({ ...order, amount: order.amount.toString(), signature });   // hand to the customer
  • expectedPayer binds the authorization to one wallet. Without it, anyone who sees the signature could settle the customer's order and deny them the purchase.
  • feeBps and feeRecipient are read from the chain at signing time, not from your config, so a fee change can never be back-dated into an old signature.
  • The signing key must be allowlisted by the contract owner: setSigner(yourSigner, true). Removing it is an instant kill switch — settled orders are unaffected.
  • The digest is public — a customer can verify exactly what you signed with signedOrderDigest(order). Never sign an amount, expiry or payout you did not intend.
signedOrderFields.ts
// Field order and types are part of the digest — they must match PayWithQuai.sol exactly,
// or every signature is rejected.
const SIGNED_ORDER_FIELDS = [
  { name: 'merchant',       type: 'address' },
  { name: 'orderId',        type: 'bytes32' },
  { name: 'token',          type: 'address' },
  { name: 'amount',         type: 'uint256' },
  { name: 'expiry',         type: 'uint256' },
  { name: 'feeBps',         type: 'uint16'  },
  { name: 'feeRecipient',   type: 'address' },
  { name: 'expectedPayer',  type: 'address' },
];
paywithquai.abi.js
const PAYWITHQUAI_ABI = [
  // Customer-paid orders — the customer creates AND settles in one call
  "function paySignedOrder((address merchant, bytes32 orderId, address token, uint256 amount, uint256 expiry, uint16 feeBps, address feeRecipient, address expectedPayer) order, bytes signature) payable",
  "function signedOrderDigest((address merchant, bytes32 orderId, address token, uint256 amount, uint256 expiry, uint16 feeBps, address feeRecipient, address expectedPayer) order) view returns (bytes32)",
  // Legacy — register first, then settle (still fully supported)
  "function registerOrder(bytes32 orderId, address token, uint256 amount, uint256 expiry)",
  "function registerOrderWithPayer(bytes32 orderId, address token, uint256 amount, uint256 expiry, address payer)",
  // Pay a pre-registered order — customer wallet
  "function payOrder(address merchant, bytes32 orderId)",
  "function payOrderNative(address merchant, bytes32 orderId) payable",
  // Read — anyone; display a checkout and verify settlement
  "function getOrder(address merchant, bytes32 orderId) view returns (address merchant, bool settled, bool exists, uint16 feeBps, address token, uint256 amount, uint256 expiry, address feeRecipient, uint256 settledAt, address expectedPayer, uint64 nonce)",
  "function isSettled(address merchant, bytes32 orderId) view returns (bool)",
  // Manage — merchant wallet
  "function cancelOrder(bytes32 orderId)",
  "function purgeSettledOrder(bytes32 orderId)",
];

Just want a link, not an integration?

Payment Links and the Gateway API do all of this for you — no keys, no signer, no gas. Use Step 1 only if you are wiring your own checkout.

Legacy: orders registered by the merchant up front still work exactly as before — nothing you already shipped breaks, and they remain payable through this upgrade.

registerOrder.ts (legacy)
import { Contract, Wallet, JsonRpcProvider, id } from 'quais';   // NOT ethers

const provider = new JsonRpcProvider('https://rpc.quai.network', undefined, { usePathing: true });
const wallet   = new Wallet(BACKEND_PRIVATE_KEY, provider);   // your payout wallet
const pay      = new Contract(PAYWITHQUAI_ADDRESS, PAYWITHQUAI_ABI, wallet);

// Cryptographically random order id — Math.random()/timestamps are predictable, and a
// guessed id is a DoS vector on the order-lookup API. Same pattern as the checkout:
const bytes = crypto.getRandomValues(new Uint8Array(24));
const orderId = id('ord_web_' + [...bytes].map((b) => b.toString(16).padStart(2, '0')).join(''));

const amount  = 25000000n;   // $25.00 for a 6-decimal stablecoin; native QUAI = 18 decimals

// registerOrder(orderId, token, amount, expiry)   expiry 0 = never expires
// NOTE: msg.sender becomes the merchant — this payout wallet is the address customers pay to.
const tx = await pay.registerOrder(orderId, TOKEN_ADDRESS, amount, 0n);
await tx.wait();

Step 2

Customer pays

Point the customer at any checkout you own. Submit the order and signature from Step 1 — the settlement call creates the order and pays it in one transaction.

ERC-20 — approve, then pay:

pay.ts
// Customer wallet. ERC-20 needs the approval first, then ONE settlement call
// that creates the order, forwards the funds and marks it settled.
await token.approve(PAYWITHQUAI_ADDRESS, amount);
await pay.paySignedOrder(order, signature);        // no msg.value: the contract pulls the tokens

Native QUAI — send exact value:

pay.ts
// Native: one transaction total, value included.
await pay.paySignedOrder(order, signature, { value: amount });

Legacy orders (registered up front by you) settle without a signature:

payLegacy.ts
await token.approve(PAYWITHQUAI_ADDRESS, amount);   // customer approves exact amount
await pay.payOrder(MERCHANT_ADDRESS, orderId);       // customer pays

await pay.payOrderNative(MERCHANT_ADDRESS, orderId, { value: amount });

The merchant field is your payout wallet — the money lands there. On the checkout page, connect the customer's wallet like this:

connect.ts
// Only these wallets can sign for Quai — detect them in this order:
//   window.quai     → Blip (mobile; injected inside Blip's in-app browser)
//   window.pelagus  → Pelagus (desktop extension)
//   window.ethereum → MetaMask (with Quai network added, chainId 15000)
const provider = new BrowserProvider(window.quai ?? window.pelagus ?? window.ethereum);
const accounts = await provider.send('quai_requestAccounts', []);   // EIP-1193
const payer    = accounts[0];

// MetaMask needs the Quai network first:
await window.ethereum.request({
  method: 'wallet_addEthereumChain',
  params: [{
    chainId: '0x9',   // 9 — Quai mainnet (Cyprus-1 zone)
    chainName: 'Quai Network (Mainnet)',
    nativeCurrency: { name: 'Quai', symbol: 'QUAI', decimals: 18 },
    rpcUrls: ['https://rpc.quai.network'],
    blockExplorerUrls: ['https://explorer.qu.ai'],
  }],
});

One transaction, zero double-fulfillment

The contract verifies the signature, creates the order, splits off the fee, forwards the rest to your wallet, and marks the order settled — all in one transaction that the customer pays for. A second payment reverts, so double-fulfillment is impossible.

Checkout

Read an order on-chain

Every order is a public on-chain record. Build the checkout page URL /checkout/<merchant>/<orderId> and render the total, fee and payer restriction from the contract — never from a client-side cart value.

read-order.ts
// The checkout renders the order FROM THE CHAIN — never trust a client-side
// cart total. getOrder is authoritative for amount, fee and payer restriction.
const provider = new JsonRpcProvider(RPC_URL, undefined, { usePathing: true });
const pay      = new Contract(PAYWITHQUAI_ADDRESS, PAYWITHQUAI_ABI, provider);

const order = await pay.getOrder(MERCHANT_ADDRESS, orderId);
// { merchant, settled, exists, feeBps, token, amount, expiry,
//   feeRecipient, settledAt, expectedPayer, nonce }

if (!order.exists)                 return 'order not found';
if (order.settled)                 return 'already paid';
if (order.expiry > 0n && Date.now() / 1000 > Number(order.expiry)) return 'expired';

const net = order.amount - (order.amount * BigInt(order.feeBps)) / 10000n;
// Display: ${formatQuai(order.amount)} QUAI due · includes ${order.feeBps / 100}% fee ·
//          merchant receives ${formatQuai(net)} QUAI
// expectedPayer != address(0) → only that wallet may pay (payOrder reverts with WrongPayer)

getOrder is the authoritative source for the checkout UI — it works with a read-only provider (no wallet needed). Order states:

  • exists = false → show “order not found” (or fall back to GET /v1/orders/... if the registration tx isn't mined yet)
  • settled = true → show “already paid”, never ask again
  • expiry > 0 and now > expiry → show “expired”, ask the merchant for a fresh link
  • expectedPayer ≠ address(0) → only that wallet can pay; payOrder reverts with WrongPayer

You don't need to build a custom checkout flow. Once an order is registered, you can simply direct customers to the hosted checkout page using a Payment Link.

Even simpler: build links in the dashboard (Links → New link) — pick any supported asset, set a fixed or customer-entered amount, and share the short URL. Customers who pay a link can leave their name, so your payment history shows who paid and for what — expand any row for full details.

payment-link.ts
// Generate a shareable payment link for any registered order
const paymentLink = `${ORIGIN}/checkout/${merchant}/${orderId}`;

// Share via email, SMS, or QR code
console.log("Pay here:", paymentLink);

Zero frontend required

Payment Links automatically handle wallet connection, correct network prompting, Blip Pay mobile integration, and transaction execution. You only need to register the order backend and listen for the webhook.

Blip Pay

Mobile payments & auth with Blip

TripplePay || Merchants natively supports Blip Pay for merchant auth (onboarding/login) and mobile checkouts. Instead of a standard wallet popup, you can present a QR code or deep link that opens the Blip app (iOS & Android) directly.

Encode your checkout page URL in a QR code, or deep-link mobile users into Blip's in-app browser. Both paths call payOrderNative on PayWithQuai — the merchant dashboard updates via webhook, same as a desktop wallet.

blip-link.ts
const checkoutUrl = `${ORIGIN}/checkout/${merchant}/${orderId}`;

// QR — works on any phone (Blip in-app browser or Pelagus / MetaMask in Safari/Chrome)
<QRCode value={checkoutUrl} size={160} />

// Mobile — open checkout inside the Blip app (iOS & Android)
const blipLink = `https://blippay.me/browser?url=${encodeURIComponent(checkoutUrl)}`;

Inside Blip's browser

When the checkout loads inside Blip, window.quai is injected automatically. The customer taps Pay once — the app signs payOrderNative and the relayer POSTs the signed webhook to the merchant.

Do not use blip://pay for registered orders

blip://pay?to=…&amount=… sends QUAI directly to an address and skips PayWithQuai — no order settlement, no webhook. Always route customers through your checkout URL instead.

Automatic detection

When a user browses your checkout, onboarding, or login pages from within the Blip in-app browser, it automatically injects window.quai. You can detect it to seamlessly trigger standard EIP-1193 interactions (connecting, signing, or paying) with just a tap!

Step 3

Receive & verify the webhook

When the payment is final, we POST one webhook to your endpoint:

Webhooks are optional

Only merchants that need automated fulfillment configure a receiver URL. Payment-link sellers without a website don't need one — every payment is verified on-chain and lands directly in the payout wallet, and the dashboard shows it as Confirmed regardless. The webhook is a convenience channel, never the source of truth for settlement.
POST payload
{
  "id":   "0xabc...:3",
  "type": "payment.confirmed",
  "created": 1738340000,
  "data": {
    "merchantId": "mch_ab12...",
    "chainId":    9,               // which configured chain this payment settled on
    "merchant":   "0x00...",       // on-chain payout address
    "orderId":    "0x...",
    "payer":      "0x...",
    "token":      "0x0000000000000000000000000000000000000000",
    "amount":     "25000000",   // gross the payer sent
    "feeBps":     30,           // platform fee rate locked at registration (0.3%)
    "fee":        "75000",      // platform fee = floor(amount × feeBps / 10000)
    "net":        "24925000",   // what you actually received
    "txHash":     "0x...",
    "blockNumber": 1234567,
    "timestamp":  1738340000,  // on-chain settlement time
    "nonce":      1            // per-merchant order nonce; bumps when an order id is reused after a purge
  }
}

Always verify the signature before trusting a webhook, then credit net to the order.

verify.ts
import express from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';

const app = express();
// IMPORTANT: hash the raw body — not parsed-then-restringified JSON.
app.post('/webhooks/paywithquai', express.raw({ type: 'application/json' }), (req, res) => {
  const header = req.header('X-PayWithQuai-Signature') ?? '';        // "t=...,v1=..."
  const raw    = req.body.toString('utf8');
  const { t, v1 } = Object.fromEntries(header.split(',').map((p) => p.split('=')));

  const now = Math.floor(Date.now() / 1000);
  if (Math.abs(now - Number(t)) > 300) return res.sendStatus(400);   // reject stale (>5 min)

  const expected = createHmac('sha256', WEBHOOK_SECRET).update(`${t}.${raw}`).digest();
  const received = Buffer.from(v1, 'hex');
  const ok = received.length === expected.length && timingSafeEqual(received, expected);
  if (!ok) return res.sendStatus(401);

  const { data } = JSON.parse(raw);
  // Idempotent: if you've already fulfilled this orderId/txHash, just ack and return.
  fulfillOrder(data.orderId, data.net);

  res.sendStatus(200);   // 2xx within 10s = success. Anything else is retried.
});

Endpoint requirements

Your endpoint must be https, publicly reachable, respond 2xx within 10s, and be idempotent — the same payment can arrive more than once.

Fulfillment

Confirmation & fulfillment

The checkout waits for the relayer to confirm the webhook — not just on-chain settlement. Poll GET /v1/orders/<merchant>/<orderId> until settled === true && webhook.status === "delivered" (up to ~120s), with an on-chain isSettled fallback when the API is unreachable:

wait-for-confirmation.ts
// After the customer's payOrderNative tx confirms, the relayer re-checks
// settlement and POSTs the signed webhook. Poll until delivered — that's the
// signal to fulfill. On-chain settlement alone is NOT treated as complete.

let settled = false;
const deadline = Date.now() + 120_000;
while (Date.now() < deadline) {
  const res    = await fetch(`https://<platform>/v1/orders/${merchant}/${orderId}`);
  const status = await res.json();
  // { merchant, orderId, token, amount, feeBps, expiry, settled,
  //   webhook: { status: 'pending' | 'delivered' | 'failed', attempts } | null }
  if (status.settled && status.webhook?.status === 'delivered') {
    settled = true;
    break;
  }
  await new Promise((r) => setTimeout(r, 5000));
}

// Fallback if the relayer API is unreachable: pay.isSettled(merchant, orderId)

Fulfill on the signed webhook, not a chain read

A chain read tells you the customer paid — but webhook.status === "delivered" tells you the signed payment.confirmed event reached your endpoint. For order fulfillment (shipping, access, credits) treat the signed webhook as the receipt of record.

Reference

Quick reference

Check an order's status yourself (fallback if you miss a webhook):

GET
GET /v1/orders/0x<merchant>/0x<orderId>
→ {
    merchant, orderId, token, amount, feeBps, expiry, settled,
    webhook: { status: "pending" | "delivered" | "failed", attempts } | null
  }

Common reverts to surface to customers:

RevertMeaning
OrderAlreadySettledalready paid
OrderExpiredpast the expiry timestamp
IncorrectNativeValuemsg.value ≠ the order amount (native path)
WrongPaymentPathused the ERC-20 call on a native order, or vice-versa
OrderNotFoundno such order for that merchant
WrongPayerorder registered with registerOrderWithPayer and you're not the expected payer
OrderAlreadyExiststhis orderId is already registered — use a fresh random id
TokenNotAcceptedtoken isn't allowlisted on the contract
ZeroAmountorder amount was zero

Environment variables (from the reference frontend):

.env
# Client (browser) — MUST be NEXT_PUBLIC_* or it ships as undefined
NEXT_PUBLIC_RPC_URL=https://rpc.quai.network
NEXT_PUBLIC_CHAIN_ID=9                # selects the default chain — see NEXT_PUBLIC_CHAINS below
NEXT_PUBLIC_PAYWITHQUAI_ADDRESS=0x…   # from contracts/deployments/cyprus1.json
NEXT_PUBLIC_MUSDQ_ADDRESS=0x…         # mainnet stablecoin (6 decimals)
NEXT_PUBLIC_USDT_ADDRESS=0x…          # optional override — canonical USDT is built in
NEXT_PUBLIC_WQUAI_ADDRESS=0x…         # optional override — canonical WQUAI is built in
NEXT_PUBLIC_BACKEND_URL=https://tripplepay-three.vercel.app

# Other chains (e.g. Robinhood Chain testnet, already built in) — see src/lib/chains.ts.
# Inline JSON array, merged over the built-in chains by chainId; each link picks ONE of these
# chains at creation time.
# NEXT_PUBLIC_CHAINS=[{"chainId":84532,"slug":"base-sepolia","kind":"evm","name":"Base Sepolia","rpcUrl":"...","contractAddress":"0x...","nativeCurrency":{"name":"Ether","symbol":"ETH","decimals":18}}]

# Server-only — NEVER prefix with NEXT_PUBLIC_ (ships to the browser bundle)
BACKEND_PRIVATE_KEY=...   # payout wallet: signs registrations, receives funds
WEBHOOK_SECRET=...        # shown once at onboarding
ADMIN_API_KEY=...         # relayer admin routes (onboarding)

Managing orders (all from your payout wallet):

  • cancelOrder(orderId) — cancel an unpaid order and free the id.
  • purgeSettledOrder(orderId) — reclaim storage 1 day after settlement.
  • Use a fresh orderId per payment; reusing ids makes status lookups ambiguous.

Mainnet

Deployment & local development

Terminal
# Deploy PayWithQuai to Quai mainnet (chain 9, Cyprus-1 zone):
cd contracts
cp .env.example .env
# Fill in: RPC_URL=https://rpc.quai.network, CHAIN_ID=9, CYPRUS1_PK (funded hot key),
# FEE_RECIPIENT (treasury), STABLECOIN_ADDR, MULTISIG_ADDR, PAUSE_GUARDIAN_ADDR.
npx hardhat run scripts/deploy.js --network cyprus1
# Writes contracts/deployments/cyprus1.json — copy payWithQuai into NEXT_PUBLIC_PAYWITHQUAI_ADDRESS.

Running the platform locally

Backend relayer (indexer + webhook dispatcher + API):cd backend && npm install && cp .env.example .env && npm run devFor local endpoints only, set WEBHOOK_ALLOW_INSECURE_URLS=true to allow http://localhost webhook targets. A throwaway webhook receiver is included: npm run webhook-receiver.

Ready to accept payments?

Set up your merchant profile and connect a settlement wallet.

Get started