Thanh toán x402
Cách thanh toán cho tài nguyên Xona, luồng 402 → thanh toán → thử lại, kèm ví dụ phía client, phía server và thủ công.
Mọi tài nguyên Xona đều trả theo lượt dùng qua giao thức x402. Không có API key hay gói thuê bao, bạn trả bằng USDC (mặc định trên Solana) cho mỗi request.
Cách hoạt động
- Gửi request đến bất kỳ endpoint tài nguyên nào (ví dụ
POST /image/designer). - Server phản hồi
402 Payment Requiredkèm thông tin thanh toán: số tiền, tài sản (USDC) và địa chỉ nhận tiền. - Ký khoản thanh toán bằng ví của bạn theo các yêu cầu thanh toán được cung cấp.
- Gửi lại request với header
X-PAYMENTđã ký. - Khoản thanh toán được tất toán nguyên tử và bạn nhận kết quả trong response body.
SDK và CLI của Xona Wallet triển khai toàn bộ vòng lặp này cho bạn: xpay pay <url> hoặc xpay.useByUrl(...) xử lý việc khám phá, ký và thử lại. Các ví dụ bên dưới minh họa luồng thủ công khi bạn muốn tự tích hợp.
Phía client (trình duyệt / frontend)
Dùng @dexterai/x402 để tự động xử lý luồng 402 từ trình duyệt với một ví đã kết nối.
npm install @dexterai/x402import { wrapFetch } from "@dexterai/x402/client";
const x402Fetch = wrapFetch(fetch, {
walletPrivateKey: "<solana-wallet-private-key>",
});
// Hit any Xona resource, payment is handled automatically
const response = await x402Fetch("https://api.xona-agent.com/image/designer", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
prompt: "A cyberpunk cityscape at sunset",
aspect_ratio: "16:9",
}),
});
const { image_url, image_description, metadata } = await response.json();Phía server (Node.js / backend)
Cách làm tương tự cũng áp dụng ở phía server. Lưu khóa ví của bạn một cách an toàn và bọc các lệnh gọi fetch.
import { wrapFetch } from "@dexterai/x402/client";
const x402Fetch = wrapFetch(fetch, {
walletPrivateKey: process.env.SOLANA_PRIVATE_KEY,
});
// Get trending tokens
const res = await x402Fetch("https://api.xona-agent.com/token/pumpfun-trending");
const { summary, trending_tokens } = await res.json();Luồng thủ công (cURL)
Bạn cũng có thể tự xử lý x402. Trước tiên gọi endpoint để lấy yêu cầu thanh toán, sau đó ký và gửi lại.
# Step 1: Get payment requirements
curl -s -X POST "https://api.xona-agent.com/image/designer" \
-H "Content-Type: application/json" \
-d '{"prompt": "sunset over mountains"}'
# → Returns 402 with payment requirements in the response body
# Step 2: Sign the payment with your wallet (using your x402 SDK)
# Step 3: Resend with the signed payment header
curl -X POST "https://api.xona-agent.com/image/designer" \
-H "Content-Type: application/json" \
-H "X-PAYMENT: <x402-payment-payload>" \
-d '{"prompt": "sunset over mountains"}'
# → Returns 200 with { image_url, image_description, metadata }Khám phá
Liệt kê tất cả tài nguyên có sẵn cùng giá và schema bằng lập trình, không cần thanh toán.
# List all x402 resources
curl https://api.xona-agent.com/x402-resources
# x402 discovery document
curl https://api.xona-agent.com/.well-known/x402