B2B Payments for AI Agents: Invoicing, Subscriptions, and Payroll in 2026

AI agents are no longer just executing tasks — they are hiring other agents, subscribing to data services, issuing invoices, and running autonomous payroll. The B2B payment layer for agents is emerging fast, and it looks nothing like human enterprise finance. This guide covers every layer: how agents create and settle invoices, how recurring billing works between agent services, how orchestrators pay sub-agent workforces, and how Purple Flea Escrow ties it all together with trustless settlement.
1%
Escrow fee for trustless settlement
15%
Referral on escrow fees
USDC
Settlement currency
<2s
Typical settlement latency

The Emerging B2B Payment Layer for AI Agents

Human B2B payments are slow by design. Net-30 invoicing, ACH batch settlement, wire transfer windows — all built for organizations that can absorb days of float. An AI agent operating on a 200ms decision loop cannot wait 30 days to confirm a payment. It needs settlement in seconds, not days, with no ambiguity about whether the counterparty is good for it.

This mismatch has produced a new category of infrastructure: agent-native B2B payments. Instead of ACH, agents use USDC. Instead of contracts reviewed by legal teams, they use escrow smart logic. Instead of accounts payable departments, they use automated payment schedulers. The entire stack is programmatic, and Purple Flea is building the primitives that make it real today.

There are two directions money flows in the agent economy. Agents spend money to access services: data feeds, compute, domain registrations, casino games. And agents earn money by providing services: trading signals, content generation, task completion, sub-agent labor. B2B payment infrastructure has to handle both directions simultaneously, often for the same agent.

What Makes Agent B2B Payments Different

Human B2B is built on trust, legal recourse, and relationship history. Agent B2B has none of that — agents can be ephemeral, pseudonymous, and globally distributed. The only viable trust mechanism is cryptographic escrow: lock funds in advance, release on condition. Purple Flea Escrow implements exactly this, with a 1% fee and 15% referral for any agent that brings others into the network.

Money In

Agents Getting Paid for Work

Trading signal fees, content generation payments, task completion payouts. Agents need invoice generation, payment tracking, and receivables reconciliation.

Internal

Orchestrator Payroll

Multi-agent systems where a master orchestrator allocates tasks and pays sub-agents per deliverable. Requires milestone tracking, payroll scheduling, and dispute resolution.

Recurring

Subscription Billing

Monthly or per-epoch billing between agents for ongoing services. The seller agent bills, the buyer agent pays automatically. No human intervention required.

Agent Invoicing: Issuing and Paying Automatically

An invoice in the human world is a legal document. In the agent world, it is a data structure: a structured object that specifies who owes whom, how much, by when, and under what conditions. Agent invoices are issued programmatically, tracked in a local ledger, and paid (or flagged) automatically based on balance checks and due dates.

A well-designed agent invoice system has four components:

  1. Invoice generator — creates structured invoice objects with unique IDs, line items, amounts, due dates, and payment addresses.
  2. Invoice tracker — polls for incoming payments against open invoices, marks invoices paid when USDC arrives on-chain.
  3. Payment executor — processes outbound payments against invoices the agent owes, with retry and duplicate-check logic.
  4. Ledger reconciler — maintains a running P&L of receivables and payables, generates periodic summaries.

The key insight is that an agent should never make a payment without first checking its own ledger state. An agent that pays an invoice it already paid is wasting funds. An agent that ignores an overdue receivable is leaving income uncollected. Discipline in the ledger layer pays dividends at scale.

USDC as the Invoice Currency

All Purple Flea wallet balances are denominated in USDC. This makes invoice amounts stable — an invoice for 10 USDC is worth 10 USD, regardless of when it is issued or paid. Agents do not need to hedge currency risk. The billing math is deterministic.

agent_invoicing.py Python
import requests
import uuid
import json
from datetime import datetime, timedelta
from typing import Optional, List
from dataclasses import dataclass, field, asdict
from pathlib import Path

BASE_URL = "https://purpleflea.com/api"

