Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,38 @@ These entry points authenticate the credential before reaching the Seller hooks.
Validation is non-mutating; broadcast may still fail after successful validation.
Never invoke the protected application handler based on validation alone.

### Request-time MPP pricing

Use `seller.priced(callback)` as the method registered with `Mpp`. The callback
receives pympp's `Request` and returns charge input, synchronously or asynchronously:

```python
import httpx
from mpp.server import Mpp, Request
from inflowpay.mpp import WireObject


async def price(request: Request) -> WireObject:
large = httpx.URL(request.url).params.get("bundle") == "large"
return {"amount": "0.05" if large else "0.01", "currency": "USDC"}


payments = Mpp(methods=[seller.priced(price)], realm="seller.example", secret_key=secret)
# Use @pay(payments.charge()) on the protected endpoint.
```

The callback runs for each request, including paid retries. Return consistent
terms for the same purchase; changed terms invalidate a previously quoted payment.
InFlow and Tempo inputs use the same units as `charge_request`; Stripe and CARD
use decimal USD amounts, converted to cents by their existing helpers.

Request bodies are not read for pricing unless `needs_request_body=True` is passed
to `priced`. Then `request.body` contains the bytes and the framework handler can
still read them. Apply request-size limits in your application. Body access alone
does not bind a challenge to the body; use pympp's `body` route option when needed.
Callback errors prevent payment processing and propagate through pympp. Keep the
Seller open for the lifetime of the application.

## Migrating from InFlow Python 0.3

This dependency upgrade requires an InFlow minor-version release. Integrations
Expand Down Expand Up @@ -907,6 +939,39 @@ async def serve() -> None:
asyncio.run(serve())
```

For request-time pricing in FastAPI or Starlette, import `payment_middleware` from
`inflowpay.x402.fastapi`. Route entries may be fixed `RouteConfig` objects or sync/async
callbacks returning a complete `RouteConfig`:

```python
from fastapi import Request
from x402.http.types import RouteConfig
from inflowpay.x402.fastapi import payment_middleware


async def report_route(request: Request) -> RouteConfig:
price = "0.05 USDC" if request.query_params.get("bundle") == "large" else "0.01 USDC"
return await seller.route(price)


app.middleware("http")(payment_middleware({"GET /report": report_route}, resource_server))
```

Each matching request resolves its route once, including paid retries. The callback
can select currency, payment methods, and sponsorship through `seller.route`;
verification, settlement, receipts, and server hooks remain upstream behavior.
Use upstream route patterns such as `GET /reports/:id`; this also preserves Bazaar
route metadata. Unmatched requests pass through without invoking the callback.

The callback receives the framework's request. It does not read the body unless
your callback explicitly uses `await request.body()` or `await request.json()`;
these cached reads preserve the body for the application handler. Apply request-size
limits in your application and do not consume `request.stream()` in the callback.
Failed or empty route resolution raises before payment or application handlers run;
the application controls error handling and logging. Cancellation propagates.
Fixed-price middleware can continue
using the upstream import directly.

Both clients own their HTTP connections and close them when their context exits.
`Seller.create()` requires an API key and preloads configuration and capabilities.
Configuration reads are cached for one hour; `await seller.config(refresh=True)`
Expand Down
12 changes: 11 additions & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ export MPP_SECRET_KEY="$(uv run python -c 'import secrets; print(secrets.token_h
uv run --locked python -m examples.mpp_seller
```

The Seller's request callback selects its own price on every call: **0.01 USDC**
for `/api/widgets` and **0.05 USDC** for `/api/widgets?bundle=large`. Fixed prices
can use `charge_request`, `stripe_request`, or `card_request`. For Stripe and CARD, the
callback selects **USD 1.25** or **USD 2.50**; the helpers convert dollars to cents
and attach the configured payment details.

The server listens at `http://127.0.0.1:3000`. Check both routes without paying:

```sh
Expand Down Expand Up @@ -137,7 +143,11 @@ curl -i http://127.0.0.1:3001/api/widgets
```

`/free` returns HTTP 200. `/api/widgets` returns HTTP 402 with a `PAYMENT-REQUIRED`
header describing the available offers.
header describing the available offers. Add `?bundle=large` to request **0.05 USDC**
instead. The Seller selects the price from its own price list on each request.
The async route callback calls `seller.route(...)` with the selected price and
currency. `inflowpay.x402.fastapi.payment_middleware` resolves that callback and
delegates payment handling to the upstream middleware.

Run the [Buyer](x402_buyer.py) in a second terminal:

Expand Down
22 changes: 13 additions & 9 deletions examples/mpp_seller.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

import httpx
import uvicorn
from fastapi import FastAPI, Request
from mpp import Credential, Receipt
from mpp.server import Mpp
from mpp.server import Request as PaymentRequest
from mpp.server.decorator import pay
from starlette.responses import JSONResponse

from inflowpay import ClientOptions
from inflowpay.mpp import WireObject
from inflowpay.mpp.seller import Seller


Expand All @@ -21,17 +24,17 @@ async def application(
) -> AsyncIterator[FastAPI]:
# Keep the Seller open for the whole server lifetime, not just startup.
async with await Seller.create(options, method=method) as seller:
# Stripe and CARD prices are dollars here; their challenges contain integer cents.
if method == "card":
terms = seller.card_request({"amount": "1.25"})
elif method == "stripe":
terms = seller.stripe_request({"amount": "1.25"})
else:
terms = seller.charge_request({"amount": "0.01", "currency": "USDC"})

