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
176 changes: 172 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,37 @@ fields through pympp's request retry. Plain pympp `PaymentRuntime` and `McpClien
rebuild credentials using fixed-field models and can drop additional credential
fields and an empty `source`. Their normal payment payload is retained.

### Select options for one request

Pass `PaymentOptions` through HTTPX's `extensions` argument to override a buyer's
defaults for one request. Omit a field to inherit its constructor value, or set it
to `None` to clear that value. Clearing the instrument lets InFlow select the
funding source; clearing the subscription requests a new subscription payment
instead of authorizing an existing subscription. CARD payments still require
valid merchant details, so clearing the merchant fails before requesting payment.

```python
from inflowpay.mpp.buyer import PaymentOptions

response = await http.get(
resource_url,
extensions={"inflow.payment": PaymentOptions(instrument_id=instrument_id)},
)
```

The options are local request metadata, not HTTP headers or a request body. They
are validated and copied before payment creation; concurrent requests do not
change each other's settings. Direct method calls accept the same options as
`CredentialParams(context=PaymentOptions(...), challenge=challenge)`. Cancelling
the request's asyncio task cancels that request's approval wait, not other requests
using the same buyer.

To select among offered challenges, pass pympp's native `order_challenges`
callback to `payment_transport`. It receives supported challenge candidates and
may return them in a different order or filter them. Returning an empty sequence
rejects payment without creating an approval. The transport retains its one-paid-
attempt limit regardless of the callback.

| Constructor settings | Behavior |
| --- | --- |
| Defaults: `method="inflow", intent="charge"` | Pay an InFlow charge using the rail advertised by the seller. |
Expand All @@ -242,14 +273,33 @@ fields and an empty `source`. Their normal payment payload is retained.
| `intent="subscription"` | Purchase a subscription through the create-and-approve flow. |
| `intent="subscription", subscription_id="..."` | Authorize access using that existing subscription and the current seller challenge; do not purchase another subscription. |

Instrument and subscription identifiers are UUID strings. They are fixed when the
method is constructed. This adapter rejects nonempty per-call `context`; configure
selectors on the constructor instead.
Use separate method instances for different selections; do not change
Instrument and subscription identifiers are UUID strings. Constructor values are
defaults; use `PaymentOptions` for request-specific selections. Do not mutate
one instance's settings between concurrent requests. Do not register several methods
with the same method/intent expecting pympp to choose a funding instrument: pympp
selects the first matching method. Select the intended instance in your application.

### Limit automatic MPP payments

`BuyerMethod` imposes no amount ceiling or allowlist unless you configure one.
For example, `BuyerMethod(options, max_amount="5.00", currencies=["USD"])`
accepts InFlow charges of at most five USD. Limits filter challenge selection and
are checked again before direct credential creation, before any approval request.
`PaymentOptions` cannot change or disable them.

| Method | Optional limits |
| --- | --- |
| InFlow charge | `max_amount` in decimal currency units requires `currencies`; `expected_recipients` restricts recipient identifiers. |
| Tempo charge | `max_atomic_amount` limits smallest token units. `max_amount` requires explicit `max_amount_decimals`. Either amount limit requires `currencies` containing token addresses. `allowed_chain_ids` restricts chains; `expected_recipients` checks both the primary recipient and every split recipient. |
| CARD charge | `max_amount` is USD with at most two significant decimal places; `max_atomic_amount` is cents. |

When both amount limits are supplied, both must pass. Empty allowlists reject all
payments for that field. Tempo addresses are compared case-insensitively; InFlow
currency and recipient identifiers are exact matches. Configuration is copied at
construction, so editing the caller's lists cannot relax a buyer's limits. Charge
limits are rejected on subscription methods rather than applied to recurring
payments with different approval semantics.

### Pay with a linked Visa card

Use `method="card"` for a merchant advertising CARD charge, not for an InFlow
Expand Down Expand Up @@ -422,6 +472,11 @@ when application authentication uses `Authorization`; pympp then uses
`Payment-Authorization` for the payment credential. The decorator does not implement
your application's authentication or access-control policy.

For an entire ASGI application, pympp also provides
`PaymentMiddleware(app, payments.charge(**terms))` in `mpp.server.asgi`.
It protects every HTTP route in that application; mount it only around routes
that require payment, not around public health or discovery endpoints.

pympp's `pay` decorator returns HTTP `402` for payment errors, including a pending
settlement whose Problem Details body has `status: 503`. The InFlow Seller preserves
that problem; the HTTP status is chosen by pympp. Node's middleware uses the problem's
Expand Down Expand Up @@ -979,6 +1034,108 @@ forces a refresh. `await seller.get_supported(refresh=True)` refreshes the Selle
capability lookup, not a running Facilitator or resource server. Values returned
by these methods can be modified without changing the client's cache.

