keepcalculator

06 Numbers and Powers

Verify x402 Payment Requests Before API Calls

Card No. 06·68171 · Updated · Standard formula, shown below

This guide explains how to verify x402 payment requests before your agent calls an API. x402 is a payment protocol that uses HTTP 402 responses to request payment, and verifying these requests ensures your agent only proceeds after legitimate payment confirmation, preventing fraud and wasted resources. You’ll learn the step-by-step verification process, common pitfalls, and troubleshooting tips.

What You’ll Need

  • Access to the x402 payment request object (usually received as a JSON payload in the HTTP 402 response).
  • The API endpoint URL that issued the request.
  • A basic understanding of cryptographic signatures and public/private key pairs.
  • Your agent’s payment processing logic (e.g., a wallet or payment provider integration).
  • Network access to verify the payment status (if required by the protocol).

Step-by-Step

  1. Parse the x402 request: Extract the JSON payload from the HTTP 402 response. The payload typically contains fields like paymentRequest, paymentAmount, paymentCurrency, paymentMemo, and paymentSignature. Ensure the JSON is valid and complete.
  2. Validate the request structure: Check that all required fields are present and correctly formatted. The paymentRequest should be a URL (e.g., a Lightning invoice or a payment link), paymentAmount should be a positive number, and paymentCurrency should be a recognized currency code (e.g., BTC, USD). If any field is missing or malformed, reject the request.
  3. Verify the signature: The paymentSignature is a cryptographic signature that proves the request came from the legitimate API provider. Obtain the provider’s public key (usually available from a trusted directory or the API’s documentation). Use a standard library (e.g., crypto in Node.js) to verify the signature against the payload (excluding the signature field itself). If verification fails, do not proceed.
  4. Check the payment amount and currency: Compare the paymentAmount and paymentCurrency with the expected cost for the API call. If the amount is unexpectedly high or the currency is not supported, flag it for review. This prevents overpaying due to malicious or erroneous requests.
  5. Validate the payment request URL: Ensure the paymentRequest URL uses a secure scheme (e.g., https: or a valid Lightning invoice). Do not follow or process URLs with javascript: or other insecure schemes. For Lightning invoices, you can parse the invoice to confirm it’s well-formed.
  6. Check for replay protection: If the x402 request includes a nonce or timestamp, verify that it is fresh (e.g., within the last 5 minutes) and hasn’t been used before. Maintain a local cache of recent nonces to prevent replay attacks.
  7. Confirm payment status (if required): Some x402 implementations require you to check with the payment provider that the payment has actually been settled. Use the payment provider’s API or a status endpoint to confirm the payment is complete before making the API call. This step is crucial for high-value transactions.
  8. Call the API: Once all verification steps pass, proceed to call the API endpoint with the payment proof (e.g., include the payment hash or receipt in the request headers). If any step fails, abort and handle the error gracefully.

Common Mistakes

  • Skipping signature verification: Assuming the request is legitimate because it came from a familiar API. Always verify the signature to prevent man-in-the-middle attacks.
  • Ignoring the currency: Accepting a payment request in a different currency than expected, leading to overpayment or conversion issues.
  • Not checking for replay: Reusing a previously seen payment request, which could cause duplicate payments or unauthorized access.
  • Trusting the URL blindly: Following a payment request URL that redirects to a phishing site or contains malicious parameters.
  • Assuming payment is settled: Calling the API before the payment is actually confirmed, resulting in failed API calls or lost funds.

Tips

  • Use a well-tested cryptographic library to avoid implementation errors in signature verification.
  • Implement a timeout for payment verification to avoid hanging the agent indefinitely.
  • Log all verification steps for auditability and debugging.
  • Consider using a payment middleware that handles x402 verification automatically.
  • Keep your public key store updated and secure.

Troubleshooting

If verification fails, here’s what to check:

  • Signature verification fails: Double-check that you’re using the correct public key. Ensure the signature is over the exact payload (including all fields) and that you’re not including the signature itself. Try re-verifying with a different library or tool.
  • Payment status shows unpaid: Wait a few seconds and re-check. Sometimes payment settlement is delayed. If it remains unpaid, the payment may have been cancelled—abort the API call.
  • Nonce or timestamp is invalid: Check your system clock; it may be out of sync. If the nonce is already used, it’s a replay attempt—reject it.
  • Currency mismatch: Verify that the API provider’s expected currency hasn’t changed. Check the API documentation for updates.
  • Malformed JSON: Use a JSON validator to ensure the payload is well-formed. Some providers may include extra fields—ignore them but don’t fail.

Frequently Asked Questions

What exactly is an x402 payment request?

An x402 payment request is a structured message sent in an HTTP 402 response, asking the client to pay before accessing a resource. It includes payment details and a signature to authenticate the request.

Do I always need to verify the signature?

Yes, always verify the signature. It’s the primary way to ensure the request is from the legitimate API provider and hasn’t been tampered with.

Can I skip payment status verification?

For low-value or idempotent API calls, you might skip it, but it’s not recommended. Skipping it risks calling the API without a confirmed payment, leading to errors or financial loss.

How do I get the API provider’s public key?

The public key is usually published in the API’s documentation or a well-known endpoint (e.g., /.well-known/x402). Always fetch it over HTTPS.

What if the payment request amount is higher than expected?

Reject the request and log it. It could be a mistake or a malicious attempt. Contact the API provider if it persists.

Is x402 compatible with all payment methods?

x402 is designed to be payment-method agnostic. It can support Lightning, Stripe, or other payment links, as long as the request includes a valid payment URL.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →