Build a pay-per-summary AI API with x402 and AlpRouter
Another team’s agent wants exactly one summary from your service. How does it learn the price and pay for that single result? An x402 server quotes its terms in an HTTP 402 response. In this example, your server accepts USDC and calls AlpRouter to produce the summary.
Set a price for the summary and account for inference separately
Our example charges 0.01 test USDC per summary on Base Sepolia. The buyer pays your service. AlpRouter bills the model usage to the credits associated with your server’s API key. Buyers can use the service without their own AlpRouter account or access to your key.
A flat price is predictable for buyers. Your cost still depends on what they send and how much text the model returns. The example limits inputs to 800 characters and caps output at 100 tokens. Testnet payments use test funds, while a real call to AlpRouter consumes credits.
Run the summary service on your computer
Use Node.js 22 or later. In an empty folder, create a .env file. Set PAY_TO to the public address of the wallet that will receive test USDC on Base Sepolia. Set ALPROUTER_API_KEY to a key for a funded AlpRouter account. The receiving server needs only the wallet’s public address.
Run the commands below. Your service now accepts POST /summary on local port 4021. Once the x402 middleware verifies a buyer’s authorization, your server sends the document to the AlpRouter chat API and lets alprouter/auto select the model.
curl -fsSLO https://www.alpsoft.io/examples/x402-summary.mjs
npm install express@5.3.0 @x402/express@2.32.0 @x402/core@2.32.0 @x402/evm@2.32.0
node --env-file=.env x402-summary.mjsRead the quote on the first request and get a summary on the second
Leave the server running and send the request below from another terminal. Expect 402 Payment Required. Decode the PAYMENT-REQUIRED header from Base64 to JSON. In accepts, check that the network is eip155:84532 (Base Sepolia) and that the recipient matches PAY_TO. The amount 10000 means 0.01 USDC at six decimal places. This first request incurs no payment or inference cost.
To get a summary, follow the buyer guide’s wallet signer and fetch example. Fund the buyer wallet with test USDC, point the client at your /summary route and POST the same JSON. After the buyer approves the terms, the client resends the request with a PAYMENT-SIGNATURE header. Once verification, inference and settlement succeed, read summary in the JSON body and the payment result in the PAYMENT-RESPONSE header.
curl -i http://127.0.0.1:4021/summary \
-H "Content-Type: application/json" \
-d '{"text":"Orders arrive on Monday and ship on Wednesday. Tracking is available from Thursday."}'