Contents

Xcash Documentation

Deploy your own crypto payment gateway from scratch

Xcash is an open-source, self-hosted, non-custodial crypto payment gateway. Collection flows through smart contracts straight to your own collection address — Xcash never touches the funds. This documentation covers the introduction, how it works, deployment, operations and API integration; read it through and you can stand up a complete collection infrastructure of your own.

Introduction

What is Xcash

Xcash is an open-source, self-hosted, non-custodial crypto payment gateway for merchants, SaaS products, exchanges and wallet platforms, providing invoice collection, USDT collection and deposit collection.

Unlike custodial payment processors such as CoinGate or OpenNode, Xcash is non-custodial: collection flows through smart contracts straight to your collection address, Xcash never touches the funds and takes no platform fee — you only pay the small on-chain gas. It suits business systems that need multi-chain collection, deposit collection and Webhook notifications.

Use cases: e-commerce crypto invoice collection, USDT deposit-collection systems, cross-border stablecoin settlement, SaaS crypto subscription billing, on-chain collection infrastructure, and enterprise digital-asset intake management.

Xcash is open source under the MIT license; the code is fully public and auditable. If you would rather not self-host, the official cloud-hosted edition xca.sh is ready to use, zero maintenance.

Invoice collection vs deposit collection

Xcash offers two ways to take funds; understand the distinction before you integrate:

  • Invoice collection: invoice-style collection. Each transaction creates a fixed-amount, time-limited invoice; once the buyer pays, the invoice completes. It suits one-off collection such as e-commerce orders and subscription billing. Invoice collection supports two modes, direct-to-wallet and smart contract: funds can go straight into the project wallet, or a contract collection address can be used and swept automatically after confirmation.
  • Deposit collection: exchange-style deposit collection. Each user gets a dedicated deposit address (the same address on every EVM chain), monitored in real time; users can transfer in anytime and the funds credit after block confirmations — no need to create an order per payment. It suits wallets and trading businesses that maintain user balances.
DimensionInvoice collectionDeposit collection
FormFixed-amount, time-limited one-off invoiceUser-specific, long-lived collection address
Typical scenarioE-commerce orders, subscription billingWallet top-ups, exchange deposits
Order creationAn invoice per transactionGet the address once, transfer in anytime after
AmountInvoice-specified amountAny amount
NotificationOne Webhook when the invoice completesA Webhook on each confirmed receipt

Core features

FeatureDescription
Invoice collectionFixed-amount, time-limited invoice collection for e-commerce orders, subscription billing and similar
Deposit collectionA dedicated deposit address per user; transfer in anytime, credit instantly — an exchange-grade experience
Non-custodialCollection flows through smart contracts straight to your wallet; Xcash never touches the funds
Zero platform feesNo per-transaction cut, only the small on-chain gas
Multi-chain & multi-tokenCovers major EVM chains, supports any ERC-20 token; USDT and TRX on Tron
Multi-merchant & multi-projectIsolate and manage multiple merchants and projects in a single instance
Smart contractInvoices can use contract collection addresses that sweep to your collection address after payment confirmation
On-chain risk controlOptional MistTrack integration to risk-score the source addresses of invoice and deposit collection
Webhook callbacksPushes invoice and deposit collection events in real time
EPay compatibleSupports the standard EPay V1 protocol for a smooth migration
Docker deploymentOne-command Docker Compose deployment for production

Chain & token support

Xcash covers major EVM chains and Tron; both invoice and deposit collection are available:

FeatureETHBNBArbitrumBaseTronPolygonOptimismAvalanche / Linea / Scroll
Invoice collectionYesYesYesYesYesYesYesYes
Deposit collectionYesYesYesYesYesYesYesYes

Ethereum, BNB Smart Chain, Polygon, Arbitrum, Optimism, Base, Tron and the Sepolia and Nile testnets are preset by default; Avalanche, Linea and Scroll must be added manually in the admin. Any other chain requires a code change and cannot be enabled through admin configuration alone.

For tokens:

Chain typeNative assetToken standardCurrent support
EVMETH, BNB, POL, etc. (for paying gas)ERC-20Supports any ERC-20 token; enable USDT, USDC or other on-chain assets as your business needs. Tokens used for invoice collection need a price source (tokens other than USDT, USDC and DAI must have a CoinGecko ID)
TronTRXTRC-20Currently USDT and native TRX are enabled; other TRC-20 tokens are not yet available for collection

The actual chain-token combinations available also depend on what's enabled in the admin, the on-chain token deployment relationships, and the project's collection mode and collection-address configuration. The interface code for each chain is listed under Gateway URL & chain codes.

How it works

Non-custodial security model

Xcash's core design is to completely separate the fund path from the control plane. All collection runs through a smart contract, and the contract hard-wires the fund destination to your collection address. This yields a very strong security guarantee:

Even if the server running Xcash is breached, the database is dumped, or keys leak, funds stay completely safe as long as your collection address is not altered. After service is restored, funds from completed invoice or deposit collection still flow to your collection address — the attacker can do nothing.
Buyerinitiates payment
→
Collection contractdestination hard-wired
→
Your collection addressprivate key only with you
Xcash control plane · API / Worker / Database Only matches invoices, advances states and pushes notifications — it is not on the fund path.
Attacker Even with full control of the Xcash system, they cannot change the fund destination hard-wired into the contract.

