Set up x402 payment middleware

To enable agent commerce with KYC/AML checks, install the necessary dependencies and configure the payment middleware. This layer intercepts HTTP 402 responses, ensuring that only verified agents can proceed with API calls.

1
Install the x402 SDK

Start by adding the official x402 client library to your project. This package provides the core functions for handling payment requests and verifying agent credentials. Run the following command in your terminal:

Shell
Shell
npm install @x402/sdk

This step establishes the foundation for all subsequent middleware logic. For a complete list of available packages, refer to the x402 developer documentation.

2
Configure the middleware layer

Next, initialize the middleware in your API server. This involves setting up the KYC/AML check endpoint and defining the rules for payment acceptance. The middleware will automatically respond with HTTP 402 status codes when an agent lacks valid verification or payment.

JavaScript
JavaScript
import { x402Middleware } from '@x402/sdk';

app.use(x402Middleware({
  kycEndpoint: '/api/kyc/verify',
  paymentGateway: 'stripe'
}));

Ensure your configuration points to a reliable KYC provider. Coinbase offers a quickstart guide for sellers that details best practices for integrating payment gateways with x402.

3
Test the integration

Before deploying to production, test the middleware with a simulated agent request. Use a tool like Postman or cURL to send a request to your API endpoint. You should receive an HTTP 402 response if the agent is not verified.

Shell
Shell
curl -X POST http://localhost:3000/api/agent-check

Verify that the response includes the necessary payment instructions and KYC verification links. This step confirms that your middleware is correctly intercepting requests and enforcing compliance.

Integrate KYC verification logic

Embedding KYC/AML checks as a gate before service delivery ensures compliance within the x402 flow. This approach treats verification not as an afterthought, but as a mandatory prerequisite for any transaction. By integrating these checks directly into the endpoint logic, you prevent unauthorized access and ensure that only verified entities can initiate payments or receive services.

1. Install verification dependencies

Before routing checks through an x402-enabled API, you must install the necessary dependencies. These libraries provide the cryptographic and validation tools required to handle sensitive identity data securely. Ensure your environment supports the specific versions recommended by the x402 specification to avoid compatibility issues during the verification handshake.

2. Configure the payment gateway

Configure the payment gateway to recognize KYC status as a condition for transaction approval. This involves setting up webhooks or synchronous calls that query the verification status of the user. If the user lacks a verified status, the gateway should reject the transaction attempt immediately, returning a clear error code that indicates the need for compliance review.

Note: Regulatory requirements for KYC/AML in cross-border transactions vary by jurisdiction. Ensure your integration logic accounts for the specific compliance standards of the regions involved in your transactions.

3. Implement the verification gate

Create a middleware function that acts as the gatekeeper for your x402 endpoints. This function should intercept incoming requests and check for a valid KYC token or verification ID. If the token is missing or expired, the request is halted before any business logic is executed. This ensures that no service is delivered to an unverified entity, maintaining the integrity of your compliance framework.

4. Handle verification failures gracefully

When a verification check fails, provide clear, actionable feedback to the user. Avoid generic error messages; instead, specify whether the failure was due to missing documents, expired credentials, or a mismatch in identity data. This transparency helps users resolve issues quickly, reducing friction in the user experience while maintaining strict compliance standards.

5. Log and audit verification events

Maintain detailed logs of all verification attempts and outcomes. These logs are essential for auditing and regulatory reporting. Ensure that your logging mechanism captures the timestamp, user ID, verification status, and any error codes returned by the compliance provider. This data provides a clear trail of compliance efforts and helps identify potential security threats or systemic issues.

6. Test the end-to-end flow

Thoroughly test the integration using sandbox environments provided by your compliance provider. Simulate various scenarios, including successful verifications, failed attempts, and expired tokens. This testing phase is critical to ensuring that your x402 endpoints behave correctly under all conditions, preventing compliance breaches in production.