def price(request: PaymentRequest) -> WireObject:
large = httpx.URL(request.url).params.get("bundle") == "large"
if method in ("stripe", "card"):
return {"amount": "2.50" if large else "1.25"}
return {"amount": "0.05" if large else "0.01", "currency": "USDC"}

app = FastAPI()

@app.get("/api/widgets")
@pay(Mpp(methods=[seller], realm="localhost", secret_key=secret).charge(**terms))
@pay(Mpp(methods=[seller.priced(price)], realm="localhost", secret_key=secret).charge())
async def widgets(
request: Request, credential: Credential, receipt: Receipt
) -> JSONResponse:
Expand Down Expand Up @@ -62,7 +65,8 @@ async def run() -> None:
async with application(options, secret, method=method) as app:
price = "0.01 USDC" if method == "inflow" else f"1.25 USD via {method}"
print(
f"MPP: http://127.0.0.1:3000/api/widgets costs {price}; /free requires no payment.",
f"MPP: http://127.0.0.1:3000/api/widgets starts at {price}; "
"?bundle=large selects the larger bundle; /free requires no payment.",
flush=True,
)
await uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=3000)).serve()
Expand Down
36 changes: 23 additions & 13 deletions examples/x402_seller.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
from typing import Literal

import uvicorn
from fastapi import FastAPI
from fastapi import FastAPI, Request
from x402 import x402ResourceServer
from x402.http.middleware.fastapi import payment_middleware
from x402.http.types import RouteConfig

from inflowpay import ClientOptions
from inflowpay.x402.facilitator import Facilitator
from inflowpay.x402.fastapi import payment_middleware
from inflowpay.x402.seller import Seller


Expand All @@ -31,17 +31,26 @@ async def application(
resource = x402ResourceServer(facilitator)
for registration in await seller.scheme_registrations():
resource.register(registration["network"], registration["server"])
offers = await seller.offers(
"$1.25" if instrument else "0.01 USDC",
schemes=["instrument"] if instrument else ["balance", "exact"],
payment_flow=payment_flow,
)
if not offers:
schemes = ["instrument"] if instrument else ["balance", "exact"]
if not await seller.offers(
"$1.25" if instrument else "0.01 USDC", schemes=schemes, payment_flow=payment_flow
):
raise ValueError("The Seller configuration has no matching payment offers.")

async def route(request: Request) -> RouteConfig:
large = request.query_params.get("bundle") == "large"
if instrument:
price = "$2.50" if large else "$1.25"
else:
price = "0.05 USDC" if large else "0.01 USDC"
return await seller.route(
price,
schemes=schemes,
payment_flow=payment_flow,
)

app = FastAPI()
app.middleware("http")(
payment_middleware({"GET /api/widgets": RouteConfig(accepts=offers)}, resource)
)
app.middleware("http")(payment_middleware({"GET /api/widgets": route}, resource))

@app.get("/api/widgets")
async def widgets() -> dict[str, list[int]]:
Expand Down Expand Up @@ -74,9 +83,10 @@ async def run() -> None:
instrument=scheme == "instrument",
payment_flow="upfront" if payment_flow == "upfront" else "authorization",
) as app:
price = "1.25 USD via instrument" if scheme == "instrument" else "0.01 USDC"
description = "1.25 USD via instrument" if scheme == "instrument" else "0.01 USDC"
print(
f"x402: http://127.0.0.1:3001/api/widgets costs {price}; /free requires no payment.",
f"x402: http://127.0.0.1:3001/api/widgets starts at {description}; "
"?bundle=large selects the larger bundle; /free requires no payment.",
flush=True,
)
await uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=3001)).serve()
Expand Down
35 changes: 33 additions & 2 deletions src/inflowpay/mpp/seller.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

import inspect
import re
from collections.abc import Awaitable, Callable
from copy import deepcopy
from dataclasses import dataclass, field, replace
from types import TracebackType
Expand All @@ -9,8 +11,8 @@

from mpp import Credential, Receipt
from mpp.errors import InvalidChallengeError, PaymentError
from mpp.server import ServerMethod, Validation
from mpp.server.method import ValidateContext, VerifyContext
from mpp.server import Request, ServerMethod, Validation
from mpp.server.method import RequestContext, ValidateContext, VerifyContext
from pydantic import BaseModel

from .._runtime import Client
Expand Down Expand Up @@ -234,6 +236,35 @@ async def __aexit__(
async def aclose(self) -> None:
await self._client.aclose()

def priced(
self,
request: Callable[[Request], WireObject | Awaitable[WireObject]],
*,
needs_request_body: bool = False,
) -> ServerMethod:
"""Resolve charge input per request; Stripe and CARD amounts are decimal USD."""

async def resolve(context: RequestContext) -> dict[str, object]:
if context.input is None:
raise MppSellerConfigurationError("Request-time pricing requires an HTTP request")
value = request(context.input)
terms = await value if inspect.isawaitable(value) else value
if self.name == "stripe":
prepared = self.stripe_request(terms)
elif self.name == "card":
prepared = self.card_request(terms)
else:
prepared = self.charge_request(terms)
return dict(prepared)

return ServerMethod(
method=self.method,
validate=self._validate,
broadcast=self._broadcast,
resolve_request=resolve,
needs_request_body=needs_request_body,
)

def charge_request(self, request: WireObject) -> WireObject:
if self.name in ("stripe", "card"):
raise MppSellerConfigurationError(f"Use {self.name}_request with a decimal USD amount")
Expand Down
Loading
Loading