通过 SDK 接入#
直接调用 Onchain OS Payment SDK 完成集成,SDK 内置 402 协议响应处理与链上交易验证,无需自定义 API 实现。
准备工作#
- 收款钱包:任何 EVM 兼容钱包(如Agentic Wallet)
- API 密钥:通过 OKX 开发者管理平台 申请。如果你的收款钱包是 Agentic Wallet,则无需申请 API 密钥。
- 业务后端:您自己的 API 服务或后台服务器
安装 SDK#
Node.js
Go
Rust
Java
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
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 验证支付结果,并返回对应资源