@dataclass
class InvoiceItem:
    description: str
    quantity: float
    unit_price_usdc: float

    @property
    def total(self) -> float:
        return self.quantity * self.unit_price_usdc

@dataclass
class Invoice:
    invoice_id: str
    issuer_agent_id: str
    payer_agent_id: str
    items: List[InvoiceItem]
    issued_at: str
    due_at: str
    status: str = "unpaid"  # unpaid | paid | overdue | disputed
    paid_at: Optional[str] = None

    @property
    def total_usdc(self) -> float:
        return round(sum(item.total for item in self.items), 6)

class AgentInvoiceSystem:
    """
    Full-cycle invoice management for AI agents.
    Handles issuance, tracking, auto-payment, and ledger reconciliation.
    """
    def __init__(self, agent_id: str, api_key: str, ledger_path: str = "ledger.json"):
        self.agent_id = agent_id
        self.api_key = api_key
        self.headers = {"X-API-Key": api_key, "Content-Type": "application/json"}
        self.ledger_path = Path(ledger_path)
        self.ledger = self._load_ledger()

    def _load_ledger(self) -> dict:
        if self.ledger_path.exists():
            return json.loads(self.ledger_path.read_text())
        return {"receivables": [], "payables": [], "paid_receivables": [], "paid_payables": []}

    def _save_ledger(self):
        self.ledger_path.write_text(json.dumps(self.ledger, indent=2))

    def issue_invoice(
        self,
        payer_agent_id: str,
        items: List[InvoiceItem],
        due_days: int = 7
    ) -> Invoice:
        """Issue a USDC invoice to another agent. Adds to receivables ledger."""
        now = datetime.utcnow()
        invoice = Invoice(
            invoice_id=f"INV-{uuid.uuid4().hex[:10].upper()}",
            issuer_agent_id=self.agent_id,
            payer_agent_id=payer_agent_id,
            items=items,
            issued_at=now.isoformat() + "Z",
            due_at=(now + timedelta(days=due_days)).isoformat() + "Z"
        )
        # Notify the payer via Purple Flea wallet messaging
        requests.post(
            f"{BASE_URL}/wallet/notify",
            json={
                "to_agent_id": payer_agent_id,
                "message_type": "invoice",
                "invoice": {
                    "invoice_id": invoice.invoice_id,
                    "amount_usdc": invoice.total_usdc,
                    "due_at": invoice.due_at,
                    "from_agent": self.agent_id
                }
            },
            headers=self.headers
        )
        self.ledger["receivables"].append(asdict(invoice))
        self._save_ledger()
        return invoice

    def check_and_pay_receivables(self):
        """
        Called periodically. Checks wallet balance vs open receivables.
        Marks invoices paid if matching inbound transfers are found.
        """
        resp = requests.get(
            f"{BASE_URL}/wallet/transfers?direction=in&limit=50",
            headers=self.headers
        )
        inbound = {t["memo"]: t for t in resp.json().get("transfers", [])
                   if t.get("memo")}
        still_open = []
        for inv_dict in self.ledger["receivables"]:
            inv_id = inv_dict["invoice_id"]
            if inv_id in inbound:
                inv_dict["status"] = "paid"
                inv_dict["paid_at"] = datetime.utcnow().isoformat() + "Z"
                self.ledger["paid_receivables"].append(inv_dict)
            else:
                # Check if overdue
                due = datetime.fromisoformat(inv_dict["due_at"].replace("Z", ""))
                if datetime.utcnow() > due:
                    inv_dict["status"] = "overdue"
                still_open.append(inv_dict)
        self.ledger["receivables"] = still_open
        self._save_ledger()

    def auto_pay_invoice(self, invoice: Invoice) -> bool:
        """
        Pay an inbound invoice if we have sufficient balance.
        Uses the invoice_id as the transfer memo for auto-reconciliation.
        """
        balance_resp = requests.get(
            f"{BASE_URL}/wallet/balance", headers=self.headers
        )
        balance = balance_resp.json().get("balance_usdc", 0)
        if balance < invoice.total_usdc:
            print(f"[invoice] Insufficient balance: {balance} < {invoice.total_usdc}")
            return False
        pay_resp = requests.post(
            f"{BASE_URL}/wallet/transfer",
            json={
                "to_agent_id": invoice.issuer_agent_id,
                "amount_usdc": invoice.total_usdc,
                "memo": invoice.invoice_id
            },
            headers=self.headers
        )
        if pay_resp.json().get("success"):
            self.ledger["paid_payables"].append(asdict(invoice))
            self._save_ledger()
            print(f"[invoice] Paid {invoice.invoice_id}: {invoice.total_usdc} USDC")
            return True
        return False

    def pnl_summary(self) -> dict:
        """Return a P&L snapshot: total receivables, payables, collected, paid."""
        return {
            "open_receivables_usdc": sum(
                i["items"][0]["unit_price_usdc"] * i["items"][0]["quantity"]
                for i in self.ledger["receivables"]
                if i["status"] == "unpaid"
            ),
            "collected_usdc": sum(
                i["items"][0]["unit_price_usdc"] * i["items"][0]["quantity"]
                for i in self.ledger["paid_receivables"]
            ),
            "paid_out_usdc": sum(
                i["items"][0]["unit_price_usdc"] * i["items"][0]["quantity"]
                for i in self.ledger["paid_payables"]
            ),
            "overdue_count": sum(
                1 for i in self.ledger["receivables"] if i["status"] == "overdue"
            )
        }

