惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Proofpoint News Feed
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs
S
Securelist
C
Cisco Blogs
C
CERT Recently Published Vulnerability Notes
P
Palo Alto Networks Blog
V
V2EX
Microsoft Security Blog
Microsoft Security Blog
T
Threatpost
Cyberwarzone
Cyberwarzone
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Register - Security
The Register - Security
T
Tenable Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
罗磊的独立博客
Project Zero
Project Zero
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园_首页
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
月光博客
月光博客
雷峰网
雷峰网
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Heimdal Security Blog
PCI Perspectives
PCI Perspectives
G
Google Developers Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cloudbric
Cloudbric
人人都是产品经理
人人都是产品经理
Latest news
Latest news
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tor Project blog
Jina AI
Jina AI
S
Security Affairs
阮一峰的网络日志
阮一峰的网络日志
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Scott Helme
Scott Helme
M
MIT News - Artificial intelligence
The Hacker News
The Hacker News
F
Full Disclosure
宝玉的分享
宝玉的分享
Webroot Blog
Webroot Blog
Forbes - Security
Forbes - Security
SecWiki News
SecWiki News
O
OpenAI News
N
News | PayPal Newsroom
A
About on SuperTechFans
S
Security @ Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How I let AI agents pay for APIs per call (the HTTP 402 path)
LemonCake · 2026-06-18 · via DEV Community

If you've built an MCP server or any API that costs you money to run (an LLM call, a paid data source, compute), you've probably hit the same wall I did:

How do you get paid per call — when the caller is an AI agent, not a human with a credit card form?

A human can sign up, enter a card, get an API key. An autonomous agent can't fill out a Stripe checkout form mid-task. And you don't want to hand an agent a raw API key with no spending limit — one runaway loop and your bill explodes.

This post walks through the design I landed on. It's not the only way, but the pieces are reusable even if you build your own.

The core idea: HTTP 402
402 Payment Required has been a reserved HTTP status code since the beginning, basically unused. It turns out to be exactly the primitive we need.

The flow:

An agent calls your endpoint with no payment.
You respond 402 with a small JSON body describing how to pay (price, where to top up, what token format you accept).
The agent (or its owner) tops up once, getting a budget-capped token.
The agent retries with the token in the Authorization header. Now it works — and keeps working until the budget runs out, then it gets 402 again.
HTTP/1.1 402 Payment Required
Content-Type: application/json

{
"accepts": [
{
"scheme": "lemoncake-pay-token",
"price": "0.01",
"currency": "USD",
"mintUrl": "https://.../buy/",
"gatewayUrl": "https://.../g/"
}
]
}
This is the shape the x402 spec standardizes. You don't strictly need the spec to do it — but following it means agent frameworks that already understand 402 can pay you without custom glue.

The budget cap is the important part
The naive version — "give the agent an API key" — is dangerous because there's no ceiling. The whole point of an agent paying autonomously is that you stop watching it. So the token has to carry its own limits:

{
"budget": 5.00,
"spent": 0.06,
"max_calls": 50,
"calls_used": 6,
"expires_at": "2026-07-01T00:00:00Z"
}
The gateway checks these on every call before forwarding upstream. Budget exhausted → 402. Rate limit hit → 429. Expired → 402. The agent can never spend more than the token allows, even if it goes haywire.

I encode the token as a signed JWT (HS256) so the gateway can verify it without a DB round-trip on the hot path, then check the live spend counter in Postgres. The JWT carries the token id, endpoint id, and owner id; the mutable budget lives in the DB.

The gateway pattern
The key architectural move: a proxy in front of the real endpoint. The agent never calls your upstream directly. It calls a gateway URL like /g/. The gateway:

Verifies the pay token.
Checks budget / rate limit / expiry.
Forwards the request to your real upstream (with your upstream auth attached server-side, so the agent never sees your real keys).
Records the call + cost in a ledger.
Returns the upstream response.
agent ──► /g/ (gateway)
├─ verify token
├─ check budget
├─ forward ──► your real API (with your secret key)
├─ record usage + cost
└─ return response
This decouples two things that are usually tangled: who can call (the agent's pay token) and how you authenticate upstream (your secret, never exposed). It also means you can put a per-endpoint price on any existing API without touching its code.

Settling the money
Minting a budget-capped token means someone paid up front. I use Stripe Checkout as a Direct Charge on the provider's connected account (Stripe Connect), so the money lands in the provider's balance and the platform takes a small application fee — once, at payment time, not per call. The per-call cost is just a ledger figure that draws down the prepaid budget.

This matters because charging a fee on every tiny call would get eaten by Stripe's per-transaction minimums. Prepaid bundle + ledger drawdown sidesteps that entirely.

What I'd tell you before you build your own
A few things that bit me:

Don't put the fee on each call. Stripe's minimum charge makes sub-cent per-call billing impossible. Prepay a budget, draw it down in your own ledger.
The token must be re-displayable. Agents lose context. The buyer needs a way to recover the same token (I key the success page off the Stripe session id, which is single-use and unguessable).
Scope the token to one endpoint. A token minted for endpoint A should be rejected at endpoint B. Otherwise a leaked token is a blank check.
Forward upstream auth server-side only. The agent should never be able to read your real upstream key. The gateway attaches it after auth.
The result
I packaged this up as a project called LemonCake — you wrap any API/MCP endpoint, set a price per call, and get a gateway URL an agent can pay through autonomously. There's a live demo (no signup) if you want to see the 402 → top-up → call loop run end to end: https://www.lemoncake.xyz/demo

But honestly, even if you never touch it, the pattern stands on its own:

402 to advertise the price → budget-capped token → gateway that verifies, forwards, and meters.

I'm still genuinely unsure whether autonomous per-call payment is something agent builders need today or whether I'm a year or two early. If you've hit the "how do I charge an agent" problem from the other side, I'd love to hear how you solved it.