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.
| Dimension | Invoice collection | Deposit collection |
|---|---|---|
| Form | Fixed-amount, time-limited one-off invoice | User-specific, long-lived collection address |
| Typical scenario | E-commerce orders, subscription billing | Wallet top-ups, exchange deposits |
| Order creation | An invoice per transaction | Get the address once, transfer in anytime after |
| Amount | Invoice-specified amount | Any amount |
| Notification | One Webhook when the invoice completes | A Webhook on each confirmed receipt |
Core features
| Feature | Description |
|---|---|
| Invoice collection | Fixed-amount, time-limited invoice collection for e-commerce orders, subscription billing and similar |
| Deposit collection | A dedicated deposit address per user; transfer in anytime, credit instantly — an exchange-grade experience |
| Non-custodial | Collection flows through smart contracts straight to your wallet; Xcash never touches the funds |
| Zero platform fees | No per-transaction cut, only the small on-chain gas |
| Multi-chain & multi-token | Covers major EVM chains, supports any ERC-20 token; USDT and TRX on Tron |
| Multi-merchant & multi-project | Isolate and manage multiple merchants and projects in a single instance |
| Smart contract | Invoices can use contract collection addresses that sweep to your collection address after payment confirmation |
| On-chain risk control | Optional MistTrack integration to risk-score the source addresses of invoice and deposit collection |
| Webhook callbacks | Pushes invoice and deposit collection events in real time |
| EPay compatible | Supports the standard EPay V1 protocol for a smooth migration |
| Docker deployment | One-command Docker Compose deployment for production |
Chain & token support
Xcash covers major EVM chains and Tron; both invoice and deposit collection are available:
| Feature | ETH | BNB | Arbitrum | Base | Tron | Polygon | Optimism | Avalanche / Linea / Scroll |
|---|---|---|---|---|---|---|---|---|
| Invoice collection | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| Deposit collection | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
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 type | Native asset | Token standard | Current support |
|---|---|---|---|
| EVM | ETH, BNB, POL, etc. (for paying gas) | ERC-20 | Supports 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) |
| Tron | TRX | TRC-20 | Currently 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.
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:
| Layer | Technology |
|---|---|
| Backend | Django 5.2 + Django REST Framework |
| Task queue | Celery + Redis |
| Database | PostgreSQL |
| Blockchain interaction | web3.py (EVM), TronGrid HTTP API (Tron) |
| Wallet derivation | BIP44 HD wallet (bip-utils) |
| Invoice collection page | React 19 + Vite + Tailwind CSS |
| Deployment | Docker 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'sreceive()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 mode | Hardware | Chains supported |
|---|---|---|
| low | 1 core / 2 GB | 2 – 3 EVM chains |
| medium | 4 cores / 8 GB | 8 – 15 EVM chains |
| high | 8 cores / 16 GB | 15 – 30 EVM chains |
PERFORMANCE=medium Quick start
1. Clone the project
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.
./scripts/init_env.sh 3. Set the access domain
Edit .env to set SITE_DOMAIN:
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:
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:
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.
ADMIN_PATH=secure-admin 4. Start the service
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):
docker compose down Start / bring the service back up:
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:
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
| Purpose | URL |
|---|---|
| API gateway | https://pay.xca.sh (e.g. /v1/invoice) |
| EPay gateway | https://pay.xca.sh/epay/submit.php |
| SaaS console | https://dash.xca.sh |
Chains - chain
| Name | API parameter | Type | Gas token | Chain ID |
|---|---|---|---|---|
| Ethereum | ethereum | EVM | ETH | 1 |
| BNB Smart Chain | bsc | EVM | BNB | 56 |
| Polygon PoS | polygon | EVM | POL | 137 |
| Arbitrum One | arbitrum-one | EVM | ETH | 42161 |
| Optimism | optimism | EVM | ETH | 10 |
| Base | base | EVM | ETH | 8453 |
| Avalanche C-Chain | avalanche | EVM | AVAX | 43114 |
| Linea | linea | EVM | ETH | 59144 |
| Scroll | scroll | EVM | ETH | 534352 |
| Tron | tron | Tron | TRX | - |
| Sepolia | sepolia | EVM testnet | ETH | 11155111 |
| Nile | nile | Tron testnet | TRX | - |
| Anvil Local | anvil | EVM local chain | ETH | 31337 |
Tokens - crypto
crypto uses the token symbol, always uppercase. Common symbols:
| Name | API parameter | Type | Notes |
|---|---|---|---|
| Tether USD | USDT | Stablecoin | ERC-20 / TRC-20, the most common collection token |
| USD Coin | USDC | Stablecoin | ERC-20, available on several EVM chains |
| Dai | DAI | Stablecoin | ERC-20 |
| Ether | ETH | Native coin | The native gas coin of Ethereum and Arbitrum / Optimism / Base |
| BNB | BNB | Native coin | The native gas coin of BNB Smart Chain |
| Polygon | POL | Native coin | The native gas coin of Polygon PoS |
| TRON | TRX | Native coin | The 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
XC-Appid: {appid}
XC-Timestamp: {unix_timestamp}
XC-Nonce: {unique_nonce}
XC-Signature: {hmac_signature}
Content-Type: application/json | Header | Description |
|---|---|
XC-Appid | The project AppID |
XC-Timestamp | Current Unix timestamp in seconds; must be within 300 seconds of server time |
XC-Nonce | Random string, required; must not repeat within 300 seconds under the same AppID |
XC-Signature | HMAC-SHA256 signature, lowercase hexadecimal |
Signature computation
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
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
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:
{
"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
| Method | Path | Description | Signature | Rate limit |
|---|---|---|---|---|
| POST | /v1/invoice | Create invoice collection | Required | 256/min per IP |
| GET | /v1/invoice/{sys_no} | Query an invoice | Not required | 120/min per sys_no + IP |
| GET | /v1/deposit/address | Get a deposit address | Required | 60/min per appid + IP |
| GET | /v1/metadata | Chain and token metadata | Not required | 256/min per IP |
| GET/POST | /epay/submit.php | EPay V1 order creation | EPay MD5 | 60/min per IP |
Error codes
| Error code | Description | HTTP |
|---|---|---|
| 1000 | Parameter error | 400 |
| 1001 | Invalid AppID | 400 |
| 1002 | IP not allowlisted | 403 |
| 1003 | Signature error | 403 |
| 1004 | Project not ready (detail lists the missing settings) | 400 |
| 1005 | Project deactivated | 403 |
| 1007 | out_no already exists with different parameters | 400 |
| 1008 | Timestamp missing or more than 300 seconds off | 400 |
| 1009 | Repeated nonce | 400 |
| 2000 / 2001 / 2002 | Invalid chain / invalid token / token not supported on this chain | 400 |
| 4000 / 4001 | Invalid uid / project has no collection address for this chain type | 400 |
| 4002 | Deposit user count reached the account limit (official cloud only) | 403 |
| 5000 / 5008 / 5009 | Unsupported pricing fiat / no available payment method / too many pending invoices | 400 |
| 6004 | Account 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
| Field | Type | Required | Description |
|---|---|---|---|
out_no | string | Yes | Merchant order number, up to 32 chars, unique within a project (shares a namespace with EPay's out_trade_no) |
title | string | Yes | Invoice title, up to 32 chars |
currency | string | Yes | The pricing fiat code (e.g. USD, CNY); the collection crypto is specified by methods |
amount | string | Yes | Priced amount, 0.01 – 1000000, at most 2 decimal places ("10.000" counts as 3 and is rejected) |
duration | integer | No | Validity in minutes, 5 – 30, default 10 |
methods | object | No | Restrict collection methods, format {"token": ["chain code"]} |
notify_url | string | No | Invoice-level Webhook URL, takes precedence over the project's default notify URL |
return_url | string | No | Synchronous 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
5008is returned (unknown token2001, unknown chain2000). Themethodsin the response is the final effective set. - Pricing vs payment:
currencyonly sets the fiat unit ofamount; the crypto the buyer actually pays is restricted bymethods. - 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 fromamountyourself; the on-chain amount must equalpay_amountexactly to be credited. - Idempotency: if
out_noalready exists andtitle,currency,amount,notify_urlandreturn_urlall match the existing invoice, it is returned (HTTP200); otherwise1007. - Pending limit: once a project has 100 invoices in
waiting, new invoices are rejected (5009).
Request example
{
"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):
{
"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)
{
"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
| Field | Description |
|---|---|
sys_no | System order number; INV + 6-digit date (YYMMDD) + 8 uppercase alphanumerics |
chain | The selected chain, null if not selected |
crypto | The selected token, null if not selected |
pay_address | The collection address |
pay_amount | The crypto amount the buyer must pay |
payment_uri | EIP-681 payment URI available on EVM chains; null for non-EVM or when the amount can't be encoded precisely |
status | waiting / completed / expired |
payment | The matched on-chain transfer object, including hash, block, from/to, amount, status (confirming / confirmed), confirm_progress, etc. |
risk_level | AML risk level: Low / Moderate / High / Severe |
risk_score | AML risk score |
Status
waiting: awaiting payment. When a matching transfer is on-chain but not yet confirmed,paymentis set whilestatusstayswaiting.completed: confirmed, final.expired: expired, but not final: a payment made on-chain before expiry that confirms afterwards still moves the invoice tocompletedand 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.
| Field | Type | Required | Description |
|---|---|---|---|
uid | string | Yes | End-customer identifier, 1 – 128 chars, letters, digits, underscores and hyphens only |
chain | string | Yes | Chain code, e.g. ethereum, base, tron |
crypto | string | Yes | Token symbol, e.g. USDT |
Request example
GET /v1/deposit/address?uid=user-10001&chain=base&crypto=USDC When signing a GET request, request_body is the empty string. Response:
{
"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
USDTandTRX; a collection address for the matching chain type must be configured (otherwise4001). - 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:
4000invalid uid;2000chain missing, disabled, mismatched with the project's test attribute, or not supporting deposits for that token;2001token missing or disabled;2002token 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:
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-Noncestays the same across retries of one event, so use it for idempotent de-duplication;XC-Timestampis the send time of each attempt.
Response & retries
- Success response: HTTP
200with a body that equalsokafter trimming whitespace (case-sensitive; EPay V1 notifications usesuccess). Each request times out at 5 seconds. - Retried: network errors or timeouts,
5xx,408,425,429. Everything else fails immediately without retry, including200with a wrong body, non-2002xx,3xxand other4xx. - 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):
{
"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:
{
"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.
moneyranges from 0.01 to 1000000 with at most 2 decimal places;out_trade_nois up to 64 chars, unique within a project, and shares a namespace without_noof/v1/invoice.typedoes 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_nowith identical order parameters returns the same invoice; different parameters fail. pidandsecret_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
- Drop
signandsign_type; - drop fields whose value is
nullor empty string; - sort by field name in ascending ASCII order;
- concatenate
key=value, joined by&; - append
secret_keydirectly at the end; - MD5 the whole string and output lowercase hexadecimal.
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: HTTP400, plain textfail(no reason given); rate limited: HTTP429. - After the invoice completes, Xcash sends a GET notification to
notify_urlwithpid,trade_no(thesys_no),out_trade_no,type,name,money,trade_status=TRADE_SUCCESS,param(only when set),sign_typeandsign, signed with the same algorithm. A merchant response of HTTP200with bodysuccesscounts 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
| Dependency | Minimum version |
|---|---|
| WordPress | 5.8 |
| WooCommerce | 5.0 |
| PHP | 7.4 |
The plugin supports WooCommerce Checkout Blocks, the classic shortcode checkout and HPOS (high-performance order storage).
Installation
- Sign in to your WordPress admin and go to Plugins → Add New.
- 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:
| Setting | Description |
|---|---|
| App ID / HMAC key | Copy them from your project settings in the console |
| Gateway URL | Defaults to https://pay.xca.sh; keep the default when using the official service |
| Invoice currency | Follows your WooCommerce store currency automatically; must be one of USD, CNY, EUR, JPY or HKD |
| Allowed payment methods | Optional JSON that limits coin-chain pairs, e.g. {"USDT": ["ethereum", "tron"]}; leave empty to offer every pair enabled in the project |
| Payment duration | Invoice lifetime, 5 – 30 minutes, default 20 |
| Title and description | The 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
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
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.