Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

コーディングツールから支払う

最終更新 Markdown で表示Agent セットアップ

次の例では、AI コーディングツールに x402 の決済処理を追加します。ツールが 402 レスポンスに遭遇すると、自動で支払い、再試行します。

どちらの例も次が必要です。

  • ウォレットの秘密鍵(環境変数 X402_PRIVATE_KEY に設定)
  • x402 パッケージ: @x402/fetch@x402/evmviem

OpenCode プラグイン

OpenCode のプラグインは、エージェントへツールを公開します。402 レスポンスを処理する x402-fetch ツールを作るには、.opencode/plugins/x402-payment.ts を作成します。

// Use base-sepolia for testing. Get test USDC from https://faucet.circle.com/
import type { Plugin } from "@opencode-ai/plugin";
import { tool } from "@opencode-ai/plugin";
import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

export const X402PaymentPlugin: Plugin = async () => ({
	tool: {
		"x402-fetch": tool({
			description:
				"Fetch a URL with x402 payment. Use when webfetch returns 402.",
			args: {
				url: tool.schema.string().describe("The URL to fetch"),
				timeout: tool.schema.number().optional().describe("Timeout in seconds"),
			},
			async execute(args) {
				const privateKey = process.env.X402_PRIVATE_KEY;
				if (!privateKey) {
					throw new Error("X402_PRIVATE_KEY environment variable is not set.");
				}

				// Your human-in-the-loop confirmation flow...
				// const approved = await confirmPayment(args.url, estimatedCost);
				// if (!approved) throw new Error("Payment declined by user");

				const account = privateKeyToAccount(privateKey as `0x${string}`);
				const client = new x402Client();
				registerExactEvmScheme(client, { signer: account });
				const paidFetch = wrapFetchWithPayment(fetch, client);

				const response = await paidFetch(args.url, {
					method: "GET",
					signal: args.timeout
						? AbortSignal.timeout(args.timeout * 1000)
						: undefined,
				});

				if (!response.ok) {
					throw new Error(`${response.status} ${response.statusText}`);
				}

				return await response.text();
			},
		}),
	},
});

組み込みの webfetch が 402 を返すと、エージェントは x402-fetch を呼び出して、支払い付きで再試行します。

Claude Code フック

Claude Code のフックは、ツール結果を横取りします。402 を透過的に処理するには、.claude/scripts/handle-x402.mjs にスクリプトを作成します。

// Use base-sepolia for testing. Get test USDC from https://faucet.circle.com/
import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

const input = JSON.parse(await readStdin());

const haystack = JSON.stringify(input.tool_response ?? input.error ?? "");
if (!haystack.includes("402")) process.exit(0);

const url = input.tool_input?.url;
if (!url) process.exit(0);

const privateKey = process.env.X402_PRIVATE_KEY;
if (!privateKey) {
	console.error("X402_PRIVATE_KEY not set.");
	process.exit(2);
}

try {
	// Your human-in-the-loop confirmation flow...
	// const approved = await confirmPayment(url);
	// if (!approved) process.exit(0);

	const account = privateKeyToAccount(privateKey);
	const client = new x402Client();
	registerExactEvmScheme(client, { signer: account });
	const paidFetch = wrapFetchWithPayment(fetch, client);

	const res = await paidFetch(url, { method: "GET" });
	const text = await res.text();

	if (!res.ok) {
		console.error(`Paid fetch failed: ${res.status}`);
		process.exit(2);
	}

	console.log(
		JSON.stringify({
			hookSpecificOutput: {
				hookEventName: "PostToolUse",
				additionalContext: `Paid for "${url}" via x402:\n${text}`,
			},
		}),
	);
} catch (err) {
	console.error(`x402 payment failed: ${err.message}`);
	process.exit(2);
}

function readStdin() {
	return new Promise((resolve) => {
		let data = "";
		process.stdin.on("data", (chunk) => (data += chunk));
		process.stdin.on("end", () => resolve(data));
	});
}

フックを .claude/settings.json に登録します。

{
	"hooks": {
		"PostToolUse": [
			{
				"matcher": "WebFetch",
				"hooks": [
					{
						"type": "command",
						"command": "node .claude/scripts/handle-x402.mjs",
						"timeout": 30
					}
				]
			}
		]
	}
}

関連情報

役に立ちましたか?