This is possible because:

  • Xcash never handles your collection;
  • all collection runs through smart contracts, which hard-wire the fund destination to your collection address;
  • the collection contract is minimal, so the attack surface approaches zero.

System architecture

Xcash is made up of a few components with clear responsibilities; buyers and merchant systems interact with it through the API and Webhooks:

  • Xcash API: exposes endpoints to create invoice collection, query status, get deposit addresses and more — the unified entry point for merchants and buyers.
  • Xcash Worker: handles on-chain transaction monitoring, state transitions and collection scheduling — the core link between the blockchain and business state.
  • Xcash wallet engine: derives the system hot wallet address from a BIP44 HD wallet and signs system transactions such as contract deployment and sweeps. The mnemonic is stored in the database encrypted with AES-256-GCM, with the key kept in .env; back them up together.
  • Xcash Webhook: asynchronously pushes events to the merchant when invoice or deposit collection enters key states.

The fund path only flows along "buyer → collection contract → your collection address"; the components above always act as the control plane and never handle funds. The tech stack:

LayerTechnology
BackendDjango 5.2 + Django REST Framework
Task queueCelery + Redis
DatabasePostgreSQL
Blockchain interactionweb3.py (EVM), TronGrid HTTP API (Tron)
Wallet derivationBIP44 HD wallet (bip-utils)
Invoice collection pageReact 19 + Vite + Tailwind CSS
DeploymentDocker Compose

Two invoice collection modes

Only invoice collection distinguishes between collection modes. Depending on the chain type, two modes are supported; both offer identical fund security, differing only in address form and collection method:

  • Direct-to-wallet (Differ): the system collects to the project's configured direct-collection addresses. The buyer's payable amount (pay_amount) is rounded up to 0.01; when that amount is already taken by pending invoices on every wallet address, a 0.01 increment (up to +0.99) is added to tell invoices apart, so configuring more wallet addresses lets more buyers pay the exact price. Funds go straight into your wallet — no sweep needed. On EVM chains direct-to-wallet does not support native coins (ETH, BNB, etc.); on Tron, TRX is supported.
  • Smart contract (VaultSlot): the system assigns a collection address from the project's contract address pool. Invoices with different amounts can share an address, and a given amount on a given address is assigned to only one invoice at a time, so the amount never needs adjusting. After the buyer's payment is confirmed, the system schedules a sweep that moves the funds into the project's collection address for the matching chain type.

Both EVM and Tron can be used for invoice collection. The mode is configured separately per chain type (EVM / Tron) in the admin and defaults to direct-to-wallet; for a chain type using smart contract mode, you must configure the matching collection address. Deposit collection does not distinguish between these two modes and always uses smart contract mode.

How smart contract mode works

Smart contract mode (VaultSlot) is Xcash's most distinctive mechanism; understanding it helps you understand the whole security model:

  • The address can be determined in advance: each contract collection address is deterministically derived from "factory contract + implementation contract + your collection address + a salt" (CREATE2-style prediction). In other words, the address is computed before the contract is actually deployed on-chain, and the buyer can pay this "counterfactual address" directly.
  • The fund destination is hard-wired: at deployment, your collection address is written into the contract. The contract's sweep method collect() can only move the balance to this hard-wired collection address — nothing has the permission to change the destination.
  • Anyone can trigger the sweep: because collect() only sends funds to the hard-wired collection address, it performs no caller permission check — the trigger only pays gas. So Xcash only needs to maintain a single global system hot wallet to pay the gas for deployment and sweeping.
  • Native coins and tokens: when sweeping a native coin the contract uses address(0) to mean "sweep the current native balance"; when sweeping an ERC-20 it takes the matching token contract address. Tokens and native TRX on Tron can be sent to the undeployed counterfactual address; EVM native coins are detected via the deployed contract's receive() event, so the system deploys the contract in advance when it exposes such an address.
Precisely because the collection address is written into the contract and collect() has no power to redirect, not even Xcash itself can move a buyer's payment elsewhere. This is the technical root of "the funds can't be stolen even if the server is breached".

Gas cost and fund sweeping

Once smart contract collection is enabled, invoice collection uses a contract address pool and each deposit user gets a dedicated contract address. Many addresses do not mean every payment needs an immediate separate gas-paid sweep. Xcash uses two sweep gates to keep sweep frequency and gas cost low:

  • Sweep delay: after a payment is confirmed, the system waits for a configurable delay window before trying to sweep. The default is 60 minutes on EVM chains and 6 hours on Tron; multiple incoming payments to the same address during the window are combined into one sweep.
  • Minimum sweep value: when a sweep becomes due, if that address and asset are still below the value threshold (1 USD by default), the system skips this attempt and keeps accumulating instead of spending more gas on dust.

The system only starts an automatic sweep when both conditions are met: the delay has passed and the balance is large enough. Addresses below the threshold are not discarded; later incoming funds are evaluated again. The sweep delay is set per chain type (EVM / Tron) and the minimum value is global; both are tuned in the admin under System → Runtime Settings.

Xcash keeps the receiving contract minimal: each sweep is essentially the same core action as a normal transfer for that token, so the gas cost is close to a regular token transfer with almost no extra contract overhead.

Sweeping is also permissionless and unrelated to fund safety: collect() has no caller permission check, so any account can trigger a sweep and pay the gas; the destination is already hard-wired to your collection address, and the caller cannot change it. In practice, you only keep a small native-asset balance in the system wallet for sweep gas instead of managing gas for every payment or deposit individually.

Deposit collection mechanism

