autlantic-billing 0.1.0__tar.gz

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.
@@ -0,0 +1,18 @@
1
+ node_modules
2
+ dist
3
+ **/.vitepress/cache
4
+ **/.vitepress/dist
5
+ .turbo
6
+ .env
7
+ .env.local
8
+ .env*.local
9
+ *.log
10
+ .DS_Store
11
+ coverage
12
+ *.tsbuildinfo
13
+ .autlantic/
14
+ *.tgz
15
+ sdks/python/.venv/
16
+ sdks/python/.pytest_cache/
17
+ **/__pycache__/
18
+ *.pyc
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.5
2
+ Name: autlantic-billing
3
+ Version: 0.1.0
4
+ Summary: Official Autlantic Billing server SDK for Python (hosted API + webhook verify)
5
+ Project-URL: Homepage, https://autlantic.com
6
+ Project-URL: Documentation, https://docs.autlantic.com/guide/languages
7
+ Project-URL: Repository, https://github.com/Autlantic/payments-sdk
8
+ Author-email: Autlantic Limited <support@autlantic.com>
9
+ License-Expression: MIT
10
+ Keywords: autlantic,base,billing,subscriptions,usdc
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Python SDK (server)
20
+
21
+ Official Autlantic Billing HTTP client for Python backends.
22
+
23
+ ## Install (local)
24
+
25
+ ```bash
26
+ cd sdks/python
27
+ python3 -m venv .venv
28
+ source .venv/bin/activate
29
+ pip install -e ".[dev]" # or: pip install -e . pytest
30
+ pytest
31
+ ```
32
+
33
+ ## Usage
34
+
35
+ ```python
36
+ from autlantic_billing import AutlanticBilling, verify_billing_webhook
37
+
38
+ billing = AutlanticBilling.from_env()
39
+
40
+ result = billing.create_payment_link({
41
+ "amountUsdc": 42,
42
+ "merchantRefPrefix": "invoice",
43
+ "successUrl": "myapp://billing/success",
44
+ "cancelUrl": "myapp://billing/cancel",
45
+ })
46
+ url = result.get("url")
47
+ ```
48
+
49
+ Webhook handler:
50
+
51
+ ```python
52
+ from autlantic_billing import verify_billing_webhook, parse_billing_webhook_event
53
+
54
+ def handle(raw_body: str, signature: str | None, secret: str):
55
+ if not verify_billing_webhook(secret, raw_body, signature):
56
+ raise ValueError("bad signature")
57
+ event = parse_billing_webhook_event(raw_body)
58
+ # unlock access on invoice.paid / payment.paid / subscription.activated
59
+ ```
60
+
61
+ ## Notes
62
+
63
+ - Hosted API only. Pins `Autlantic-Version: 2026-01-01`.
64
+ - Not on PyPI until the first publish (`autlantic-billing`).
65
+ - Secrets stay on the server. Mobile apps use Checkout SDKs, not this package.
@@ -0,0 +1,47 @@
1
+ # Python SDK (server)
2
+
3
+ Official Autlantic Billing HTTP client for Python backends.
4
+
5
+ ## Install (local)
6
+
7
+ ```bash
8
+ cd sdks/python
9
+ python3 -m venv .venv
10
+ source .venv/bin/activate
11
+ pip install -e ".[dev]" # or: pip install -e . pytest
12
+ pytest
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ from autlantic_billing import AutlanticBilling, verify_billing_webhook
19
+
20
+ billing = AutlanticBilling.from_env()
21
+
22
+ result = billing.create_payment_link({
23
+ "amountUsdc": 42,
24
+ "merchantRefPrefix": "invoice",
25
+ "successUrl": "myapp://billing/success",
26
+ "cancelUrl": "myapp://billing/cancel",
27
+ })
28
+ url = result.get("url")
29
+ ```
30
+
31
+ Webhook handler:
32
+
33
+ ```python
34
+ from autlantic_billing import verify_billing_webhook, parse_billing_webhook_event
35
+
36
+ def handle(raw_body: str, signature: str | None, secret: str):
37
+ if not verify_billing_webhook(secret, raw_body, signature):
38
+ raise ValueError("bad signature")
39
+ event = parse_billing_webhook_event(raw_body)
40
+ # unlock access on invoice.paid / payment.paid / subscription.activated
41
+ ```
42
+
43
+ ## Notes
44
+
45
+ - Hosted API only. Pins `Autlantic-Version: 2026-01-01`.
46
+ - Not on PyPI until the first publish (`autlantic-billing`).
47
+ - Secrets stay on the server. Mobile apps use Checkout SDKs, not this package.
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "autlantic-billing"
7
+ version = "0.1.0"
8
+ description = "Official Autlantic Billing server SDK for Python (hosted API + webhook verify)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "Autlantic Limited", email = "support@autlantic.com" }]
13
+ keywords = ["autlantic", "billing", "usdc", "base", "subscriptions"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Typing :: Typed",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.urls]
24
+ Homepage = "https://autlantic.com"
25
+ Documentation = "https://docs.autlantic.com/guide/languages"
26
+ Repository = "https://github.com/Autlantic/payments-sdk"
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["src/autlantic_billing"]
30
+
31
+ [tool.pytest.ini_options]
32
+ testpaths = ["tests"]
@@ -0,0 +1,25 @@
1
+ """Official Autlantic Billing server client (hosted API)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .client import AutlanticBilling, AutlanticBillingError
6
+ from .version import AUTLANTIC_API_VERSION, SDK_VERSION
7
+ from .webhook import (
8
+ BILLING_WEBHOOK_SIGNATURE_HEADER,
9
+ BILLING_WEBHOOK_TOLERANCE_SEC,
10
+ parse_billing_webhook_event,
11
+ verify_billing_webhook,
12
+ verify_billing_webhook_detailed,
13
+ )
14
+
15
+ __all__ = [
16
+ "AUTLANTIC_API_VERSION",
17
+ "SDK_VERSION",
18
+ "AutlanticBilling",
19
+ "AutlanticBillingError",
20
+ "BILLING_WEBHOOK_SIGNATURE_HEADER",
21
+ "BILLING_WEBHOOK_TOLERANCE_SEC",
22
+ "parse_billing_webhook_event",
23
+ "verify_billing_webhook",
24
+ "verify_billing_webhook_detailed",
25
+ ]
@@ -0,0 +1,213 @@
1
+ """Hosted Autlantic Billing HTTP client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import secrets
8
+ import time
9
+ import urllib.error
10
+ import urllib.parse
11
+ import urllib.request
12
+ from typing import Any
13
+
14
+ from .version import AUTLANTIC_API_VERSION, SDK_VERSION, USER_AGENT
15
+
16
+ _RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
17
+ _MAX_ATTEMPTS = 3
18
+
19
+
20
+ class AutlanticBillingError(Exception):
21
+ def __init__(
22
+ self,
23
+ message: str,
24
+ *,
25
+ code: str | None = None,
26
+ status_code: int | None = None,
27
+ request_id: str | None = None,
28
+ body: Any = None,
29
+ ) -> None:
30
+ super().__init__(message)
31
+ self.message = message
32
+ self.code = code
33
+ self.status_code = status_code
34
+ self.request_id = request_id
35
+ self.body = body
36
+
37
+
38
+ def billing_mode_from_api_key(api_key: str | None) -> str:
39
+ key = (api_key or "").strip()
40
+ if "_live_" in key:
41
+ return "live"
42
+ return "test"
43
+
44
+
45
+ class AutlanticBilling:
46
+ """Merchant server client for `https://billing.autlantic.com` (hosted only)."""
47
+
48
+ def __init__(
49
+ self,
50
+ *,
51
+ api_key: str,
52
+ api_base_url: str = "https://billing.autlantic.com",
53
+ merchant_id: str | None = None,
54
+ timeout_sec: float = 30.0,
55
+ max_retries: int = _MAX_ATTEMPTS - 1,
56
+ ) -> None:
57
+ if not api_key.strip():
58
+ raise AutlanticBillingError("api_key is required", code="configuration")
59
+ self.api_key = api_key.strip()
60
+ self.api_base_url = api_base_url.rstrip("/")
61
+ self.merchant_id = merchant_id
62
+ self.timeout_sec = timeout_sec
63
+ self.max_retries = max(0, max_retries)
64
+ self.mode = billing_mode_from_api_key(self.api_key)
65
+
66
+ @classmethod
67
+ def from_env(cls, env: dict[str, str] | None = None) -> AutlanticBilling:
68
+ e = env if env is not None else os.environ
69
+ api_key = (e.get("AUTLANTIC_BILLING_API_KEY") or "").strip()
70
+ if not api_key:
71
+ raise AutlanticBillingError(
72
+ "AUTLANTIC_BILLING_API_KEY is required",
73
+ code="configuration",
74
+ )
75
+ return cls(
76
+ api_key=api_key,
77
+ api_base_url=(e.get("AUTLANTIC_BILLING_API_URL") or "https://billing.autlantic.com").strip(),
78
+ merchant_id=(e.get("AUTLANTIC_BILLING_MERCHANT_ID") or None),
79
+ )
80
+
81
+ def list_products(self) -> dict[str, Any]:
82
+ return self._request("GET", "/v1/products")
83
+
84
+ def create_subscription(self, body: dict[str, Any]) -> dict[str, Any]:
85
+ return self._request("POST", "/v1/subscriptions", body=body)
86
+
87
+ def get_subscription(self, subscription_id: str) -> dict[str, Any]:
88
+ return self._request("GET", f"/v1/subscriptions/{urllib.parse.quote(subscription_id)}")
89
+
90
+ def activate_subscription(self, subscription_id: str) -> dict[str, Any]:
91
+ return self._request(
92
+ "POST",
93
+ f"/v1/subscriptions/{urllib.parse.quote(subscription_id)}/activate",
94
+ body={},
95
+ )
96
+
97
+ def cancel_subscription(
98
+ self, subscription_id: str, body: dict[str, Any] | None = None
99
+ ) -> dict[str, Any]:
100
+ return self._request(
101
+ "POST",
102
+ f"/v1/subscriptions/{urllib.parse.quote(subscription_id)}/cancel",
103
+ body=body or {},
104
+ )
105
+
106
+ def create_payment(self, body: dict[str, Any]) -> dict[str, Any]:
107
+ return self._request("POST", "/v1/payments", body=body)
108
+
109
+ def get_payment(self, payment_id: str) -> dict[str, Any]:
110
+ return self._request("GET", f"/v1/payments/{urllib.parse.quote(payment_id)}")
111
+
112
+ def create_payment_link(self, body: dict[str, Any]) -> dict[str, Any]:
113
+ return self._request("POST", "/v1/payment-links", body=body)
114
+
115
+ def list_payment_links(self) -> dict[str, Any]:
116
+ return self._request("GET", "/v1/payment-links")
117
+
118
+ def get_payment_link(self, link_id: str) -> dict[str, Any]:
119
+ return self._request("GET", f"/v1/payment-links/{urllib.parse.quote(link_id)}")
120
+
121
+ def disable_payment_link(self, link_id: str) -> dict[str, Any]:
122
+ return self._request(
123
+ "POST",
124
+ f"/v1/payment-links/{urllib.parse.quote(link_id)}/disable",
125
+ body={},
126
+ )
127
+
128
+ def list_invoices(self, *, subscription_id: str | None = None) -> dict[str, Any]:
129
+ path = "/v1/invoices"
130
+ if subscription_id:
131
+ path += f"?subscriptionId={urllib.parse.quote(subscription_id)}"
132
+ return self._request("GET", path)
133
+
134
+ def _request(
135
+ self,
136
+ method: str,
137
+ path: str,
138
+ *,
139
+ body: dict[str, Any] | None = None,
140
+ idempotent: bool = True,
141
+ ) -> dict[str, Any]:
142
+ request_id = f"req_{int(time.time() * 1000):x}_{secrets.token_hex(4)}"
143
+ url = f"{self.api_base_url}{path}"
144
+ encoded = None if body is None else json.dumps(body).encode("utf-8")
145
+ idem_key = None
146
+ if method == "POST" and idempotent:
147
+ idem_key = f"sdk_{int(time.time() * 1000)}_{secrets.token_hex(4)}"
148
+
149
+ attempts = self.max_retries + 1
150
+ last_error: Exception | None = None
151
+ for attempt in range(attempts):
152
+ headers = {
153
+ "Accept": "application/json",
154
+ "User-Agent": USER_AGENT,
155
+ "X-Autlantic-Api-Key": self.api_key,
156
+ "X-Autlantic-Sdk-Version": SDK_VERSION,
157
+ "X-Autlantic-Client-Request-Id": request_id,
158
+ "Autlantic-Version": AUTLANTIC_API_VERSION,
159
+ }
160
+ if body is not None:
161
+ headers["Content-Type"] = "application/json"
162
+ if idem_key:
163
+ headers["Idempotency-Key"] = idem_key
164
+
165
+ req = urllib.request.Request(url, data=encoded, headers=headers, method=method)
166
+ try:
167
+ with urllib.request.urlopen(req, timeout=self.timeout_sec) as res:
168
+ raw = res.read().decode("utf-8")
169
+ payload = json.loads(raw) if raw else {}
170
+ if not isinstance(payload, dict):
171
+ raise AutlanticBillingError(
172
+ "Unexpected response shape",
173
+ status_code=getattr(res, "status", None),
174
+ request_id=request_id,
175
+ body=payload,
176
+ )
177
+ return payload
178
+ except urllib.error.HTTPError as exc:
179
+ raw = exc.read().decode("utf-8") if exc.fp else ""
180
+ try:
181
+ err_body = json.loads(raw) if raw else {}
182
+ except json.JSONDecodeError:
183
+ err_body = {"error": raw or exc.reason}
184
+ message = (
185
+ err_body.get("error") if isinstance(err_body, dict) else None
186
+ ) or str(exc.reason)
187
+ code = err_body.get("code") if isinstance(err_body, dict) else None
188
+ err = AutlanticBillingError(
189
+ str(message),
190
+ code=code if isinstance(code, str) else None,
191
+ status_code=exc.code,
192
+ request_id=request_id,
193
+ body=err_body,
194
+ )
195
+ last_error = err
196
+ if exc.code in _RETRYABLE_STATUS and attempt + 1 < attempts:
197
+ time.sleep(0.25 * (2**attempt))
198
+ continue
199
+ raise err from exc
200
+ except urllib.error.URLError as exc:
201
+ err = AutlanticBillingError(
202
+ f"Network error: {exc.reason}",
203
+ code="network_error",
204
+ request_id=request_id,
205
+ )
206
+ last_error = err
207
+ if attempt + 1 < attempts:
208
+ time.sleep(0.25 * (2**attempt))
209
+ continue
210
+ raise err from exc
211
+
212
+ assert last_error is not None
213
+ raise last_error
@@ -0,0 +1,5 @@
1
+ """Version pins for the Python Billing SDK."""
2
+
3
+ SDK_VERSION = "0.1.0"
4
+ AUTLANTIC_API_VERSION = "2026-01-01"
5
+ USER_AGENT = f"autlantic-python/{SDK_VERSION}"
@@ -0,0 +1,108 @@
1
+ """Webhook signature helpers matching @autlantic/payments-recurring."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import time
9
+ from typing import Any
10
+
11
+ BILLING_WEBHOOK_SIGNATURE_HEADER = "x-autlantic-signature"
12
+ BILLING_WEBHOOK_TOLERANCE_SEC = 300
13
+
14
+
15
+ def _hmac_hex(secret: str, payload: str) -> str:
16
+ return hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
17
+
18
+
19
+ def _safe_equal_hex(a: str, b: str) -> bool:
20
+ try:
21
+ return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))
22
+ except Exception:
23
+ return False
24
+
25
+
26
+ def sign_billing_webhook_body(
27
+ secret: str,
28
+ raw_body: str,
29
+ timestamp_sec: int | None = None,
30
+ ) -> str:
31
+ """Emit Stripe-style `t=<unix>,v1=<hmac>`."""
32
+ t = str(int(time.time() if timestamp_sec is None else timestamp_sec))
33
+ v1 = _hmac_hex(secret, f"{t}.{raw_body}")
34
+ return f"t={t},v1={v1}"
35
+
36
+
37
+ def verify_billing_webhook_detailed(
38
+ secret: str,
39
+ raw_body: str,
40
+ signature_header: str | None,
41
+ *,
42
+ tolerance_sec: int = BILLING_WEBHOOK_TOLERANCE_SEC,
43
+ now_sec: int | None = None,
44
+ ) -> dict[str, Any]:
45
+ if not secret.strip():
46
+ return {"ok": False, "reason": "empty_secret"}
47
+ if not signature_header or not signature_header.strip():
48
+ return {"ok": False, "reason": "missing_header"}
49
+
50
+ header = signature_header.strip()
51
+ now = int(time.time() if now_sec is None else now_sec)
52
+
53
+ if "t=" in header and "v1=" in header:
54
+ parts: dict[str, str] = {}
55
+ for piece in header.split(","):
56
+ if "=" not in piece:
57
+ continue
58
+ k, v = piece.split("=", 1)
59
+ parts[k] = v
60
+ try:
61
+ t = int(parts.get("t", ""))
62
+ except ValueError:
63
+ return {"ok": False, "reason": "timestamp_invalid"}
64
+ v1 = (parts.get("v1") or "").strip()
65
+ if not v1:
66
+ return {"ok": False, "reason": "timestamp_invalid"}
67
+ if abs(now - t) > tolerance_sec:
68
+ return {"ok": False, "reason": "timestamp_expired"}
69
+ expected = _hmac_hex(secret, f"{t}.{raw_body}")
70
+ if not _safe_equal_hex(expected, v1):
71
+ return {"ok": False, "reason": "invalid_signature"}
72
+ return {"ok": True}
73
+
74
+ expected = _hmac_hex(secret, raw_body)
75
+ if len(expected) != len(header):
76
+ return {"ok": False, "reason": "length_mismatch"}
77
+ if not _safe_equal_hex(expected, header):
78
+ return {"ok": False, "reason": "invalid_signature"}
79
+ return {"ok": True}
80
+
81
+
82
+ def verify_billing_webhook(
83
+ secret: str,
84
+ raw_body: str,
85
+ signature_header: str | None,
86
+ *,
87
+ tolerance_sec: int = BILLING_WEBHOOK_TOLERANCE_SEC,
88
+ now_sec: int | None = None,
89
+ ) -> bool:
90
+ return verify_billing_webhook_detailed(
91
+ secret,
92
+ raw_body,
93
+ signature_header,
94
+ tolerance_sec=tolerance_sec,
95
+ now_sec=now_sec,
96
+ )["ok"] is True
97
+
98
+
99
+ def parse_billing_webhook_event(raw_body: str) -> dict[str, Any] | None:
100
+ try:
101
+ data = json.loads(raw_body)
102
+ except json.JSONDecodeError:
103
+ return None
104
+ if not isinstance(data, dict):
105
+ return None
106
+ if "type" not in data or "data" not in data:
107
+ return None
108
+ return data
@@ -0,0 +1,19 @@
1
+ from autlantic_billing import AutlanticBilling, AutlanticBillingError, AUTLANTIC_API_VERSION
2
+ from autlantic_billing.client import billing_mode_from_api_key
3
+
4
+
5
+ def test_api_version_pin():
6
+ assert AUTLANTIC_API_VERSION == "2026-01-01"
7
+
8
+
9
+ def test_mode_from_key():
10
+ assert billing_mode_from_api_key("abk_test_x") == "test"
11
+ assert billing_mode_from_api_key("abk_live_x") == "live"
12
+
13
+
14
+ def test_from_env_requires_key():
15
+ try:
16
+ AutlanticBilling.from_env({})
17
+ assert False, "expected error"
18
+ except AutlanticBillingError as exc:
19
+ assert exc.code == "configuration"
@@ -0,0 +1,37 @@
1
+ from autlantic_billing.webhook import (
2
+ parse_billing_webhook_event,
3
+ sign_billing_webhook_body,
4
+ verify_billing_webhook,
5
+ verify_billing_webhook_detailed,
6
+ )
7
+
8
+
9
+ def test_sign_and_verify_timestamped():
10
+ body = '{"type":"invoice.paid","data":{}}'
11
+ sig = sign_billing_webhook_body("whsec_test", body, timestamp_sec=1_700_000_000)
12
+ assert verify_billing_webhook(
13
+ "whsec_test",
14
+ body,
15
+ sig,
16
+ now_sec=1_700_000_000,
17
+ )
18
+
19
+
20
+ def test_rejects_expired():
21
+ body = '{"type":"invoice.paid","data":{}}'
22
+ sig = sign_billing_webhook_body("whsec_test", body, timestamp_sec=1_700_000_000)
23
+ result = verify_billing_webhook_detailed(
24
+ "whsec_test",
25
+ body,
26
+ sig,
27
+ now_sec=1_700_000_000 + 301,
28
+ )
29
+ assert result["ok"] is False
30
+ assert result["reason"] == "timestamp_expired"
31
+
32
+
33
+ def test_parse_event():
34
+ raw = '{"type":"invoice.paid","id":"evt_1","data":{"id":"in_1"}}'
35
+ event = parse_billing_webhook_event(raw)
36
+ assert event is not None
37
+ assert event["type"] == "invoice.paid"