InFlow Python SDK
Python integration for InFlow payments using the Machine Payments Protocol (MPP)
and x402. The Python distribution and import namespace are both inflowpay.
Python 3.11 or newer is required.
See the shared SDK compatibility and support policy
for supported releases, dependency expectations, and security reporting.
Start with the runnable Sandbox examples for MPP and x402
Buyers and Sellers, including account setup, commands, and expected results.
Working with the repository
Install uv, then run:
make sync
make verify
make sync installs the exact development dependencies from uv.lock, including
optional integrations. make verify checks formatting, lint, strict typing, tests,
and complete line and branch coverage for each source file. It also builds the
source distribution and wheel, checks package metadata, and installs the wheel
outside the checkout to verify imports and the py.typed marker.
The consumer check exercises both the base installation and the combined optional
dependencies without issuing payments or contacting InFlow.
Shared conformance checks exercise the public SDK against
pinned InFlow contract fixtures and produce reports for Python 3.11–3.14.
Protocol and framework dependencies are optional. The mpp and x402 extras
select payment libraries; evm and svm select x402 external-wallet dependencies;
mcp selects MCP dependencies for both protocols; fastapi selects the optional
web framework. The tap extra installs Ed25519 cryptography for agent recognition,
independently of payment libraries. The base package does not install those extras.
Runtime dependencies use compatible version ranges; uv.lock records the exact
versions used in development and CI. MCP dependencies use the 1.x line required by
pympp. No framework or blockchain package is imported by import inflowpay.
TAP agent recognition
Visa Trusted Agent Protocol (TAP) lets a Seller recognize a request signed by a
trusted Agent key. It does not identify the customer, authorize access to their
account, approve a purchase, or prove payment. Keep application authentication,
AEP enrollment, and MPP or x402 payment checks separate.
pip install 'inflowpay[tap]'
The import is inflowpay.tap.seller. No InFlow account or API key is needed for
verification. The default resolver retrieves public keys from
https://mcp.visa.com/.well-known/jwks; a successful request needs a signature
created with a private key registered with that trusted source.
from inflowpay.tap.seller import TapRequest, TapVerifier
async def verify_agent_request(verifier: TapVerifier, method, absolute_url, headers, body):
return await verifier.verify(
TapRequest(
method=method,
url=absolute_url,
headers=headers,
body=body,
)
)
Create the verifier at server startup and close it at shutdown with aclose()
or an application-lifetime async with TapVerifier() scope. Pass that verifier
to request handlers, as the runnable TAP example
does. Creating one per request discards its key cache and process-local replay
history. verify() returns immutable TapVerificationFacts; alternatively,
await verifier.with_verified(request, async_handler) invokes your handler only
after signature verification and the replay claim succeed, returning its result.
Supply the method without changing its case, the absolute external URL with its
original encoded path and query, and the exact body bytes. body=None means no
body; b"" is a supplied empty body and still requires signed content-digest
and content-type fields. Strings are encoded as UTF-8. Do not parse and
reserialize JSON before verification. Header names are case-insensitive. A mapping
can contain string values or lists of values; httpx.Headers is also accepted.
Duplicate values for required fields are rejected, not silently selected.
Obtain the external origin from trusted deployment configuration rather than
unvalidated Forwarded or X-Forwarded-* headers.
This implements InFlow's restricted Visa profile: one sig2 Ed25519 signature
covering method, authority, path and query, plus body digest and content type when
a body is supplied. Signature lifetimes are at most eight minutes. Both
ed25519 and Ed25519 are accepted; facts report ed25519. Intent is browse
or pay, reflecting the signer's tag, not proof of payment. Repeated signature
parameters use their last value while retaining their first position, as required
by Structured Fields; duplicate covered components remain invalid.
Keys, replay storage and cleanup
VisaTapKeyResolver accepts url, cache_ttl (3600 seconds), cache_max_age
(86400 seconds), timeout (3 seconds), clock and an optional HTTPX transport.
It shares concurrent refreshes, replaces the whole key set on success, and
remembers missing identifiers within that cache generation. A failed retrieval
can use a previously trusted matching key within cache_max_age; it cannot
introduce an unknown key or restore one removed by a successful refresh.
Redirects are not followed. The resolver owns its transport and closes it with
aclose(); do not share that transport with other clients.
For another trusted key source, pass key_resolver to TapVerifier. Implement
the public TapKeyResolver protocol's async resolve(keyid, algorithm) method,
returning a trusted cryptography Ed25519PublicKey or None. The request's
untrusted key identifier must not choose a network destination. The verifier
still checks the signature. An explicitly supplied resolver remains application-owned;
the verifier closes only the default resolver it creates itself.
MemoryTapReplayStore atomically claims a (keyid, nonce) pair until expiration,
but only within one process. For multiple workers or servers, supply a shared
TapReplayStore with an async, atomic claim(keyid, nonce, expires) operation.
Return False for a retained duplicate; let storage failures propagate. Invalid
signatures never consume a claim, and store failures never invoke the handler.
Nonce replay protection is not payment idempotency.
Python clocks return Unix seconds (time.time by default), rather than Node's
milliseconds. Validity is checked when verification starts, not again after
key retrieval or replay storage. Cancelling a caller stops its wait without
cancelling a shared key refresh needed by other requests. Closing the resolver
cancels and drains that refresh. Use a resolver on one event loop, and keep it
open until requests have finished.
TapVerificationError.code distinguishes malformed input, digest mismatch,
invalid lifetime, not-yet-valid or expired signatures, missing or unavailable
keys, invalid signatures, and replayed nonces. Exceptions from a custom resolver,
store, or handler propagate unchanged. Your application chooses the HTTP response;
the example returns a generic 401 for verification failures without exposing key
service details. TAP does not enable or modify any payment route automatically.
Client configuration and lifetime
ClientOptions selects production (the default, https://api.inflowpay.ai) or
sandbox (https://sandbox.inflowpay.ai). base_url overrides that destination.
Choose one of api_key, an asynchronous api_key_provider, or an asynchronous
access_token callback. Omit all three for anonymous requests. api_key_provider
returns the API key to send in X-API-KEY; its result is not cached. Each callback
runs for each HTTP attempt, allowing your application to refresh a token; its errors
propagate without being retried. It must support concurrent calls and cancellation.
The shared runtime owns its HTTPX client. It also owns any AsyncBaseTransport
supplied through ClientOptions.transport: closing the client closes that transport.
Give each client its own transport rather than sharing one between clients. Use
async with to close an SDK client when leaving its scope, or explicitly await
aclose() after all operations finish. An existing application-owned HTTPX client
cannot be supplied. Custom transports must honor task cancellation and perform one
request without following redirects or retrying it themselves.
The request timeout is 30 seconds by default and covers sending the HTTP request
and reading its response. Like the Node SDK, token retrieval occurs before this
request timeout; your token provider controls its own timeout. Cancelling the caller's
task interrupts token retrieval, requests, retry waits, and polling.
Retries, polling, and approval cancellation
The shared transport performs one attempt unless the protocol operation explicitly
permits retries. Permitted retries are capped at three additional attempts, for
network failures, timeouts, and HTTP 429, 502, 503, or 504. They use exponential delays
starting at 200 milliseconds, with jitter. Redirects are returned as errors; request
credentials are not forwarded to another destination, and response cookies are not
sent on later requests.
Polling has a separate overall deadline. The protocol flow decides which states
are terminal and which failures permit another poll. An approved request is not,
by itself, evidence of a completed payment.
Approval cleanup performs one cancellation request with a five-second limit. It
waits independently of the cancelled payment operation, so cancelling that operation
does not immediately abort its cleanup request. Cleanup failures do not replace the
original payment failure. This deliberately differs from Node's fire-and-forget
cleanup: Python waits for completion or the limit before returning, matching the
Go SDK's bounded cleanup. No background cancellation queue is created. If the process
is forcibly terminated, delivery cannot be guaranteed. Cancelling an approval does
not reverse a settled payment or issue a refund.
InflowApiError exposes code, http_status, endpoint, request_id, body, and
response headers. Server error messages are preserved. Credential fields and the
credential used for the failed attempt are redacted from error responses; sensitive
response headers are omitted. Transport errors use TIMEOUT or NETWORK_ERROR with
http_status=0. Python task cancellation remains asyncio.CancelledError.
MPP Buyer
Install inflowpay[mpp]. The Buyer obtains payment credentials from InFlow; it does
not sign transfers locally. Use an InFlow API key or Bearer-token provider belonging
to the paying account. The platform determines which payments that account may make.
import os
import httpx
from inflowpay import ClientOptions
from inflowpay.mpp.buyer import BuyerMethod, payment_transport
async def buy(url: str) -> bytes:
async with BuyerMethod(
ClientOptions(environment="sandbox", api_key=os.environ["INFLOW_API_KEY"])
) as method:
async with httpx.AsyncClient(transport=payment_transport([method])) as http:
response = await http.get(url)
response.raise_for_status()
return response.content
The first request reaches the seller without a payment credential. If the seller
returns a compatible MPP challenge, the method asks InFlow to create the payment,
waits for approval when required, and returns the platform's credential. pympp then
sends that credential to the seller. Your InFlow API key goes only to InFlow, not
to the seller. Keep redirects disabled on the HTTPX client, its default setting.
Select a payment method
BuyerMethod is a native pympp ClientMethod with asynchronous resource cleanup. Pass it to
payment_transport for HTTP requests or to pympp's PaymentRuntime for an existing
integration. For direct credential creation, call
await method.create_credential(CredentialParams(challenge=challenge)), importing
CredentialParams from mpp.runtime. The result is the complete Payment ...
authorization string, retaining the platform's payload, payer source, and additional
wire fields. Send that string without parsing and rebuilding it.
Use InFlow's payment_transport when sending HTTP payments: it preserves those
fields through pympp's request retry. Plain pympp PaymentRuntime and McpClient
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.
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