Agent Wranglers

USG-24Optional

Verify an HTTP 402 payment before doing the work

If you charge per request with HTTP 402, as x402 and MPP do, settle each payment through a provider before the work runs. Refuse any payment proof used twice.

How to do it

The server answers an unpaid request with 402 and the price. x402 puts it in a PAYMENT-REQUIRED header. MPP sends a challenge in WWW-Authenticate: Payment. The client pays and repeats the request with its proof. Hand the proof to your payment provider or the protocol's verifying service. Do the work only after it confirms. Store each proof's ID under a unique constraint, so a replay is refused. Record a usage event for each paid request, as Give every usage event a key and count it once says. Many of these payments settle in stablecoins, so ask your accountant how to book them.

Examples

JavaScript example

app.get('/api/reports/:id', async (req, res) => {
  const proof = req.get('PAYMENT-SIGNATURE')
  if (!proof) return res.status(402).set('PAYMENT-REQUIRED', paymentRequirements(req)).end()
  const payment = await paymentVerifier.verifyAndSettle(proof, paymentRequirements(req))
  if (!payment.ok || !(await payments.claimOnce(payment.id))) return res.status(402).end()
  res.json(await reports.build(req.params.id))
})

Python example

@app.get("/api/reports/{report_id}")
def get_report(report_id: str, request: Request):
    proof = request.headers.get("PAYMENT-SIGNATURE")
    if proof is None:
        return Response(status_code=402, headers={"PAYMENT-REQUIRED": payment_requirements(request)})
    payment = payment_verifier.verify_and_settle(proof, payment_requirements(request))
    if not payment.ok or not payments.claim_once(payment.id):
        return Response(status_code=402)
    return reports.build(report_id)

How to check

A test calls a paid endpoint without proof and gets 402 with a price. A valid proof gets 200 once. The same proof sent again gets 402, and the work runs once.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/usage-billing/agentic-payments/http-402-payments">Agent Wranglers usage-based billing playbook</a>. In code you write, add a comment next to it with the same link.