Communitygithub.com

智能体支付执行(x402)

为AI智能体添加x402支付执行能力,支持每任务预算、支出控制和非托管钱包。兼容Base(通过agentwallet-sdk)和X Layer(通过OKX Payments / OKX Agent Payments Protocol)。当智能体需要自主支付并需要每任务预算、支出控制和非托管钱包时使用。

智能体支付执行(x402) 是什么?

此技能使AI智能体能够通过x402 HTTP支付协议执行受策略控制的支付,集成内置支出控制机制。它支持两种集成路径:对于Base及其他多链网络,使用agentwallet-sdk作为MCP支付服务器;对于X Layer,则使用OKX Agent Payments Protocol。核心功能包括非托管钱包(基于ERC-4337智能账户)、每任务和每会话预算限制、白名单收款人以及速率限制。该技能提供MCP工具(get_balance、send_payment、check_spending、list_transactions),方便接入Claude Code或任何智能体编排系统。最佳实践强调在代理前设置预算、锁定依赖版本、保留审计追踪以及在支付工具不可用时采取失败封闭策略。对于外部服务付费的开发者,推荐使用TypeScript、Go、Rust、Java或Python(如果可用)的OKX Payments SDK实现卖家端API。

兼容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/agent-payment-x402

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

智能体支付执行(x402) 是做什么的?

使AI智能体能够执行受策略控制的支付,并内置支出控制功能。采用x402 HTTP支付协议和MCP工具,让智能体能够为外部服务、API或其他智能体付费,且无托管风险。

使用时机

在以下场景使用:您的智能体需要为API调用付费、购买服务、与其他智能体结算、强制执行每任务支出限制或管理非托管钱包。此技能与cost-aware-llm-pipeline和security-review技能天然搭配。

决策树

根据您的智能体是购买对402付费API的访问权限,还是为自己的API向他人收费,选择相应的集成路径:

需求推荐路径
智能体支付Base或其他agentwallet支持链上的402付费API使用agentwallet-sdk作为MCP支付服务器,并设置严格的支出策略
智能体支付X Layer上的402付费API使用okx/onchainos-skills中的OKX Agent Payments Protocol;okx-x402-payment是已弃用的旧别名
TypeScript API向智能体收费使用OKX Payments TypeScript卖家SDK文档(适用于Express、Hono、Fastify或Next.js)
Go API向智能体收费使用OKX Payments Go卖家SDK文档(适用于Gin、Echo或net/http)
Rust API向智能体收费使用OKX Payments Rust卖家SDK文档(适用于Axum)
Java API向智能体收费使用OKX Payments Java卖家SDK文档(适用于Spring Boot 2/3、Java EE或Jakarta)
Python API向智能体收费在实施前检查当前OKX Payments仓库;Python卖家指南可能不可用

支持的网络

  • agentwallet-sdk:在生产环境前,使用包文档确认当前网络覆盖范围。Base Sepolia是最安全的开发默认网络;原始技能指定的生产路径是Base主网。
  • OKX Payments / X Layer:当前卖家SDK文档针对X Layer(eip155:196)和USDT0结算。在生成生产代码前请获取最新的SDK文档,因为支付包和协助节点行为可能快速变化。

工作原理

x402协议

x402将HTTP 402(需要付费)扩展为机器可协商的流程。当服务器返回402时,智能体的支付工具协商价格、检查预算、签署交易,并仅在编排器设定的策略和确认边界内重试。

支出控制

每次支付工具调用都会强制执行SpendingPolicy:

  • 每任务预算 — 单次智能体操作的最大支出
  • 每会话预算 — 整个会话的累积限制
  • 白名单收款人 — 限制智能体可以向哪些地址/服务付费
  • 速率限制 — 每分钟/小时的最大交易数

非托管钱包

智能体通过ERC-4337智能账户持有自己的密钥。编排器在委托前设置策略;智能体只能在限制范围内支出。无资金池,无托管风险。

MCP集成

支付层暴露了标准的MCP工具,可以轻松插入任何Claude Code或智能体框架设置。

安全说明:请始终锁定包版本。此工具管理私钥 — 未锁定的npx安装会引入供应链风险。

选项A:agentwallet-sdk (Base / 多链)

{
  "mcpServers": {
    "agentpay": {
      "command": "npx",
      "args": ["[email protected]"]
    }
  }
}

可用工具(智能体可调用)

工具用途
get_balance检查智能体钱包余额
send_payment向地址或ENS发送支付
check_spending查询剩余预算
list_transactions所有支付的审计追踪

注意:支出策略由编排器在委托给智能体之前设置 — 而非智能体自身。这可以防止智能体自行提高支出限额。在您的编排层或任务前钩子中通过set_policy配置策略,切勿将其作为智能体可调用的工具。

选项B:OKX Agent Payments Protocol (X Layer)

此路径用于X Layer x402、多方支付(MPP)、会话支付、收费和A2A收费流程。