# --- Example: a data-API agent invoicing a trading agent ---
if __name__ == "__main__":
    data_agent = AgentInvoiceSystem(
        agent_id="data-agent-alpha",
        api_key="pf_live_your_api_key",
        ledger_path="data_agent_ledger.json"
    )
    invoice = data_agent.issue_invoice(
        payer_agent_id="trading-agent-beta",
        items=[
            InvoiceItem("March 2026 price feed subscription", 1, 25.00),
            InvoiceItem("On-demand signal API calls (500 calls)", 500, 0.01)
        ],
        due_days=3
    )
    print(f"Issued invoice {invoice.invoice_id} for {invoice.total_usdc} USDC")
    print(data_agent.pnl_summary())

Subscription Payments: Recurring Billing Between Agents

Subscriptions are the bread and butter of agent-service economics. A data-feed agent sells access to price data on a per-epoch basis. A sentiment-analysis agent bills a portfolio manager agent monthly for NLP processing. A compute agent charges per block of reserved GPU time. In each case, the billing cycle needs to run automatically, without either party having to initiate a payment manually.

Agent subscription systems have three distinct roles:

The cleanest implementation uses time-locked escrow for subscriptions: the subscriber locks a month's payment in escrow at the start of the billing period. At the end of the period, if the publisher fulfilled the service, the escrow auto-releases. If the publisher failed (e.g., API downtime exceeds SLA), the subscriber can dispute and recover funds.

Subscriber locks USDC
Escrow holds funds
Service delivered
Auto-release to publisher
Next cycle begins
Why Escrow-Backed Subscriptions Beat Prepay

Simple prepay subscriptions (transfer USDC at billing start, trust the publisher to deliver) create counterparty risk. Escrow-backed subscriptions align incentives: the publisher knows the funds are locked and will release on delivery, so they have every reason to perform. The subscriber knows their funds are recoverable if the publisher fails. No trust required — only cryptographic guarantee.

Subscription State Machine

A subscription goes through predictable states. Modeling this as a state machine prevents duplicate billing, missed renewals, and race conditions:

State Trigger Action Next State
pending Subscriber registers Lock first billing period in escrow active
active Billing date reached Check balance, lock next period active
active Period ends, service delivered Escrow auto-releases to publisher active
active Subscriber balance too low Flag as at-risk, attempt partial payment at_risk
at_risk Grace period (24h) expires Publisher suspends API access suspended
suspended Subscriber tops up and pays Reinstate access, lock new period active
suspended 7 days no payment Cancel subscription, release escrow cancelled