7. Monitor and update compliance rules

Compliance requirements evolve over time. Regularly review and update your verification logic to align with the latest regulatory guidelines. Subscribe to updates from relevant financial authorities and your compliance provider to stay informed about changes that may impact your integration. Proactive monitoring helps you maintain compliance without disrupting your service delivery.

Structure payment schemes for access

When integrating x402 endpoints for KYC/AML checks, your payment model determines how the agent handles verification costs. The protocol supports two primary billing structures: exact and upto. Choosing the right scheme depends on whether your service has fixed pricing or variable compliance requirements.

Exact payment model

The exact model requires the agent to pay a predetermined amount before the endpoint processes the request. This approach works best for standardized checks with fixed costs, such as a basic identity verification or a simple sanctions list scan. The agent calculates the precise fee, includes it in the payment, and the service responds only if the funds are sufficient.

This model is predictable and simple to implement. There is no ambiguity about the cost, which reduces friction in automated workflows. However, it lacks flexibility for complex cases where the verification might require additional steps or deeper background checks that exceed the initial estimate.

Upto payment model

The upto model allows the agent to send a maximum allowable amount, while the actual charge is determined after the service completes the work. This is ideal for KYC processes that vary in complexity. For example, a basic check might cost $0.50, but a full enhanced due diligence process could cost $2.00. The agent sends $2.00 as the limit, and the endpoint charges only what is necessary.

This approach protects the user from overpaying for simple tasks while ensuring the service provider is compensated for more intensive work. It requires the endpoint to return the actual charged amount in the response, allowing the agent to reconcile the transaction accurately.

Comparison of payment schemes

The table below outlines the key differences between the two models to help you decide which fits your integration.

FeatureExact PaymentUpto PaymentBest Use Case

Secure agent commerce transactions

When an AI agent acts as a buyer or seller, the stakes are higher than in standard e-commerce. A malicious facilitator could theoretically intercept a transaction, steal the funds, or lie about whether a service was actually delivered. x402 solves this by removing the middleman’s ability to hold your money.

The security comes from how the payment is structured. Every PaymentPayload is cryptographically signed by the buyer. This signature proves intent and authorizes the specific amount for that specific service. Crucially, the settlement happens directly onchain. The funds don’t sit in a third-party escrow account where they can be frozen or stolen; they move from the buyer’s wallet to the agent’s wallet only when the conditions are met.

This onchain settlement means there is no ambiguity. If a facilitator tries to lie about the settlement status, the blockchain ledger provides the single source of truth. The transaction either exists on the chain, or it doesn’t. There is no hidden ledger for the facilitator to manipulate.

100%
of settlements are onchain

By keeping the money flow transparent and direct, x402 ensures that your agent’s commerce interactions are secure against common fraud vectors like fund misappropriation or false reporting.

Verify integration with test flows

Before launching x402 endpoints for KYC/AML checks, run a complete end-to-end test. This ensures the payment triggers the verification correctly and the agent receives access only after clearance. Follow this sequence to validate the handshake between the payment layer and the compliance check.

  • Initiate a test transaction: Send a small payment from a test agent or buyer wallet to your x402 endpoint.
  • Confirm payment receipt: Verify that the endpoint detects the transaction on-chain and pauses the service response.
  • Trigger KYC check: Ensure the endpoint calls your compliance provider (e.g., Sumsub, Onfido) with the user’s identifier.
  • Validate compliance response: Confirm the endpoint receives a "pass" or "fail" status from the provider.
  • Grant or deny access: If the check passes, the endpoint should return the service data; if it fails, it should return an error.
  • Test edge cases: Run tests with failed KYC checks, expired tokens, and network timeouts to ensure graceful handling.

For detailed implementation steps, refer to the Coinbase x402 Quickstart guide.

Common integration: what to check next

Integrating x402 for KYC/AML checks requires understanding how payments and compliance interact. Here are answers to frequent developer concerns.