### Native x402 extensions

`Buyer` inherits upstream extension registration. Sellers register native
extensions on `x402ResourceServer` and attach declarations to `RouteConfig.extensions`.
There is no separate InFlow extension registry. For the examples below, install
`x402[extensions]` alongside `inflowpay[evm,fastapi]` in compatible versions.

#### Wallet authentication for paid resources

Sign-In-With-X lets an external wallet prove ownership of the address that paid
for a resource. Register the upstream client extension on your buyer:

```python
from x402.extensions.sign_in_with_x import (
CreateSIWxClientExtensionOptions,
create_siwx_client_extension,
)

buyer.register_extension(
create_siwx_client_extension(CreateSIWxClientExtensionOptions(signers=[wallet]))
)
```

Here `wallet` is your external signing account, such as an `eth_account` account;
the InFlow managed wallet does not provide this message-signing interface. Use the
native `x402AsyncTransport` with the buyer so its HTTP authentication hooks run.
Calling `create_payment_payload` directly does not perform HTTP authentication.

On the seller, configure the public origin and storage, then declare the extension
on each applicable route:

```python
from x402.extensions.sign_in_with_x import (
CreateSIWxResourceServerExtensionOptions,
DeclareSIWxOptions,
create_siwx_resource_server_extension,
declare_siwx_extension,
)

resource_server.register_extension(
create_siwx_resource_server_extension(
CreateSIWxResourceServerExtensionOptions(origin="https://store.example", storage=storage)
)
)
route = await seller.route("0.10 USDC", schemes=["exact"])
route.extensions = declare_siwx_extension(DeclareSIWxOptions(expiration_seconds=300))
```

Storage must implement paid-resource tracking. For replay detection, also provide
both `has_used_nonce` and `record_nonce`; upstream's `InMemorySIWxStorage` does not
implement those two methods. Choose persistence and concurrency handling suitable
for your deployment. The upstream hooks record access after successful settlement
and check wallet proofs before running the protected handler. Authentication can
avoid another payment for a resource whose access has already been recorded.
If authentication fails, upstream can fall back to payment; configure buyer payment
policies accordingly. Registering this extension does not enroll a user with AEP.

#### Discovery metadata and explicit attribution

Bazaar metadata describes a paid HTTP route. Attach its declaration to the same
route used by the middleware, including request-time route resolvers:

```python
from x402.extensions.bazaar import declare_discovery_extension

route = await seller.route("0.10 USDC")
route.extensions = declare_discovery_extension()
```

Native middleware enriches route templates and request path parameters. This does
not publish the service to the InFlow Directory or replace an ODP catalog.

Builder attribution is opt-in. A seller can attach
`{"builder-code": declare_builder_code_extension("your_app")}` using
`x402.extensions.builder_code`. An external-wallet buyer can register
`BuilderCodeClientExtension("your_client")` from that module. The facilitator must
support builder-code settlement for those declarations to become on-chain
attribution. InFlow's facilitator does not promise that capability; attaching
metadata alone is not proof that a settlement transaction carries it. No InFlow
builder code is injected automatically. The installed Python x402 extension set
does not provide the signed-offer/signed-receipt extension available in Node.

#### Browser paywalls

The native paywall provider can be passed through the InFlow request-pricing
middleware. For an EVM USDC route:

```python
from x402.http.paywall import create_paywall, evm_paywall
from inflowpay.x402.fastapi import payment_middleware

paywall = create_paywall().with_network(evm_paywall).with_config(app_name="Reports").build()
app.middleware("http")(
payment_middleware({"GET /report": route}, resource_server, paywall_provider=paywall)
)
```

Browser requests accepting HTML receive the native payment page; API clients
receive the protocol's payment challenge. Configure a route and network the
paywall actually supports. The native EVM paywall is not an InFlow hosted-wallet,
balance, or CARD checkout interface.

### Prices, payment methods, and metering

`seller.offers()` accepts `"$0.01"`, `"0.01 USDC"`, or `"0.01"` with
Expand Down Expand Up @@ -1086,6 +1243,17 @@ settlement require a Seller account.

## x402 facilitator capabilities

Verification and settlement results expose valid `EXTENSION-RESPONSES` header
metadata as `result.extension_responses` for seller hooks. Missing or malformed
metadata is ignored; it does not change whether verification or settlement
succeeded. Upstream response models exclude this field from serialized buyer
receipts.

