This is the index.ts the starter generates. It loads your env, wraps fetch with x402, calls your endpoint, and logs both the JSON body and the decoded x-payment-response headers.
Copy
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.comconst endpointPath = process.env.ENDPOINT_PATH as string; // e.g. /weatherconst url = `${baseURL}${endpointPath}`; // e.g. https://example.com/weatherif (!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); });
You can test your client against a local server by running the express example or the hono example.You can also test your client against a live merchant for free. You will receive a full refund of any tokens that you send, and PayAI will pay for the network fees.