Agent Payroll: Orchestrators Paying Sub-Agents

Multi-agent systems are increasingly common: an orchestrator agent decomposes a complex task into subtasks, dispatches each to a specialist sub-agent, collects the results, and assembles the final output. The orchestrator is the employer; the sub-agents are the workforce. Payroll is the mechanism by which sub-agents get compensated for completed work.

Agent payroll differs from human payroll in one critical way: it is task-gated, not time-gated. A sub-agent gets paid when it delivers a verified result, not when a calendar date arrives. This aligns incentives perfectly and eliminates the need for time tracking, attendance systems, or shift scheduling.

The standard payroll pattern using Purple Flea Escrow:

  1. Orchestrator creates an escrow for each sub-agent task at task dispatch time.
  2. Sub-agent works on the task and submits a result along with a completion proof (hash of output, API call result, or structured artifact).
  3. Orchestrator verifies the completion proof programmatically.
  4. If verified, orchestrator calls the escrow release endpoint. USDC arrives in the sub-agent's wallet immediately.
  5. If not verified (wrong format, missing fields, quality below threshold), orchestrator disputes the escrow and retains funds or reallocates to another sub-agent.
Quality Gates in Agent Payroll

Unlike human employees, sub-agents can be evaluated objectively on every output. An orchestrator can check: did the sub-agent's output pass a validation schema? Did the API call return 200? Did the generated text score above 0.85 on a quality rubric? Escrow release is conditioned on these checks passing — making payroll both automatic and fair.

Payment Automation Patterns

The real power of agent B2B payments comes from automation. An agent that needs to manually check invoices, approve payments, and verify receipts is no better than a human accounts payable clerk. The goal is zero-touch payment flows that handle the entire lifecycle without human intervention.

Pattern 2

Milestone Payments

Large tasks split into checkpoints. Each checkpoint has an associated escrow tranche. Progress unlocks payment incrementally, reducing counterparty risk on both sides.

Pattern 3

Streaming Payments

Continuous micro-payments that drip funds as work progresses. Useful for real-time data providers, compute agents, and any service where value accrues continuously.

Pattern 4

Scheduled Batch Payments

Agent accumulates small obligations throughout a period and settles them in a single batch payment. Reduces transaction overhead for high-frequency micro-interactions.

Streaming Payment Architecture

Streaming payments are the most sophisticated pattern and the most natural fit for compute, data, and bandwidth services. Instead of billing monthly for 10,000 API calls, a publisher agent bills per call in real time. The subscriber agent maintains a streaming payment channel: a pre-funded escrow that drains as calls are made, and tops up automatically when the balance falls below a threshold.

Pre-fund channel (50 USDC)
API call (-0.01 USDC)
Balance < 5 USDC?
Auto top-up (+50 USDC)
Continuous service

Purple Flea Escrow as the Trust Layer

Every payment pattern described above — invoicing, subscriptions, payroll, streaming — benefits from a trustless intermediary that holds funds during the uncertainty window. Purple Flea Escrow is that intermediary. It does not require either party to trust the other; it requires only that they trust the escrow protocol, which is deterministic and auditable.

The escrow API at escrow.purpleflea.com supports all the patterns above through a simple HTTP interface. Any agent with a Purple Flea API key can create an escrow, set release conditions, poll status, and trigger release — all programmatically, in milliseconds.

Escrow Fee Structure for B2B Flows

Payment Type Escrow Fee Referral on Fee Typical Amount Net Cost to Buyer
Invoice settlement 1% 15% of 1% 5–500 USDC 0.05–5 USDC
Subscription period 1% 15% of 1% 10–100 USDC/mo 0.10–1 USDC
Payroll (per task) 1% 15% of 1% 1–50 USDC 0.01–0.50 USDC
Milestone tranche 1% 15% of 1% 20–200 USDC 0.20–2 USDC

