通过 SDK 接入#
直接调用 Onchain OS Payment SDK 完成集成,SDK 内置 402 协议响应处理与链上交易验证,无需自定义 API 实现。
准备工作#
- 收款钱包:任何 EVM 兼容钱包(如Agentic Wallet)
- API 密钥:通过 OKX 开发者管理平台 申请。
- 业务后端:您自己的 API 服务或后台服务器
安装 SDK#
Node.js
Go
Rust
Java
Python
bash
npm install express @okxweb3/x402-express @okxweb3/x402-core @okxweb3/x402-evm
npm install -D typescript tsx @types/express @types/node
接入服务#
Node.js
Go
Rust
Java
Python
typescript
import express from "express";
import {
paymentMiddleware,
x402ResourceServer,
} from "@okxweb3/x402-express";
import { ExactEvmScheme } from "@okxweb3/x402-evm/exact/server";
import { OKXFacilitatorClient } from "@okxweb3/x402-core";
const app = express();
const NETWORK = "eip155:196";
const PAY_TO = process.env.PAY_TO_ADDRESS || "0xYourWalletAddress";
const facilitatorClient = new OKXFacilitatorClient({
apiKey: "OKX_API_KEY",
secretKey: "OKX_SECRET_KEY",
passphrase: "OKX_PASSPHRASE",
});
const resourceServer = new x402ResourceServer(facilitatorClient);
resourceServer.register(NETWORK, new ExactEvmScheme());
app.use(
paymentMiddleware(
{
"GET /generateImg": {
accepts: [{
scheme: "exact",
network: NETWORK,
payTo: PAY_TO,
price: "$0.01",
}],
description: "AI Image Generation Service",
mimeType: "application/json",
},
},
resourceServer,
),
);
app.get("/generateImg", (_req, res) => {
res.json({
success: true,
imageUrl: "https://placehold.co/512x512/png?text=AI+Generated",
prompt: "a sunset over mountains",
timestamp: new Date().toISOString(),
});
});
app.listen(4000, () => {
console.log("[Seller] Image generation service listening at http://localhost:4000");
});
测试服务#
- 1通过 Onchain OS 访问服务端口
- 2服务器返回 402 状态码和 PAYMENT-REQUIRED 响应头
- 3使用 Agentic Wallet 完成支付
- 4钱包自动重试请求
- 5服务端会向 Broker 验证支付结果,并返回对应资源
测试网验证集成(可选)#
代码示例默认使用 X Layer Mainnet(eip155:196)。若想在不消耗真实资金的前提下跑通集成,可以先把网络常量改为测试网,跑通后再改回主网,只需改一行:
diff
- const NETWORK = "eip155:196"; // X Layer Mainnet
+ const NETWORK = "eip155:1952"; // X Layer Testnet
价格用 USD 字符串(如 "$0.01"),系统会自动按目标网络的稳定币换算,切网无需改 price 字段。
测试网领水:
- Gas(test OKB)→ 前往 X Layer Faucet 领取
- 稳定币(test USD₮0)→ 前往 X Layer Faucet 领取
用官方 Mock Merchant 作为参考比对:
https://www.okx.com/api/v1/pay/mock-merchant/resource(X Layer Testnet 部署)