For Solana exact offers, seller configuration's matching supported capability
supplies `extra.transactionVersions`. The SDK preserves that value and does not
advertise version support when it is absent. The managed buyer forwards the
selected requirement unchanged; the wallet service constructs the transaction.

Facilitator capabilities describe the payment schemes, networks, and extensions
the facilitator supports. InFlow fetches these capabilities asynchronously during
adapter creation. Setup fails if that request fails, rather than returning an
Expand Down
30 changes: 23 additions & 7 deletions conformance/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@
from mpp.server.decorator import pay
from mpp.server.method import ValidateContext, VerifyContext
from starlette.responses import JSONResponse
from x402.schemas import PaymentPayload, PaymentRequirements, ResourceInfo
from x402.schemas import (
PaymentPayload,
PaymentRequirements,
ResourceInfo,
SettleResponse,
VerifyResponse,
)

from conformance.tap import tap_execute
from inflowpay import ClientOptions, InflowApiError, mpp, x402
Expand Down Expand Up @@ -380,16 +386,26 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
) as facilitator:
payload = PaymentPayload.model_validate(data["payment_payload"])
requirement = PaymentRequirements.model_validate(data["payment_requirements"])

def observe(result: VerifyResponse | SettleResponse) -> Data:
# Metadata is observable by sellers but intentionally absent from wire serialization.
return {
**result.model_dump(exclude_none=True),
**(
{"extensionResponses": result.extension_responses}
if result.extension_responses is not None
else {}
),
}

if operation == "x402.seller.settle":
return (await facilitator.settle(payload, requirement)).model_dump(exclude_none=True)
return observe(await facilitator.settle(payload, requirement))
verified = await facilitator.verify(payload, requirement)
if operation == "x402.seller.verify":
return verified.model_dump(exclude_none=True)
observations = {"verification": verified.model_dump(exclude_none=True)}
return observe(verified)
observations = {"verification": observe(verified)}
if verified.is_valid:
observations["settlement"] = (
await facilitator.settle(payload, requirement)
).model_dump(exclude_none=True)
observations["settlement"] = observe(await facilitator.settle(payload, requirement))
return observations


Expand Down
2 changes: 1 addition & 1 deletion conformance/inflow-specs.lock.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"repository": "inflowpayai/inflow-specs",
"revision": "20c518990672db7d29020ba22056a4c372d356c4"
"revision": "efdccacc338ed5397e2a37e1f12f6568f83b4811"
}
2 changes: 1 addition & 1 deletion interop/node.lock.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"repository": "inflowpayai/inflow-node",
"revision": "309aab2650dcb06dd652a5076dc176d5c41196d7"
"revision": "c28b402ebdfc0f59efd84be21396f403768b3394"
}
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ dev = [
"ruff==0.17.5",
"twine==7.0.0",
"uvicorn==0.52.4",
"x402[extensions]==2.28.0",
]

[tool.hatch.build.targets.sdist]
Expand Down
2 changes: 2 additions & 0 deletions scripts/interoperability.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ async function runCase(
problem: {
type: "https://paymentauth.org/problems/verification-failed",
title: "Rejected test payment",
detail: "The synthetic payment was rejected during validation.",
status: 402,
},
});
Expand All @@ -272,6 +273,7 @@ async function runCase(
problem: {
type: "https://paymentauth.org/problems/verification-failed",
title: "Rejected test payment",
detail: "The synthetic payment was rejected during settlement.",
status: 402,
},
});
Expand Down
6 changes: 4 additions & 2 deletions src/inflowpay/_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ async def request(
body: object = None,
headers: Mapping[str, str] | None = None,
retries: int = 0,
response_parser: Callable[[httpx.Response], object] = _parse,
) -> object:
# Retry permission belongs to the protocol operation, not the HTTP method.
if not path.startswith("/") or path.startswith("//") or "#" in path:
Expand All @@ -181,7 +182,7 @@ async def request(
content = None if body is None else json.dumps(body, allow_nan=False).encode()
attempt = 0
while True:
error = await self._attempt(method, path, content, extra)
error = await self._attempt(method, path, content, extra, response_parser)
if not isinstance(error, InflowApiError):
return error
if attempt >= min(retries, 3) or (
Expand All @@ -197,6 +198,7 @@ async def _attempt(
path: str,
content: bytes | None,
extra: dict[str, str],
response_parser: Callable[[httpx.Response], object],
) -> object:
await asyncio.sleep(0)
token = self._options.api_key
Expand Down Expand Up @@ -244,7 +246,7 @@ async def _attempt(
endpoint=path,
)
if response.is_success:
return _parse(response)
return response_parser(response)
return _error(path, response, (token,) if token else ())

async def get_payment_status(
Expand Down
Loading
Loading