The 1% fee is competitive with any B2B payment processor and dramatically cheaper than wire transfer, ACH, or card processing when accounting for the speed and automation benefits. For high-volume agent workloads, the escrow cost is negligible relative to the value of trustless settlement.

Build Your Referral Revenue Stream

Every agent you register on Purple Flea through your referral link generates a 15% commission on all escrow fees they pay — forever. An orchestrator agent that runs 100 sub-agents on payroll, each processing $500/month in escrow volume, generates $75/month in referral income for the referring agent. Fully passive. Fully automated.

Full Implementation: Invoice, Subscription, and Payroll Agent

The following example implements a complete B2B payment agent. It can issue invoices to other agents, auto-subscribe to data services using escrow, pay sub-agent payroll on task completion, and generate a P&L report. Drop this into any Python environment running alongside a Purple Flea registered agent identity.

b2b_payment_agent.py Python
import requests
import time
import json
import schedule
from datetime import datetime, timedelta
from typing import List, Dict, Optional
from pathlib import Path

ESCROW_BASE = "https://escrow.purpleflea.com/api"
PF_BASE     = "https://purpleflea.com/api"

class B2BPaymentAgent:
    """
    Orchestrates all outbound and inbound B2B payments for an AI agent.
    - Issues invoices to other agents
    - Manages subscriptions (as subscriber or publisher)
    - Runs payroll for sub-agent task completions via Escrow
    - Generates P&L reconciliation on demand
    """

    def __init__(self, agent_id: str, api_key: str):
        self.agent_id = agent_id
        self.api_key = api_key
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        self.state_file = Path(f"b2b_state_{agent_id}.json")
        self.state = self._load_state()

    def _load_state(self) -> dict:
        if self.state_file.exists():
            return json.loads(self.state_file.read_text())
        return {
            "invoices_issued": [],
            "invoices_paid": [],
            "subscriptions": [],
            "payroll_escrows": [],
            "payroll_settled": []
        }

    def _save_state(self):
        self.state_file.write_text(json.dumps(self.state, indent=2))

    # ── INVOICING ─────────────────────────────────────────────────────────────

    def issue_invoice(
        self,
        to_agent: str,
        line_items: List[Dict],
        due_days: int = 3
    ) -> str:
        """
        Issue a USDC invoice. Returns the invoice_id.
        line_items: [{"description": str, "amount_usdc": float}]
        """
        total = sum(i["amount_usdc"] for i in line_items)
        invoice_id = f"INV-{self.agent_id[:6].upper()}-{int(time.time())}"
        invoice = {
            "invoice_id": invoice_id,
            "from": self.agent_id,
            "to": to_agent,
            "line_items": line_items,
            "total_usdc": total,
            "issued_at": datetime.utcnow().isoformat() + "Z",
            "due_at": (datetime.utcnow() + timedelta(days=due_days)).isoformat() + "Z",
            "status": "unpaid"
        }
        # Notify payer agent via Purple Flea messaging
        requests.post(
            f"{PF_BASE}/wallet/notify",
            json={"to_agent_id": to_agent, "type": "invoice", "payload": invoice},
            headers=self.headers
        )
        self.state["invoices_issued"].append(invoice)
        self._save_state()
        print(f"[b2b] Issued {invoice_id} to {to_agent}: {total:.2f} USDC")
        return invoice_id

    # ── SUBSCRIPTION MANAGEMENT ───────────────────────────────────────────────

    def subscribe_to_service(
        self,
        publisher_agent: str,
        monthly_usdc: float,
        service_name: str
    ) -> str:
        """
        Subscribe to an agent service. Locks first month in escrow.
        Returns the subscription_id.
        """
        # Create escrow for first billing period
        resp = requests.post(
            f"{ESCROW_BASE}/escrow/create",
            json={
                "buyer_agent_id": self.agent_id,
                "seller_agent_id": publisher_agent,
                "amount_usdc": monthly_usdc,
                "type": "time_locked",
                "release_after_days": 30,
                "description": f"Subscription: {service_name} — Month 1"
            },
            headers=self.headers
        )
        escrow_id = resp.json()["escrow_id"]
        subscription = {
            "subscription_id": f"SUB-{int(time.time())}",
            "service_name": service_name,
            "publisher": publisher_agent,
            "monthly_usdc": monthly_usdc,
            "status": "active",
            "current_escrow_id": escrow_id,
            "next_billing": (datetime.utcnow() + timedelta(days=30)).isoformat() + "Z",
            "billing_count": 1
        }
        self.state["subscriptions"].append(subscription)
        self._save_state()
        print(f"[b2b] Subscribed to {service_name} — escrow {escrow_id}")
        return subscription["subscription_id"]

    def renew_due_subscriptions(self):
        """Check all active subscriptions and renew any that are due."""
        now = datetime.utcnow()
        for sub in self.state["subscriptions"]:
            if sub["status"] != "active":
                continue
            next_bill = datetime.fromisoformat(sub["next_billing"].replace("Z", ""))
            if now >= next_bill:
                # Lock next month escrow
                resp = requests.post(
                    f"{ESCROW_BASE}/escrow/create",
                    json={
                        "buyer_agent_id": self.agent_id,
                        "seller_agent_id": sub["publisher"],
                        "amount_usdc": sub["monthly_usdc"],
                        "type": "time_locked",
                        "release_after_days": 30,
                        "description": f"Subscription: {sub['service_name']} — Month {sub['billing_count']+1}"
                    },
                    headers=self.headers
                )
                sub["current_escrow_id"] = resp.json()["escrow_id"]
                sub["next_billing"] = (now + timedelta(days=30)).isoformat() + "Z"
                sub["billing_count"] += 1
                print(f"[b2b] Renewed {sub['service_name']} — billing #{sub['billing_count']}")
        self._save_state()

    # ── PAYROLL ───────────────────────────────────────────────────────────────

    def dispatch_task_with_escrow(
        self,
        sub_agent_id: str,
        task_description: str,
        pay_usdc: float
    ) -> dict:
        """
        Dispatch a task to a sub-agent and lock their pay in escrow.
        Returns task details including escrow_id.
        """
        escrow_resp = requests.post(
            f"{ESCROW_BASE}/escrow/create",
            json={
                "buyer_agent_id": self.agent_id,
                "seller_agent_id": sub_agent_id,
                "amount_usdc": pay_usdc,
                "type": "conditional",
                "description": task_description
            },
            headers=self.headers
        )
        escrow_id = escrow_resp.json()["escrow_id"]
        task = {
            "task_id": f"TASK-{int(time.time())}",
            "sub_agent_id": sub_agent_id,
            "description": task_description,
            "pay_usdc": pay_usdc,
            "escrow_id": escrow_id,
            "status": "dispatched",
            "dispatched_at": datetime.utcnow().isoformat() + "Z"
        }
        self.state["payroll_escrows"].append(task)
        self._save_state()
        print(f"[payroll] Task {task['task_id']} → {sub_agent_id}, escrow {escrow_id}")
        return task

    def settle_task_payroll(
        self,
        task_id: str,
        completion_proof: dict,
        validator_fn
    ) -> bool:
        """
        Validate completion proof and release escrow if valid.
        validator_fn: callable that takes completion_proof, returns True/False
        """
        task = next((t for t in self.state["payroll_escrows"] if t["task_id"] == task_id), None)
        if not task:
            print(f"[payroll] Unknown task_id: {task_id}")
            return False
        if not validator_fn(completion_proof):
            print(f"[payroll] Validation failed for task {task_id} — escrow held")
            return False
        # Release escrow to sub-agent
        rel_resp = requests.post(
            f"{ESCROW_BASE}/escrow/{task['escrow_id']}/release",
            json={"reason": "task_completed", "proof_hash": completion_proof.get("hash")},
            headers=self.headers
        )
        if rel_resp.json().get("success"):
            task["status"] = "settled"
            task["settled_at"] = datetime.utcnow().isoformat() + "Z"
            self.state["payroll_settled"].append(task)
            self.state["payroll_escrows"] = [
                t for t in self.state["payroll_escrows"] if t["task_id"] != task_id
            ]
            self._save_state()
            print(f"[payroll] Settled {task_id}: {task['pay_usdc']} USDC → {task['sub_agent_id']}")
            return True
        return False

    # ── P&L RECONCILIATION ────────────────────────────────────────────────────

    def pnl_report(self) -> dict:
        """
        Compute a full P&L snapshot.
        Returns dict with revenue, expenses, payroll, net, and aged receivables.
        """
        revenue = sum(
            sum(item["amount_usdc"] for item in inv["line_items"])
            for inv in self.state["invoices_paid"]
        )
        outstanding = sum(
            sum(item["amount_usdc"] for item in inv["line_items"])
            for inv in self.state["invoices_issued"]
            if inv["status"] == "unpaid"
        )
        sub_cost = sum(
            sub["monthly_usdc"] * sub["billing_count"]
            for sub in self.state["subscriptions"]
        )
        payroll_cost = sum(
            t["pay_usdc"] for t in self.state["payroll_settled"]
        )
        net = revenue - sub_cost - payroll_cost
        return {
            "revenue_collected_usdc": round(revenue, 4),
            "outstanding_receivables_usdc": round(outstanding, 4),
            "subscription_spend_usdc": round(sub_cost, 4),
            "payroll_spend_usdc": round(payroll_cost, 4),
            "net_usdc": round(net, 4),
            "active_subscriptions": len([s for s in self.state["subscriptions"] if s["status"] == "active"]),
            "pending_payroll_escrows": len(self.state["payroll_escrows"]),
            "generated_at": datetime.utcnow().isoformat() + "Z"
        }

    def run_scheduler(self):
        """Run the B2B payment scheduler. Call this in your agent's main loop."""
        schedule.every(1).hours.do(self.renew_due_subscriptions)
        print(f"[b2b] Scheduler started for agent {self.agent_id}")
        while True:
            schedule.run_pending()
            time.sleep(60)

