mitulabs-payments 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of mitulabs-payments might be problematic. Click here for more details.
- mitulabs_payments/__init__.py +17 -0
- mitulabs_payments/_version.py +1 -0
- mitulabs_payments/amounts.py +39 -0
- mitulabs_payments/api.py +126 -0
- mitulabs_payments/charge.py +243 -0
- mitulabs_payments/credentials.py +87 -0
- mitulabs_payments/environment.py +50 -0
- mitulabs_payments/errors.py +18 -0
- mitulabs_payments/frameworks/__init__.py +41 -0
- mitulabs_payments/frameworks/django.py +31 -0
- mitulabs_payments/frameworks/fastapi.py +38 -0
- mitulabs_payments/frameworks/flask.py +31 -0
- mitulabs_payments/mitu.py +152 -0
- mitulabs_payments/models.py +49 -0
- mitulabs_payments/py.typed +0 -0
- mitulabs_payments-0.1.0.dist-info/METADATA +173 -0
- mitulabs_payments-0.1.0.dist-info/RECORD +19 -0
- mitulabs_payments-0.1.0.dist-info/WHEEL +4 -0
- mitulabs_payments-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
from ._version import __version__
|
|
4
|
+
from .errors import MituApiError, MituConfigError, MituError
|
|
5
|
+
from .mitu import Mitu
|
|
6
|
+
from .models import Payment
|
|
7
|
+
|
|
8
|
+
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Mitu",
|
|
12
|
+
"MituApiError",
|
|
13
|
+
"MituConfigError",
|
|
14
|
+
"MituError",
|
|
15
|
+
"Payment",
|
|
16
|
+
"__version__",
|
|
17
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from decimal import Decimal
|
|
3
|
+
|
|
4
|
+
from .errors import MituConfigError
|
|
5
|
+
|
|
6
|
+
_AMOUNT = re.compile(r"[0-9]+(?:\.[0-9]{1,2})?")
|
|
7
|
+
_CURRENCY = re.compile(r"[A-Za-z]{2,10}")
|
|
8
|
+
MAX_DESCRIPTION_LENGTH = 500
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def parse_price(value: object) -> Decimal:
|
|
12
|
+
"""Parses a price such as ``"5000"`` or ``"12.50"``: positive, at most two decimal places."""
|
|
13
|
+
if not (isinstance(value, str) and _AMOUNT.fullmatch(value)):
|
|
14
|
+
raise MituConfigError(
|
|
15
|
+
f"amount must be a decimal string with at most 2 decimal places, got {value!r}"
|
|
16
|
+
)
|
|
17
|
+
amount = Decimal(value)
|
|
18
|
+
if not amount:
|
|
19
|
+
raise MituConfigError("amount must be greater than 0; return None to serve free")
|
|
20
|
+
# Mitu reads the amount as a JSON number, so it must survive the trip through a float.
|
|
21
|
+
if Decimal(repr(float(amount))) != amount:
|
|
22
|
+
raise MituConfigError(f"amount {value} is too precise to send to Mitu")
|
|
23
|
+
return amount
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def parse_currency(value: object) -> str:
|
|
27
|
+
if not (isinstance(value, str) and _CURRENCY.fullmatch(value)):
|
|
28
|
+
raise MituConfigError(f"currency must be a currency code such as USD, got {value!r}")
|
|
29
|
+
return value.upper()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse_description(value: object) -> str | None:
|
|
33
|
+
if value is None:
|
|
34
|
+
return None
|
|
35
|
+
if not isinstance(value, str) or len(value) > MAX_DESCRIPTION_LENGTH:
|
|
36
|
+
raise MituConfigError(
|
|
37
|
+
f"description must be a string of at most {MAX_DESCRIPTION_LENGTH} characters"
|
|
38
|
+
)
|
|
39
|
+
return value or None
|
mitulabs_payments/api.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import os
|
|
3
|
+
import threading
|
|
4
|
+
import weakref
|
|
5
|
+
from collections.abc import Callable, Mapping
|
|
6
|
+
from typing import Final
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from ._version import __version__
|
|
11
|
+
from .errors import MituConfigError
|
|
12
|
+
|
|
13
|
+
TIMEOUT_SECONDS: Final = 10.0
|
|
14
|
+
PAYMENTS_PATH: Final = "/v1/public/payments"
|
|
15
|
+
|
|
16
|
+
_USER_AGENT: Final = f"mitulabs-payments-python/{__version__}"
|
|
17
|
+
|
|
18
|
+
Transport = httpx.BaseTransport | httpx.AsyncBaseTransport
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class MituApi:
|
|
22
|
+
"""Builds and sends the requests of the payment flow, from sync and async code alike.
|
|
23
|
+
|
|
24
|
+
Only requests to the Mitu API carry ``x-api-key``; requests to an ``agent_url`` carry the
|
|
25
|
+
agent's payment headers and nothing else. Redirects are never followed.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, api_key: str, base_url: str, *, transport: Transport | None = None) -> None:
|
|
29
|
+
self._api_key = api_key
|
|
30
|
+
self._payments_url = f"{base_url}{PAYMENTS_PATH}"
|
|
31
|
+
self._transport = transport
|
|
32
|
+
self._timeout = httpx.Timeout(TIMEOUT_SECONDS).as_dict()
|
|
33
|
+
self._lock = threading.Lock()
|
|
34
|
+
self._client: httpx.Client | None = None
|
|
35
|
+
# One per event loop: pooled connections cannot move between loops, and Django runs
|
|
36
|
+
# each async view of a WSGI app on a loop of its own.
|
|
37
|
+
self._async_clients: weakref.WeakKeyDictionary[
|
|
38
|
+
asyncio.AbstractEventLoop, httpx.AsyncClient
|
|
39
|
+
] = weakref.WeakKeyDictionary()
|
|
40
|
+
_after_fork_in_child(self._forget_clients)
|
|
41
|
+
|
|
42
|
+
def create_payment(self, body: Mapping[str, object]) -> httpx.Request:
|
|
43
|
+
return self._request("POST", self._payments_url, self._api_headers(), json=body)
|
|
44
|
+
|
|
45
|
+
def get_payment(self, payment_id: str) -> httpx.Request:
|
|
46
|
+
return self._request("GET", f"{self._payments_url}/{payment_id}", self._api_headers())
|
|
47
|
+
|
|
48
|
+
def agent(self, url: str, payment_headers: Mapping[str, str]) -> httpx.Request:
|
|
49
|
+
return self._request("GET", url, {**self._base_headers(), **payment_headers})
|
|
50
|
+
|
|
51
|
+
def send(self, request: httpx.Request) -> httpx.Response:
|
|
52
|
+
with self._lock:
|
|
53
|
+
if self._client is None:
|
|
54
|
+
self._client = httpx.Client(
|
|
55
|
+
follow_redirects=False, transport=self._typed(httpx.BaseTransport)
|
|
56
|
+
)
|
|
57
|
+
client = self._client
|
|
58
|
+
return client.send(request)
|
|
59
|
+
|
|
60
|
+
async def asend(self, request: httpx.Request) -> httpx.Response:
|
|
61
|
+
loop = asyncio.get_running_loop()
|
|
62
|
+
with self._lock:
|
|
63
|
+
if not (client := self._async_clients.get(loop)):
|
|
64
|
+
client = self._async_clients[loop] = httpx.AsyncClient(
|
|
65
|
+
follow_redirects=False, transport=self._typed(httpx.AsyncBaseTransport)
|
|
66
|
+
)
|
|
67
|
+
return await client.send(request)
|
|
68
|
+
|
|
69
|
+
def close(self) -> None:
|
|
70
|
+
with self._lock:
|
|
71
|
+
client, self._client = self._client, None
|
|
72
|
+
if client:
|
|
73
|
+
client.close()
|
|
74
|
+
|
|
75
|
+
async def aclose(self) -> None:
|
|
76
|
+
with self._lock:
|
|
77
|
+
client = self._async_clients.pop(asyncio.get_running_loop(), None)
|
|
78
|
+
self._async_clients.clear()
|
|
79
|
+
if client:
|
|
80
|
+
await client.aclose()
|
|
81
|
+
self.close()
|
|
82
|
+
|
|
83
|
+
def _request(
|
|
84
|
+
self,
|
|
85
|
+
method: str,
|
|
86
|
+
url: str,
|
|
87
|
+
headers: Mapping[str, str],
|
|
88
|
+
*,
|
|
89
|
+
json: Mapping[str, object] | None = None,
|
|
90
|
+
) -> httpx.Request:
|
|
91
|
+
return httpx.Request(
|
|
92
|
+
method, url, headers=headers, json=json, extensions={"timeout": self._timeout}
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
def _base_headers(self) -> dict[str, str]:
|
|
96
|
+
return {"accept": "application/json", "user-agent": _USER_AGENT}
|
|
97
|
+
|
|
98
|
+
def _api_headers(self) -> dict[str, str]:
|
|
99
|
+
return {**self._base_headers(), "x-api-key": self._api_key}
|
|
100
|
+
|
|
101
|
+
def _typed[T: Transport](self, kind: type[T]) -> T | None:
|
|
102
|
+
match self._transport:
|
|
103
|
+
case None:
|
|
104
|
+
return None
|
|
105
|
+
case transport if isinstance(transport, kind):
|
|
106
|
+
return transport
|
|
107
|
+
raise MituConfigError(f"transport must be an {kind.__name__} for this view")
|
|
108
|
+
|
|
109
|
+
def _forget_clients(self) -> None:
|
|
110
|
+
# Not closed: the parent process still owns those pooled sockets.
|
|
111
|
+
self._client = None
|
|
112
|
+
self._async_clients = weakref.WeakKeyDictionary()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _after_fork_in_child(method: Callable[[], None]) -> None:
|
|
116
|
+
# Pooled sockets must not be shared with the parent (Gunicorn --preload). The weak
|
|
117
|
+
# reference keeps the hook from holding the client alive.
|
|
118
|
+
if not hasattr(os, "register_at_fork"):
|
|
119
|
+
return
|
|
120
|
+
ref = weakref.WeakMethod(method)
|
|
121
|
+
|
|
122
|
+
def run() -> None:
|
|
123
|
+
if bound := ref():
|
|
124
|
+
bound()
|
|
125
|
+
|
|
126
|
+
os.register_at_fork(after_in_child=run)
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""One request to a charged route, written once as a generator of HTTP requests and driven by a
|
|
2
|
+
sync or an async client."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import secrets
|
|
7
|
+
from collections.abc import Generator, Iterable, Mapping
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from datetime import UTC, datetime, timedelta
|
|
10
|
+
from decimal import Decimal, InvalidOperation
|
|
11
|
+
from typing import Final, cast
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from ._version import __version__
|
|
16
|
+
from .api import MituApi
|
|
17
|
+
from .credentials import Credential, credential_of
|
|
18
|
+
from .environment import is_secure_url
|
|
19
|
+
from .errors import MituApiError
|
|
20
|
+
from .models import Incoming, Outcome, Paid, Payment, Price, Reply
|
|
21
|
+
|
|
22
|
+
PAYMENT_TTL: Final = timedelta(minutes=15)
|
|
23
|
+
RETRY_AFTER_SECONDS: Final = 5
|
|
24
|
+
|
|
25
|
+
Flow = Generator[httpx.Request, httpx.Response, Outcome]
|
|
26
|
+
|
|
27
|
+
_SDK: Final = f"mitulabs-payments@{__version__}"
|
|
28
|
+
_RELAYED_HEADERS: Final = ("Content-Type", "WWW-Authenticate", "PAYMENT-REQUIRED", "Retry-After")
|
|
29
|
+
_RECEIPT_HEADERS: Final = ("Payment-Receipt", "PAYMENT-RESPONSE")
|
|
30
|
+
_NO_STORE: Final = {"Cache-Control": "no-store"}
|
|
31
|
+
_MAX_ERROR_CODE_LENGTH: Final = 64
|
|
32
|
+
|
|
33
|
+
UNAVAILABLE: Final = Reply(
|
|
34
|
+
503,
|
|
35
|
+
{
|
|
36
|
+
"Content-Type": "application/problem+json",
|
|
37
|
+
"Retry-After": str(RETRY_AFTER_SECONDS),
|
|
38
|
+
**_NO_STORE,
|
|
39
|
+
},
|
|
40
|
+
json.dumps(
|
|
41
|
+
{"type": "about:blank", "title": "Payment service unavailable", "status": 503}
|
|
42
|
+
).encode(),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
logger = logging.getLogger(__name__)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _Unavailable(Exception):
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True, slots=True)
|
|
53
|
+
class _Stored:
|
|
54
|
+
payment_id: str
|
|
55
|
+
reference: str
|
|
56
|
+
amount: Decimal
|
|
57
|
+
currency: str
|
|
58
|
+
agent_url: str
|
|
59
|
+
metadata: Mapping[str, object]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def charge(api: MituApi, price: Price, incoming: Incoming) -> Flow:
|
|
63
|
+
if (credential := credential_of(incoming.headers)) and (
|
|
64
|
+
stored := (yield from _bound_payment(api, credential, price, incoming))
|
|
65
|
+
):
|
|
66
|
+
response = yield api.agent(stored.agent_url, credential.forward)
|
|
67
|
+
if response.status_code == 200:
|
|
68
|
+
receipt = {**_copy(response, _RECEIPT_HEADERS), **_NO_STORE}
|
|
69
|
+
return Paid(_payment(stored, response), receipt)
|
|
70
|
+
return _relay(response)
|
|
71
|
+
return (yield from _challenge(api, price, incoming))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def run(api: MituApi, flow: Flow) -> Outcome:
|
|
75
|
+
try:
|
|
76
|
+
request = next(flow)
|
|
77
|
+
while True:
|
|
78
|
+
request = flow.send(api.send(request))
|
|
79
|
+
except StopIteration as done:
|
|
80
|
+
return cast(Outcome, done.value)
|
|
81
|
+
except (httpx.RequestError, _Unavailable) as error:
|
|
82
|
+
return _unavailable(error)
|
|
83
|
+
finally:
|
|
84
|
+
flow.close()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async def arun(api: MituApi, flow: Flow) -> Outcome:
|
|
88
|
+
try:
|
|
89
|
+
request = next(flow)
|
|
90
|
+
while True:
|
|
91
|
+
request = flow.send(await api.asend(request))
|
|
92
|
+
except StopIteration as done:
|
|
93
|
+
return cast(Outcome, done.value)
|
|
94
|
+
except (httpx.RequestError, _Unavailable) as error:
|
|
95
|
+
return _unavailable(error)
|
|
96
|
+
finally:
|
|
97
|
+
flow.close()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def now() -> datetime:
|
|
101
|
+
return datetime.now(UTC)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _bound_payment(
|
|
105
|
+
api: MituApi, credential: Credential, price: Price, incoming: Incoming
|
|
106
|
+
) -> Generator[httpx.Request, httpx.Response, _Stored | None]:
|
|
107
|
+
"""The credential's payment, if it is this merchant's and priced for this very route."""
|
|
108
|
+
response = yield api.get_payment(credential.payment_id)
|
|
109
|
+
if response.status_code in (400, 404):
|
|
110
|
+
logger.info("Payment %s is not this merchant's; issuing a new one", credential.payment_id)
|
|
111
|
+
return None
|
|
112
|
+
stored = _stored(_data(response))
|
|
113
|
+
if (
|
|
114
|
+
stored.payment_id == credential.payment_id
|
|
115
|
+
and stored.amount == price.amount
|
|
116
|
+
and stored.currency == price.currency
|
|
117
|
+
and stored.metadata.get("method") == incoming.method
|
|
118
|
+
and stored.metadata.get("path") == incoming.path
|
|
119
|
+
):
|
|
120
|
+
return stored
|
|
121
|
+
logger.info("Payment %s is for another route or price; issuing a new one", stored.payment_id)
|
|
122
|
+
return None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _challenge(api: MituApi, price: Price, incoming: Incoming) -> Flow:
|
|
126
|
+
created = yield api.create_payment(_new_payment(price, incoming))
|
|
127
|
+
stored = _stored(_data(created))
|
|
128
|
+
response = yield api.agent(stored.agent_url, {})
|
|
129
|
+
if response.is_server_error:
|
|
130
|
+
raise _Unavailable(f"agent_url answered {response.status_code}")
|
|
131
|
+
return _relay(response)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _new_payment(price: Price, incoming: Incoming) -> dict[str, object]:
|
|
135
|
+
expires_at = now() + PAYMENT_TTL
|
|
136
|
+
return {
|
|
137
|
+
# Exact: parse_price only accepts amounts that survive the float.
|
|
138
|
+
"amount": float(price.amount),
|
|
139
|
+
"currency": price.currency,
|
|
140
|
+
"reference": f"sdk_{secrets.token_hex(16)}",
|
|
141
|
+
**({"description": price.description} if price.description else {}),
|
|
142
|
+
"expires_at": expires_at.isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
|
143
|
+
"metadata": {"sdk": _SDK, "method": incoming.method, "path": incoming.path},
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _data(response: httpx.Response) -> Mapping[str, object]:
|
|
148
|
+
status = response.status_code
|
|
149
|
+
if status == 429 or response.is_server_error:
|
|
150
|
+
raise _Unavailable(f"Mitu API answered {status}")
|
|
151
|
+
if not response.is_success:
|
|
152
|
+
call = f"{response.request.method} {response.request.url.path}"
|
|
153
|
+
raise MituApiError(status, f"Mitu API {call} failed ({status}{_error_code(response)})")
|
|
154
|
+
match _json(response):
|
|
155
|
+
case {"data": dict(data)}:
|
|
156
|
+
return data
|
|
157
|
+
raise _Unavailable("Mitu API answered without a payment")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _stored(data: Mapping[str, object]) -> _Stored:
|
|
161
|
+
match data:
|
|
162
|
+
case {
|
|
163
|
+
"id": str(payment_id),
|
|
164
|
+
"reference": str(reference),
|
|
165
|
+
"amount": str(amount),
|
|
166
|
+
"currency": str(currency),
|
|
167
|
+
"agent_url": str(agent_url),
|
|
168
|
+
} if (value := _decimal(amount)) is not None and is_secure_url(agent_url):
|
|
169
|
+
metadata = data.get("metadata")
|
|
170
|
+
return _Stored(
|
|
171
|
+
payment_id,
|
|
172
|
+
reference,
|
|
173
|
+
value,
|
|
174
|
+
currency.upper(),
|
|
175
|
+
agent_url,
|
|
176
|
+
metadata if isinstance(metadata, dict) else {},
|
|
177
|
+
)
|
|
178
|
+
raise _Unavailable("Mitu API answered with an unreadable payment")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _payment(stored: _Stored, response: httpx.Response) -> Payment:
|
|
182
|
+
match _json(response):
|
|
183
|
+
case {"receipt": dict(receipt)}:
|
|
184
|
+
pass
|
|
185
|
+
case _:
|
|
186
|
+
receipt = {}
|
|
187
|
+
return Payment(
|
|
188
|
+
payment_id=stored.payment_id,
|
|
189
|
+
reference=stored.reference,
|
|
190
|
+
tx_hash=_text(receipt.get("tx_hash")),
|
|
191
|
+
amount_paid=_decimal(receipt.get("amount_paid")),
|
|
192
|
+
currency=_text(receipt.get("currency")),
|
|
193
|
+
network=_text(receipt.get("network")),
|
|
194
|
+
payment_method=_text(receipt.get("payment_method")),
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _relay(response: httpx.Response) -> Reply:
|
|
199
|
+
return Reply(
|
|
200
|
+
response.status_code,
|
|
201
|
+
{**_copy(response, _RELAYED_HEADERS), **_NO_STORE},
|
|
202
|
+
response.content,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _copy(response: httpx.Response, names: Iterable[str]) -> dict[str, str]:
|
|
207
|
+
return {
|
|
208
|
+
name: ", ".join(values) for name in names if (values := response.headers.get_list(name))
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _unavailable(error: Exception) -> Reply:
|
|
213
|
+
reason = str(error) if isinstance(error, _Unavailable) else type(error).__name__
|
|
214
|
+
logger.warning("Mitu is unavailable (%s); answering 503", reason)
|
|
215
|
+
return UNAVAILABLE
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _json(response: httpx.Response) -> object:
|
|
219
|
+
try:
|
|
220
|
+
return response.json()
|
|
221
|
+
except ValueError:
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _error_code(response: httpx.Response) -> str:
|
|
226
|
+
match _json(response):
|
|
227
|
+
case {"error": str(code)}:
|
|
228
|
+
return f": {code[:_MAX_ERROR_CODE_LENGTH]}"
|
|
229
|
+
return ""
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _decimal(value: object) -> Decimal | None:
|
|
233
|
+
if isinstance(value, bool) or not isinstance(value, str | int | float):
|
|
234
|
+
return None
|
|
235
|
+
try:
|
|
236
|
+
amount = Decimal(str(value))
|
|
237
|
+
except InvalidOperation:
|
|
238
|
+
return None
|
|
239
|
+
return amount if amount.is_finite() else None
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _text(value: object) -> str | None:
|
|
243
|
+
return value if isinstance(value, str) and value else None
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Reading the Mitu payment id from an MPP or x402 credential.
|
|
2
|
+
|
|
3
|
+
The id only selects the payment to look up and settle. Mitu verifies the credential itself, so
|
|
4
|
+
nothing here trusts it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import base64
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Final
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
|
|
15
|
+
MPP_HEADERS: Final = ("authorization", "payment-authorization")
|
|
16
|
+
X402_HEADERS: Final = ("payment-signature", "x-payment")
|
|
17
|
+
PAYMENT_HEADERS: Final = (*MPP_HEADERS, *X402_HEADERS)
|
|
18
|
+
|
|
19
|
+
PAYMENT_ID = re.compile(r"pmt_[0-9a-z]{1,46}")
|
|
20
|
+
|
|
21
|
+
_MAX_ENCODED_LENGTH = 32_768
|
|
22
|
+
_TO_STANDARD_BASE64 = str.maketrans("-_", "+/")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class Credential:
|
|
27
|
+
payment_id: str
|
|
28
|
+
forward: dict[str, str]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def credential_of(headers: Mapping[str, str]) -> Credential | None:
|
|
32
|
+
"""The first credential in ``headers`` naming a Mitu payment, with the headers to forward.
|
|
33
|
+
|
|
34
|
+
An MPP credential is always forwarded as ``Authorization``, the only header Mitu reads it from.
|
|
35
|
+
"""
|
|
36
|
+
for name in MPP_HEADERS:
|
|
37
|
+
if (token := _payment_token(headers.get(name))) and (payment_id := _mpp_scope(token)):
|
|
38
|
+
return Credential(payment_id, {"authorization": f"Payment {token}"})
|
|
39
|
+
for name in X402_HEADERS:
|
|
40
|
+
if (value := headers.get(name)) and (payment_id := _x402_resource_id(value)):
|
|
41
|
+
return Credential(payment_id, {name: value})
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _payment_token(value: str | None) -> str | None:
|
|
46
|
+
match (value or "").split(maxsplit=1):
|
|
47
|
+
case [scheme, token] if scheme.lower() == "payment":
|
|
48
|
+
return token.strip()
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _mpp_scope(token: str) -> str | None:
|
|
53
|
+
match _decode(token):
|
|
54
|
+
case {"challenge": {"opaque": str(opaque)}}:
|
|
55
|
+
meta = _decode(opaque)
|
|
56
|
+
case {"challenge": {"opaque": dict() as meta}}:
|
|
57
|
+
pass
|
|
58
|
+
case _:
|
|
59
|
+
return None
|
|
60
|
+
match meta:
|
|
61
|
+
case {"_mppx_scope": str(scope)} if PAYMENT_ID.fullmatch(scope):
|
|
62
|
+
return scope
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _x402_resource_id(value: str) -> str | None:
|
|
67
|
+
match _decode(value):
|
|
68
|
+
case {"resource": {"url": str(url)}}:
|
|
69
|
+
try:
|
|
70
|
+
path = urlsplit(url).path
|
|
71
|
+
except ValueError:
|
|
72
|
+
return None
|
|
73
|
+
match path.rsplit("/", 2):
|
|
74
|
+
case [_, "pay", payment_id] if PAYMENT_ID.fullmatch(payment_id):
|
|
75
|
+
return payment_id
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _decode(text: str) -> object:
|
|
80
|
+
"""Base64 (standard or URL-safe, padded or not) JSON, or None."""
|
|
81
|
+
if len(text) > _MAX_ENCODED_LENGTH:
|
|
82
|
+
return None
|
|
83
|
+
padded = text.translate(_TO_STANDARD_BASE64) + "=" * (-len(text) % 4)
|
|
84
|
+
try:
|
|
85
|
+
return json.loads(base64.b64decode(padded, validate=True))
|
|
86
|
+
except (ValueError, RecursionError):
|
|
87
|
+
return None
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Final, Literal
|
|
4
|
+
from urllib.parse import urlsplit
|
|
5
|
+
|
|
6
|
+
from .errors import MituConfigError
|
|
7
|
+
|
|
8
|
+
Environment = Literal["sandbox", "production"]
|
|
9
|
+
|
|
10
|
+
BASE_URL: Final = "https://api.mitu.ai/economy"
|
|
11
|
+
|
|
12
|
+
_API_KEY = re.compile(r"sk_(test|live)_[A-Za-z0-9]{16,}")
|
|
13
|
+
_LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class ResolvedEnvironment:
|
|
18
|
+
environment: Environment
|
|
19
|
+
base_url: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def resolve_environment(api_key: str, base_url: str | None = None) -> ResolvedEnvironment:
|
|
23
|
+
"""Derives the environment from the key: ``sk_test_`` is sandbox, ``sk_live_`` production."""
|
|
24
|
+
if not (isinstance(api_key, str) and (key := _API_KEY.fullmatch(api_key))):
|
|
25
|
+
raise MituConfigError("api_key must be a Mitu secret key (sk_test_... or sk_live_...)")
|
|
26
|
+
environment: Environment = "production" if key[1] == "live" else "sandbox"
|
|
27
|
+
return ResolvedEnvironment(environment, BASE_URL if base_url is None else _base(base_url))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def is_secure_url(url: str) -> bool:
|
|
31
|
+
"""True for https URLs, and for http ones that point at this machine."""
|
|
32
|
+
try:
|
|
33
|
+
parts = urlsplit(url)
|
|
34
|
+
host = parts.hostname
|
|
35
|
+
_ = parts.port
|
|
36
|
+
except ValueError:
|
|
37
|
+
return False
|
|
38
|
+
return bool(host) and (
|
|
39
|
+
parts.scheme == "https" or (parts.scheme == "http" and host in _LOCAL_HOSTS)
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _base(url: str) -> str:
|
|
44
|
+
if not is_secure_url(url):
|
|
45
|
+
raise MituConfigError("base_url must be an https URL")
|
|
46
|
+
parts = urlsplit(url)
|
|
47
|
+
host = parts.hostname or ""
|
|
48
|
+
netloc = f"[{host}]" if ":" in host else host
|
|
49
|
+
port_suffix = "" if parts.port is None else f":{parts.port}"
|
|
50
|
+
return f"{parts.scheme}://{netloc}{port_suffix}{parts.path.rstrip('/')}"
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
class MituError(Exception):
|
|
2
|
+
"""Base class for every error the package raises. Messages never contain keys or credentials."""
|
|
3
|
+
|
|
4
|
+
code = "MITU_ERROR"
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MituConfigError(MituError):
|
|
8
|
+
code = "MITU_CONFIG"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MituApiError(MituError):
|
|
12
|
+
"""The Mitu API refused a request in a way a retry will not fix, such as an invalid key."""
|
|
13
|
+
|
|
14
|
+
code = "MITU_API"
|
|
15
|
+
|
|
16
|
+
def __init__(self, status: int, message: str) -> None:
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.status = status
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Where each framework keeps its request, its response and the payment the view reads."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import importlib
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any, Protocol
|
|
7
|
+
|
|
8
|
+
from ..credentials import PAYMENT_HEADERS
|
|
9
|
+
from ..models import Incoming, Payment, Reply
|
|
10
|
+
|
|
11
|
+
_FRAMEWORKS = ("fastapi", "django", "flask")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class HeaderLookup(Protocol):
|
|
15
|
+
def get(self, key: str, /) -> str | None: ...
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Adapter(Protocol):
|
|
19
|
+
def request_of(self, args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> Any | None:
|
|
20
|
+
"""The framework request among a view's arguments, or None for another framework."""
|
|
21
|
+
|
|
22
|
+
def incoming(self, request: Any) -> Incoming: ...
|
|
23
|
+
|
|
24
|
+
def respond(self, reply: Reply) -> Any: ...
|
|
25
|
+
|
|
26
|
+
def finish(self, result: Any, headers: Mapping[str, str]) -> Any:
|
|
27
|
+
"""The view's return value as a response carrying ``headers``."""
|
|
28
|
+
|
|
29
|
+
def attach(self, request: Any, payment: Payment | None) -> None: ...
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def installed_adapters() -> list[Adapter]:
|
|
33
|
+
found: list[Adapter] = []
|
|
34
|
+
for name in _FRAMEWORKS:
|
|
35
|
+
with contextlib.suppress(ImportError):
|
|
36
|
+
found.append(importlib.import_module(f"{__name__}.{name}").ADAPTER)
|
|
37
|
+
return found
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def payment_headers(headers: HeaderLookup) -> dict[str, str]:
|
|
41
|
+
return {name: value for name in PAYMENT_HEADERS if (value := headers.get(name))}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Django: the payment is on ``request.mitu_payment``."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from django.http import HttpRequest, HttpResponse
|
|
7
|
+
|
|
8
|
+
from ..models import Incoming, Payment, Reply
|
|
9
|
+
from . import payment_headers
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DjangoAdapter:
|
|
13
|
+
def request_of(self, args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> HttpRequest | None:
|
|
14
|
+
return next((value for value in args if isinstance(value, HttpRequest)), None)
|
|
15
|
+
|
|
16
|
+
def incoming(self, request: HttpRequest) -> Incoming:
|
|
17
|
+
return Incoming(request.method or "GET", request.path, payment_headers(request.headers))
|
|
18
|
+
|
|
19
|
+
def respond(self, reply: Reply) -> HttpResponse:
|
|
20
|
+
return self.finish(HttpResponse(reply.body, status=reply.status), reply.headers)
|
|
21
|
+
|
|
22
|
+
def finish(self, result: Any, headers: Mapping[str, str]) -> Any:
|
|
23
|
+
for name, value in headers.items():
|
|
24
|
+
result[name] = value
|
|
25
|
+
return result
|
|
26
|
+
|
|
27
|
+
def attach(self, request: HttpRequest, payment: Payment | None) -> None:
|
|
28
|
+
request.mitu_payment = payment
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
ADAPTER = DjangoAdapter()
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""FastAPI and Starlette: the route takes ``request: Request``; the payment is on
|
|
2
|
+
``request.state.mitu_payment``."""
|
|
3
|
+
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from fastapi.encoders import jsonable_encoder
|
|
8
|
+
from starlette.requests import Request
|
|
9
|
+
from starlette.responses import JSONResponse, Response
|
|
10
|
+
|
|
11
|
+
from ..models import Incoming, Payment, Reply
|
|
12
|
+
from . import payment_headers
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class StarletteAdapter:
|
|
16
|
+
def request_of(self, args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> Request | None:
|
|
17
|
+
return next(
|
|
18
|
+
(value for value in (*args, *kwargs.values()) if isinstance(value, Request)), None
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
def incoming(self, request: Request) -> Incoming:
|
|
22
|
+
return Incoming(request.method, request.url.path, payment_headers(request.headers))
|
|
23
|
+
|
|
24
|
+
def respond(self, reply: Reply) -> Response:
|
|
25
|
+
return Response(reply.body, status_code=reply.status, headers=reply.headers)
|
|
26
|
+
|
|
27
|
+
def finish(self, result: Any, headers: Mapping[str, str]) -> Response:
|
|
28
|
+
response = (
|
|
29
|
+
result if isinstance(result, Response) else JSONResponse(jsonable_encoder(result))
|
|
30
|
+
)
|
|
31
|
+
response.headers.update(headers)
|
|
32
|
+
return response
|
|
33
|
+
|
|
34
|
+
def attach(self, request: Request, payment: Payment | None) -> None:
|
|
35
|
+
request.state.mitu_payment = payment
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
ADAPTER = StarletteAdapter()
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Flask: the payment is on ``flask.g.mitu_payment``."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import flask
|
|
7
|
+
|
|
8
|
+
from ..models import Incoming, Payment, Reply
|
|
9
|
+
from . import payment_headers
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class FlaskAdapter:
|
|
13
|
+
def request_of(self, args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> flask.Request | None:
|
|
14
|
+
return flask.request if flask.has_request_context() else None
|
|
15
|
+
|
|
16
|
+
def incoming(self, request: flask.Request) -> Incoming:
|
|
17
|
+
return Incoming(request.method, request.path, payment_headers(request.headers))
|
|
18
|
+
|
|
19
|
+
def respond(self, reply: Reply) -> flask.Response:
|
|
20
|
+
return flask.Response(reply.body, status=reply.status, headers=reply.headers)
|
|
21
|
+
|
|
22
|
+
def finish(self, result: Any, headers: Mapping[str, str]) -> flask.Response:
|
|
23
|
+
response = flask.make_response(result)
|
|
24
|
+
response.headers.update(headers)
|
|
25
|
+
return response
|
|
26
|
+
|
|
27
|
+
def attach(self, request: flask.Request, payment: Payment | None) -> None:
|
|
28
|
+
flask.g.mitu_payment = payment
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
ADAPTER = FlaskAdapter()
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import inspect
|
|
3
|
+
from collections.abc import Awaitable, Callable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any, cast
|
|
6
|
+
|
|
7
|
+
from .amounts import parse_currency, parse_description, parse_price
|
|
8
|
+
from .api import MituApi, Transport
|
|
9
|
+
from .charge import arun, charge, run
|
|
10
|
+
from .environment import resolve_environment
|
|
11
|
+
from .errors import MituConfigError
|
|
12
|
+
from .frameworks import Adapter, installed_adapters
|
|
13
|
+
from .models import Paid, Price, Reply
|
|
14
|
+
|
|
15
|
+
PriceFn = Callable[[Any], str | None | Awaitable[str | None]]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class _Route:
|
|
20
|
+
amount: str | PriceFn
|
|
21
|
+
currency: str
|
|
22
|
+
description: str | None
|
|
23
|
+
fixed: Price | None
|
|
24
|
+
|
|
25
|
+
def price(self, amount: str | None) -> Price | None:
|
|
26
|
+
if amount is None:
|
|
27
|
+
return None
|
|
28
|
+
return self.fixed or Price(parse_price(amount), self.currency, self.description)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Mitu:
|
|
32
|
+
"""Puts Mitu's payment flow in front of your routes.
|
|
33
|
+
|
|
34
|
+
Agents pay with MPP or x402. Mitu issues the challenges, settles the payment on chain and
|
|
35
|
+
sends your ``payment.completed`` webhook; this object only asks Mitu for a payment, checks
|
|
36
|
+
that the one an agent presents is for the route it calls, and serves the route once paid.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
api_key: str,
|
|
42
|
+
*,
|
|
43
|
+
default_currency: str = "USD",
|
|
44
|
+
base_url: str | None = None,
|
|
45
|
+
transport: Transport | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
resolved = resolve_environment(api_key, base_url)
|
|
48
|
+
self.environment = resolved.environment
|
|
49
|
+
self.default_currency = parse_currency(default_currency)
|
|
50
|
+
self._api = MituApi(api_key, resolved.base_url, transport=transport)
|
|
51
|
+
|
|
52
|
+
def __repr__(self) -> str:
|
|
53
|
+
return f"Mitu(environment={self.environment!r})"
|
|
54
|
+
|
|
55
|
+
def charge[**P, R](
|
|
56
|
+
self,
|
|
57
|
+
amount: str | PriceFn,
|
|
58
|
+
*,
|
|
59
|
+
currency: str | None = None,
|
|
60
|
+
description: str | None = None,
|
|
61
|
+
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
62
|
+
"""Route decorator charging ``amount`` in ``currency`` (default ``default_currency``).
|
|
63
|
+
|
|
64
|
+
``amount`` is a decimal string with at most two decimal places, or a function of the
|
|
65
|
+
request returning one, or None to serve that request free. The view reads the
|
|
66
|
+
:class:`Payment` from ``request.state.mitu_payment`` (FastAPI), ``g.mitu_payment``
|
|
67
|
+
(Flask) or ``request.mitu_payment`` (Django).
|
|
68
|
+
"""
|
|
69
|
+
route_currency = self.default_currency if currency is None else parse_currency(currency)
|
|
70
|
+
route_description = parse_description(description)
|
|
71
|
+
fixed: Price | None
|
|
72
|
+
match amount:
|
|
73
|
+
case str():
|
|
74
|
+
fixed = Price(parse_price(amount), route_currency, route_description)
|
|
75
|
+
case _ if callable(amount):
|
|
76
|
+
fixed = None
|
|
77
|
+
case _:
|
|
78
|
+
raise MituConfigError("amount must be a decimal string or a function")
|
|
79
|
+
route = _Route(amount, route_currency, route_description, fixed)
|
|
80
|
+
|
|
81
|
+
def decorate(view: Callable[P, R]) -> Callable[P, R]:
|
|
82
|
+
if inspect.iscoroutinefunction(view):
|
|
83
|
+
return cast(Callable[P, R], self._wrap_async(route, view))
|
|
84
|
+
return cast(Callable[P, R], self._wrap_sync(route, view))
|
|
85
|
+
|
|
86
|
+
return decorate
|
|
87
|
+
|
|
88
|
+
async def close(self) -> None:
|
|
89
|
+
"""Closes the HTTP connections to Mitu."""
|
|
90
|
+
await self._api.aclose()
|
|
91
|
+
|
|
92
|
+
def close_sync(self) -> None:
|
|
93
|
+
""":meth:`close` for sync apps, such as Flask and Django."""
|
|
94
|
+
self._api.close()
|
|
95
|
+
|
|
96
|
+
def _wrap_async(
|
|
97
|
+
self, route: _Route, view: Callable[..., Awaitable[Any]]
|
|
98
|
+
) -> Callable[..., Awaitable[Any]]:
|
|
99
|
+
adapters = installed_adapters()
|
|
100
|
+
|
|
101
|
+
@functools.wraps(view)
|
|
102
|
+
async def charged(*args: Any, **kwargs: Any) -> Any:
|
|
103
|
+
adapter, request = _find(adapters, args, kwargs, view)
|
|
104
|
+
amount = route.amount(request) if callable(route.amount) else route.amount
|
|
105
|
+
if inspect.isawaitable(amount):
|
|
106
|
+
amount = await amount
|
|
107
|
+
if not (price := route.price(amount)):
|
|
108
|
+
adapter.attach(request, None)
|
|
109
|
+
return await view(*args, **kwargs)
|
|
110
|
+
match await arun(self._api, charge(self._api, price, adapter.incoming(request))):
|
|
111
|
+
case Reply() as reply:
|
|
112
|
+
return adapter.respond(reply)
|
|
113
|
+
case Paid(payment, headers):
|
|
114
|
+
adapter.attach(request, payment)
|
|
115
|
+
return adapter.finish(await view(*args, **kwargs), headers)
|
|
116
|
+
|
|
117
|
+
return charged
|
|
118
|
+
|
|
119
|
+
def _wrap_sync(self, route: _Route, view: Callable[..., Any]) -> Callable[..., Any]:
|
|
120
|
+
adapters = installed_adapters()
|
|
121
|
+
|
|
122
|
+
@functools.wraps(view)
|
|
123
|
+
def charged(*args: Any, **kwargs: Any) -> Any:
|
|
124
|
+
adapter, request = _find(adapters, args, kwargs, view)
|
|
125
|
+
amount = route.amount(request) if callable(route.amount) else route.amount
|
|
126
|
+
if inspect.isawaitable(amount):
|
|
127
|
+
if inspect.iscoroutine(amount):
|
|
128
|
+
amount.close()
|
|
129
|
+
raise MituConfigError(f"{view.__qualname__}: an async price needs an async view")
|
|
130
|
+
if not (price := route.price(amount)):
|
|
131
|
+
adapter.attach(request, None)
|
|
132
|
+
return view(*args, **kwargs)
|
|
133
|
+
match run(self._api, charge(self._api, price, adapter.incoming(request))):
|
|
134
|
+
case Reply() as reply:
|
|
135
|
+
return adapter.respond(reply)
|
|
136
|
+
case Paid(payment, headers):
|
|
137
|
+
adapter.attach(request, payment)
|
|
138
|
+
return adapter.finish(view(*args, **kwargs), headers)
|
|
139
|
+
|
|
140
|
+
return charged
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _find(
|
|
144
|
+
adapters: list[Adapter], args: Any, kwargs: Any, view: Callable[..., Any]
|
|
145
|
+
) -> tuple[Adapter, Any]:
|
|
146
|
+
for adapter in adapters:
|
|
147
|
+
if (request := adapter.request_of(args, kwargs)) is not None:
|
|
148
|
+
return adapter, request
|
|
149
|
+
raise MituConfigError(
|
|
150
|
+
f"@mitu.charge found no request for {view.__qualname__}: FastAPI routes must take "
|
|
151
|
+
"`request: Request`; Flask and Django views are found on their own"
|
|
152
|
+
)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from decimal import Decimal
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
6
|
+
class Payment:
|
|
7
|
+
"""A payment Mitu has settled for this request, as the view receives it."""
|
|
8
|
+
|
|
9
|
+
payment_id: str
|
|
10
|
+
reference: str
|
|
11
|
+
tx_hash: str | None
|
|
12
|
+
amount_paid: Decimal | None
|
|
13
|
+
currency: str | None
|
|
14
|
+
network: str | None
|
|
15
|
+
payment_method: str | None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class Price:
|
|
20
|
+
amount: Decimal
|
|
21
|
+
currency: str
|
|
22
|
+
description: str | None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class Incoming:
|
|
27
|
+
"""What the flow reads from a request: never its body, cookies or other headers."""
|
|
28
|
+
|
|
29
|
+
method: str
|
|
30
|
+
path: str
|
|
31
|
+
headers: dict[str, str]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class Reply:
|
|
36
|
+
"""A response sent instead of running the view: a 402, Mitu's refusal, or a 503."""
|
|
37
|
+
|
|
38
|
+
status: int
|
|
39
|
+
headers: dict[str, str]
|
|
40
|
+
body: bytes
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True, slots=True)
|
|
44
|
+
class Paid:
|
|
45
|
+
payment: Payment
|
|
46
|
+
headers: dict[str, str]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
Outcome = Reply | Paid
|
|
File without changes
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mitulabs-payments
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Charge AI agents for API routes through Mitu, with standard MPP and x402 payments.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Mitulabs/payments/tree/main/python
|
|
6
|
+
Project-URL: Issues, https://github.com/Mitulabs/payments/issues
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Python: >=3.12
|
|
10
|
+
Requires-Dist: httpx<1,>=0.27
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: django==6.1.3; extra == 'dev'
|
|
13
|
+
Requires-Dist: fastapi==0.165.0; extra == 'dev'
|
|
14
|
+
Requires-Dist: flask==3.1.3; extra == 'dev'
|
|
15
|
+
Requires-Dist: mypy==2.4.1; extra == 'dev'
|
|
16
|
+
Requires-Dist: pip-audit==2.10.1; extra == 'dev'
|
|
17
|
+
Requires-Dist: pytest==9.2.0; extra == 'dev'
|
|
18
|
+
Requires-Dist: ruff==0.17.6; extra == 'dev'
|
|
19
|
+
Provides-Extra: django
|
|
20
|
+
Requires-Dist: django>=5; extra == 'django'
|
|
21
|
+
Provides-Extra: fastapi
|
|
22
|
+
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
|
|
23
|
+
Provides-Extra: flask
|
|
24
|
+
Requires-Dist: flask>=3; extra == 'flask'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# mitulabs-payments
|
|
28
|
+
|
|
29
|
+
Python SDK for charging AI agents per request on HTTP APIs. It places Mitu's payment flow in front of a route:
|
|
30
|
+
agents pay through the [Machine Payments Protocol](https://mpp.dev) (MPP) or [x402](https://x402.org), and Mitu
|
|
31
|
+
issues the payment challenges, settles each payment on chain, and delivers the `payment.completed` webhook.
|
|
32
|
+
|
|
33
|
+
The SDK does not verify payments, hold receiving addresses, or convert currencies. For each request it creates a
|
|
34
|
+
payment through the Mitu API, confirms that the payment an agent presents belongs to the route and price being
|
|
35
|
+
requested, and serves the route once Mitu has settled it. Prices in local currencies are converted at the rate
|
|
36
|
+
Mitu locks when the payment is created.
|
|
37
|
+
|
|
38
|
+
## Requirements
|
|
39
|
+
|
|
40
|
+
- Python 3.12 or later
|
|
41
|
+
- FastAPI, Flask or Django
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install "mitulabs-payments[fastapi]" # or [flask], [django]
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Configuration
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
import os
|
|
53
|
+
|
|
54
|
+
from mitulabs_payments import Mitu
|
|
55
|
+
|
|
56
|
+
mitu = Mitu(os.environ["MITU_API_KEY"])
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
| Option | Default | Description |
|
|
60
|
+
| --- | --- | --- |
|
|
61
|
+
| `api_key` | required | Mitu secret key. `sk_test_` selects the sandbox, `sk_live_` production. |
|
|
62
|
+
| `default_currency` | `"USD"` | Currency code for prices that do not specify one. |
|
|
63
|
+
| `base_url` | Mitu API for the key's environment | API origin override, for testing. Must use HTTPS unless it is `localhost`. |
|
|
64
|
+
| `transport` | — | An `httpx` transport, for testing. |
|
|
65
|
+
|
|
66
|
+
The API key is sent only to the Mitu API, as `x-api-key`. It is never forwarded to an agent payment URL, logged,
|
|
67
|
+
or included in an error message.
|
|
68
|
+
|
|
69
|
+
## Usage
|
|
70
|
+
|
|
71
|
+
Decorate a route with `@mitu.charge`. The decorator sits below the framework's route decorator.
|
|
72
|
+
|
|
73
|
+
### FastAPI
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from fastapi import FastAPI, Request
|
|
77
|
+
|
|
78
|
+
app = FastAPI()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@app.get("/v1/search")
|
|
82
|
+
@mitu.charge(amount="0.01", currency="USD", description="Search")
|
|
83
|
+
async def search(request: Request):
|
|
84
|
+
return run_search(request.query_params, request.state.mitu_payment)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Charged FastAPI routes accept `request: Request`. Both `async def` and `def` routes are supported.
|
|
88
|
+
|
|
89
|
+
### Flask
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from flask import g, request
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@app.get("/v1/search")
|
|
96
|
+
@mitu.charge(amount="0.01", currency="USD")
|
|
97
|
+
def search():
|
|
98
|
+
return run_search(request.args, g.mitu_payment)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Django
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
@mitu.charge(amount="0.01", currency="USD")
|
|
105
|
+
def search(request):
|
|
106
|
+
return JsonResponse(run_search(request.GET, request.mitu_payment))
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Sync and async Django views are supported.
|
|
110
|
+
|
|
111
|
+
### Shutdown
|
|
112
|
+
|
|
113
|
+
Call `await mitu.close()` (or `mitu.close_sync()` in sync applications) at shutdown to release HTTP connections.
|
|
114
|
+
|
|
115
|
+
## Request flow
|
|
116
|
+
|
|
117
|
+
1. **No payment credential.** The SDK creates a payment for the route's price, with a 15-minute expiry and the
|
|
118
|
+
route's method and path in its metadata, and returns Mitu's `402 Payment Required` response, including the MPP
|
|
119
|
+
`WWW-Authenticate` and x402 `PAYMENT-REQUIRED` challenges.
|
|
120
|
+
2. **Payment credential present.** The SDK reads the Mitu payment id from the MPP or x402 credential, retrieves the
|
|
121
|
+
payment, and checks that its amount, currency, method and path match the route. A credential for any other
|
|
122
|
+
route or price receives a new `402`.
|
|
123
|
+
3. **Settlement.** The SDK forwards only the payment headers to the payment's `agent_url`. When Mitu confirms
|
|
124
|
+
settlement, the view runs and the response carries Mitu's receipt header (`Payment-Receipt` or
|
|
125
|
+
`PAYMENT-RESPONSE`). Any other answer from Mitu, such as a replayed or expired payment, is returned to the agent
|
|
126
|
+
unchanged, and the view does not run.
|
|
127
|
+
|
|
128
|
+
Every response that carries payment state includes `Cache-Control: no-store`. If Mitu cannot be reached, or
|
|
129
|
+
answers with a server error, the route responds `503 Service Unavailable` with `Retry-After: 5` and is not served.
|
|
130
|
+
|
|
131
|
+
## Pricing
|
|
132
|
+
|
|
133
|
+
`amount` is a decimal string greater than zero with at most two decimal places, such as `"0.01"` or `"1500"`. It
|
|
134
|
+
can also be a function of the request that returns such a string, or `None` to serve that request without payment.
|
|
135
|
+
On async views the function may be async. The function is evaluated on the initial request and on the paid retry,
|
|
136
|
+
and must return the same price for both. Derive prices from server-side state, never from the request body.
|
|
137
|
+
|
|
138
|
+
## Payments
|
|
139
|
+
|
|
140
|
+
The view receives a `Payment` with:
|
|
141
|
+
|
|
142
|
+
| Field | Description |
|
|
143
|
+
| --- | --- |
|
|
144
|
+
| `payment_id` | The Mitu payment id (`pmt_...`). |
|
|
145
|
+
| `reference` | The payment reference the SDK generated. |
|
|
146
|
+
| `tx_hash` | The settlement transaction hash, where the payment method has one. |
|
|
147
|
+
| `amount_paid` | The amount the agent paid, as a `Decimal`. |
|
|
148
|
+
| `currency` | The currency the agent paid in. |
|
|
149
|
+
| `network` | The network the payment settled on. |
|
|
150
|
+
| `payment_method` | The payment method used. |
|
|
151
|
+
|
|
152
|
+
The payment is final when the view runs. If the view fails afterwards, retry the operation or refund the payment.
|
|
153
|
+
Free requests receive `None`.
|
|
154
|
+
|
|
155
|
+
## Error handling
|
|
156
|
+
|
|
157
|
+
| Error | Raised when |
|
|
158
|
+
| --- | --- |
|
|
159
|
+
| `MituConfigError` | The API key, base URL, currency, price or description is invalid, or a view has no request. |
|
|
160
|
+
| `MituApiError` | The Mitu API refuses a request in a way a retry will not fix, such as an invalid API key. Exposes `status`. |
|
|
161
|
+
|
|
162
|
+
Both derive from `MituError`.
|
|
163
|
+
|
|
164
|
+
## Development
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
|
|
168
|
+
ruff check . && ruff format --check . && mypy --strict src && pytest
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## License
|
|
172
|
+
|
|
173
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
mitulabs_payments/__init__.py,sha256=gw-PyUzUI7E0caThoCk91_nlMYc8MOLFNg7Htwv3Bl8,346
|
|
2
|
+
mitulabs_payments/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
3
|
+
mitulabs_payments/amounts.py,sha256=YrEtzOwKvTJpD3yJBZMY4jeAAPTXMxKjguZlak-pUjI,1469
|
|
4
|
+
mitulabs_payments/api.py,sha256=4Ng5quBfYHfGiDuCQN6wjX4ggn4Mxkr9Z_5DDbmDOuU,4615
|
|
5
|
+
mitulabs_payments/charge.py,sha256=NGL3BqdaDatnkTK_jNLDL1-Vd2QG0vdz-X7AUHwaaho,7997
|
|
6
|
+
mitulabs_payments/credentials.py,sha256=SZZ2MfpbjDbKWa02f8GqDkL3i4OE2OuEJ6gassCGqok,2829
|
|
7
|
+
mitulabs_payments/environment.py,sha256=DHKtxdMoUAM2HRLz7_7LD7kMymegpIQ133C9rv4-ACI,1763
|
|
8
|
+
mitulabs_payments/errors.py,sha256=A5vphtASruHTeNFxldGL5GV8cHy_GZ8iw4vM6u_i1ME,490
|
|
9
|
+
mitulabs_payments/mitu.py,sha256=fAvHg7HgYvX6LwrryRfl9tiiMbvdSF5GuGkAYHx9fKw,6101
|
|
10
|
+
mitulabs_payments/models.py,sha256=BNtfl6pWNGlrK6FsAOa31N85PHiA5LMMgWe-uRt-xqo,1027
|
|
11
|
+
mitulabs_payments/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
mitulabs_payments/frameworks/__init__.py,sha256=TvwWJGCDC0wqZyuqZj7H4ECQSvRP1IybRZySa68s3RI,1343
|
|
13
|
+
mitulabs_payments/frameworks/django.py,sha256=Sn0BKZdROoMePz48C1fLw3oBwjRXhHP959TVQxNEAso,1068
|
|
14
|
+
mitulabs_payments/frameworks/fastapi.py,sha256=7AKkPO47pCmbZOMIBzVjsxK3t_Nifh90KD9UuqTiB_4,1340
|
|
15
|
+
mitulabs_payments/frameworks/flask.py,sha256=2hbiG63FgSfY0iqf3t7U7u-EqUqkwJppjMikKCLy_uY,1031
|
|
16
|
+
mitulabs_payments-0.1.0.dist-info/METADATA,sha256=v9RkkrB6xF7WIloH4CGM-EsCwc7uRidhByXeeRFXDqA,6360
|
|
17
|
+
mitulabs_payments-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
18
|
+
mitulabs_payments-0.1.0.dist-info/licenses/LICENSE,sha256=pDfNDzi0stjzx-JEjUzW_ajDZyyf1LO-Gj1fhAtZx8M,1066
|
|
19
|
+
mitulabs_payments-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mitu Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|