Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Base network

How I Made a Pay-Per-Call API Payable with a 60-Line x402 Adapter

By Freedom251 Team · · 10 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

My API kept returning HTTP 402 because I had built a USDC transfer workflow, not an x402 payment flow. Clients cannot satisfy x402 by sending a transaction hash after a separate transfer; they need a machine-readable payment challenge, a locally signed EIP-3009 authorization, and a payment payload in the protocol’s expected header. I fixed the integration with a small Python adapter that sends the payload and requirements to a facilitator for verification, calls settlement only after verification succeeds, and returns the resource with a settlement receipt. The repair was roughly 60 lines, but the important work was aligning the protocol version, network identifier, headers, and request order.

Why did my pay-per-call API return 402 forever?

The API returned 402 indefinitely because the server and client disagreed about what payment meant. My server accepted a USDC transfer and a transaction hash, while an x402 client expected a payment challenge and a signed authorization it could submit for verification and settlement. A blockchain transaction hash is evidence of a broadcast transaction; it is not an x402 payment payload.

As an Amazon Associate I earn from qualifying purchases.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A compatible endpoint starts by returning HTTP 402 with an accepts array. Each entry tells the client which scheme to use, which network and asset are accepted, how much is required, and where funds should go. The client then signs an EIP-3009 transferWithAuthorization locally. It does not broadcast that authorization itself. The retry carries the signed data, encoded as base64 in the protocol’s payment header, so the server can pass it to a facilitator.

This distinction matters for agents. An agent can inspect the challenge, select a supported requirement, sign the prescribed authorization, and retry without learning a private server-side transfer procedure. If the challenge is missing, uses unknown field names, or advertises a network identifier that does not match the declared x402 version, the client has no interoperable way to pay.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

What does a correct x402 request sequence look like?

The reliable sequence is challenge, authorization, verification, settlement, and fulfillment. The server must not deliver the paid resource before the facilitator confirms that the payload can be settled.

  1. Initial request: The client sends a normal request to the protected endpoint.
  2. Payment challenge: The server responds with HTTP 402 and an accepts array containing the scheme, network, amount, recipient (payTo), and USDC asset details.
  3. Local signing: The client chooses a compatible requirement and signs an EIP-3009 authorization. The authorization includes the payer and recipient addresses, amount in atomic units, validity timestamps, and a nonce. The client does not broadcast a transaction at this stage.
  4. Paid retry: The client serializes the signed payload and places its base64 representation in the payment header expected by the selected x402 version.
  5. Verification: The server sends the payload and the original payment requirements to the facilitator’s /verify interface. Verification is read-only; it checks whether the signature, amounts, recipient, time window, nonce, scheme, and network are acceptable.
  6. Settlement: Only after a positive verification response does the server send the same material to /settle. Settlement commits the payment and returns a success result and, when available, a transaction hash.
  7. Fulfillment and receipt: The server returns the requested resource and includes the settlement result in the payment-response header. A failed verification or settlement must stop fulfillment.

The order is part of the payment scheme, not an implementation preference. Calling settlement before verification can create avoidable failures or commit a payment the application has not validated against its own requirements.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which fields must the client and server agree on?

Most integration failures are schema mismatches rather than cryptographic failures. Treat the requirement object as a contract and keep every field consistent between the 402 challenge, the signed authorization, and the facilitator request.

Field or concept What it controls Typical mistake
x402Version Selects the wire format, header conventions, and version-specific identifiers. Declaring version 1 while sending version-2 fields or network names.
scheme Chooses the payment mechanism and the authorization format. Accepting a payload signed for a different scheme.
network Identifies the chain on which the asset and recipient are resolved. Using eip155:8453 in a v1 requirement that expects base.
amount States the charge in the asset’s smallest units. Sending a decimal display amount where an integer atomic amount is required.
payTo Names the recipient address used by verification and settlement. Comparing the signature against one address but settling to another.
Asset Identifies the USDC contract or other supported token for the requirement. Allowing a token with the right symbol but the wrong contract.
Validity window Limits when the authorization may be used. Letting an expired authorization reach application fulfillment.
Nonce Makes each authorization distinct and helps prevent replay. Reusing a nonce or failing to retain the facilitator’s replay result.

In the v2 specification, these values appear in typed PaymentRequired and PaymentPayload objects. EVM authorization data explicitly includes payer and recipient addresses, an amount in atomic units, validity timestamps, and a nonce. The nonce is not decorative metadata: it is part of replay protection.