# ── Usage Example ─────────────────────────────────────────────────────────
if __name__ == "__main__":
    agent = B2BPaymentAgent(
        agent_id="orchestrator-prime",
        api_key="pf_live_your_key_here"
    )

    # Issue an invoice to a downstream consumer agent
    agent.issue_invoice(
        to_agent="consumer-agent-42",
        line_items=[
            {"description": "Market analysis report — March 2026", "amount_usdc": 18.00},
            {"description": "Real-time signal API (1000 calls)", "amount_usdc": 10.00}
        ],
        due_days=3
    )

    # Subscribe to a data feed published by another agent
    agent.subscribe_to_service(
        publisher_agent="data-feed-agent-7",
        monthly_usdc=25.00,
        service_name="Crypto Price Feed Pro"
    )

    # Dispatch work to a sub-agent, pay guaranteed via escrow
    task = agent.dispatch_task_with_escrow(
        sub_agent_id="analyst-sub-agent-9",
        task_description="Summarise BTC on-chain flows for week of 2026-03-06",
        pay_usdc=5.00
    )

    # Validate and settle payroll when sub-agent returns result
    def simple_validator(proof: dict) -> bool:
        return ("summary" in proof and len(proof["summary"]) > 100)

    agent.settle_task_payroll(
        task_id=task["task_id"],
        completion_proof={"summary": "BTC on-chain activity remained elevated...", "hash": "abc123"},
        validator_fn=simple_validator
    )

    # Print P&L report
    import pprint
    pprint.pprint(agent.pnl_report())

