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
Register an order
Your backend registers the expected payment on-chain.
Customer pays
One contract call — ERC-20 or native QUAI.
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 receive | What it's for |
|---|---|
| PAYWITHQUAI_ADDRESS | The contract address you register orders on |
| webhookSecret | Secret key to verify webhooks are really from us(shown once — store it safely) |
| merchantId | Your platform id, e.g. mch_ab12... |
Quai mainnet (chain 9)
Use the `quais` package, not ethers
Same zone — this matters
Amounts are in the token's smallest unit
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:
| Asset | Address | Decimals | Notes |
|---|---|---|---|
| QUAI | address(0) | 18 | Native gas asset — always accepted |
| USDT | 0x0049F7cbCa3556C2DfaE62Aafa7015F99de1b8f5 | 6 | Tether USD — canonical mainnet token |
| WQUAI | 0x006C3e2AaAE5DB1bCd11A1a097cE572312EADdBB | 18 | Wrapped Quai — ERC-20 form of QUAI |
| mUSDQ | 0x003fafB5126a5296c6edC7C23De55daf2E84B503 | 6 | Mock stablecoin — testnet faucet only |
Registry-driven frontend
Tokens must be allowlisted on the contract
Blip pays every listed asset
Step 1
Authorize the order (from your backend)
npm install quais # Quai's ethers fork — usePathing, formatQuai, parseQuaiOrders 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.
// 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.
// 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' },
];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?
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.
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:
// 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 tokensNative QUAI — send exact value:
// Native: one transaction total, value included.
await pay.paySignedOrder(order, signature, { value: amount });Legacy orders (registered up front by you) settle without a signature:
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:
// 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
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.
// 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
Shareable Checkouts
Payment Links
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.
// 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
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.
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
Do not use blip://pay for registered orders
Automatic detection
Step 3
Receive & verify the webhook
When the payment is final, we POST one webhook to your endpoint:
Webhooks are optional
{
"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.
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
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:
// 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
Reference
Quick reference
Check an order's status yourself (fallback if you miss a webhook):
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:
| Revert | Meaning |
|---|---|
| OrderAlreadySettled | already paid |
| OrderExpired | past the expiry timestamp |
| IncorrectNativeValue | msg.value ≠ the order amount (native path) |
| WrongPaymentPath | used the ERC-20 call on a native order, or vice-versa |
| OrderNotFound | no such order for that merchant |
| WrongPayer | order registered with registerOrderWithPayer and you're not the expected payer |
| OrderAlreadyExists | this orderId is already registered — use a fresh random id |
| TokenNotAccepted | token isn't allowlisted on the contract |
| ZeroAmount | order amount was zero |
Environment variables (from the reference frontend):
# 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
# 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
Ready to accept payments?
Set up your merchant profile and connect a settlement wallet.