What does an x402 facilitator do?

A facilitator separates payment infrastructure from your API process. It evaluates whether a signed payload satisfies the requirements, then submits or otherwise performs the settlement step on your behalf. The official interface distinguishes three operations: /supported advertises capabilities, /verify checks a payload without committing funds, and /settle commits the payment.

Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Verification is a read-only gate

Your server should send both the decoded payment payload and the exact requirement that produced the 402 challenge. A positive verification result means the facilitator considers the authorization valid for that requirement; it is not yet a settlement receipt. If the response says isValid is false, preserve the returned invalid reason for logs and do not serve the paid response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Settlement is the commit step

Settlement can produce a transaction hash and a success flag. Treat a missing, malformed, or contradictory response as failure. Do not infer success from an HTTP 200 alone, and do not fulfill the request merely because signature verification passed.

Capability discovery prevents bad assumptions

Before production, query the facilitator’s /supported endpoint and confirm the x402 version, scheme, network, asset, and authentication requirements you intend to use. The facilitator guidance calls for failing closed when the service is unavailable or its response cannot be parsed. That may mean asking the client to retry payment later rather than delivering a resource for free.

The reported implementation used a permissionless facilitator on Base mainnet. Marcus Chen described his experience this way: “The key word is facilitator. I thought I needed a Coinbase CDP account (phone verification, the works). I don’t: PayAI runs a permissionless facilitator on Base mainnet — no API key, no signup.” That is his operational report, not a guarantee that every facilitator or network has the same access policy. Confirm current support and limits yourself.

How did the 60-line Python adapter fix the flow?

The adapter does only the protocol plumbing: decode the header, construct the facilitator request, verify, settle, and return the result. This is the core shape reported for the repair:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
def settle_x402(x_payment_b64, requirements):
    payload = json.loads(base64.b64decode(x_payment_b64))
    body = {'x402Version': 1, 'paymentPayload': payload,
            'paymentRequirements': requirements}
    v = post('https://facilitator.payai.network/verify', body)
    if not v.get('isValid'):
        return False, v.get('invalidReason')
    s = post('https://facilitator.payai.network/settle', body)
    return s.get('success'), s.get('txHash')

The endpoint names above reflect the author’s implementation pattern. Do not hard-code an unverified third-party service in a production deployment. Check the facilitator’s supported versions, schemes, networks, authentication, timeout behavior, and response fields first. The verification URL used in the example is https://facilitator.payai.network/verify; the corresponding settlement call is https://facilitator.payai.network/settle.

In a real handler, validate base64 decoding and JSON parsing before calling the facilitator, enforce the requirement object you generated, and set finite network timeouts. Log a request identifier, the selected scheme and network, facilitator status, invalid reason, settlement success, and transaction hash without logging private keys or sensitive authorization material. Keep the application response separate from the facilitator response so a malformed receipt cannot accidentally become a successful API result.

Why did the Base network name break my integration?

The protocol version determines the network spelling. The author’s first mismatch declared x402 version 1 but sent the v2-style CAIP-2 identifier eip155:8453. In the reported v1 flow, the literal network name was base. The v2 specification uses CAIP-2 identifiers such as eip155:8453.

Concern Version 1 behavior reported in the postmortem Version 2 specification behavior
Network identifier Literal base CAIP-2 form such as eip155:8453
Object model Version-1 payment requirements and payload conventions Typed PaymentRequired and PaymentPayload objects
Compatibility rule Use v1 field names, headers, and facilitator expectations together Use v2 field names, headers, and identifiers together

Do not “fix” a rejection by changing only the network string. Select the protocol version first, then copy its field names, headers, scheme, and identifier format as one set. The facilitator’s capability response is the authority for what it currently accepts.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How should an endpoint behave when directory crawlers send GET?

Probe requests may be ordinary GET requests with no application body. The reported directory crawlers treated a 404 on an advertised /run path as evidence that the service did not exist, even though a real client would have sent a paid request.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Expose the x402 challenge before application-specific body validation on routes you advertise. A probe should reach the same authentication and payment middleware as a normal request and receive HTTP 402 with a valid accepts array, not a body-schema 400 or a route-level 404. Keep health checks and genuinely public metadata separate so crawler behavior does not weaken access control on the paid endpoint.

How can I test an x402 integration without spending USDC?