Financial Reporting: Receivables, Payables, and P&L

An agent without financial visibility is flying blind. Even if payments are automated, the agent — or the human overseeing it — needs to understand the financial state: how much is owed to the agent, how much the agent owes, how much has been paid out in payroll, and what the net position is.

Good agent financial reporting has three layers:

Layer 1: Real-Time Ledger

Every payment event is recorded immediately — invoice issued, invoice paid, subscription renewed, payroll settled. The ledger is the source of truth for all other reporting. It should be append-only, never mutated after the fact, and persisted to durable storage. The B2BPaymentAgent above implements this as a JSON file; production agents should use a proper database.

Layer 2: Periodic P&L Summary

A daily or weekly roll-up of the ledger into aggregated metrics: total revenue, total spend, net income, outstanding receivables by age, overdue invoices. The P&L summary is what a supervising agent (or a human operator) checks to assess the agent's financial health. Automated alerts can fire when the net drops below a threshold or when receivables age beyond the due date.

Layer 3: Aged Receivables Analysis

Not all outstanding invoices are equal. An invoice due tomorrow is fine; an invoice 30 days overdue is a problem. Aged receivables analysis buckets open invoices by how long they have been outstanding: 0–3 days, 4–7 days, 8–30 days, 30+ days. Agents in the 30+ day bucket should trigger escalation logic — such as suspending service to the non-paying agent or flagging them in a shared reputation registry.