Deposit collection is for businesses that maintain user balances. Via the API you request a deposit address for a given end user (uid) on a given chain; the same project, same uid and same chain consistently return the same contract address (shared by all tokens on that chain; identical across EVM chains, separate on Tron), so it's convenient to show users an address they can keep using long-term.

Once the user transfers to that address, the Worker detects the on-chain transfer and, when it meets the confirmation requirement, treats it as credited; it then schedules a sweep that moves the funds into the project's collection address for the matching chain type, and pushes a deposit Webhook to your notify URL. The whole process needs no order created per deposit.

Deposit addresses are contract addresses too, so sweeping requires the system hot wallet to keep a little gas / Energy on the matching chain. Deposit collection currently supports EVM and Tron, with USDT and native TRX enabled on Tron.

On-chain risk control (AML)

Xcash has built-in risk querying, caching, recording and display; the current risky-address detection relies on the external MistTrack service, not an in-house blacklist or on-chain risk model. Risk control covers two core fund entry points:

  • Invoice collection: once an invoice is confirmed, it runs an async risk query on the payer's address and syncs the risk level and score to the invoice record.
  • Deposit collection: once a deposit is confirmed, it runs an async risk query on the source address of the incoming funds and syncs the risk level and score to the deposit record.

Risk results are written to a separate risk assessment record (query status, target type, source address, transaction hash, risk level, risk score), viewable directly in the admin for manual review and handling. The invoice query endpoint returns the latest risk_level and risk_score. Webhooks carry these fields too, but as a snapshot at send time: screening runs asynchronously after confirmation, so they are usually null, and no follow-up notification is sent once screening finishes.

Risk control is off by default. Turn on "Enable AML Screening" in the admin under System → Runtime Settings and fill in a MistTrack OpenAPI API key (preferred) or a QuickNode MistTrack endpoint (used as the fallback); only invoices and deposits worth more than the "AML Query Threshold (USD)" are screened.

Deployment

Before you start

Before deploying, prepare the following:

  • A Linux server, ideally Ubuntu 22.04+ or Debian 12+;
  • Docker and Docker Compose;
  • A domain that resolves to the server's IP;
  • RPC node endpoints for the public chains you want to enable;
  • A TronGrid API key if you want to enable Tron collection.

Performance tiers

EVM invoice collection and deposit collection both sense and confirm state via on-chain event scanning, and both are enabled by default and must be monitored together. The number of chains you can actually handle depends on RPC node throughput, block speed and event volume — configure conservatively. The performance tier is controlled by PERFORMANCE in .env, one of low / medium / high; if unset it defaults to low.

Performance modeHardwareChains supported
low1 core / 2 GB2 – 3 EVM chains
medium4 cores / 8 GB8 – 15 EVM chains
high8 cores / 16 GB15 – 30 EVM chains
env
PERFORMANCE=medium

Quick start

1. Clone the project

bash
git clone https://github.com/xca-sh/xcash.git
cd xcash

2. Initialize environment variables

This command generates .env and auto-fills the random secrets and database password needed to run. If .env already exists, the script refuses to overwrite and exits; to regenerate, back up and delete the old file first.

bash
./scripts/init_env.sh

3. Set the access domain

Edit .env to set SITE_DOMAIN:

env
SITE_DOMAIN=xcash.example.com

Make sure the domain's DNS resolves to the server's IP, and configure a reverse proxy such as Nginx or Caddy to forward traffic to http://127.0.0.1:6688, with the reverse proxy handling TLS.

The reverse proxy must forward the real client IP and scheme. Merchant IP allowlists and all rate limits use the real client IP, and HSTS and Secure cookies depend on the scheme. Without them, merchants with an allowlist are all rejected and every rate limit collapses into a single site-wide bucket.

Caddy forwards X-Forwarded-For and X-Forwarded-Proto automatically, so no extra setup is needed:

Caddyfile
xcash.example.com {
    reverse_proxy 127.0.0.1:6688
}

Nginx must set X-Real-IP and X-Forwarded-Proto explicitly. Do not rely on the append-style X-Forwarded-For alone; its leftmost value can be forged by the client:

nginx
location / {
    proxy_pass http://127.0.0.1:6688;
    proxy_set_header Host $host;
    # Real client IP: must use $remote_addr (overwrite semantics)
    proxy_set_header X-Real-IP $remote_addr;
    # Original scheme, required by HSTS and Secure cookies
    proxy_set_header X-Forwarded-Proto $scheme;
}

Optional: set ADMIN_PATH to move the admin entry to a custom path. If unset, the admin stays at the site root and shows a security reminder in the top-right corner of the admin.

env
ADMIN_PATH=secure-admin

4. Start the service

bash
docker compose up -d

The application image is published at ghcr.io/xca-sh/xcash (public) and pulled automatically on first start; nothing is built locally. The start script runs database migrations first and seeds default chains, tokens and other base data.

On the first start, if there's no admin account in the database yet, the system creates the admin account admin with the password from DJANGO_DEFAULT_SUPERUSER_PASSWORD in .env. It is randomly generated by init_env.sh and printed once when the script runs.

Store that password in a password manager. In production, if it is empty, shorter than 12 characters or equal to the sample value shipped in the repo, the system refuses to create the admin and aborts startup. We strongly recommend also setting ADMIN_PATH to hide the admin entry.

Configure chain RPC

