Payments API

Create and manage payments between agents and users using the x402 and h402 protocols.

Create Payment

Create a new payment request between agents or users.

bash
POST /api/payments

Request Body

ParameterTypeDescription
amountstringPayment amount in the specified currency
currencystringCurrency code (ETH, USDC, DAI)
descriptionstringDescription of the payment
typestringPayment type (immediate, escrow, time-locked)
expiresInstring?Optional expiration time (e.g. "30m", "24h", "7d")
requirementsobject?Optional payment requirements (callbackUrl, etc.)
metadataobject?Optional metadata for the payment

Response

json
{
  "status": 200,
  "message": "Payment request created successfully",
  "data": {
    "paymentRequest": {
      "id": "uuid",
      "amount": "1.0",
      "currency": "ETH",
      "description": "Payment for services",
      "status": "pending",
      "expiresAt": "2024-03-21T12:00:00Z",
      "createdAt": "2024-03-20T12:00:00Z",
      "metadata": {}
    },
    "paymentUrl": "https://paydirect.com/pay/uuid"
  }
}

Get Payment

Retrieve details of a specific payment.

bash
GET /api/payments/:paymentId

Parameters

ParameterTypeDescription
paymentIdstringUnique identifier of the payment

Response

json
{
  "status": 200,
  "message": "Payment request retrieved successfully",
  "data": {
    "paymentRequest": {
      "id": "uuid",
      "amount": "1.0",
      "currency": "ETH",
      "description": "Payment for services",
      "status": "pending",
      "expiresAt": "2024-03-21T12:00:00Z",
      "createdAt": "2024-03-20T12:00:00Z",
      "metadata": {}
    }
  }
}

Update Payment

Update the status or metadata of a payment.

bash
PATCH /api/payments/:paymentId

Request Body

ParameterTypeDescription
statusstringNew payment status (pending, completed, failed, expired, cancelled)
metadataobject?Optional metadata to update

Response

json
{
  "status": 200,
  "message": "Payment request updated successfully",
  "data": {
    "paymentRequest": {
      "id": "uuid",
      "amount": "1.0",
      "currency": "ETH",
      "description": "Payment for services",
      "status": "completed",
      "expiresAt": "2024-03-21T12:00:00Z",
      "createdAt": "2024-03-20T12:00:00Z",
      "metadata": {
        "customField": "value"
      }
    }
  }
}

Cancel Payment

Cancel a pending payment request.

bash
DELETE /api/payments/:paymentId

Parameters

ParameterTypeDescription
paymentIdstringUnique identifier of the payment to cancel

Response

json
{
  "status": 200,
  "message": "Payment request cancelled successfully"
}

List Payments

Retrieve a list of payments with optional filtering.

bash
GET /api/payments

Query Parameters

ParameterTypeDescription
statusstring?Filter by payment status (pending, completed, failed, expired, cancelled)
currencystring?Filter by currency
pagenumber?Page number for pagination (default: 1)
limitnumber?Number of items per page (default: 20, max: 100)

Response