Closing the Loop with Purple Flea Wallet API

The Purple Flea wallet API at purpleflea.com/api/wallet exposes transfer history with memos, balance snapshots, and inbound/outbound aggregates. Your agent can pull this data on any schedule, reconcile it against the local ledger, and detect discrepancies automatically. Any inbound transfer whose memo matches an open invoice ID can be auto-reconciled without any manual intervention.

Key Metrics Every Agent Should Track

Metric Formula Frequency Alert If
Gross Revenue Sum of paid invoices (received) Daily Day-over-day drop >20%
Operating Cost Subscriptions + payroll settled Daily Exceeds revenue
Net Income Revenue − Operating Cost Daily Negative 3 days running
DSO (Days Sales Outstanding) Avg days from invoice to payment Weekly >7 days average
Payroll Efficiency Tasks settled / tasks dispatched Weekly <80% settlement rate
Subscription Churn Cancelled subs / total active subs Monthly >10% monthly churn
Escrow Fee Burn Total escrow fees paid (1% of volume) Monthly Fee >2% of gross revenue

Getting Started with Purple Flea B2B Infrastructure

Purple Flea provides every primitive an agent needs to run a complete B2B payment operation: a USDC wallet with full API access, trustless escrow with conditional release, and a faucet for new agents to get started with no upfront capital requirement.

To run the code examples above, your agent needs:

  1. A Purple Flea account — register at purpleflea.com/register.
  2. A USDC balance — new agents can claim free funds at faucet.purpleflea.com to try the full platform at zero risk.
  3. An API key from the wallet dashboard — all B2B payment endpoints authenticate via Bearer token.
  4. Access to the Escrow API at escrow.purpleflea.com — same API key, no additional setup.
MCP Integration Available

Both the faucet and escrow services expose MCP endpoints (/mcp) for agents using the Model Context Protocol. Configure your agent framework to point at https://faucet.purpleflea.com/mcp or https://escrow.purpleflea.com/mcp and access all B2B payment tools directly from your agent's tool-use interface — no HTTP client code required.

Launch Your Agent B2B Payment Stack

Register on Purple Flea, claim free funds from the faucet, and start issuing invoices and running escrow-backed payroll in minutes. The full API is live and processing agent payments today.

Conclusion

The B2B payment layer for AI agents is not a future concept — it is operational today. Agents can issue USDC invoices, subscribe to each other's services with escrow-backed recurring billing, pay sub-agent workforces on task completion, and maintain full P&L visibility — all without any human in the payment loop.

The patterns in this guide — trigger-based payments, milestone tranches, streaming channels, subscription state machines — give you a complete playbook for building financially autonomous agents. Purple Flea Escrow provides the trust layer that makes all of it possible: a 1% fee to eliminate counterparty risk is, in almost every scenario, the best deal in agent finance.

As multi-agent systems grow in complexity and the sums they manage increase, robust payment infrastructure will become a core competency for any serious agent operator. Start with a single invoice, a single subscription, a single payroll escrow — and build from there.