The system ships with the basic info for major chains preset, but the RPC node endpoints must be filled in yourself so the gateway can talk to the blockchain. Log in to the admin, go to Blockchain → Chains, and enter an RPC endpoint for each chain you want to use.

We recommend node providers such as QuickNode, Alchemy or Infura. Tron collection requires registering at TronGrid and obtaining an API key.

Fund the system wallet with gas

Log in to the admin, go to System → System wallet, copy the system wallet address, and on each enabled EVM chain top it up with a small amount of native asset to pay gas (e.g. ETH, BNB, POL).

On Tron, deployment and sweeps only consume the system wallet's reserved energy: each broadcast is re-simulated first and waits for more energy if there isn't enough, rather than burning TRX for energy. So provision energy for the system wallet (for example by staking TRX), and keep a little TRX to pay bandwidth fees when bandwidth runs short.

The system wallet is used only for platform infrastructure transactions — for example contract deployment and sweeping, the on-chain operations the system must initiate itself; business collection funds still flow to your collection address per the contract rules. You don't need to deposit business funds here, just keep a small amount of gas to cover recent operations so a low balance doesn't prevent contract deployment or sweep tasks from broadcasting. Sweeping is not triggered once per payment; Xcash batches it through delay and value gates. See Gas cost and fund sweeping.
Even if the system wallet runs low on gas, it causes no security issue. When a sweep transaction can't broadcast, the funds simply sit temporarily in the collection smart contract — the destination is still hard-wired to your collection address and no one can change it. Once gas is topped up, the system resumes sweeping automatically and moves the parked funds into your collection address.

Configure a project

Log in to the admin, go to Projects → Project list, and create or edit a project. A project is the basic isolation unit for API integration; each has its own Appid and HMAC key for endpoint authentication and signing. Confirm at least the following:

  • IP allowlist: restrict which merchant server IPs may call the gateway API; during testing you can use *, but in production narrow it to fixed egress IPs or ranges.
  • Notify URL: receives Webhook events for invoice and deposit collection; if it's not yet configured, the project shows as not ready.
  • Collection address: where smart-contract collection funds ultimately land, configured per chain type. Before enabling smart-contract invoice collection or deposit collection, you must configure the collection address for the matching chain type (EVM / Tron). It is written into the contracts and cannot be changed once set; a multisig wallet is strongly recommended. EVM collection addresses must be checksum addresses; Tron collection addresses must be Base58 addresses.
  • Direct-collection addresses: for direct-to-wallet mode, add your own receiving wallets per chain type under the project's "Direct Wallet Address" tab.

A project is ready only when it has at least one active direct-collection address or collection address, plus an IP allowlist and a notify URL; otherwise the API returns 1004.

Once configured, follow API integration to integrate invoice collection, deposit collection and Webhook callbacks.

Operations

Common commands

Stop the service (stops and removes the production containers, but does not delete the database data volume):

bash
docker compose down

Start / bring the service back up:

bash
docker compose up -d

Upgrade to the latest version

On the main branch, run git pull first to update the compose file and scripts, then run the upgrade script:

bash
git pull
./scripts/upgrade.sh

The script pulls the latest images, runs a migration rehearsal when needed, stops the old services gracefully, applies production migrations and starts the new version, reporting success only after all readiness checks pass. Images are pulled before any service is stopped, so a failed pull does not affect the running service; just run it again. The script requires a clean working tree and never switches branches or updates code itself.

Gas maintenance

Smart contract mode and deposit collection rely on the system hot wallet to initiate contract deployment and sweep transactions on the matching chains. Periodically check the native-asset balance of the system wallet on each enabled chain and keep a small gas reserve. Once gas runs out, contract deployment or sweep tasks can't broadcast — but this does not affect fund security; the funds just sit temporarily in the collection contract and the system resumes sweeping automatically once gas is topped up.

Risk review

The admin lets you view the risk information in invoice and deposit collection records as well as the separate risk-assessment records, making it easy for operators to do manual review, release the business or take further action. The invoice query endpoint returns the latest risk_level and risk_score, so your system can mirror the display or feed your own handling flow.

Screening runs asynchronously after confirmation. The risk fields in a Webhook are usually null, and no follow-up notification is sent once screening finishes; rely on the query endpoint for invoices and on the admin's risk-assessment records for deposits.

API integration

Gateway URL & chain codes

All Django/DRF API routes carry no trailing /; request the paths exactly as shown in the examples.

Self-hosted deployment

The API gateway URL is the SITE_DOMAIN you configured in .env, e.g. https://{your-domain}/v1/invoice; the admin is on the same domain, at /{ADMIN_PATH} when ADMIN_PATH is set.

Xcash official service

PurposeURL
API gatewayhttps://pay.xca.sh (e.g. /v1/invoice)
EPay gatewayhttps://pay.xca.sh/epay/submit.php
SaaS consolehttps://dash.xca.sh

Chains - chain

NameAPI parameterTypeGas tokenChain ID
EthereumethereumEVMETH1
BNB Smart ChainbscEVMBNB56
Polygon PoSpolygonEVMPOL137
Arbitrum Onearbitrum-oneEVMETH42161
OptimismoptimismEVMETH10
BasebaseEVMETH8453
Avalanche C-ChainavalancheEVMAVAX43114
LinealineaEVMETH59144
ScrollscrollEVMETH534352
TrontronTronTRX-
SepoliasepoliaEVM testnetETH11155111
NilenileTron testnetTRX-
Anvil LocalanvilEVM local chainETH31337

Tokens - crypto