json
{
  "status": 200,
  "message": "Payments retrieved successfully",
  "data": {
    "payments": [
      {
        "id": "uuid",
        "amount": "1.0",
        "currency": "ETH",
        "description": "Payment for services",
        "status": "completed",
        "expiresAt": "2024-03-21T12:00:00Z",
        "createdAt": "2024-03-20T12:00:00Z",
        "metadata": {}
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 20,
      "total": 1
    }
  }
}

Payment Statuses

StatusDescription
pendingPayment request is waiting to be processed
completedPayment has been successfully processed
failedPayment processing failed
expiredPayment request has expired
cancelledPayment request was cancelled

Expiration

Payment requests can have an expiration time specified using the expiresIn parameter. The expiration time can be specified in the following formats:

FormatExampleDescription
minutes30m30 minutes from creation
hours24h24 hours from creation
days7d7 days from creation

If no expiration time is specified, the payment request will expire after 24 hours by default. Expired payment requests cannot be processed and will need to be recreated.

Status Tracking

Payment status can be tracked through the API. The status will automatically update to "expired" when the expiration time is reached. You can also manually update the status using the Update Payment endpoint.

Webhooks

You can receive real-time updates about payment status changes by configuring a webhook URL in the payment requirements. The webhook will be called with the following events:

EventDescription
payment.createdPayment request was created
payment.completedPayment was successfully processed
payment.failedPayment processing failed
payment.expiredPayment request has expired
payment.cancelledPayment request was cancelled

Example Webhook Payload

json
{
  "event": "payment.expired",
  "data": {
    "paymentRequest": {
      "id": "uuid",
      "amount": "1.0",
      "currency": "ETH",
      "description": "Payment for services",
      "status": "expired",
      "expiresAt": "2024-03-21T12:00:00Z",
      "createdAt": "2024-03-20T12:00:00Z"
    }
  },
  "timestamp": "2024-03-21T12:00:00Z"
}

Error Codes

CodeDescription
400Bad Request - Invalid parameters or missing required fields
401Unauthorized - Invalid or missing API key
403Forbidden - Payment does not belong to merchant
404Not Found - Payment not found
429Too Many Requests - Rate limit exceeded
500Internal Server Error

Try it Out

Visit our interactive playground to test the Payments API with real examples:

Transaction Status Tracking

Track the status of blockchain transactions associated with payments.

Transaction Statuses

StatusDescription
pendingTransaction is pending confirmation on the blockchain
confirmedTransaction has been confirmed on the blockchain
failedTransaction failed on the blockchain
droppedTransaction was dropped from the mempool

Get Transaction Status

bash
GET /api/payments/:paymentId/transaction

Response

json
{
  "status": 200,
  "data": {
    "transaction": {
      "hash": "0x...",
      "status": "confirmed",
      "confirmations": 12,
      "blockNumber": 12345678,
      "timestamp": "2024-03-21T12:00:00Z",
      "error": null
    }
  }
}

Error Handling

Error CodeDescription
INSUFFICIENT_GASTransaction failed due to insufficient gas
INSUFFICIENT_FUNDSTransaction failed due to insufficient balance
NONCE_TOO_LOWTransaction nonce is too low
REPLACEMENT_UNDERPRICEDTransaction replacement is under-priced

Wallet Integration

Check wallet balances and validate addresses before processing payments.

Get Wallet Balance

bash
GET /api/wallets/:address/balance

Parameters

ParameterTypeDescription
addressstringWallet address to check
currencystring?Optional currency to check (default: ETH)

Response

json
{
  "status": 200,
  "data": {
    "address": "0x...",
    "balances": {
      "ETH": "1.23456789",
      "USDC": "1000.00",
      "DAI": "500.00"
    },
    "isValid": true,
    "lastUpdated": "2024-03-21T12:00:00Z"
  }
}

Validate Address

bash
POST /api/wallets/validate

Request Body

ParameterTypeDescription
addressstringWallet address to validate
chainIdnumber?Optional chain ID for validation (default: 1 for Ethereum mainnet)

Response

json
{
  "status": 200,
  "data": {
    "address": "0x...",
    "isValid": true,
    "checksumAddress": "0x...",
    "chainId": 1,
    "validationDetails": {
      "isContract": false,
      "isEOA": true,
      "hasCode": false
    }
  }
}

When creating a payment, the system will automatically check the sender's wallet balance. If the balance is insufficient, the payment request will be rejected with an INSUFFICIENT_FUNDS error.

Transaction Confirmation System

Monitor and track blockchain transaction confirmations in real-time.

Get Transaction Confirmation Status

bash
GET /api/payments/:paymentId/transaction/confirmation

Response

json
{
  "status": 200,
  "data": {
    "transaction": {
      "hash": "0x...",
      "status": "confirmed",
      "confirmations": 12,
      "requiredConfirmations": 6,
      "blockNumber": 12345678,
      "blockHash": "0x...",
      "receipt": {
        "status": true,
        "gasUsed": "21000",
        "effectiveGasPrice": "20000000000",
        "logs": []
      },
      "timestamp": "2024-03-21T12:00:00Z"
    }
  }
}

Webhook Events

EventDescription
transaction.confirmedTransaction has reached required confirmations
transaction.failedTransaction failed on the blockchain
transaction.replacedTransaction was replaced with a new one

Payment Flow Completion

Handle payment completion with redirects and callbacks.

Configurable Redirect URLs

Configure where users are redirected after different payment states.

StatusURL ParameterDescription
SuccesssuccessUrlRedirect after successful payment completion
FailurefailureUrlRedirect after payment failure or error
CancelledcancelUrlRedirect when user cancels the payment
PendingpendingUrlRedirect while payment is being processed

Example Configuration

json
{
  "amount": "1.0",
  "currency": "ETH",
  "description": "Payment for services",
  "requirements": {
    "successUrl": "https://your-domain.com/payment/success",
    "failureUrl": "https://your-domain.com/payment/failed",
    "cancelUrl": "https://your-domain.com/payment/cancelled",
    "pendingUrl": "https://your-domain.com/payment/pending"
  }
}

All redirect URLs are optional. If not provided, users will stay on the payment page and see the appropriate status message. We recommend implementing all URLs for the best user experience.

URL Parameters

The following parameters are appended to your redirect URLs:

ParameterDescription
paymentIdUnique identifier for the payment
statusPayment status (completed, failed, cancelled, pending)
amountPayment amount
currencyPayment currency

Example Redirect

bash
https://your-domain.com/payment/success?paymentId=123&status=completed&amount=1.0&currency=ETH

Implementation Example

typescript
// Create payment request with redirect URLs
const paymentRequest = await X402Protocol.createPaymentRequest(merchantId, {
  amount: "1.0",
  currency: "ETH",
  description: "Payment for services",
  requirements: {
    successUrl: "https://your-domain.com/payment/success",
    failureUrl: "https://your-domain.com/payment/failed",
    cancelUrl: "https://your-domain.com/payment/cancelled",
    pendingUrl: "https://your-domain.com/payment/pending"
  }
});

// Handle redirect in your frontend
const handlePaymentComplete = async (status: PaymentStatus) => {
  const redirectUrl = X402Protocol.getRedirectUrl(paymentRequest, status);
  if (redirectUrl) {
    window.location.href = redirectUrl;
  }
};

Error Recovery

Handle failed transactions and implement recovery mechanisms.

Retry Failed Transaction

bash
POST /api/payments/:paymentId/transaction/retry

Request Body

ParameterTypeDescription
gasPricestring?Optional gas price for retry (in wei)
maxFeePerGasstring?Optional max fee per gas (EIP-1559)
maxPriorityFeePerGasstring?Optional max priority fee per gas (EIP-1559)

Response

json
{
  "status": 200,
  "data": {
    "transaction": {
      "hash": "0x...",
      "status": "pending",
      "previousHash": "0x...",
      "retryCount": 1,
      "timestamp": "2024-03-21T12:00:00Z"
    }
  }
}

The system will automatically attempt to recover from common transaction failures: - Insufficient gas: Will retry with higher gas price - Nonce issues: Will automatically adjust nonce - Network congestion: Will implement exponential backoff

Error Recovery Status

StatusDescription
retryingTransaction is being retried with adjusted parameters
recoveredTransaction was successfully recovered
failedTransaction failed after all retry attempts

Error Response Format

All API errors follow a standardized format for easier handling and debugging.

json
{
  "status": 401,
  "message": "Unauthorized: Missing or invalid API key",
  "code": "INVALID_API_KEY",
  "details": null,
  "data": null
}

Common Error Codes

CodeDescription
INVALID_API_KEYAPI key is missing, invalid, or revoked
RATE_LIMIT_EXCEEDEDToo many requests; rate limit exceeded
EXPIRED_PAYMENTPayment request has expired
INSUFFICIENT_FUNDSWallet does not have enough funds
INTERNAL_SERVER_ERRORUnexpected server error

Process Transaction

Handle transaction processing with the processTransaction function.

typescript
processTransaction(
  paymentId: string,
  walletAddress: string,
  merchantWalletAddress: string,
  amount: string,
  currency: string
)
ParameterTypeDescription
paymentIdstringID of the payment request to process
walletAddressstringSender's wallet address
merchantWalletAddressstringRecipient's wallet address
amountstringPayment amount
currencystringPayment currency

Response

json
{
  "success": true,
  "transactionId": "tx-abc123..."
}

The processTransaction function requires all 5 parameters to be provided as separate arguments. Do not pass them as a single object. The function will return an error if any required parameter is missing.