Set up the x402 payment gate

Before you can verify identity or process sensitive data, you need a way to ensure the requester has paid. This section walks you through converting a standard HTTP route into an x402-gated endpoint. The goal is simple: verify the payment signature before your KYC/AML logic ever runs.

We follow the official Coinbase CDP quickstart logic, which moves you from an unprotected route to a verified endpoint in a few distinct steps.

x402 Endpoints for KYC/AML Checks
1
Create the base endpoint

Start with a standard HTTP endpoint that returns your KYC/AML response. At this stage, it should be open and unprotected. This serves as your baseline to ensure the data payload is correct before adding the payment layer. Think of this as the "after" state—you want to protect what is already working.

x402 Endpoints for KYC/AML Checks
2
Add the x402 middleware

Insert the x402 middleware function into your route handler. This middleware intercepts the incoming request and checks for a valid payment signature in the headers. If the signature is missing or invalid, the middleware returns a 402 Payment Required error immediately, preventing any further execution of your KYC logic.

to x402 Endpoints for KYC/AML Checks
3
Configure the payment verification

Define the expected payment amount and the verification logic within the middleware. You must ensure that the middleware is configured to accept the specific payment token or currency required for your service. This step locks down the financial requirement, ensuring that only verified, paid requests proceed to the identity verification stage.

to x402 Endpoints for KYC/AML Checks
4
Test the gate with a payment

Send a test request with a valid x402 payment signature. If the setup is correct, the middleware should validate the payment and allow the request to pass through to your KYC/AML endpoint. If it fails, check the signature format and the middleware configuration. This confirms that the gate is functioning as intended.

By following this sequence, you ensure that your KYC/AML checks are only triggered by legitimate, paid requests. This reduces unnecessary load on your verification services and ensures compliance with payment-gated data access standards.

Integrate KYC identity verification

The x402 protocol treats every request as a payable interaction. To satisfy KYC and AML requirements, you must verify the payer’s identity before the endpoint returns sensitive data. This ensures that only verified entities can access the resource, turning the payment flow into a compliance gate.

The process follows the standard KYC lifecycle: Customer Identification Program (CIP), Customer Due Diligence (CDD), and ongoing monitoring. You embed these checks directly into the x402 request handler. If the identity verification fails, the endpoint returns an error or a specific "unverified" response code rather than the requested data.

1. Collect Identity Data

Before processing the payment, your frontend or API gateway must collect the necessary identity fields. This typically includes full legal name, government-issued ID number, and date of birth. Store this data securely and link it to the transaction ID generated by the x402 payment.

2. Verify with a Trusted Provider

Send the collected identity data to a reputable KYC provider (e.g., Jumio, Onfido, or Sumsub). Use their API to validate the ID document and perform a live identity check. The provider returns a verification status (verified, rejected, or pending). Do not proceed until you receive a clear "verified" status.

Once the identity is confirmed, associate the verification result with the x402 payment transaction. You can store this link in your database or on-chain (if applicable). This creates an audit trail: the payer has paid, and their identity is confirmed. This step is critical for regulatory reporting.

4. Return Data or Reject

If the identity verification is successful and the payment is confirmed, the endpoint returns the sensitive data. If verification fails or is pending, the endpoint should return a specific error code (e.g., 403 Forbidden: Identity Unverified) and no data. This prevents unauthorized access while maintaining the x402 payment integrity.

Add AML screening to the flow

Once you have verified the user’s identity, you need to ensure their funds aren’t linked to illegal activity. This is where AML (Anti-Money Laundering) screening comes in. While KYC confirms who the user is, AML checks if they are allowed to move money. You’ll need to screen both the sender and the recipient against global sanctions lists and Politically Exposed Persons (PEPs) databases.

Think of this step as a background check for the transaction itself. Even if the user is real, their wallet address or bank account might be flagged for ties to terrorism, drug trafficking, or sanctioned countries. Integrating this into your x402 endpoint ensures compliance before any payment is processed.

1
Fetch the screening data

Before sending the transaction, extract the relevant identifiers. This usually means the user’s wallet address, bank account number, or IBAN. If you’re dealing with fiat, you might also need the account holder’s name. Ensure you’re capturing the most granular data possible, as sanctions lists often flag specific addresses rather than general account numbers.

2
Call the AML API endpoint

Make a synchronous or asynchronous API call to your chosen AML provider. Common providers include Chainalysis, Elliptic, or Refinitiv. Send the extracted identifiers in the request body. Most providers offer a "screening" endpoint that returns a risk score and a list of any matches found on sanctions lists (like OFAC, UN, or EU lists) or PEP databases.