crypto uses the token symbol, always uppercase. Common symbols:

NameAPI parameterTypeNotes
Tether USDUSDTStablecoinERC-20 / TRC-20, the most common collection token
USD CoinUSDCStablecoinERC-20, available on several EVM chains
DaiDAIStablecoinERC-20
EtherETHNative coinThe native gas coin of Ethereum and Arbitrum / Optimism / Base
BNBBNBNative coinThe native gas coin of BNB Smart Chain
PolygonPOLNative coinThe native gas coin of Polygon PoS
TRONTRXNative coinThe native gas coin of Tron

The table above is just common examples: EVM chains support any ERC-20 token — add the token contract address in the admin and enable it to collect; the available symbols aren't limited to these. Tron currently only enables USDT and native TRX. The actual chain-token combinations available depend on the chains, tokens and on-chain deployment relationships enabled in the admin; query the currently enabled chains and tokens via the public endpoint GET /v1/metadata. Test projects can only use testnets or local chains; non-test projects can only use mainnet chains.

Fiat - currency

The pricing fiat of an invoice. Built in: USD, CNY, EUR, JPY, HKD (case-sensitive).

Authentication & signing

Except for the public endpoints GET /v1/invoice/{sys_no} and GET /v1/metadata, all /v1/* endpoints require an HMAC-SHA256 signature. After you create a project in the admin, the system generates an appid (e.g. XC-A3BK7NMG) and a 32-character hmac_key.

Request headers

http
XC-Appid: {appid}
XC-Timestamp: {unix_timestamp}
XC-Nonce: {unique_nonce}
XC-Signature: {hmac_signature}
Content-Type: application/json
HeaderDescription
XC-AppidThe project AppID
XC-TimestampCurrent Unix timestamp in seconds; must be within 300 seconds of server time
XC-NonceRandom string, required; must not repeat within 300 seconds under the same AppID
XC-SignatureHMAC-SHA256 signature, lowercase hexadecimal

Signature computation

text
message   = XC-Nonce + XC-Timestamp + request_body
signature = HMAC-SHA256(message, hmac_key).hexdigest()

request_body must be the exact raw request-body string you send; do not re-serialize it after signing. GET requests use the empty string "", and query parameters are not signed.

Signed endpoints check in this order and return on the first failure: 1001 invalid AppID → 1005 project deactivated → 1008 timestamp missing or out of window → 1004 project not ready → 1002 IP not allowlisted → 1003 bad signature → 1000 missing nonce → 1009 repeated nonce.

Python example

python
import hashlib
import hmac
import json
import time
import uuid

import requests

url = "https://pay.xca.sh/v1/invoice"
appid = "XC-A3BK7NMG"
hmac_key = "your_hmac_key"

payload = {
    "out_no": "order-001",
    "title": "Premium Plan",
    "currency": "USD",
    "amount": "29.99",
}
body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
timestamp = str(int(time.time()))
nonce = str(uuid.uuid4())
signature = hmac.new(
    hmac_key.encode(),
    f"{nonce}{timestamp}{body}".encode(),
    hashlib.sha256,
).hexdigest()

headers = {
    "XC-Appid": appid,
    "XC-Timestamp": timestamp,
    "XC-Nonce": nonce,
    "XC-Signature": signature,
    "Content-Type": "application/json",
}

# Send exactly the body you signed (encode only converts it to UTF-8 bytes).
# Do not use json=payload: requests would re-serialize it and break the signature.
requests.post(url, data=body.encode("utf-8"), headers=headers)

Node.js example

javascript
const crypto = require("crypto");

const appid = "XC-A3BK7NMG";
const hmacKey = "your_hmac_key";
const body = JSON.stringify({
  out_no: "order-001",
  title: "Premium Plan",
  currency: "USD",
  amount: "29.99",
});
const timestamp = Math.floor(Date.now() / 1000).toString();
const nonce = crypto.randomUUID();
const signature = crypto
  .createHmac("sha256", hmacKey)
  .update(`${nonce}${timestamp}${body}`)
  .digest("hex");

Responses & error codes

On success the business JSON is returned directly; amounts are always strings and times are ISO 8601 UTC. A business error response:

json
{
  "code": "1001",
  "message": "Invalid AppID",
  "detail": ""
}

Use code to identify the error: message is localized by Accept-Language, and detail may be a string or an object (per-field errors for parameter errors). Framework-level errors (e.g. resource not found 404, method not allowed 405, rate limit 429) return { "detail": "..." }.

Endpoint list

MethodPathDescriptionSignatureRate limit
POST/v1/invoiceCreate invoice collectionRequired256/min per IP
GET/v1/invoice/{sys_no}Query an invoiceNot required120/min per sys_no + IP
GET/v1/deposit/addressGet a deposit addressRequired60/min per appid + IP
GET/v1/metadataChain and token metadataNot required256/min per IP
GET/POST/epay/submit.phpEPay V1 order creationEPay MD560/min per IP

Error codes

Error codeDescriptionHTTP
1000Parameter error400
1001Invalid AppID400
1002IP not allowlisted403
1003Signature error403
1004Project not ready (detail lists the missing settings)400
1005Project deactivated403
1007out_no already exists with different parameters400
1008Timestamp missing or more than 300 seconds off400
1009Repeated nonce400
2000 / 2001 / 2002Invalid chain / invalid token / token not supported on this chain400
4000 / 4001Invalid uid / project has no collection address for this chain type400
4002Deposit user count reached the account limit (official cloud only)403
5000 / 5008 / 5009Unsupported pricing fiat / no available payment method / too many pending invoices400
6004Account frozen (official cloud only)403

Create an invoice

POST /v1/invoice (signature required). Creates an invoice collection; on success it returns a pay_url, and the buyer opens the invoice collection page to pick token, pick chain and pay.

Request parameters

FieldTypeRequiredDescription
out_nostringYesMerchant order number, up to 32 chars, unique within a project (shares a namespace with EPay's out_trade_no)
titlestringYesInvoice title, up to 32 chars
currencystringYesThe pricing fiat code (e.g. USD, CNY); the collection crypto is specified by methods
amountstringYesPriced amount, 0.01 – 1000000, at most 2 decimal places ("10.000" counts as 3 and is rejected)
durationintegerNoValidity in minutes, 5 – 30, default 10
methodsobjectNoRestrict collection methods, format {"token": ["chain code"]}
notify_urlstringNoInvoice-level Webhook URL, takes precedence over the project's default notify URL
return_urlstringNoSynchronous redirect URL after the invoice completes

Rules

  • methods: when omitted, all chain-token combinations currently available to the project are used; when passed, it must be a subset of them, otherwise 5008 is returned (unknown token 2001, unknown chain 2000). The methods in the response is the final effective set.
  • Pricing vs payment: currency only sets the fiat unit of amount; the crypto the buyer actually pays is restricted by methods.
  • Payable amount: the buyer pays pay_amount, which comes from the exchange-rate conversion and may include an increment that tells invoices apart. Do not derive it from amount yourself; the on-chain amount must equal pay_amount exactly to be credited.
  • Idempotency: if out_no already exists and title, currency, amount, notify_url and return_url all match the existing invoice, it is returned (HTTP 200); otherwise 1007.
  • Pending limit: once a project has 100 invoices in waiting, new invoices are rejected (5009).

Request example

json
{
  "out_no": "order-20260602-001",
  "title": "Premium Plan",
  "currency": "USD",
  "amount": "29.99",
  "duration": 15,
  "methods": {
    "USDT": ["ethereum"],
    "USDC": ["base"]
  },
  "notify_url": "https://merchant.example.com/xcash/webhook",
  "return_url": "https://merchant.example.com/payment/success"
}

Restrict the buyer to a single stablecoin (priced in USD + methods restricted to USDT):

json
{
  "out_no": "order-20260602-002",
  "title": "Contract Invoice",
  "currency": "USD",
  "amount": "100",
  "duration": 15,
  "methods": {
    "USDT": ["ethereum", "base"]
  },
  "notify_url": "https://merchant.example.com/xcash/webhook"
}

Response example (HTTP 201)

json
{
  "appid": "XC-A3BK7NMG",
  "sys_no": "INV2606028X7K2P9Q",
  "out_no": "order-20260602-001",
  "title": "Premium Plan",
  "currency": "USD",
  "amount": "29.99",
  "methods": { "USDT": ["ethereum"], "USDC": ["base"] },
  "chain": null,
  "crypto": null,
  "crypto_address": null,
  "pay_address": null,
  "pay_amount": null,
  "pay_url": "https://pay.xca.sh/pay/INV2606028X7K2P9Q",
  "started_at": "2026-06-02T12:00:00.123456Z",
  "created_at": "2026-06-02T12:00:00.123456Z",
  "expires_at": "2026-06-02T12:15:00.123456Z",
  "notify_url": "https://merchant.example.com/xcash/webhook",
  "return_url": "https://merchant.example.com/payment/success",
  "payment": null,
  "status": "waiting",
  "risk_level": null,
  "risk_score": null
}

An omitted notify_url / return_url is returned as an empty string "". If only one collection combination remains, the system selects it automatically at creation time, in which case chain, crypto, pay_address and pay_amount already have values.

Query an invoice

GET /v1/invoice/{sys_no} (public endpoint, no signature needed). Used by the invoice collection page or the buyer side to poll status; it does not return appid, out_no or notify_url; an unknown invoice returns 404.

Key response fields

FieldDescription
sys_noSystem order number; INV + 6-digit date (YYMMDD) + 8 uppercase alphanumerics
chainThe selected chain, null if not selected
cryptoThe selected token, null if not selected
pay_addressThe collection address
pay_amountThe crypto amount the buyer must pay
payment_uriEIP-681 payment URI available on EVM chains; null for non-EVM or when the amount can't be encoded precisely
statuswaiting / completed / expired
paymentThe matched on-chain transfer object, including hash, block, from/to, amount, status (confirming / confirmed), confirm_progress, etc.
risk_levelAML risk level: Low / Moderate / High / Severe
risk_scoreAML risk score

Status

  • waiting: awaiting payment. When a matching transfer is on-chain but not yet confirmed, payment is set while status stays waiting.
  • completed: confirmed, final.
  • expired: expired, but not final: a payment made on-chain before expiry that confirms afterwards still moves the invoice to completed and triggers the Webhook.
  • Invoices worth less than the project's fast-confirm threshold (10 USD by default) confirm as soon as the payment is seen, without waiting for block confirmations.

Get a deposit address

GET /v1/deposit/address (signature required). Gets a deposit address for an end customer under a project; the same project, same uid and same chain consistently return the same address, regardless of crypto.

Although EVM chains return the same address for a given uid, still call this endpoint for each chain + crypto combination rather than reusing an address obtained for another combination: for EVM native coins (ETH, BNB, POL, etc.), the system deploys the address's contract only after this endpoint has been called with crypto set to the native coin, and native coins received before deployment are credited only once deployment completes.

FieldTypeRequiredDescription
uidstringYesEnd-customer identifier, 1 – 128 chars, letters, digits, underscores and hyphens only
chainstringYesChain code, e.g. ethereum, base, tron
cryptostringYesToken symbol, e.g. USDT

Request example

http
GET /v1/deposit/address?uid=user-10001&chain=base&crypto=USDC

When signing a GET request, request_body is the empty string. Response:

json
{
  "deposit_address": "0xAbCd1234..."
}
  • The requested chain, token and the chain-token relationship must all be enabled, and the project's test/mainnet attribute must match the chain; Tron supports only USDT and TRX; a collection address for the matching chain type must be configured (otherwise 4001).
  • EVM native-coin deposit addresses are contracts, so the payer's gas limit must be above 21000 (letting the wallet estimate is enough); transfers hard-coded to 21000 will fail.
  • Common errors: 4000 invalid uid; 2000 chain missing, disabled, mismatched with the project's test attribute, or not supporting deposits for that token; 2001 token missing or disabled; 2002 token not enabled on this chain.

Webhook callbacks

Xcash delivers a Webhook to the merchant when an invoice completes or a deposit is credited. Invoice events go to the notify_url passed at creation, falling back to the project's notify URL; deposit events use the project's notify URL. By default delivery is allowed only to public HTTPS URLs; http, localhost and private addresses fail immediately (self-hosted deployments can allow them with WEBHOOK_ALLOW_INTERNAL_TARGETS=true).

Signature headers

Xcash native-protocol events use POST application/json with HMAC headers; the signing algorithm is the same as for API requests:

http
XC-Appid: {appid}
XC-Nonce: {event_nonce}
XC-Timestamp: {unix_timestamp}
XC-Signature: {hmac_signature}
Content-Type: application/json
  • Verify the signature against the raw request body; do not parse and re-serialize it (JSON key order and spacing are not guaranteed).
  • XC-Nonce stays the same across retries of one event, so use it for idempotent de-duplication; XC-Timestamp is the send time of each attempt.

Response & retries

  • Success response: HTTP 200 with a body that equals ok after trimming whitespace (case-sensitive; EPay V1 notifications use success). Each request times out at 5 seconds.
  • Retried: network errors or timeouts, 5xx, 408, 425, 429. Everything else fails immediately without retry, including 200 with a wrong body, non-200 2xx, 3xx and other 4xx.
  • By default an event is delivered at most 5 times (including the first), with exponential backoff of about 4 / 8 / 16 / 32 seconds (capped at 120 seconds per wait), adjustable under "System → Runtime Settings"; failed events can be redelivered from "Notifications → Notification" in the admin.
  • If the project's notification toggle is off or no notify URL is set, the event is held and retried every 10 minutes, which also counts toward the delivery limit.
  • The retry window is short, so reconcile invoice status with the query endpoint as a fallback.

Invoice collection Webhook

Sent once after the invoice enters completed (confirmed=true):

json
{
  "type": "invoice",
  "data": {
    "sys_no": "INV2606028X7K2P9Q",
    "out_no": "order-20260602-001",
    "crypto": "USDT",
    "chain": "ethereum",
    "pay_address": "0xAbCd1234...",
    "pay_amount": "29.870001",
    "hash": "0xabc123...",
    "block": 12345678,
    "confirmed": true,
    "risk_level": null,
    "risk_score": null
  }
}

Deposit collection Webhook

Sent once after the deposit's on-chain transfer meets the confirmation requirement (confirmed=true); deposits of tokens disabled in the admin are credited without a Webhook:

json
{
  "type": "deposit",
  "data": {
    "sys_no": "DXC2606026K9P2QWX",
    "uid": "user-10001",
    "chain": "base",
    "block": 12345678,
    "hash": "0xabc123...",
    "crypto": "USDC",
    "amount": "500",
    "confirmed": true,
    "risk_level": null,
    "risk_score": null
  }
}

risk_level / risk_score are a snapshot at send time. AML screening runs asynchronously after confirmation, so they are usually null in Webhooks, and no follow-up notification is sent once screening finishes.

EPay V1 compatibility

Xcash provides an EPay V1 compatible entry point that works with common EPay plugins for Typecho, WordPress, Discuz and more. The EPay entry does not use Xcash HMAC headers; it uses EPay's own MD5 signature. For WooCommerce stores, use the official WooCommerce plugin instead.

Create an order

GET /epay/submit.php or POST /epay/submit.php. For POST, use application/x-www-form-urlencoded or multipart/form-data form encoding — do not send JSON. Core parameters: pid, out_trade_no, notify_url, name, money, sign, sign_type=MD5; optional currency (default CNY), param, return_url, type.

  • money ranges from 0.01 to 1000000 with at most 2 decimal places; out_trade_no is up to 64 chars, unique within a project, and shares a namespace with out_no of /v1/invoice.
  • type does not restrict chain or token; the buyer can choose any payment method available to the project on the payment page. The invoice is valid for a fixed 15 minutes.
  • Resubmitting the same out_trade_no with identical order parameters returns the same invoice; different parameters fail.
  • pid and secret_key: on the official cloud, find them in the console; when self-hosting, add them under "EPay Configuration" on the project page in the admin.

EPay signature

  1. Drop sign and sign_type;
  2. drop fields whose value is null or empty string;
  3. sort by field name in ascending ASCII order;
  4. concatenate key=value, joined by &;
  5. append secret_key directly at the end;
  6. MD5 the whole string and output lowercase hexadecimal.
python
import hashlib

params = {
    "pid": "1001",
    "out_trade_no": "order-001",
    "notify_url": "https://merchant.example.com/epay/notify",
    "return_url": "https://merchant.example.com/epay/return",
    "name": "Premium Plan",
    "money": "29.99",
    "sign_type": "MD5",
}

filtered = {
    k: str(v)
    for k, v in params.items()
    if k not in {"sign", "sign_type"} and v not in (None, "")
}
sign_string = "&".join(f"{k}={v}" for k, v in sorted(filtered.items()))
secret_key = "your_epay_secret_key"
params["sign"] = hashlib.md5(
    f"{sign_string}{secret_key}".encode("utf-8"),
    usedforsecurity=False,
).hexdigest()

Response & notification

  • Success: HTTP 302, redirect to the invoice collection page /pay/{sys_no}; failure: HTTP 400, plain text fail (no reason given); rate limited: HTTP 429.
  • After the invoice completes, Xcash sends a GET notification to notify_url with pid, trade_no (the sys_no), out_trade_no, type, name, money, trade_status=TRADE_SUCCESS, param (only when set), sign_type and sign, signed with the same algorithm. A merchant response of HTTP 200 with body success counts as success; retries follow the Webhook rules.
  • Core fulfillment logic should rely on the async notification; the synchronous redirect only signals that the invoice collection page flow is finished.

Plugins

WooCommerce plugin

The official Xcash for WooCommerce plugin is listed in the WordPress.org plugin directory. WooCommerce stores can accept invoice payments without writing any code: the plugin creates an Xcash invoice for each order, sends the buyer to the hosted payment page, and marks the order paid automatically through a signed webhook.

Requirements

DependencyMinimum version
WordPress5.8
WooCommerce5.0
PHP7.4

The plugin supports WooCommerce Checkout Blocks, the classic shortcode checkout and HPOS (high-performance order storage).

Installation

  1. Sign in to your WordPress admin and go to Plugins → Add New.
  2. Search for Xcash for WooCommerce, click Install Now, then Activate.
Install the official plugin from your WordPress admin or the WordPress.org plugin page: new releases then show up in your dashboard's update list and upgrade in one click.

Configuration

Go to WooCommerce → Settings → Payments, enable Xcash and click Manage:

SettingDescription
App ID / HMAC keyCopy them from your project settings in the console
Gateway URLDefaults to https://pay.xca.sh; keep the default when using the official service
Invoice currencyFollows your WooCommerce store currency automatically; must be one of USD, CNY, EUR, JPY or HKD
Allowed payment methodsOptional JSON that limits coin-chain pairs, e.g. {"USDT": ["ethereum", "tron"]}; leave empty to offer every pair enabled in the project
Payment durationInvoice lifetime, 5 – 30 minutes, default 20
Title and descriptionThe payment method name and text shown to buyers at checkout

After saving, click Test Configuration to validate your credentials, store currency and payment methods without placing a real order. The project itself must also be ready (see Configure a project), and its IP allowlist must include your WordPress server's outbound IP.

Webhook

When creating an invoice the plugin automatically passes https://your-site.com/?wc-api=xcash_webhook as the invoice-level notify_url, so there is nothing to fill in. Incoming notifications are verified with the HMAC signature and deduplicated by nonce and invoice; on success the plugin replies ok and shows the chain, coin, amount and transaction hash on the order screen.

  • Keep notifications enabled for the project in the console, and make sure your site is reachable over public HTTPS.
  • Failed notifications can be resent from the console.

Troubleshooting

  • If Test Configuration fails, check that the credentials are filled in, the store currency is supported, and the payment-method JSON is valid and enabled in your project.
  • With debug logging on, plugin logs appear under WooCommerce → Status → Logs.
  • The plugin UI switches to Simplified Chinese automatically when the site language is set to it; English is the default otherwise.

More

FAQ & support

Full invoice collection flow

text
Merchant server -> Xcash:  POST /v1/invoice
Xcash -> Merchant server:  returns sys_no / pay_url
Buyer -> Xcash:            opens pay_url, picks token & chain
Buyer -> Blockchain:       sends the transfer
Xcash -> Merchant server:  Webhook invoice
Merchant server -> Xcash:  ok

Full deposit collection flow

text
Merchant server -> Xcash:  GET /v1/deposit/address
Xcash -> Merchant server:  returns deposit_address
Merchant system -> User:   shows deposit_address
User -> Blockchain:        sends the transfer
Xcash -> Merchant server:  Webhook deposit
Merchant server -> Xcash:  ok

Does Xcash charge fees?

The open-source edition is completely free (MIT license) with zero platform fees — you only pay on-chain gas. If you'd rather not self-host, an official cloud-hosted edition is available (pay as you go, no monthly fee); see pricing. Either way, collection flows through smart contracts straight to your collection address.

Do funds pass through Xcash?

No. The fund destination is hard-wired to your collection address in the smart contract; Xcash never holds, handles or can move the crypto you collect. See Non-custodial security model.

Getting support

Run into a deployment or integration issue? Open an issue on GitHub, or email [email protected] for commercial technical support. You can also refer to the README and API.md in the repository.