Start with a deliberately invalid signature. The author sent an invalid authorization and checked that the facilitator returned invalid_exact_evm_signature. That test exercises base64 decoding, JSON parsing, header extraction, requirement construction, and facilitator reachability without attempting a successful payment.

  1. Call the endpoint without a payment header and confirm it returns the expected 402 challenge.
  2. Capture the challenge exactly as the client sees it, including version, scheme, network, amount, recipient, and asset.
  3. Create a syntactically valid payload with an intentionally invalid EVM signature; do not broadcast anything.
  4. Encode the payload as the payment header and retry the endpoint.
  5. Confirm that your server calls /verify, returns the facilitator’s invalid reason, and does not call /settle.
  6. Inspect logs for a clean distinction between challenge generation, verification failure, and application errors.

A negative signature test proves plumbing only. It does not prove that a valid authorization settles, that replayed nonces are rejected, that the recipient and amount are enforced, or that your service behaves correctly when the facilitator times out. Add those tests with a funded test arrangement or a controlled production-like environment before charging real users.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What should I check before putting a pay-per-call API in production?

  • Version alignment: Keep the declared x402 version, typed objects, headers, and network identifier from the same protocol generation.
  • Challenge correctness: Return a 402 challenge on the first request and on probeable GET routes, before request-body validation.
  • Asset and amount checks: Compare the facilitator-facing requirement with your own expected USDC asset, atomic amount, and recipient.
  • Authorization safety: Enforce validity timestamps and rely on nonce handling that prevents replay.
  • Facilitator capabilities: Check /supported for the exact scheme, version, network, and asset; do not assume support from a marketing page.
  • Fail-closed behavior: Never return the paid resource when verification is false, settlement fails, or a facilitator response is malformed or unavailable.
  • Timeouts and retries: Bound network calls and make retries idempotent so a transport retry does not create an unintended second settlement attempt.
  • Receipts: Preserve the settlement success result and transaction hash, then expose the protocol’s payment-response header to the client.
  • Observability: Record request IDs, protocol version, scheme, network, facilitator outcome, and invalid reasons while excluding private keys and full sensitive payloads.
  • Operational claims: Treat statements such as “zero paying calls so far” as an author’s self-report, not as audited uptime, conversion, or settlement performance.

What is the difference between a custom transfer flow and x402?

A custom transfer flow can be valid for a private integration, but it is not automatically compatible with x402 clients. The practical differences are visible at the wire level.

Implementation choice Client input Server responsibility Main interoperability risk
Custom USDC transfer plus transaction hash A separately broadcast transfer and a hash Invent transfer checks, confirmation rules, and error handling x402 clients cannot discover or construct the expected payment payload
x402 with facilitator Signed authorization in the protocol payment header Emit requirements, call verification, then settlement, and return a receipt Version, scheme, network, facilitator, or header mismatch

The x402 approach gives agents a predictable challenge and a standard verification/settlement boundary. It does not remove trust decisions: you still choose a facilitator, enforce your own price and recipient, protect against replay, and decide how to handle unavailable infrastructure.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

What was the actual lesson from the postmortem?

The bug was not that USDC could not pay for an API. The bug was treating payment as an application-specific transfer instead of implementing the x402 contract that clients already understand. Once the endpoint emitted a precise challenge, accepted a signed EIP-3009 authorization, and delegated verification and settlement in the required order, the API could participate in the agent payment flow without embedding wallet custody or a bespoke transaction parser.

Frequently Asked Questions

Can I send a transaction hash in the x402 payment header?

No. A transaction hash refers to a broadcast transaction and does not contain the signed authorization that the facilitator verifies before settlement. The header must carry the payment payload format required by the selected x402 version and scheme.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which EIP-3009 values are important for replay protection?

The authorization’s nonce, validity start and end times, payer, recipient, and amount all matter. A unique nonce prevents the same authorization from being accepted repeatedly, while the time window limits when it can be used.

What should my API do if the facilitator is down?

Fail closed: do not return the paid resource when verification or settlement cannot be completed. Record the outage and let the client retry according to a bounded policy rather than silently treating an unavailable facilitator as payment success.

Does an invalid-signature test prove that settlement works?

No. It confirms that your endpoint can parse the header and reach verification, but it intentionally stops before a valid authorization is settled. You still need a controlled test for successful settlement, receipt handling, timeout recovery, and replay rejection.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Base networkEIP-3009Facilitatorpay-per-call APIPythonUSDCx402

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.