=============== LIBRARY RULES =============== From library maintainers: - Call the API only from a server: the x-tenant-api-key header must never appear in frontend code. - Use a new, unique orderId for each invoice; it is the idempotency key. - Verify x-webhook-signature against the raw request body before parsing JSON; reject the webhook if verification fails. - Fulfil orders on invoice.statusChanged webhooks (paid, partially_paid, overpaid), not on the customer returning to successUrl. - For pay-per-request APIs, use the x402 packages with Cryptonly as the facilitator instead of invoices. ### Install buyer packages Source: https://docs.cryptonly.net/guides/x402/quickstart Install the required packages for the buyer to make a paid call. Requires a buyer wallet with USDC on Base and the private key in `BUYER_PRIVATE_KEY`. ```bash npm install @x402/fetch @x402/evm viem ``` -------------------------------- ### Install Fastify middleware packages Source: https://docs.cryptonly.net/guides/x402/quickstart Install the required packages for the Fastify middleware. Requires Node.js 18 or later and a Cryptonly account with business verification approved. ```bash npm install @cryptonly/x402-fastify @x402/core @x402/fastify @x402/evm fastify ``` -------------------------------- ### Install Express middleware packages Source: https://docs.cryptonly.net/guides/x402/quickstart Install the required packages for the Express middleware. Requires Node.js 18 or later and a Cryptonly account with business verification approved. ```bash npm install @cryptonly/x402-express @x402/core @x402/express @x402/evm express ``` -------------------------------- ### Go buyer client using x402http.WrapHTTPClientWithPayment Source: https://docs.cryptonly.net/guides/x402/reference Go example that creates a signer from BUYER_PRIVATE_KEY, registers an EVM scheme, and makes a paid HTTP GET request to an x402 endpoint. ```go package main "fmt" "io" "net/http" "os" x402 "github.com/x402-foundation/x402/go" x402http "github.com/x402-foundation/x402/go/http" evm "github.com/x402-foundation/x402/go/mechanisms/evm/exact/client" evmsigners "github.com/x402-foundation/x402/go/signers/evm" ) func main() { signer, err := evmsigners.NewClientSignerFromPrivateKey(os.Getenv("BUYER_PRIVATE_KEY")) if err != nil { panic(err) } client := x402.Newx402Client().Register("eip155:*", evm.NewExactEvmScheme(signer, nil)) pay := x402http.WrapHTTPClientWithPayment(http.DefaultClient, x402http.Newx402HTTPClient(client)) resp, err := pay.Get("http://localhost:4021/v1/weather/paris") if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(resp.StatusCode, string(body)) } ``` -------------------------------- ### Fastify middleware setup Source: https://docs.cryptonly.net/guides/x402/quickstart Registers the Cryptonly payment plugin with a Fastify app. The middleware loads prices from the dashboard and refreshes every minute. `app.cryptonlyX402.ready()` fails at startup if prices can't load. ```ts const app = Fastify(); await app.register(cryptonlyPayments, { apiKey: process.env.CRYPTONLY_API_KEY!, }); app.get('/v1/weather/:city', async (request) => { const { city } = request.params as { city: string }; return { city, temperatureC: 21 }; }); await app.cryptonlyX402.ready(); // fails at startup if the prices can't load await app.listen({ port: 4021 }); ``` -------------------------------- ### Install x402 Go package Source: https://docs.cryptonly.net/guides/x402/reference Install the x402 Go client library. ```bash go get github.com/x402-foundation/x402/go ``` -------------------------------- ### Express middleware setup Source: https://docs.cryptonly.net/guides/x402/quickstart Adds the Cryptonly payment middleware to an Express app. Free routes must be defined before the middleware. The middleware loads prices from the dashboard and refreshes every minute. `payments.ready()` fails at startup if prices can't load. ```ts const app = express(); app.get('/health', (_req, res) => res.send('ok')); // free routes go first const payments = cryptonlyPaymentMiddleware({ apiKey: process.env.CRYPTONLY_API_KEY!, }); app.use(payments); app.get('/v1/weather/:city', (req, res) => { res.json({ city: req.params.city, temperatureC: 21 }); }); await payments.ready(); // fails at startup if the prices can't load app.listen(4021); ``` -------------------------------- ### Python: Register Bazaar extension and configure routes Source: https://docs.cryptonly.net/guides/x402/discovery Installs the x402 extensions package and registers the Bazaar resource server extension. Defines a route configuration with an exact payment option, description, tags, and discovery output example. ```Python # pip install "x402[extensions]" from x402.extensions.bazaar import OutputConfig, bazaar_resource_server_extension, declare_discovery_extension server.register_extension(bazaar_resource_server_extension) routes = { "GET /v1/quote/:symbol": RouteConfig( accepts=PaymentOption(scheme="exact", price="$0.005", network="eip155:8453", pay_to=os.environ["PAY_TO"]), description="Token price quote", tags=["finance", "prices"], extensions=declare_discovery_extension(output=OutputConfig(example={"symbol": "SOL", "usd": 150.25})), ), } ``` -------------------------------- ### Python buyer client using x402Client and wrapHttpxWithPayment Source: https://docs.cryptonly.net/guides/x402/reference Python example that registers an EVM signer and makes a paid HTTP GET request to an x402 endpoint. Requires BUYER_PRIVATE_KEY environment variable. ```python from eth_account import Account from x402 import x402Client from x402.http.clients import wrapHttpxWithPayment from x402.mechanisms.evm.exact import register_exact_evm_client from x402.mechanisms.evm.signers import EthAccountSigner client = x402Client() register_exact_evm_client(client, EthAccountSigner(Account.from_key(os.environ["BUYER_PRIVATE_KEY"]))) async def main(): async with wrapHttpxWithPayment(client) as http: response = await http.get("http://localhost:4021/v1/weather/paris") print(response.status_code, response.json()) asyncio.run(main()) ``` -------------------------------- ### NestJS middleware setup Source: https://docs.cryptonly.net/guides/x402/quickstart Configures the Cryptonly payment module in a NestJS app. Only handlers with `@X402()` ask for payment. The price comes from the dashboard. Works on both Express and Fastify platforms. Listen on port 4021 in `main.ts`. ```ts @Controller('v1/weather') class WeatherController { @X402() // the price comes from the dashboard @Get(':city') get(@Param('city') city: string) { return { city, temperatureC: 21 }; } } @Module({ imports: [ X402Module.forRoot({ apiKey: process.env.CRYPTONLY_API_KEY!, isGlobal: true }), ], controllers: [WeatherController], }) export class AppModule {} ``` -------------------------------- ### Install x402 Python package Source: https://docs.cryptonly.net/guides/x402/reference Install the x402 Python client with HTTPX and EVM support. ```bash pip install "x402[httpx,evm]" ``` -------------------------------- ### Install Go dependencies for Cryptonly x402 Source: https://docs.cryptonly.net/guides/x402/prices-in-code Install the required Go packages for using the stock x402 HTTP facilitator client with Gin. ```bash go get github.com/x402-foundation/x402/go github.com/gin-gonic/gin ``` -------------------------------- ### Install Vendure Cryptonly Plugin Source: https://docs.cryptonly.net/integration/plugins/vendure Install the plugin via npm. Requires Vendure 3.8+ and Node 22.12+. ```bash npm install @cryptonly/vendure-plugin-cryptonly ``` -------------------------------- ### Check endpoint returns 402 Source: https://docs.cryptonly.net/guides/x402/quickstart Curl command to verify the endpoint asks for payment. Expected response is `HTTP/1.1 402 Payment Required`. ```bash curl -i http://localhost:4021/v1/weather/paris # HTTP/1.1 402 Payment Required ``` -------------------------------- ### Make a paid call as buyer Source: https://docs.cryptonly.net/guides/x402/quickstart Uses the buyer's private key to pay for the endpoint. The response status should be 200 with the weather data. The buyer wallet needs USDC on Base but no ETH. ```ts const account = privateKeyToAccount(process.env.BUYER_PRIVATE_KEY as `0x${string}`); const publicClient = createPublicClient({ chain: base, transport: http() }); const pay = wrapFetchWithPaymentFromConfig(fetch, { schemes: [ { network: 'eip155:8453', client: new ExactEvmScheme(toClientEvmSigner(account, publicClient)) }, ], }); const response = await pay('http://localhost:4021/v1/weather/paris'); console.log(response.status, await response.json()); // 200 { city: 'paris', temperatureC: 21 } ``` -------------------------------- ### Fetch discovery resources with Python x402 SDK Source: https://docs.cryptonly.net/guides/x402/discovery Python client using the x402 extensions package to list resources. Requires pip install "x402[extensions]". ```python # pip install "x402[extensions]" from x402.extensions.bazaar import with_bazaar from x402.http import FacilitatorConfig, HTTPFacilitatorClientSync client = with_bazaar(HTTPFacilitatorClientSync(FacilitatorConfig(url="https://api.cryptonly.net/x402"))) items = client.extensions.bazaar.list_resources().items ``` -------------------------------- ### Install Cryptonly Medusa Plugin Source: https://docs.cryptonly.net/integration/plugins/medusa Install the @cryptonly/medusa-plugin-cryptonly package via npm. Requires Medusa v2.8+ and Node 20+. ```bash npm install @cryptonly/medusa-plugin-cryptonly ``` -------------------------------- ### GET /x402/config Source: https://docs.cryptonly.net/api-reference/openapi Gets x402 configuration. ```APIDOC ## GET /x402/config ### Description Gets x402 configuration. ### Method GET ### Endpoint /x402/config ``` -------------------------------- ### Install @cryptonly/sdk via npm Source: https://docs.cryptonly.net/integration/sdk Install the official JavaScript/TypeScript SDK for the Cryptonly merchant API from npm. ```bash npm install @cryptonly/sdk ``` -------------------------------- ### GET /x402/supported Source: https://docs.cryptonly.net/guides/x402/reference Returns the list of supported payment mechanisms. Requires the x402.verify scope. ```APIDOC ## GET /x402/supported ### Description Returns the list of supported payment mechanisms. Requires the x402.verify scope. ### Method GET ### Endpoint /x402/supported ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) None ### Request Example None #### Response Example None ``` -------------------------------- ### GET /x402/config Source: https://docs.cryptonly.net/guides/x402/reference Returns the configuration for the x402 service. Requires the x402.verify scope. ```APIDOC ## GET /x402/config ### Description Returns the configuration for the x402 service. Requires the x402.verify scope. ### Method GET ### Endpoint /x402/config ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) None ### Request Example None #### Response Example None ``` -------------------------------- ### Install Python dependencies for Cryptonly x402 Source: https://docs.cryptonly.net/guides/x402/prices-in-code Install the required Python packages for using Cryptonly with FastAPI and uvicorn. ```bash pip install cryptonly-x402 "x402[fastapi,evm]" fastapi uvicorn ``` -------------------------------- ### Install NestJS dependencies for Cryptonly x402 Source: https://docs.cryptonly.net/guides/x402/prices-in-code Install the required npm packages for using Cryptonly with NestJS. ```bash npm install @cryptonly/x402-nestjs @x402/core @x402/evm ``` -------------------------------- ### Create invoice with cURL Source: https://docs.cryptonly.net/quickstart Sends a POST request to the sandbox API endpoint /invoice. Uses x-tenant-api-key header with your API key and includes amount, fiatCurrencyCode, orderId, description, and webhookUrl. The orderId is your idempotency key, so use a new value for each invoice. The response is 201 Created with the invoice in created status. ```bash curl -X POST https://sandbox-api-merchant.cryptonly.net/invoice \ -H "x-tenant-api-key: $CRYPTONLY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "amount": 25, "fiatCurrencyCode": "USD", "orderId": "order_1001", "description": "Order #1001", "webhookUrl": "https://your-server.example.com/webhooks/cryptonly" }' ``` -------------------------------- ### Quick start: create invoice with Cryptonly client Source: https://docs.cryptonly.net/integration/sdk Initialize the Cryptonly client with an API key and sandbox mode, then create an invoice. Use sandbox: true for testing; omit it to call production. ```ts const client = new Cryptonly({ apiKey: process.env.CRYPTONLY_API_KEY!, sandbox: true, // omit to call production }); const invoice = await client.invoice.create({ amount: 100, fiatCurrencyCode: 'USD', description: 'Order #123', orderId: 'order_123', }); ``` -------------------------------- ### Install Express dependencies for Cryptonly x402 Source: https://docs.cryptonly.net/guides/x402/prices-in-code Install the required npm packages for using Cryptonly with Express middleware. ```bash npm install @cryptonly/x402 @x402/core @x402/express @x402/evm express ``` -------------------------------- ### Express middleware setup with CryptonlyFacilitatorClient Source: https://docs.cryptonly.net/llms-full.txt Sets up x402 payment middleware in Express with a fixed price and payTo address. Requires CRYPTONLY_API_KEY and PAY_TO environment variables. The same client works with @x402/fastify, @x402/hono, and @x402/next. ```typescript const facilitator = new CryptonlyFacilitatorClient({ apiKey: process.env.CRYPTONLY_API_KEY!, }); const server = new x402ResourceServer(facilitator).register( 'eip155:8453', new ExactEvmScheme(), ); const app = express(); app.use( paymentMiddleware( { 'GET /v1/weather/:city': { accepts: [ { scheme: 'exact', price: '$0.01', network: 'eip155:8453', payTo: process.env.PAY_TO! }, ], description: 'Current weather for a city', }, }, server, ), ); app.get('/v1/weather/:city', (req, res) => { res.json({ city: req.params.city, temperatureC: 21 }); }); app.listen(4021); ``` -------------------------------- ### Set environment variables for API key and webhook secret Source: https://docs.cryptonly.net/quickstart Store the sandbox API key and webhook signing key in your server environment. The API key is bound to the account, so no account ID is passed in requests. The webhook secret is used to verify incoming webhooks. ```bash CRYPTONLY_API_KEY=your_sandbox_api_key CRYPTONLY_WEBHOOK_SECRET=your_webhook_signing_key ``` -------------------------------- ### FastAPI middleware setup with CryptonlyFacilitatorClient Source: https://docs.cryptonly.net/llms-full.txt Sets up x402 payment middleware in FastAPI with a fixed price and payTo. Requires CRYPTONLY_API_KEY and PAY_TO environment variables. Run with `uvicorn main:app --port 4021`. For Flask, use CryptonlyFacilitatorClientSync with x402ResourceServerSync. ```python from cryptonly_x402 import CryptonlyFacilitatorClient from fastapi import FastAPI from x402.http import PaymentOption, RouteConfig from x402.http.middleware.fastapi import PaymentMiddlewareASGI from x402.mechanisms.evm.exact import ExactEvmServerScheme from x402.server import x402ResourceServer facilitator = CryptonlyFacilitatorClient(os.environ["CRYPTONLY_API_KEY"]) server = x402ResourceServer(facilitator) server.register("eip155:8453", ExactEvmServerScheme()) routes = { "GET /v1/weather/:city": RouteConfig( accepts=PaymentOption(scheme="exact", price="$0.01", network="eip155:8453", pay_to=os.environ["PAY_TO"]), description="Current weather for a city", ), } app = FastAPI() app.add_middleware(PaymentMiddlewareASGI, routes=routes, server=server) @app.get("/v1/weather/{city}") async def weather(city: str): return {"city": city, "temperatureC": 21} ``` -------------------------------- ### GET /x402/config Source: https://api.cryptonly.net/tenant-api-docs-yaml Provides everything a seller needs to issue 402 responses for this account: `payTo`, accepted assets, paid resources and prices, fees and limits. `cryptonlyPaymentMiddleware` builds its routes from it. Requires the `x402.verify` scope. ```APIDOC ## [GET] /x402/config ### Description Everything a seller needs to issue 402 responses for this account: `payTo`, accepted assets, paid resources and prices, fees and limits. `cryptonlyPaymentMiddleware` builds its routes from it. ### Method GET ### Endpoint /x402/config ### Parameters #### Query Parameters - (none documented) ### Response #### Success Response (200) - (schema reference: X402ConfigResponseDto) #### Error Responses - **400**: Request validation failed (e.g. missing or malformed body / query). - **401**: Missing or invalid `x-tenant-api-key` header. Code: `exceptions.auth.invalidApiKey`. - **403**: Request origin IP is not on the tenant API allowlist (`exceptions.auth.ipNotAllowed`), or the API key is missing the required scope (`exceptions.auth.insufficientScope`), or the organization has been blocked (`exceptions.tenant.blocked`). - **429**: Rate limit exceeded. Code: `exceptions.rateLimit.exceeded`. The `extension.msBeforeNext` field indicates wait time. - **500**: Unexpected server error. Safe to retry idempotent operations after backoff. ``` -------------------------------- ### GET /invoice Source: https://api.cryptonly.net/tenant-api-docs-yaml Lists invoices for the account bound to the API key. Requires the `invoices.list` scope. ```APIDOC ## [GET] /invoice ### Description Lists invoices for the account bound to the API key. ### Method GET ### Endpoint /invoice ### Parameters #### Query Parameters - (none documented) ### Response #### Success Response (200) - (schema reference: MerchantApiErrorResponseDto) #### Error Responses - **400**: Bad request - **401**: Missing or invalid `x-tenant-api-key` header. Code: `exceptions.auth.invalidApiKey`. - **403**: Request origin IP is not on the tenant API allowlist (`exceptions.auth.ipNotAllowed`), or the API key is missing the required scope (`exceptions.auth.insufficientScope`), or the organization has been blocked (`exceptions.tenant.blocked`). - **429**: Rate limit exceeded. Code: `exceptions.rateLimit.exceeded`. The `extension.msBeforeNext` field indicates wait time. - **500**: Unexpected server error. Safe to retry idempotent operations after backoff. ``` -------------------------------- ### POST /invoice Source: https://docs.cryptonly.net/quickstart Creates a new invoice on the account associated with the API key. The orderId serves as your own reference and idempotency key, so use a new value for each invoice. The response is 201 Created with the invoice in 'created' status, and the paymentPageUrl field provides the hosted checkout to send to your customer. ```APIDOC ## POST /invoice ### Description Creates a new invoice on the account associated with the API key. The orderId serves as your own reference and idempotency key, so use a new value for each invoice. The response is 201 Created with the invoice in 'created' status, and the paymentPageUrl field provides the hosted checkout to send to your customer. ### Method POST ### Endpoint https://sandbox-api-merchant.cryptonly.net/invoice ### Parameters #### Request Body - **amount** (number) - Required - Invoice amount - **fiatCurrencyCode** (string) - Required - Currency code (e.g., USD) - **orderId** (string) - Required - Your own reference and idempotency key - **description** (string) - Optional - Description of the invoice - **webhookUrl** (string) - Optional - Webhook URL for notifications; can be omitted if a default invoice webhook URL is set under Settings → Integration ### Response #### Success Response (201 Created) - **paymentPageUrl** (string) - Hosted checkout URL to send to your customer ### Request Example ```bash curl -X POST https://sandbox-api-merchant.cryptonly.net/invoice \ -H "x-tenant-api-key: $CRYPTONLY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "amount": 25, "fiatCurrencyCode": "USD", "orderId": "order_1001", "description": "Order #1001", "webhookUrl": "https://your-server.example.com/webhooks/cryptonly" }' ``` ``` -------------------------------- ### GET /deposit/list Source: https://api.cryptonly.net/tenant-api-docs-yaml Lists merchant top-up deposits with pagination and optional status filter. Requires the `deposits.list` scope. ```APIDOC ## GET /deposit/list ### Description Lists merchant top-up deposits. ### Method GET ### Endpoint /deposit/list ### Parameters #### Query Parameters - **page** (number) - Optional - 1-indexed page number. Default: 1. Minimum: 1. - **limit** (number) - Optional - Items per page. Capped at 100. Default: 20. Minimum: 1, Maximum: 100. - **status** (string) - Optional - Filter by deposit status. Enum: created, processing, completed, suspended, failed, expired, cancelled. ### Response #### Success Response (200) - Deposit list #### Error Responses - **400**: Request validation failed (e.g. missing or malformed body / query). - **401**: Missing or invalid `x-tenant-api-key` header. Code: `exceptions.auth.invalidApiKey`. - **403**: Request origin IP is not on the tenant API allowlist (`exceptions.auth.ipNotAllowed`), or the API key is missing the scope required by this operation (`exceptions.auth.insufficientScope`), or the organization has been blocked; contact support@cryptonly.net (`exceptions.tenant.blocked`). - **429**: Rate limit exceeded for this endpoint. Retry after the window resets. Code: `exceptions.rateLimit.exceeded`. The `extension.msBeforeNext` field tells you how long to wait. - **500**: Unexpected server error. Safe to retry idempotent operations after a backoff. ### Security - TENANT_API_KEY ``` -------------------------------- ### GET /x402/supported Source: https://docs.cryptonly.net/api-reference/openapi Checks if x402 is supported. ```APIDOC ## GET /x402/supported ### Description Checks if x402 is supported. ### Method GET ### Endpoint /x402/supported ``` -------------------------------- ### Prompt to start with for AI coding assistants Source: https://docs.cryptonly.net/integration/ai-assistants Paste this prompt into an AI coding assistant from the root of your project. It instructs the assistant to use the Cryptonly documentation and sandbox, and to follow specific integration steps. ```text Integrate Cryptonly crypto payments into this project. Start with https://docs.cryptonly.net/llms.txt and open the pages you need; every link there is a Markdown page. The API schema is https://api.cryptonly.net/tenant-api-docs-yaml. - If the shop runs on a platform with a Cryptonly plugin (WooCommerce, WHMCS, Blesta, FOSSBilling, Paymenter, Medusa, Vendure, FluentCart), set up the plugin instead of writing custom code. - On a Node.js / TypeScript backend use @cryptonly/sdk; otherwise call the REST API. - Work against the sandbox: https://sandbox-api-merchant.cryptonly.net, or sandbox: true in the SDK. - Read the API key and the webhook signing key from CRYPTONLY_API_KEY and CRYPTONLY_WEBHOOK_SECRET. Never hard-code them. - Create one invoice per order with my order ID as orderId, and send the customer to paymentPageUrl. - Handle the invoice.statusChanged webhook: verify x-webhook-signature against the raw request body, and fulfil orders by the rules in https://docs.cryptonly.net/guides/invoices/statuses.md. - Tell me how to test the whole flow with Simulate payment in the sandbox dashboard. ``` -------------------------------- ### Express: Register Bazaar extension and declare discovery extension Source: https://docs.cryptonly.net/guides/x402/discovery Adds the Bazaar extension to an Express server and configures payment middleware for a route with an exact price, description, tags, and discovery output example. The route is listed after its first payment. ```TypeScript server.registerExtension(bazaarResourceServerExtension); app.use( paymentMiddleware( { 'GET /v1/quote/:symbol': { accepts: [ { scheme: 'exact', price: '$0.005', network: 'eip155:8453', payTo: process.env.PAY_TO! }, ], description: 'Token price quote', tags: ['finance', 'prices'], extensions: declareDiscoveryExtension({ output: { example: { symbol: 'SOL', usd: 150.25 } }, }), }, }, server, ), ); ``` -------------------------------- ### FastAPI middleware setup with Cryptonly facilitator Source: https://docs.cryptonly.net/guides/x402/prices-in-code Configure the Cryptonly facilitator client and register the x402 resource server with an exact EVM scheme. Then add the PaymentMiddlewareASGI to a FastAPI app, defining a route with a price and payTo address. ```python from cryptonly_x402 import CryptonlyFacilitatorClient from fastapi import FastAPI from x402.http import PaymentOption, RouteConfig from x402.http.middleware.fastapi import PaymentMiddlewareASGI from x402.mechanisms.evm.exact import ExactEvmServerScheme from x402.server import x402ResourceServer facilitator = CryptonlyFacilitatorClient(os.environ["CRYPTONLY_API_KEY"]) server = x402ResourceServer(facilitator) server.register("eip155:8453", ExactEvmServerScheme()) routes = { "GET /v1/weather/:city": RouteConfig( accepts=PaymentOption(scheme="exact", price="$0.01", network="eip155:8453", pay_to=os.environ["PAY_TO"]), description="Current weather for a city", ), } app = FastAPI() app.add_middleware(PaymentMiddlewareASGI, routes=routes, server=server) @app.get("/v1/weather/{city}") async def weather(city: str): return {"city": city, "temperatureC": 21} ``` -------------------------------- ### GET /x402/supported Source: https://api.cryptonly.net/tenant-api-docs-yaml Returns schemes, networks, and fee-payer signers this account may use. Empty `kinds` while x402 is off for the account. Follows the x402 v2 facilitator protocol. Requires the `x402.verify` scope. ```APIDOC ## [GET] /x402/supported ### Description Schemes, networks and fee-payer signers this account may use. Empty `kinds` while x402 is off for the account. Request and response bodies follow the x402 v2 facilitator protocol. Protocol failures are HTTP 200 with `isValid: false` / `success: false` and a reason code, so stock x402 clients can read them. ### Method GET ### Endpoint /x402/supported ### Parameters #### Query Parameters - (none documented) ### Response #### Success Response (200) - (schema reference: X402SupportedResponseDto) #### Error Responses - **400**: Request validation failed (e.g. missing or malformed body / query). - **401**: Missing or invalid `x-tenant-api-key` header. Code: `exceptions.auth.invalidApiKey`. - **403**: Request origin IP is not on the tenant API allowlist (`exceptions.auth.ipNotAllowed`), or the API key is missing the required scope (`exceptions.auth.insufficientScope`), or the organization has been blocked (`exceptions.tenant.blocked`). - **429**: Rate limit exceeded. Code: `exceptions.rateLimit.exceeded`. The `extension.msBeforeNext` field indicates wait time. - **500**: Unexpected server error. Safe to retry idempotent operations after backoff. ``` -------------------------------- ### GET /x402/discovery/resources Source: https://docs.cryptonly.net/guides/x402/discovery Retrieves the public feed of listed endpoints in the x402 Bazaar format. The feed is public and requires no API key. Supports filtering and pagination via query parameters. ```APIDOC ## [GET] /x402/discovery/resources ### Description Retrieves the public feed of listed endpoints in the x402 Bazaar format. The feed is public and requires no API key. Supports filtering and pagination via query parameters. ### Method GET ### Endpoint https://api.cryptonly.net/x402/discovery/resources ### Parameters #### Query Parameters - **limit** (integer) - Optional - Maximum number of items to return. - **offset** (integer) - Optional - Number of items to skip for pagination. - **payTo** (string) - Optional - Filter by payment address. - **network** (string) - Optional - Filter by network (e.g., 'eip155:8453'). - **scheme** (string) - Optional - Filter by payment scheme. - **extensions** (string) - Optional - Filter by extension (e.g., 'bazaar'). ### Response #### Success Response (200) - **items** (array) - List of resources. Each item contains fields such as `serviceName`, `iconUrl`, `tags`, `description`, and `accepts`. ### Request Example ```bash curl "https://api.cryptonly.net/x402/discovery/resources?limit=20" ``` ``` -------------------------------- ### GET /currencies Source: https://docs.cryptonly.net/guides/fees-and-commissions Returns per-crypto-currency fee and amount information, including deposit network fee, deposit commission, minimum deposit amount, and minimum withdrawal amount. ```APIDOC ## GET /currencies ### Description Returns per-crypto-currency fee and amount information, including deposit network fee, deposit commission, minimum deposit amount, and minimum withdrawal amount. ### Method GET ### Endpoint /currencies ### Response #### Success Response (200) - **depositNetworkFee** (number) - Network fee for deposits. - **depositCommission** (number) - Commission for deposits. - **minDepositAmount** (number) - Minimum deposit amount. - **minWithdrawalAmount** (number) - Minimum withdrawal amount. ``` -------------------------------- ### Express middleware setup with Cryptonly facilitator Source: https://docs.cryptonly.net/guides/x402/prices-in-code Configure the Cryptonly facilitator client and register the x402 resource server with an exact EVM scheme. Then apply payment middleware to an Express app, defining a route with a price and payTo address. ```typescript const facilitator = new CryptonlyFacilitatorClient({ apiKey: process.env.CRYPTONLY_API_KEY!, }); const server = new x402ResourceServer(facilitator).register( 'eip155:8453', new ExactEvmScheme(), ); const app = express(); app.use( paymentMiddleware( { 'GET /v1/weather/:city': { accepts: [ { scheme: 'exact', price: '$0.01', network: 'eip155:8453', payTo: process.env.PAY_TO! }, ], description: 'Current weather for a city', }, }, server, ), ); app.get('/v1/weather/:city', (req, res) => { res.json({ city: req.params.city, temperatureC: 21 }); }); app.listen(4021); ``` -------------------------------- ### NestJS: Use @X402 decorator with discovery extension Source: https://docs.cryptonly.net/guides/x402/discovery Decorates a NestJS route with @X402, including accepts, description, tags, and discovery extension. The @X402() decorator registers the Bazaar extension itself when @x402/extensions is installed. ```TypeScript @X402({ accepts: { scheme: 'exact', price: '$0.005', network: 'eip155:8453', payTo: process.env.PAY_TO! }, description: 'Token price quote', tags: ['finance', 'prices'], extensions: declareDiscoveryExtension({ output: { example: { symbol: 'SOL', usd: 150.25 } }, }), }) @Get('quote/:symbol') quote(@Param('symbol') symbol: string) { return { symbol, usd: 150.25 }; } ``` -------------------------------- ### GET /invoice/list Source: https://api.cryptonly.net/tenant-api-docs-yaml Returns invoices for the account bound to the API key, most recent first. Paginated. Each item includes `paymentPageUrl` for the hosted payment page. Requires the `invoices.list` scope. ```APIDOC ## GET /invoice/list ### Description Returns invoices for the account bound to the API key, most recent first. Paginated. Each item includes `paymentPageUrl` for the hosted payment page. Requires the `invoices.list` scope. ### Method GET ### Endpoint /invoice/list ### Parameters #### Query Parameters - **page** (number) - Optional - 1-indexed page number. Default: 1. Minimum: 1. - **limit** (number) - Optional - Items per page. Capped at 100. Default: 20. Minimum: 1, Maximum: 100. - **status** (string) - Optional - Filter by invoice status. Enum: created, processing, paid, partially_paid, overpaid, expired, cancelled, failed, suspended. ### Response #### Success Response (200) - **InvoiceListResponseDto** - List of invoices. #### Error Responses - **400** - Request validation failed (e.g. missing or malformed body / query). - **401** - Missing or invalid `x-tenant-api-key` header. Code: `exceptions.auth.invalidApiKey`. - **403** - Request origin IP is not on the tenant API allowlist (`exceptions.auth.ipNotAllowed`), or the API key is missing the required scope (`exceptions.auth.insufficientScope`), or the organization has been blocked (`exceptions.tenant.blocked`). - **429** - Rate limit exceeded. Retry after the window resets. Code: `exceptions.rateLimit.exceeded`. The `extension.msBeforeNext` field indicates how long to wait. - **500** - Unexpected server error. Safe to retry idempotent operations after a backoff. ``` -------------------------------- ### Verify invoice.statusChanged webhook with express.raw Source: https://docs.cryptonly.net/quickstart Use this Express endpoint to receive Cryptonly's invoice.statusChanged webhook. Verify the x-webhook-signature header against the raw request body using verifyInvoiceWebhook; respond 401 on failure, mark the order as paid when status is 'paid', and always respond with a 2xx status quickly to avoid retries. ```TypeScript const app = express(); app.post( '/webhooks/cryptonly', express.raw({ type: 'application/json' }), (req, res) => { const signature = req.header('x-webhook-signature'); const result = verifyInvoiceWebhook(req.body, signature, process.env.CRYPTONLY_WEBHOOK_SECRET!); if (!result.ok) { return res.status(401).end(); } const { data } = result.envelope; if (data.status === 'paid') { // Mark data.orderId as paid in your system. } res.status(200).end(); }, ); ``` -------------------------------- ### GET /currencies Source: https://api.cryptonly.net/tenant-api-docs-yaml Returns every crypto currency the platform supports together with their network, decimal places, deposit/withdrawal minimums, the payer network fee added to each deposit, and the effective tenant-wide deposit commission. Optionally filterable by network. Required scope: currencies.list. ```APIDOC ## [GET] /currencies ### Description Returns every crypto currency the platform supports together with their network, decimal places, deposit / withdrawal minimums, the payer network fee added to each deposit, and the **effective** tenant-wide deposit commission. Optionally filterable by `network`. Required scope: `currencies.list`. ### Method GET ### Endpoint /currencies ### Parameters #### Query Parameters - **network** (string) - Optional - Optional filter: only return currencies on this network (e.g. `Tron` to fetch only TRC-20 assets). Enum: Tron, Solana, Ethereum, BNB, BTC, Base. ### Response #### Success Response (200) - **MerchantCurrencyListResponseDto** - The list of supported crypto currencies. #### Error Responses - **400** - Invalid `network` filter value. - **401** - Missing or invalid `x-tenant-api-key` header. Code: `exceptions.auth.invalidApiKey`. - **403** - Request origin IP is not on the tenant API allowlist (`exceptions.auth.ipNotAllowed`), or the API key is missing the scope required by this operation (`exceptions.auth.insufficientScope`), or the organization has been blocked; contact support@cryptonly.net (`exceptions.tenant.blocked`). - **429** - Rate limit exceeded for this endpoint. Retry after the window resets. Code: `exceptions.rateLimit.exceeded`. The `extension.msBeforeNext` field tells you how long to wait. - **500** - Unexpected server error. Safe to retry idempotent operations after a backoff. ``` -------------------------------- ### GET /x402/settlements Source: https://api.cryptonly.net/tenant-api-docs-yaml List settlements of this key's account, newest first. In wallet mode the token went to `payTo`; in balance mode (Base) it was credited to the account. Required scope: `x402.list`. ```APIDOC ## [GET] /x402/settlements ### Description List settlements of this key's account, newest first. In wallet mode the token went to `payTo`; in balance mode (Base) it was credited to the account. Required scope: `x402.list`. ### Method GET ### Endpoint /x402/settlements ### Parameters #### Query Parameters - **page** (number) - Optional - 1-indexed page number. Default: 1. Minimum: 1. - **limit** (number) - Optional - Items per page. Capped at 100. Default: 20. Minimum: 1, Maximum: 100. - **accountId** (uuid) - Optional - Dashboard only: one account of the tenant. The merchant API always uses the account of the API key. - **resourceId** (uuid) - Optional - Payments for one resource. - **status** (string) - Optional - Enum: submitted, confirmed, credited, failed. - **outcome** (string) - Optional - `paid`: confirmed or credited. `pending`: submitted. `failed`: failed. Combines with `status` (both must match). Enum: paid, pending, failed. - **from** (date-time) - Optional - Include settlements created at or after this instant. - **to** (date-time) - Optional - Include settlements created at or before this instant. - **payer** (string) - Optional - Payer address. Compared case-insensitively. - **payTo** (string) - Optional - Recipient address. Compared case-insensitively. - **transaction** (string) - Optional - Transaction hash, exact match. ### Response #### Success Response (200) Schema: X402SettlementListResponseDto #### Error Responses - **400** - Request validation failed (e.g. missing or malformed body / query). - **401** - Missing or invalid `x-tenant-api-key` header. Code: `exceptions.auth.invalidApiKey`. - **403** - Request origin IP is not on the tenant API allowlist (`exceptions.auth.ipNotAllowed`), or the API key is missing the scope required by this operation (`exceptions.auth.insufficientScope`), or the organization has been blocked; contact support@cryptonly.net (`exceptions.tenant.blocked`). - **429** - Rate limit exceeded for this endpoint. Retry after the window resets. Code: `exceptions.rateLimit.exceeded`. The `extension.msBeforeNext` field tells you how long to wait. - **500** - Unexpected server error. Safe to retry idempotent operations after a backoff. ### Security - TENANT_API_KEY: [] ### Required Scope x402.list ``` -------------------------------- ### GET /deposit Source: https://api.cryptonly.net/tenant-api-docs-yaml Retrieves deposit information by either the deposit `id` or the merchant `orderId`. At least one query parameter should be provided. Required scope: `deposits.read` (implied by operation). ```APIDOC ## [GET] /deposit ### Description Retrieves deposit details. Use either `id` or `orderId` to identify the deposit. ### Method GET ### Endpoint /deposit ### Parameters #### Query Parameters - `id` (uuid) - Optional - The deposit identifier. - `orderId` (string) - Optional - The merchant's order identifier. ### Response #### Success Response (200) - `TenantApiKeyDepositDataResponseDto` - The deposit data. #### Error Responses - **400** - Request validation failed (e.g. missing or malformed body / query). ``` -------------------------------- ### GET /x402/supported Source: https://docs.cryptonly.net/api-reference/openapi/operations/x402supported Retrieves the schemes, networks, and fee-payer signers this account may use. Empty kinds indicate x402 is off for the account. Request and response bodies follow the x402 v2 facilitator protocol; protocol failures are HTTP 200 with isValid: false / success: false and a reason code. ```APIDOC ## GET /x402/supported ### Description Retrieves the schemes, networks, and fee-payer signers this account may use. Empty `kinds` while x402 is off for the account. Request and response bodies follow the x402 v2 facilitator protocol. Protocol failures are HTTP 200 with `isValid: false` / `success: false` and a reason code, so stock x402 clients can read them. ### Method GET ### Endpoint /x402/supported ### Authorizations Required scope: `x402.verify`. ### Response #### Success Response (200) - **kinds** (array) - Schemes, networks, and fee-payer signers this account may use. Empty when x402 is off. #### Error Response (400) Bad request. #### Error Response (401) Unauthorized. #### Error Response (403) Forbidden. #### Error Response (429) Too many requests. #### Error Response (500) Internal server error. ``` -------------------------------- ### GET /currencies/fiat Source: https://api.cryptonly.net/tenant-api-docs-yaml Returns every fiat currency that can be used as `fiatCurrencyCode` on `POST /invoice`. Includes per-currency `minInvoiceAmount` so callers can validate their amounts client-side. Required scope: `currencies.list`. ```APIDOC ## [GET] /currencies/fiat ### Description Returns every fiat currency that can be used as `fiatCurrencyCode` on `POST /invoice`. Includes per-currency `minInvoiceAmount` so callers can validate their amounts client-side. Required scope: `currencies.list`. ### Method GET ### Endpoint /currencies/fiat ### Parameters None ### Response #### Success Response (200) - **MerchantFiatCurrencyListResponseDto** - The list of supported fiat currencies. #### Error Responses - **400** - Request validation failed (e.g. missing or malformed body / query). - **401** - Missing or invalid `x-tenant-api-key` header. Code: `exceptions.auth.invalidApiKey`. - **403** - Request origin IP is not on the tenant API allowlist (`exceptions.auth.ipNotAllowed`), or the API key is missing the scope required by this operation (`exceptions.auth.insufficientScope`), or the organization has been blocked; contact support@cryptonly.net (`exceptions.tenant.blocked`). - **429** - Rate limit exceeded for this endpoint. Retry after the window resets. Code: `exceptions.rateLimit.exceeded`. The `extension.msBeforeNext` field tells you how long to wait. - **500** - Unexpected server error. Safe to retry idempotent operations after a backoff. ``` -------------------------------- ### Go: Define x402 payment routes in code with Gin Source: https://docs.cryptonly.net/guides/x402/prices-in-code Sets up an x402 HTTP facilitator client and Gin middleware to require a $0.01 exact payment on the GET /v1/weather/:city route. Uses the Cryptonly API key from the CRYPTONLY_API_KEY environment variable and the PAY_TO address. After the first payment, the route appears on the Endpoints tab as 'Priced in code'. ```go package main "context" "os" "github.com/gin-gonic/gin" x402http "github.com/x402-foundation/x402/go/http" ginmw "github.com/x402-foundation/x402/go/http/gin" evm "github.com/x402-foundation/x402/go/mechanisms/evm/exact/server" ) // apiKey sends your Cryptonly API key with every facilitator call. type apiKey string func (k apiKey) GetAuthHeaders(context.Context) (x402http.AuthHeaders, error) { h := map[string]string{"x-tenant-api-key": string(k)} return x402http.AuthHeaders{Verify: h, Settle: h, Supported: h}, nil } func main() { facilitator := x402http.NewHTTPFacilitatorClient(&x402http.FacilitatorConfig{ URL: "https://api-merchant.cryptonly.net/x402", AuthProvider: apiKey(os.Getenv("CRYPTONLY_API_KEY")), }) routes := x402http.RoutesConfig{ "GET /v1/weather/:city": { Accepts: x402http.PaymentOptions{ {Scheme: "exact", Price: "$0.01", Network: "eip155:8453", PayTo: os.Getenv("PAY_TO")}, }, Description: "Current weather for a city", }, } r := gin.Default() r.Use(ginmw.X402Payment(ginmw.Config{ Routes: routes, Facilitator: facilitator, Schemes: []ginmw.SchemeConfig{{Network: "eip155:8453", Server: evm.NewExactEvmScheme()}}, })) r.GET("/v1/weather/:city", func(c *gin.Context) { c.JSON(200, gin.H{"city": c.Param("city"), "temperatureC": 21}) }) r.Run(":4021") } ``` -------------------------------- ### GET /invoice Source: https://docs.cryptonly.net/api-reference/openapi Gets an invoice. ```APIDOC ## GET /invoice ### Description Gets an invoice. ### Method GET ### Endpoint /invoice ``` -------------------------------- ### GET /deposit Source: https://docs.cryptonly.net/api-reference/openapi Gets a deposit. ```APIDOC ## GET /deposit ### Description Gets a deposit. ### Method GET ### Endpoint /deposit ```