3
Evaluate the risk score

Analyze the response. A low risk score (e.g., 0-30) typically means the transaction is clear. A medium score (30-70) might require manual review or additional due diligence. A high score (70-100) or a direct match on a sanctions list means you must block the transaction immediately. Do not proceed with the payment if there is a positive hit on a sanctions list.

4
Log the compliance decision

Record the screening result in your database. This is crucial for audits. You need to prove that you checked the user against sanctions lists at the time of the transaction. Store the risk score, the timestamp, and the provider’s response ID. If you blocked the transaction, note the reason (e.g., "OFAC Match").

It’s worth noting that AML screening is not a one-time check. If the user’s risk profile changes (e.g., they are added to a sanctions list later), you may need to re-screen them for future transactions. Some providers offer continuous monitoring APIs that alert you to changes in real-time.

Handle compliance errors and retries

KYC and AML endpoints are rarely 100% deterministic. You will encounter network timeouts, provider outages, and false-positive screening flags. Treating these failures as system errors rather than business signals leads to frustrated users and potential regulatory gaps.

Your error handling strategy must distinguish between transient technical issues and definitive compliance decisions. A 503 service unavailable from the screening provider is a retry candidate. A "match found" response from a sanctions list is a hard stop that requires human review, not an automatic retry.

Timeouts and transient failures

When an x402 endpoint times out, the payment status is ambiguous. Did the screening complete? Did the money move? Never assume success. Implement exponential backoff for transient network errors (408, 500, 502, 503, 504). Limit retries to three attempts to avoid blocking the user indefinitely.

If the endpoint remains unreachable after retries, pause the transaction and queue the request. Log the error context, including the user ID and screen attempt count. Inform the user that their verification is under review rather than failing outright. This maintains trust while you investigate.

Screening mismatches and false positives

A screening match does not always mean the user is a sanctioned entity. Name matches are common. Your system must return a specific error code indicating a "potential match" rather than a hard "blocked" status. This allows your backend to trigger a manual review workflow.

Do not retry the screening immediately for a match. Retrying will yield the same result. Instead, flag the record for compliance officer review. Provide the officer with the raw screening response, the user's provided data, and any previous attempts. This context speeds up resolution and reduces false negatives.

Payment timeouts and idempotency

If the x402 payment request times out, you cannot assume the funds were transferred. Use idempotency keys for all payment attempts. If the same key is sent again, the provider should return the original response rather than charging the user twice.

Implement a reconciliation job that runs periodically. This job checks the status of any transactions that were in a "pending" state for more than a defined threshold (e.g., 24 hours). If the provider's status is still unknown, attempt a status check using the original transaction ID. If the transaction is lost, refund the user and notify them.

Compliance error checklist

Before launching your integration, verify these error handling paths:

  • Timeouts trigger exponential backoff, not immediate failure
  • Screening matches return a "potential match" code, not a hard block
  • Idempotency keys are used for all payment requests
  • Reconciliation jobs run periodically for pending transactions
  • Users are informed of review status, not just "error"

Robust error handling protects your platform from regulatory fines and your users from unnecessary friction. Treat compliance errors as part of the user journey, not as exceptions to be ignored.

Select tools for agent commerce

Building an agent commerce layer requires balancing speed with strict regulatory overhead. You need infrastructure that automates identity verification without becoming a bottleneck for autonomous transactions. The right tools reduce manual review while keeping your compliance posture intact.

Start with an automated KYC provider that supports API-first integration. Look for services that offer real-time document verification and watchlist screening. These tools handle the heavy lifting of initial identity checks, allowing your agents to proceed with transactions only after verification is complete. This reduces the risk of onboarding bad actors.

For the payment layer, choose an x402-compliant gateway that natively supports machine-to-machine payments. The gateway must handle microtransactions efficiently while logging every interaction for audit trails. This dual approach ensures that financial flows are both fast and traceable.

x402 Endpoints for KYC/AML Checks

Finally, implement a continuous monitoring system. Identity status can change; a verified user today might be flagged tomorrow. Integrate tools that allow you to pause or flag transactions based on real-time risk scores. This proactive stance is essential for high-stakes agent commerce where automated decisions happen without human intervention.

Common questions about x402 and compliance

Integrating x402 endpoints with KYC/AML checks often raises specific implementation questions. Here are answers to the most frequent developer concerns.

For more details on setting up the basic x402 flow, refer to the Coinbase CDP quickstart guide.