对于买家端智能体流程:

  1. 安装或引用当前的okx/onchainos-skills仓库。
  2. 使用skills/okx-agent-payments-protocol/SKILL.md作为分发器。
  3. 将skills/okx-x402-payment/SKILL.md视为已弃用的兼容别名,而非标准文档。
  4. 在钱包状态检查或支付操作前要求用户明确确认。不要将支付执行隐藏在通用工具调用背后。

对于卖家端API流程,请在生成代码前获取最新的语言特定指南:

运行环境当前指南
TypeScripthttps://raw.githubusercontent.com/okx/payments/main/typescript/SELLER.md
Gohttps://raw.githubusercontent.com/okx/payments/main/go/x402/SELLER.md
Rusthttps://raw.githubusercontent.com/okx/payments/main/rust/x402/SELLER.md
Javahttps://raw.githubusercontent.com/okx/payments/main/java/SELLER.md

不要在不检查当前OKX仓库的情况下复制旧文档中的示例。当前OKX指南使用okx-agent-payments-protocol作为分发器,并且Java卖家文档现已可用。

示例

MCP客户端中的预算执行

在构建调用agentpay MCP服务器的编排器时,在分派付费工具调用前强制执行预算。

先决条件:在添加MCP配置前安装包 — 在非交互式环境中,不带-y的npx会提示确认,导致服务器挂起:npm install -g [email protected]

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

async function main() {
  // 1. 在构造传输层前验证凭证。
  //    缺失的密钥必须立即失败 — 绝不允许子进程在无认证的情况下启动。
  const walletKey = process.env.WALLET_PRIVATE_KEY;
  if (!walletKey) {
    throw new Error("WALLET_PRIVATE_KEY未设置 — 拒绝启动支付服务器");
  }

  // 通过stdio传输层连接到agentpay MCP服务器。
  // 仅白名单服务器需要的环境变量 — 切勿将整个process.env转发给管理私钥的第三方子进程。
  const transport = new StdioClientTransport({
    command: "npx",
    args: ["[email protected]"],
    env: {
      PATH: process.env.PATH ?? "",
      NODE_ENV: process.env.NODE_ENV ?? "production",
      WALLET_PRIVATE_KEY: walletKey,
    },
  });
  const agentpay = new Client({ name: "orchestrator", version: "1.0.0" });
  await agentpay.connect(transport);

  // 2. 在委托给智能体前设置支出策略。
  //    始终验证成功 — 静默失败意味着没有控制措施生效。
  const policyResult = await agentpay.callTool({
    name: "set_policy",
    arguments: {
      per_task_budget: 0.50,
      per_session_budget: 5.00,
      allowlisted_recipients: ["api.example.com"],
    },
  });
  if (policyResult.isError) {
    throw new Error(
      `设置支出策略失败 — 请勿委托: ${JSON.stringify(policyResult.content)}`
    );
  }

  // 3. 在任何付费操作前使用preToolCheck
  await preToolCheck(agentpay, 0.01);
}

// 预工具钩子:具有四个不同错误路径的失败封闭预算执行。
async function preToolCheck(agentpay: Client, apiCost: number): Promise<void> {
  // 路径1:拒绝无效输入(NaN/Infinity会绕过<比较)
  if (!Number.isFinite(apiCost) || apiCost < 0) {
    throw new Error(`无效的apiCost: ${apiCost} — 操作已阻止`);
  }

  // 路径2:传输/连接失败
  let result;
  try {
    result = await agentpay.callTool({ name: "check_spending" });
  } catch (err) {
    throw new Error(`支付服务不可达 — 操作已阻止: ${err}`);
  }

  // 路径3:工具返回错误(例如,认证失败、钱包未初始化)
  if (result.isError) {
    throw new Error(
      `check_spending失败 — 操作已阻止: ${JSON.stringify(result.content)}`
    );
  }

  // 路径4:解析并验证响应格式
  let remaining: number;
  try {
    const parsed = JSON.parse(
      (result.content as Array<{ text: string }>)[0].text
    );
    if (!Number.isFinite(parsed?.remaining)) {
      throw new TypeError("缺少'remaining'字段或该字段非有限数字");
    }
    remaining = parsed.remaining;
  } catch (err) {
    throw new Error(
      `check_spending返回了意外格式 — 操作已阻止: ${err}`
    );
  }

  // 路径5:预算超支
  if (remaining < apiCost) {
    throw new Error(
      `预算超支: 需要 $${apiCost},但仅剩余 $${remaining}`
    );
  }
}

main().catch((err) => {
  console.error(err);
  process.exitCode = 1;
});

最佳实践

  • 在委托前设置预算:生成子智能体时,通过编排层附加SpendingPolicy。绝不要让智能体拥有无限支出权限。
  • 锁定依赖版本:始终在MCP配置中指定精确版本(例如,[email protected])。在部署到生产环境前验证包完整性。
  • 审计追踪:在任务后钩子中使用list_transactions记录支出内容和原因。
  • 失败封闭:如果支付工具不可达,阻止付费操作 — 不要退回到未计量访问。
  • 与security-review配合:支付工具是高权限工具。应用与shell访问相同的审查标准。
  • 先在测试网上测试:使用Base Sepolia进行开发;部署到生产环境时切换到Base主网。

生产参考

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

相关技能