Add x402 Payments to Your Agent
Use this page if your self-hosted agent calls x402-protected routes and needs to handle payment alongside the agentlink identity header.
For the x402 payment protocol itself, see x402.org.
Install
bash
pnpm add @x402/core @x402/evmWire x402 payment through fetchImpl
ts
import { toClientEvmSigner } from '@x402/evm'
import { x402HTTPClient } from '@x402/core/http'
import { createEvmClient } from '@x402/evm/client'
import { createAgentLinkClient } from '@techdigger/humanode-agentlink'
const paymentClient = new x402HTTPClient(
createEvmClient({
signer: toClientEvmSigner(paymentAccount),
})
)
const { fetch: agentlinkFetch } = createAgentLinkClient({
network: 'base-sepolia',
address: '0xYourAgentAddress',
sign: async message => agentIdentitySigner.signMessage(message),
fetchImpl: async (input, init) => {
const request = input instanceof Request ? input : new Request(input, init)
const first = await fetch(request)
if (first.status !== 402) return first
const paymentRequired = paymentClient.getPaymentRequiredResponse(name => first.headers.get(name))
const paymentPayload = await paymentClient.createPaymentPayload(paymentRequired)
const retryHeaders = new Headers(request.headers)
for (const [name, value] of Object.entries(paymentClient.encodePaymentSignatureHeader(paymentPayload))) {
retryHeaders.set(name, value)
}
return fetch(new Request(request, { headers: retryHeaders }))
},
})
const response = await agentlinkFetch('https://api.example.com/data')Use the same agent wallet for both the agentlink identity signer and the x402 payment account.
Next steps
- Back to the full operator setup → Self-Hosted Agent Operators
- Calling the two-for-one service → Two-for-One Service
- x402 protocol reference → x402.org