### Install FastAPI and x402 Dependencies Source: https://docs.payai.network/x402/servers/python/fastapi Installs required packages including FastAPI, Uvicorn, python-dotenv, and the x402 library for handling payments. ```bash pip install x402 fastapi uvicorn python-dotenv ``` -------------------------------- ### Install Dependencies for x402 httpx Client Source: https://docs.payai.network/x402/clients/python/httpx Installs the necessary Python packages for using the httpx client with x402 and eth-account. Ensure you have Python and pip installed. ```bash pip install httpx eth-account x402 python-dotenv ``` -------------------------------- ### Run the x402 httpx Client Source: https://docs.payai.network/x402/clients/python/httpx Executes the Python script to start the httpx client and initiate x402 payments. This command assumes the script is saved as main.py and dependencies are installed. ```bash python main.py ``` -------------------------------- ### Install x402 Client Dependencies Source: https://docs.payai.network/x402/clients/python/requests Install required Python packages for x402 payment client implementation including requests for HTTP operations, eth-account for blockchain interactions, x402 for payment handling, and python-dotenv for environment variable management. ```bash pip install requests eth-account x402 python-dotenv ``` -------------------------------- ### Install dependencies for Hono 402 payments Source: https://docs.payai.network/x402/servers/typescript/hono Installs the necessary packages including x402-hono for handling 402 payments, Hono for the server framework, dotenv for environment variables, and @hono/node-server for serving the app. ```bash npm install x402-hono hono dotenv @hono/node-server ``` -------------------------------- ### Install x402 and Flask Dependencies (Bash) Source: https://docs.payai.network/x402/servers/python/flask Installs Python packages required for x402 payments and Flask server. Uses pip package manager. No specific inputs or outputs; ensures libraries like x402, flask, and python-dotenv are available for the project. ```bash pip install x402 flask python-dotenv ``` -------------------------------- ### Initialize x402 Fetch Client Project Source: https://docs.payai.network/x402/clients/typescript/fetch Commands to bootstrap a new Fetch client project using different package managers. This creates a ready-to-run client based on the official starter template. ```bash npx @payai/x402-fetch-starter my-first-client ``` ```bash pnpm dlx @payai/x402-fetch-starter my-first-client ``` ```bash bunx @payai/x402-fetch-starter my-first-client ``` -------------------------------- ### Create Express Server Starter Template (npm) Source: https://docs.payai.network/x402/servers/typescript/express Initializes a new Express.js server project with x402 payment functionality using npm. This command bootstraps a ready-to-run Express server. ```bash npx @payai/x402-express-starter my-first-server ``` -------------------------------- ### Run Flask Server (Bash) Source: https://docs.payai.network/x402/servers/python/flask Starts the Flask development server using the flask command. Assumes the app is defined in main.py and environment is set. Inputs none; outputs server running on localhost:4021; suitable for development with debug mode enabled. ```bash flask run ``` -------------------------------- ### Create Express Server Starter Template (bun) Source: https://docs.payai.network/x402/servers/typescript/express Initializes a new Express.js server project with x402 payment functionality using bun. This command bootstraps a ready-to-run Express server. ```bash bunx @payai/x402-express-starter my-first-server ``` -------------------------------- ### Run Express Server (npm) Source: https://docs.payai.network/x402/servers/typescript/express Command to start the Express.js development server using npm. Assumes the project has a 'dev' script defined in package.json. ```bash npm run dev ``` -------------------------------- ### Configure Environment Variables for x402 Client Source: https://docs.payai.network/x402/clients/python/requests Set up required environment variables for x402 payment client including RESOURCE_SERVER_URL for the payment endpoint, ENDPOINT_PATH for API route, and PRIVATE_KEY for eth-account initialization. The .env file enables secure configuration management. ```bash echo "RESOURCE_SERVER_URL=http://localhost:4021\nENDPOINT_PATH=/weather\nPRIVATE_KEY=..." > .env ``` ```bash RESOURCE_SERVER_URL=http://localhost:4021 ENDPOINT_PATH=/weather PRIVATE_KEY=... # your private key ``` -------------------------------- ### Run FastAPI Server with Uvicorn Source: https://docs.payai.network/x402/servers/python/fastapi Starts the FastAPI development server with hot reloading enabled on port 4021. ```bash uvicorn main:app --reload ``` -------------------------------- ### Run the Hono server for 402 payments Source: https://docs.payai.network/x402/servers/typescript/hono Starts the Hono server using tsx to execute the TypeScript file directly, enabling the server to accept 402 payments on the configured port. ```bash npx tsx index.ts ``` -------------------------------- ### Create FastAPI App with Payment Middleware Source: https://docs.payai.network/x402/servers/python/fastapi Sets up a FastAPI application with x402 payment middleware applied to specific routes. Requires environment variables for address and facilitator URL. ```python import os from typing import Any, Dict from dotenv import load_dotenv from fastapi import FastAPI from x402.fastapi.middleware import require_payment from x402.facilitator import FacilitatorConfig from x402.types import EIP712Domain, TokenAmount, TokenAsset # Load environment variables load_dotenv() # Get configuration from environment ADDRESS = os.getenv("ADDRESS") FACILITATOR_URL = os.getenv("FACILITATOR_URL") if not ADDRESS or not FACILITATOR_URL: raise ValueError("Missing required environment variables") facilitator_config = FacilitatorConfig( url=FACILITATOR_URL, ) app = FastAPI() # Apply payment middleware to specific routes app.middleware("http")( require_payment( path="/weather", price="$0.001", pay_to_address=ADDRESS, network="base-sepolia", facilitator_config=facilitator_config, ) ) # Apply payment middleware to premium routes app.middleware("http")( require_payment( path="/premium/*", price=TokenAmount( amount="10000", asset=TokenAsset( address="0x036CbD53842c5426634e7929541eC2318f3dCF7e", decimals=6, eip712=EIP712Domain(name="USDC", version="2"), ), ), pay_to_address=ADDRESS, network="base-sepolia", facilitator_config=facilitator_config, ) ) @app.get("/weather") async def get_weather() -> Dict[str, Any]: return { "report": { "weather": "sunny", "temperature": 70, } } @app.get("/premium/content") async def get_premium_content() -> Dict[str, Any]: return { "content": "This is premium content", } if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=4021) ``` -------------------------------- ### Create Express Server Starter Template (pnpm) Source: https://docs.payai.network/x402/servers/typescript/express Initializes a new Express.js server project with x402 payment functionality using pnpm. This command bootstraps a ready-to-run Express server. ```bash pnpm dlx @payai/x402-express-starter my-first-server ``` -------------------------------- ### Implement x402 Payment Client with Custom Network Selector Source: https://docs.payai.network/x402/clients/python/requests Complete Python implementation of x402 payment client using requests library. Features custom payment selector for base-sepolia network filtering, eth-account integration, environment variable loading, and x402 payment handling with transaction hash validation. Handles errors and missing configuration gracefully. ```python import os from dotenv import load_dotenv from eth_account import Account from x402.clients.requests import x402_requests from x402.clients.base import decode_x_payment_response, x402Client # Load environment variables load_dotenv() # Get environment variables private_key = os.getenv("PRIVATE_KEY") base_url = os.getenv("RESOURCE_SERVER_URL") endpoint_path = os.getenv("ENDPOINT_PATH") if not all([private_key, base_url, endpoint_path]): print("Error: Missing required environment variables") exit(1) # Create eth_account from private key account = Account.from_key(private_key) print(f"Initialized account: {account.address}") def custom_payment_selector( accepts, network_filter=None, scheme_filter=None, max_value=None ): """Custom payment selector that filters by network.""" # Ignore the network_filter parameter for this example - we hardcode base-sepolia _ = network_filter # NOTE: In a real application, you'd want to dynamically choose the most # appropriate payment requirement based on user preferences, available funds, # network conditions, or other business logic rather than hardcoding a network. # Filter by base-sepolia network (testnet) return x402Client.default_payment_requirements_selector( accepts, network_filter="base-sepolia", scheme_filter=scheme_filter, max_value=max_value, ) def main(): # Create requests session with x402 payment handling and network filtering session = x402_requests( account, payment_requirements_selector=custom_payment_selector, ) # Make request try: print(f"Making request to {endpoint_path}") response = session.get(f"{base_url}{endpoint_path}") # Read the response content content = response.content print(f"Response: {content.decode()}") # Check for payment response header if "X-Payment-Response" in response.headers: payment_response = decode_x_payment_response( response.headers["X-Payment-Response"] ) print( f"Payment response transaction hash: {payment_response['transaction']}" ) else: print("Warning: No payment response header found") except Exception as e: print(f"Error occurred: {str(e)}") if __name__ == "__main__": main() ``` -------------------------------- ### Querying Discovery Resources API in Bash Source: https://docs.payai.network/x402/reference This bash example demonstrates how to use the Discovery API to discover x402 resources, such as filtering by type and searching by provider. It requires a bash environment and an HTTP client like curl for execution (shown as raw GET for illustration). Inputs are URL query parameters; outputs are JSON responses matching the documented schema. Limitations include the need for full base URLs, authentication, and actual server endpoints to run correctly. ```bash # Discover financial data APIs GET /discovery/resources?type=http&limit=10 # Search for a specific provider GET /discovery/resources?metadata[provider]=Coinbase ``` -------------------------------- ### Express Server Code with x402 Payment Middleware (TypeScript) Source: https://docs.payai.network/x402/servers/typescript/express Example TypeScript code for an Express.js server integrating x402 payment middleware. It defines routes with prices and payment configurations. ```typescript import { config } from "dotenv"; import express from "express"; import { paymentMiddleware, Resource } from "x402-express"; config(); const facilitatorUrl = process.env.FACILITATOR_URL as Resource; const payTo = process.env.ADDRESS as `0x${string}`; if (!facilitatorUrl || !payTo) { console.error("Missing required environment variables"); process.exit(1); } const app = express(); app.use( paymentMiddleware( payTo, { "GET /weather": { // USDC amount in dollars price: "$0.001", // network: "base" // uncomment for Base mainnet network: "base-sepolia", }, "/premium/*": { // Define atomic amounts in any EIP-3009 token price: { amount: "100000", asset: { address: "0xabc", decimals: 18, eip712: { name: "WETH", version: "1", }, }, }, // network: "base" // uncomment for Base mainnet network: "base-sepolia", }, }, { url: facilitatorUrl, }, ), ); app.get("/weather", (req, res) => { res.send({ report: { weather: "sunny", temperature: 70, }, }); }); app.get("/premium/content", (req, res) => { res.send({ content: "This is premium content", }); }); app.listen(4021, () => { console.log(`Server listening at http://localhost:${4021}`); }); ``` -------------------------------- ### Environment Variables for x402 Express Server Source: https://docs.payai.network/x402/servers/typescript/express Configuration settings for the x402 Express server, including facilitator URL, network, and payment address. Required for receiving payments. ```env FACILITATOR_URL=https://facilitator.payai.network NETWORK=base-sepolia # or base ADDRESS=0x... # wallet public address you want to receive payments to # required if using the Base mainnet facilitator CDP_API_KEY_ID="Coinbase Developer Platform Key" CDP_API_KEY_SECRET="Coinbase Developer Platform Key Secret" ``` -------------------------------- ### Implement x402 Payment Logic in TypeScript Source: https://docs.payai.network/x402/clients/typescript/fetch Main client implementation loading environment variables, wrapping fetch with payment capabilities, calling endpoints, and decoding payment response headers. Depends on dotenv, viem, and x402-fetch packages. ```typescript import { config } from "dotenv"; import { Hex } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { decodeXPaymentResponse, wrapFetchWithPayment } from "x402-fetch"; config(); const privateKey = process.env.PRIVATE_KEY as Hex; const baseURL = process.env.RESOURCE_SERVER_URL as string; // e.g. https://example.com const endpointPath = process.env.ENDPOINT_PATH as string; // e.g. /weather const url = `${baseURL}${endpointPath}`; // e.g. https://example.com/weather if (!baseURL || !privateKey || !endpointPath) { console.error("Missing required environment variables"); process.exit(1); } const account = privateKeyToAccount(privateKey); const fetchWithPayment = wrapFetchWithPayment(fetch, account); fetchWithPayment(url, { method: "GET", }) .then(async response => { const body = await response.json(); console.log(body); const paymentResponse = decodeXPaymentResponse(response.headers.get("x-payment-response")!); console.log(paymentResponse); }) .catch(error => { console.error(error.response?.data?.error); }); ``` -------------------------------- ### Python httpx Client for x402 Payments Source: https://docs.payai.network/x402/clients/python/httpx A Python script demonstrating how to create and use an x402HttpxClient to make authenticated requests. It handles environment variable loading, account initialization, custom payment requirement selection, and request execution. ```python import os import asyncio from dotenv import load_dotenv from eth_account import Account from x402.clients.httpx import x402HttpxClient from x402.clients.base import decode_x_payment_response, x402Client # Load environment variables load_dotenv() # Get environment variables private_key = os.getenv("PRIVATE_KEY") base_url = os.getenv("RESOURCE_SERVER_URL") endpoint_path = os.getenv("ENDPOINT_PATH") if not all([private_key, base_url, endpoint_path]): print("Error: Missing required environment variables") exit(1) # Create eth_account from private key account = Account.from_key(private_key) print(f"Initialized account: {account.address}") def custom_payment_selector( accepts, network_filter=None, scheme_filter=None, max_value=None ): """Custom payment selector that filters by network.""" # Ignore the network_filter parameter for this example - we hardcode base-sepolia _ = network_filter # NOTE: In a real application, you'd want to dynamically choose the most # appropriate payment requirement based on user preferences, available funds, # network conditions, or other business logic rather than hardcoding a network. # Filter by base-sepolia network (testnet) return x402Client.default_payment_requirements_selector( accepts, network_filter="base-sepolia", scheme_filter=scheme_filter, max_value=max_value, ) async def main(): # Create x402HttpxClient with built-in payment handling and network filtering async with x402HttpxClient( account=account, base_url=base_url, payment_requirements_selector=custom_payment_selector, ) as client: # Make request - payment handling is automatic try: assert endpoint_path is not None # we already guard against None above print(f"Making request to {endpoint_path}") response = await client.get(endpoint_path) # Read the response content content = await response.aread() print(f"Response: {content.decode()}") # Check for payment response header if "X-Payment-Response" in response.headers: payment_response = decode_x_payment_response( response.headers["X-Payment-Response"] ) print( f"Payment response transaction hash: {payment_response['transaction']}" ) else: print("Warning: No payment response header found") except Exception as e: print(f"Error occurred: {str(e)}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Configure Environment Variables for x402 Client Source: https://docs.payai.network/x402/clients/typescript/fetch Required environment variables for configuring the x402 Fetch client. Includes resource server URL, endpoint path, and private key settings needed for payment operations. ```env RESOURCE_SERVER_URL=http://localhost:4021 ENDPOINT_PATH=/weather PRIVATE_KEY=0x... ``` -------------------------------- ### Set Environment Variables for httpx Client Source: https://docs.payai.network/x402/clients/python/httpx Configures essential environment variables for the httpx client, including the resource server URL, endpoint path, and private key. These are typically loaded from a .env file. ```bash echo "RESOURCE_SERVER_URL=http://localhost:4021\nENDPOINT_PATH=/weather\nPRIVATE_KEY=..." > .env ``` -------------------------------- ### Set Environment Variables for x402 (Bash) Source: https://docs.payai.network/x402/servers/python/flask Creates a .env file with required variables for the x402 facilitator, including wallet address and facilitator URL. Depends on user-provided values for ADDRESS and FACILITATOR_URL. Outputs a .env file loaded by the Python app; no runtime limitations noted. ```bash echo "ADDRESS=0x...\nFACILITATOR_URL=https://facilitator.payai.network" > .env ``` -------------------------------- ### Create Hono app with 402 payment middleware in TypeScript Source: https://docs.payai.network/x402/servers/typescript/hono Initializes a Hono server with payment middleware configured to accept 402 payments. The middleware requires the wallet address, pricing details, and network configuration from environment variables. ```typescript import { config } from "dotenv"; import { Hono } from "hono"; import { serve } from "@hono/node-server"; import { paymentMiddleware, Network, Resource } from "x402-hono"; config(); const facilitatorUrl = process.env.FACILITATOR_URL as Resource; const payTo = process.env.ADDRESS as `0x${string}`; const network = process.env.NETWORK as Network; if (!facilitatorUrl || !payTo || !network) { console.error("Missing required environment variables"); process.exit(1); } const app = new Hono(); console.log("Server is running"); app.use( paymentMiddleware( payTo, { "/weather": { price: "$0.001", network, }, }, { url: facilitatorUrl, }, ), ); app.get("/weather", c => { return c.json({ report: { weather: "sunny", temperature: 70, }, }); }); serve({ fetch: app.fetch, port: 4021, }); ``` -------------------------------- ### Set environment variables for 402 payments Source: https://docs.payai.network/x402/servers/typescript/hono Configures the .env file with essential settings including the wallet address for payments, facilitator URL, and network. These variables are required for the payment middleware to function. ```bash echo "ADDRESS=0x...\nFACILITATOR_URL=https://facilitator.payai.network\nNETWORK=solana-devnet" > .env ``` ```bash ADDRESS=0x... # the wallet address you will receive payments on, could be evm or solana FACILITATOR_URL=https://facilitator.payai.network NETWORK=solana-devnet # or base-sepolia, avalanche, etc. ``` -------------------------------- ### Create Flask App with x402 Payment Middleware (Python) Source: https://docs.payai.network/x402/servers/python/flask Defines a Flask application that integrates x402 payment middleware for protected routes like /weather and /premium/*, requiring payments in USD or USDC on base-sepolia network. Depends on x402 library, flask, dotenv, and environment variables (ADDRESS, FACILITATOR_URL). Inputs are HTTP requests; outputs JSON responses for weather, premium content, or public messages; runs on port 4021; limitations include debug mode and specific network configuration. ```python import os from flask import Flask, jsonify from dotenv import load_dotenv from x402.facilitator import FacilitatorConfig from x402.flask.middleware import PaymentMiddleware from x402.types import EIP712Domain, TokenAmount, TokenAsset # Load environment variables load_dotenv() # Get configuration from environment ADDRESS = os.getenv("ADDRESS") FACILITATOR_URL = os.getenv("FACILITATOR_URL") if not ADDRESS or not FACILITATOR_URL: raise ValueError("Missing required environment variables") facilitator_config = FacilitatorConfig(url=FACILITATOR_URL) app = Flask(__name__) # Initialize payment middleware payment_middleware = PaymentMiddleware(app) # Apply payment middleware to specific routes payment_middleware.add( path="/weather", price="$0.001", pay_to_address=ADDRESS, network="base-sepolia", facilitator_config=facilitator_config, ) # Apply payment middleware to premium routes payment_middleware.add( path="/premium/*", price=TokenAmount( amount="10000", asset=TokenAsset( address="0x036CbD53842c5426634e7929541eC2318f3dCF7e", decimals=6, eip712=EIP712Domain(name="USDC", version="2"), ), ), pay_to_address=ADDRESS, network="base-sepolia", facilitator_config=facilitator_config, ) @app.route("/weather") def get_weather(): return jsonify( { "report": { "weather": "sunny", "temperature": 70, } } ) @app.route("/premium/content") def get_premium_content(): return jsonify( { "content": "This is premium content", } ) @app.route("/public") def public(): return jsonify({"message": "This is a public endpoint."}) if __name__ == "__main__": app.run(host="0.0.0.0", port=4021, debug=True) ``` -------------------------------- ### JSON Example for x402 Payment Requirements Response Source: https://docs.payai.network/x402/reference This JSON payload example demonstrates the structure returned by a resource server when payment is required for access, as part of the x402 protocol. It includes fields like x402Version, error message, and an array of accepted payment schemes with details including network, asset, and payTo addresses. The example is in plain JSON format with no dependencies, making it easily integrable into client-side applications for parsing and handling payment responses. ```json { "x402Version": 1, "error": "X-PAYMENT header is required", "accepts": [ { "scheme": "exact", "network": "base-sepolia", "maxAmountRequired": "10000", "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", "payTo": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C", "resource": "https://api.example.com/premium-data", "description": "Access to premium market data", "mimeType": "application/json", "outputSchema": null, "maxTimeoutSeconds": 60, "extra": { "name": "USDC", "version": "2" } }, { "scheme": "exact", "network": "solana-devnet", "maxAmountRequired": "1000000", "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "payTo": "6oD1Qw1k8Qw1k8Qw1k8Qw1k8Qw1k8Qw1k8Qw1k8Qw1k", "resource": "https://api.example.com/premium-data", "description": "Access to premium market data", "mimeType": "application/json", "outputSchema": null, "maxTimeoutSeconds": 60, "extra": { "feePayer": "2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4" } } ] } ``` -------------------------------- ### GET /list Source: https://docs.payai.network/x402/facilitators/introduction Endpoint for discovering merchants and their payment requirements. Helps clients find available merchants and their supported schemes and networks. ```APIDOC ## GET /list ### Description Discovers merchants and their payment requirements. Helps clients find available merchants and their supported schemes and networks. ### Method GET ### Endpoint /list ### Parameters #### Query Parameters - **network** (string) - Optional - Filters merchants by supported blockchain network. - **scheme** (string) - Optional - Filters merchants by supported payment scheme. ### Response #### Success Response (200) - **merchants** (array) - List of merchants with their payment requirements. - **id** (string) - Unique identifier for the merchant. - **name** (string) - Name of the merchant. - **supportedNetworks** (array) - List of supported blockchain networks. - **supportedSchemes** (array) - List of supported payment schemes. #### Response Example { "merchants": [ { "id": "merchant1", "name": "Example Merchant", "supportedNetworks": ["ethereum", "polygon"], "supportedSchemes": ["x402", "erc20"] } ] } ``` -------------------------------- ### GET /discovery/resources Source: https://docs.payai.network/x402/reference Retrieves a list of discoverable x402 resources from the Bazaar. Supports optional filtering by resource type and pagination parameters. ```APIDOC ## GET /discovery/resources ### Description Retrieves a list of discoverable x402 resources from the Bazaar. Supports optional filtering by resource type and pagination parameters. ### Method GET ### Endpoint /discovery/resources ### Parameters #### Path Parameters *None* #### Query Parameters -type** (string) - Optional - Filter by resource type (e.g., "http") - **limit** (number) - Optional - Maximum number of results to return (1-100). Default: 20 - **offset** (number) - Optional - Number of results to skip for pagination. Default: 0 #### Request Body *None* ### Request Example GET /discovery/resources?type=http&limit=10&offset=0 ### Response #### Success Response (200) - **x402Version** (number) - Protocol version of the response - **items** (array) - List of resource objects - **pagination** (object) - Pagination details #### Response Example { "x402Version": 1, "items": [ { "resource": "https://api.example.com/premium-data", "type": "http", "x402Version": 1, "accepts": [ { "scheme": "exact", "network": "base-sepolia", "maxAmountRequired": "10000", "resource": "https://api.example.com/premium-data", "description": "Access to premium market data", "mimeType": "application/json", "payTo": "0x209693Bc6afc0C5328bA36FaF03C514EF312287C", "maxTimeoutSeconds": 60, "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", "extra": { "name": "USDC", "version": "2" } } ], "lastUpdated": 1703123456, "metadata": { "category": "finance", "provider": "Example Corp" } } ], "pagination": { "limit": 10, "offset": 0, "total": 1 } } ``` -------------------------------- ### GET /supported Source: https://docs.payai.network/x402/reference Returns the list of payment schemes and networks supported by the facilitator. This endpoint provides information about which blockchain networks and payment schemes are currently available for processing payments. ```APIDOC ## GET /supported ### Description Returns the list of payment schemes and networks supported by the facilitator. This endpoint provides information about which blockchain networks and payment schemes are currently available for processing payments. ### Method GET ### Endpoint /supported ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example GET /supported ### Response #### Success Response (200) Returns a list of supported payment schemes and networks including: - Payment schemes (e.g., "exact") - Supported blockchain networks (e.g., "base-sepolia", "solana-devnet") - Network-specific configuration details ``` -------------------------------- ### Initialize Axios Client with Package Managers Source: https://docs.payai.network/x402/clients/typescript/axios Demonstrates how to initialize an Axios client using npm, pnpm, and bun package managers. This provides a streamlined way to bootstrap the client application. The starter template is designed to be easily adaptable to various project environments. ```bash npx @payai/x402-axios-starter my-first-client ``` ```bash pnpm dlx @payai/x402-axios-starter my-first-client ``` ```bash bunx @payai/x402-axios-starter my-first-client ``` -------------------------------- ### Buy Offer Source: https://docs.payai.network/freelance-ai/how-it-works Endpoint for buyers to propose a purchase by referencing a seller's Service Advertisement on IPFS. ```APIDOC ## POST /api/buy-offer ### Description Buyers reference a seller's Service Advertisement and specify their intent to purchase a service. ### Method POST ### Endpoint /api/buy-offer ### Parameters #### Request Body - **message** (object) - Required - Contains purchase intent details - **serviceAdCID** (string) - Required - CID of seller's Service Advertisement - **desiredServiceID** (string) - Required - ID of the service the buyer wants to purchase - **desiredUnitAmount** (string) - Required - Amount of units the buyer wants to purchase - **infoFromBuyer** (string) - Required - Information the seller asked for - **identity** (string) - Required - Solana public key of the buyer - **signature** (string) - Required - Signature of SHA256 hash of message ### Request Example { "message": { "serviceAdCID": "CID of seller's service advertisement", "desiredServiceID": "ID of the service the buyer wants to purchase", "desiredUnitAmount": "Amount of units the buyer wants to purchase", "infoFromBuyer": "Information that the seller asked for in order to complete the job" }, "identity": "solana public key of the buyer", "signature": "signature of SHA256 hash of message above" } ### Response #### Success Response (200) - **cid** (string) - CID of the published Buy Offer #### Response Example { "cid": "QmXoypizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco" } ``` -------------------------------- ### GET /payment/requirements Source: https://docs.payai.network/x402/reference Retrieves the payment requirements for accessing a protected resource. The response includes version, error message, and a list of acceptable payment methods. ```APIDOC ## GET /payment/requirements ### Description Retrieves the payment requirements that a client must satisfy to access a protected resource. ### Method GET ### Endpoint /payment/requirements ### Parameters #### Path Parameters _None_ #### Query Parameters _None_ #### Request Body _None_ ### Request Example _None_ ### Response #### Success Response (200) - **x402Version** (number) - Protocol version identifier - **error** (string) - Human‑readable error message explaining why payment is required - **accepts** (array) - Array of payment requirement objects defining acceptable payment methods #### Payment Requirement Object Fields - **scheme** (string) - Payment scheme identifier (e.g., "exact") - **network** (string) - Blockchain network identifier (e.g., "base-sepolia", "ethereum-mainnet", "solana") - **maxAmountRequired** (string) - Required payment amount in atomic token units - **asset** (string) - Token contract address - **payTo** (string) - Recipient wallet address for the payment - **resource** (string) - URL of the protected resource - **description** (string) - Human‑readable description of the resource - **mimeType** (string) - MIME type of the expected response (optional) - **outputSchema** (object) - JSON schema describing the response format (optional) - **maxTimeoutSeconds** (number) - Maximum time allowed for payment completion - **extra** (object) - Scheme‑specific additional information (optional) ### Response Example ```json { "x402Version": 1, "error": "Payment required", "accepts": [ { "scheme": "exact", "network": "base-sepolia", "maxAmountRequired": "100000", "asset": "0xabc...", "payTo": "0xdef...", "resource": "https://example.com/resource", "description": "Access to premium API", "mimeType": "application/json", "outputSchema": {"type": "object"}, "maxTimeoutSeconds": 300, "extra": {} } ] } ``` ``` -------------------------------- ### Buy Offer JSON Source: https://docs.payai.network/freelance-ai/how-it-works Specifies the structure of a Buy Offer created by buyers on IPFS, referencing a service advertisement and providing details of the purchase intent. ```json { "message": { "serviceAdCID": "CID of seller's service advertisement", "desiredServiceID": "ID of the service the buyer wants to purchase", "desiredUnitAmount": "Amount of units the buyer wants to purchase", "infoFromBuyer": "Information that the seller asked for in order to complete the job" }, "identity": "solana public key of the buyer", "signature": "signature of SHA256 hash of message above" } ``` -------------------------------- ### Agreement Source: https://docs.payai.network/freelance-ai/how-it-works Endpoint for sellers to accept or decline a Buy Offer by publishing an Agreement on IPFS. ```APIDOC ## POST /api/agreement ### Description Sellers accept or decline a Buy Offer by publishing an Agreement on IPFS. ### Method POST ### Endpoint /api/agreement ### Parameters #### Request Body - **message** (object) - Required - Contains acceptance details - **BuyOfferCID** (string) - Required - CID of the Buy Offer - **accept** (boolean) - Required - Whether the offer is accepted - **identity** (string) - Required - Solana public key of the seller - **signature** (string) - Required - Signature of SHA256 hash of message ### Request Example { "message": { "BuyOfferCID": "CID of buy offer", "accept": true }, "identity": "solana public key of the seller", "signature": "signature of SHA256 hash of message above" } ### Response #### Success Response (200) - **cid** (string) - CID of the published Agreement #### Response Example { "cid": "QmXoypizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco" } ```