bucli 0.6.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.
- bucli/__init__.py +52 -0
- bucli/_version.py +1 -0
- bucli/client.py +274 -0
- bucli/constants.py +92 -0
- bucli/contrib/__init__.py +1 -0
- bucli/contrib/django/__init__.py +6 -0
- bucli/contrib/django/access.py +99 -0
- bucli/contrib/django/admin.py +19 -0
- bucli/contrib/django/apps.py +8 -0
- bucli/contrib/django/conf.py +140 -0
- bucli/contrib/django/exceptions.py +17 -0
- bucli/contrib/django/management/__init__.py +0 -0
- bucli/contrib/django/management/commands/__init__.py +0 -0
- bucli/contrib/django/management/commands/bucli_flush_usage.py +18 -0
- bucli/contrib/django/management/commands/bucli_sync.py +66 -0
- bucli/contrib/django/metering.py +137 -0
- bucli/contrib/django/migrations/0001_initial.py +102 -0
- bucli/contrib/django/migrations/0002_billingaccount_bucli_updated_at.py +15 -0
- bucli/contrib/django/migrations/0003_pendingusage.py +40 -0
- bucli/contrib/django/migrations/__init__.py +0 -0
- bucli/contrib/django/models.py +122 -0
- bucli/contrib/django/services.py +617 -0
- bucli/contrib/django/signals.py +22 -0
- bucli/contrib/django/urls.py +11 -0
- bucli/contrib/django/views.py +50 -0
- bucli/contrib/django/webhooks.py +236 -0
- bucli/errors.py +193 -0
- bucli/keys.py +18 -0
- bucli/metering.py +331 -0
- bucli/objects.py +168 -0
- bucli/py.typed +0 -0
- bucli/resources.py +1002 -0
- bucli/webhook.py +136 -0
- bucli-0.6.0.dist-info/METADATA +541 -0
- bucli-0.6.0.dist-info/RECORD +37 -0
- bucli-0.6.0.dist-info/WHEEL +4 -0
- bucli-0.6.0.dist-info/licenses/LICENSE +21 -0
bucli/__init__.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Bucli for Python: the ``/v1`` client, webhook verification and (optionally)
|
|
2
|
+
a Django app (``bucli.contrib.django``).
|
|
3
|
+
|
|
4
|
+
import bucli
|
|
5
|
+
|
|
6
|
+
client = bucli.Bucli("sk_test_…")
|
|
7
|
+
customer = client.customers.create(email="ana@tienda.co")
|
|
8
|
+
event = bucli.Webhook.construct_event(request.body, request.headers["Bucli-Signature"], "whsec_…")
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from bucli._version import __version__
|
|
12
|
+
from bucli.client import Bucli
|
|
13
|
+
from bucli.constants import API_VERSION, EVENT_TYPES, RUNNING_STATUSES, SUBSCRIPTION_STATUSES
|
|
14
|
+
from bucli.errors import (
|
|
15
|
+
APIConnectionError,
|
|
16
|
+
APIError,
|
|
17
|
+
AuthenticationError,
|
|
18
|
+
BillingError,
|
|
19
|
+
BucliError,
|
|
20
|
+
CardError,
|
|
21
|
+
IdempotencyError,
|
|
22
|
+
InvalidRequestError,
|
|
23
|
+
PermissionError, # noqa: A004 — Stripe's name, scoped to this package
|
|
24
|
+
RateLimitError,
|
|
25
|
+
SignatureVerificationError,
|
|
26
|
+
)
|
|
27
|
+
from bucli.objects import BucliObject, ListObject
|
|
28
|
+
from bucli.webhook import Webhook, WebhookSignature
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"API_VERSION",
|
|
32
|
+
"EVENT_TYPES",
|
|
33
|
+
"RUNNING_STATUSES",
|
|
34
|
+
"SUBSCRIPTION_STATUSES",
|
|
35
|
+
"APIConnectionError",
|
|
36
|
+
"APIError",
|
|
37
|
+
"AuthenticationError",
|
|
38
|
+
"BillingError",
|
|
39
|
+
"Bucli",
|
|
40
|
+
"BucliError",
|
|
41
|
+
"BucliObject",
|
|
42
|
+
"CardError",
|
|
43
|
+
"IdempotencyError",
|
|
44
|
+
"InvalidRequestError",
|
|
45
|
+
"ListObject",
|
|
46
|
+
"PermissionError",
|
|
47
|
+
"RateLimitError",
|
|
48
|
+
"SignatureVerificationError",
|
|
49
|
+
"Webhook",
|
|
50
|
+
"WebhookSignature",
|
|
51
|
+
"__version__",
|
|
52
|
+
]
|
bucli/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.6.0"
|
bucli/client.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""The HTTP client of the API ``/v1``.
|
|
2
|
+
|
|
3
|
+
* **The key decides the mode**: ``sk_test_…`` (Wompi's sandbox) or ``sk_live_…``.
|
|
4
|
+
A publishable key (``pk_``) is refused: it belongs in a browser.
|
|
5
|
+
* **Idempotency**: every POST carries an ``Idempotency-Key`` (a uuid4 unless
|
|
6
|
+
you pass one) and the SAME key on every retry, so a retried POST never does
|
|
7
|
+
the thing twice.
|
|
8
|
+
* **Retries** with exponential backoff and jitter, only when retrying is safe
|
|
9
|
+
and useful: network errors, ``409 idempotency_key_in_use``, ``429``
|
|
10
|
+
(honouring ``Retry-After``) and ``5xx``. Never on another 4xx.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import datetime
|
|
16
|
+
import json as jsonlib
|
|
17
|
+
import platform
|
|
18
|
+
import random
|
|
19
|
+
import time
|
|
20
|
+
import uuid
|
|
21
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
import requests
|
|
25
|
+
|
|
26
|
+
from bucli import resources
|
|
27
|
+
from bucli._version import __version__
|
|
28
|
+
from bucli.constants import (
|
|
29
|
+
API_PREFIX,
|
|
30
|
+
API_VERSION,
|
|
31
|
+
DEFAULT_BASE_URL,
|
|
32
|
+
IDEMPOTENCY_HEADER,
|
|
33
|
+
PUBLISHABLE_KEY_PREFIXES,
|
|
34
|
+
SECRET_KEY_PREFIXES,
|
|
35
|
+
VERSION_HEADER,
|
|
36
|
+
)
|
|
37
|
+
from bucli.errors import APIConnectionError, APIError, BucliError, error_from_response, parse_retry_after
|
|
38
|
+
from bucli.objects import BucliObject, LastResponse, ListObject, convert
|
|
39
|
+
|
|
40
|
+
#: Network failures after which the request may be retried (the same
|
|
41
|
+
#: ``Idempotency-Key`` makes a retried POST safe).
|
|
42
|
+
RETRYABLE_EXCEPTIONS = (
|
|
43
|
+
requests.exceptions.ConnectionError,
|
|
44
|
+
requests.exceptions.Timeout,
|
|
45
|
+
requests.exceptions.ChunkedEncodingError,
|
|
46
|
+
)
|
|
47
|
+
RETRYABLE_CODES = ("idempotency_key_in_use",)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _check_key(api_key: str) -> str:
|
|
51
|
+
if not isinstance(api_key, str) or not api_key.strip():
|
|
52
|
+
raise ValueError("Falta la llave secreta de Bucli (sk_test_… o sk_live_…).")
|
|
53
|
+
api_key = api_key.strip()
|
|
54
|
+
if api_key.startswith(PUBLISHABLE_KEY_PREFIXES):
|
|
55
|
+
raise ValueError(
|
|
56
|
+
"Esa es una llave publicable (pk_): solo sirve en el navegador para abrir un checkout. "
|
|
57
|
+
"En el servidor usa la llave secreta (sk_test_… o sk_live_…)."
|
|
58
|
+
)
|
|
59
|
+
if not api_key.startswith(SECRET_KEY_PREFIXES):
|
|
60
|
+
raise ValueError("La llave de Bucli debe empezar por sk_test_ o sk_live_.")
|
|
61
|
+
return api_key
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _query_value(value: Any) -> Any:
|
|
65
|
+
if isinstance(value, bool):
|
|
66
|
+
return "true" if value else "false"
|
|
67
|
+
return value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def encode_params(params: Mapping[str, Any] | None) -> list[tuple[str, Any]]:
|
|
71
|
+
"""Query parameters as Bucli reads them: booleans as ``true``/``false``,
|
|
72
|
+
lists repeated (``expand[]=a&expand[]=b``), ``None`` left out."""
|
|
73
|
+
pairs: list[tuple[str, Any]] = []
|
|
74
|
+
for key, value in (params or {}).items():
|
|
75
|
+
if value is None:
|
|
76
|
+
continue
|
|
77
|
+
if isinstance(value, list | tuple | set):
|
|
78
|
+
name = key if key.endswith("[]") else f"{key}[]"
|
|
79
|
+
pairs.extend((name, _query_value(item)) for item in value)
|
|
80
|
+
else:
|
|
81
|
+
pairs.append((key, _query_value(value)))
|
|
82
|
+
return pairs
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Bucli:
|
|
86
|
+
"""``Bucli("sk_test_…")`` — one client per key; thread-safe for requests."""
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
api_key: str,
|
|
91
|
+
*,
|
|
92
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
93
|
+
api_version: str = API_VERSION,
|
|
94
|
+
timeout: float = 30.0,
|
|
95
|
+
max_retries: int = 2,
|
|
96
|
+
max_retry_after: float = 20.0,
|
|
97
|
+
session: requests.Session | None = None,
|
|
98
|
+
) -> None:
|
|
99
|
+
self.api_key = _check_key(api_key)
|
|
100
|
+
self.livemode = self.api_key.startswith("sk_live_")
|
|
101
|
+
self.base_url = base_url.rstrip("/")
|
|
102
|
+
if self.base_url.endswith(API_PREFIX):
|
|
103
|
+
self.base_url = self.base_url[: -len(API_PREFIX)]
|
|
104
|
+
self.api_version = api_version
|
|
105
|
+
self.timeout = timeout
|
|
106
|
+
self.max_retries = max(0, int(max_retries))
|
|
107
|
+
#: A ``Retry-After`` longer than this is not waited for: the error is raised.
|
|
108
|
+
self.max_retry_after = max_retry_after
|
|
109
|
+
self.session = session or requests.Session()
|
|
110
|
+
self._sleep: Callable[[float], None] = time.sleep
|
|
111
|
+
|
|
112
|
+
self.account = resources.Account(self)
|
|
113
|
+
self.customers = resources.Customers(self)
|
|
114
|
+
self.products = resources.Products(self)
|
|
115
|
+
self.prices = resources.Prices(self)
|
|
116
|
+
self.subscriptions = resources.Subscriptions(self)
|
|
117
|
+
self.subscription_items = resources.SubscriptionItems(self)
|
|
118
|
+
self.payment_methods = resources.PaymentMethods(self)
|
|
119
|
+
self.invoices = resources.Invoices(self)
|
|
120
|
+
self.payments = resources.Payments(self)
|
|
121
|
+
self.refunds = resources.Refunds(self)
|
|
122
|
+
self.coupons = resources.Coupons(self)
|
|
123
|
+
self.fixed_term_offers = resources.FixedTermOffers(self)
|
|
124
|
+
self.events = resources.Events(self)
|
|
125
|
+
self.webhook_endpoints = resources.WebhookEndpoints(self)
|
|
126
|
+
self.checkout_sessions = resources.CheckoutSessions(self)
|
|
127
|
+
self.payment_links = resources.PaymentLinks(self)
|
|
128
|
+
self.portal_sessions = resources.PortalSessions(self)
|
|
129
|
+
self.features = resources.Features(self)
|
|
130
|
+
self.meters = resources.Meters(self)
|
|
131
|
+
self.usage = resources.Usage(self)
|
|
132
|
+
self.grant_offers = resources.GrantOffers(self)
|
|
133
|
+
self.grants = resources.Grants(self)
|
|
134
|
+
|
|
135
|
+
def __repr__(self) -> str:
|
|
136
|
+
mode = "live" if self.livemode else "test"
|
|
137
|
+
return f"Bucli(mode={mode!r}, base_url={self.base_url!r}, api_version={self.api_version!r})"
|
|
138
|
+
|
|
139
|
+
# -- requests -------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
def _headers(self, method: str, idempotency_key: str | None, *, has_body: bool) -> dict[str, str]:
|
|
142
|
+
headers = {
|
|
143
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
144
|
+
"Accept": "application/json",
|
|
145
|
+
VERSION_HEADER: self.api_version,
|
|
146
|
+
"User-Agent": f"bucli-python/{__version__} (Python {platform.python_version()})",
|
|
147
|
+
}
|
|
148
|
+
if has_body:
|
|
149
|
+
headers["Content-Type"] = "application/json"
|
|
150
|
+
if idempotency_key:
|
|
151
|
+
headers[IDEMPOTENCY_HEADER] = idempotency_key
|
|
152
|
+
return headers
|
|
153
|
+
|
|
154
|
+
def _delay(self, attempt: int, retry_after: float | None) -> float:
|
|
155
|
+
if retry_after is not None:
|
|
156
|
+
return retry_after
|
|
157
|
+
base = min(0.5 * (2**attempt), 8.0)
|
|
158
|
+
return base * random.uniform(0.5, 1.0)
|
|
159
|
+
|
|
160
|
+
def request(
|
|
161
|
+
self,
|
|
162
|
+
method: str,
|
|
163
|
+
path: str,
|
|
164
|
+
*,
|
|
165
|
+
params: Mapping[str, Any] | None = None,
|
|
166
|
+
body: Mapping[str, Any] | None = None,
|
|
167
|
+
idempotency_key: str | None = None,
|
|
168
|
+
expand: Iterable[str] | None = None,
|
|
169
|
+
timeout: float | None = None,
|
|
170
|
+
max_retries: int | None = None,
|
|
171
|
+
) -> Any:
|
|
172
|
+
"""One call to the API, retried when safe. Answers the converted object.
|
|
173
|
+
|
|
174
|
+
``path`` is relative to ``/v1`` (``"/customers"``). ``timeout`` and
|
|
175
|
+
``max_retries`` override the client's for this call (the metering
|
|
176
|
+
guard asks with 2 s and no retry)."""
|
|
177
|
+
method = method.upper()
|
|
178
|
+
if method == "POST" and not idempotency_key:
|
|
179
|
+
idempotency_key = str(uuid.uuid4())
|
|
180
|
+
if method != "POST":
|
|
181
|
+
idempotency_key = None
|
|
182
|
+
query = dict(params or {})
|
|
183
|
+
if expand:
|
|
184
|
+
query["expand[]"] = list(expand)
|
|
185
|
+
url = f"{self.base_url}{API_PREFIX}{path}"
|
|
186
|
+
data = None
|
|
187
|
+
clean = {key: value for key, value in (body or {}).items() if value is not None}
|
|
188
|
+
if method in ("POST", "PATCH") or (method == "DELETE" and clean):
|
|
189
|
+
data = jsonlib.dumps(clean, separators=(",", ":"), default=_json_default)
|
|
190
|
+
headers = self._headers(method, idempotency_key, has_body=data is not None)
|
|
191
|
+
|
|
192
|
+
retries = self.max_retries if max_retries is None else max(0, int(max_retries))
|
|
193
|
+
wait = self.timeout if timeout is None else timeout
|
|
194
|
+
attempt = 0
|
|
195
|
+
while True:
|
|
196
|
+
try:
|
|
197
|
+
response = self.session.request(
|
|
198
|
+
method,
|
|
199
|
+
url,
|
|
200
|
+
params=encode_params(query),
|
|
201
|
+
data=data,
|
|
202
|
+
headers=headers,
|
|
203
|
+
timeout=wait,
|
|
204
|
+
allow_redirects=False,
|
|
205
|
+
)
|
|
206
|
+
except RETRYABLE_EXCEPTIONS as exc:
|
|
207
|
+
if attempt < retries:
|
|
208
|
+
self._sleep(self._delay(attempt, None))
|
|
209
|
+
attempt += 1
|
|
210
|
+
continue
|
|
211
|
+
raise APIConnectionError(
|
|
212
|
+
f"No se pudo conectar con Bucli ({type(exc).__name__}) tras {attempt + 1} intento(s).",
|
|
213
|
+
) from exc
|
|
214
|
+
except requests.exceptions.RequestException as exc:
|
|
215
|
+
raise APIConnectionError(f"No se pudo hacer la petición a Bucli: {exc}") from exc
|
|
216
|
+
|
|
217
|
+
response_headers = dict(response.headers)
|
|
218
|
+
try:
|
|
219
|
+
payload = response.json() if response.content else None
|
|
220
|
+
except ValueError:
|
|
221
|
+
payload = None
|
|
222
|
+
|
|
223
|
+
if response.status_code < 400:
|
|
224
|
+
if payload is None and response.content:
|
|
225
|
+
raise APIError(
|
|
226
|
+
f"Bucli respondió HTTP {response.status_code} con un cuerpo que no es JSON.",
|
|
227
|
+
http_status=response.status_code,
|
|
228
|
+
headers=response_headers,
|
|
229
|
+
)
|
|
230
|
+
obj = convert(payload, self)
|
|
231
|
+
if isinstance(obj, BucliObject):
|
|
232
|
+
obj.last_response = LastResponse(response.status_code, response_headers, idempotency_key)
|
|
233
|
+
return obj
|
|
234
|
+
|
|
235
|
+
error = error_from_response(response.status_code, payload, response_headers)
|
|
236
|
+
retry_after = parse_retry_after(response_headers.get("Retry-After"))
|
|
237
|
+
if attempt < retries and self._should_retry(response.status_code, error, retry_after):
|
|
238
|
+
self._sleep(self._delay(attempt, retry_after))
|
|
239
|
+
attempt += 1
|
|
240
|
+
continue
|
|
241
|
+
raise error
|
|
242
|
+
|
|
243
|
+
def _should_retry(self, status: int, error: BucliError, retry_after: float | None) -> bool:
|
|
244
|
+
if retry_after is not None and retry_after > self.max_retry_after:
|
|
245
|
+
return False
|
|
246
|
+
if status == 409:
|
|
247
|
+
return error.code in RETRYABLE_CODES
|
|
248
|
+
return status == 429 or status >= 500
|
|
249
|
+
|
|
250
|
+
def _get_list(self, path: str, params: Mapping[str, Any] | None = None) -> ListObject:
|
|
251
|
+
params = dict(params or {})
|
|
252
|
+
expand = params.pop("expand[]", None) or params.pop("expand", None)
|
|
253
|
+
if isinstance(expand, str):
|
|
254
|
+
expand = [expand]
|
|
255
|
+
result = self.request("GET", path, params=params, expand=expand)
|
|
256
|
+
if isinstance(result, ListObject):
|
|
257
|
+
object.__setattr__(result, "_path", path)
|
|
258
|
+
stored = dict(params)
|
|
259
|
+
if expand:
|
|
260
|
+
stored["expand[]"] = list(expand)
|
|
261
|
+
object.__setattr__(result, "_params", stored)
|
|
262
|
+
return result
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _json_default(value: Any) -> Any:
|
|
266
|
+
"""Dates (``billing_cycle_anchor``, ``trial_end``) go as ISO 8601 with
|
|
267
|
+
their time zone; a naive datetime is refused (Bucli would guess wrong)."""
|
|
268
|
+
if isinstance(value, datetime.datetime):
|
|
269
|
+
if value.tzinfo is None or value.utcoffset() is None:
|
|
270
|
+
raise ValueError("Envía las fechas con zona horaria (datetime aware), p. ej. datetime.UTC.")
|
|
271
|
+
return value.isoformat()
|
|
272
|
+
if isinstance(value, datetime.date):
|
|
273
|
+
return value.isoformat()
|
|
274
|
+
raise TypeError(f"{type(value).__name__} no se puede enviar como JSON")
|
bucli/constants.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""What the Bucli API promises and this library relies on.
|
|
2
|
+
|
|
3
|
+
Mirrors Bucli's API constants; ``tests/test_contract.py`` fails when they
|
|
4
|
+
drift apart.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
#: The date-version this library is written against (``Bucli-Version``).
|
|
8
|
+
API_VERSION = "2026-11-01"
|
|
9
|
+
|
|
10
|
+
DEFAULT_BASE_URL = "https://api.bucli.co"
|
|
11
|
+
API_PREFIX = "/v1"
|
|
12
|
+
|
|
13
|
+
#: Headers of the API.
|
|
14
|
+
VERSION_HEADER = "Bucli-Version"
|
|
15
|
+
IDEMPOTENCY_HEADER = "Idempotency-Key"
|
|
16
|
+
REPLAYED_HEADER = "Idempotent-Replayed"
|
|
17
|
+
REQUEST_ID_HEADER = "Request-Id"
|
|
18
|
+
SIGNATURE_HEADER = "Bucli-Signature"
|
|
19
|
+
SIGNATURE_SCHEME = "v1"
|
|
20
|
+
SIGNATURE_TOLERANCE_SECONDS = 300
|
|
21
|
+
|
|
22
|
+
#: Key prefixes. The key decides the mode; a publishable key (``pk_``) lives
|
|
23
|
+
#: in a browser and has no business in a server library.
|
|
24
|
+
SECRET_KEY_PREFIXES = ("sk_test_", "sk_live_")
|
|
25
|
+
PUBLISHABLE_KEY_PREFIXES = ("pk_test_", "pk_live_")
|
|
26
|
+
|
|
27
|
+
#: Subscription statuses (the subscription statuses of Bucli's API).
|
|
28
|
+
INCOMPLETE = "incomplete"
|
|
29
|
+
INCOMPLETE_EXPIRED = "incomplete_expired"
|
|
30
|
+
TRIALING = "trialing"
|
|
31
|
+
ACTIVE = "active"
|
|
32
|
+
PAST_DUE = "past_due"
|
|
33
|
+
CANCELED = "canceled"
|
|
34
|
+
PAUSED = "paused"
|
|
35
|
+
SUBSCRIPTION_STATUSES = (INCOMPLETE, INCOMPLETE_EXPIRED, TRIALING, ACTIVE, PAST_DUE, CANCELED, PAUSED)
|
|
36
|
+
#: A subscription that is still billing (Bucli's ``RUNNING``).
|
|
37
|
+
RUNNING_STATUSES = (TRIALING, ACTIVE, PAST_DUE)
|
|
38
|
+
#: A subscription that will never bill again.
|
|
39
|
+
ENDED_STATUSES = (CANCELED, INCOMPLETE_EXPIRED)
|
|
40
|
+
|
|
41
|
+
#: Every event type Bucli sends (the event types of Bucli's API).
|
|
42
|
+
EVENT_TYPES = (
|
|
43
|
+
"customer.created",
|
|
44
|
+
"customer.updated",
|
|
45
|
+
"customer.deleted",
|
|
46
|
+
"product.created",
|
|
47
|
+
"product.updated",
|
|
48
|
+
"subscription.created",
|
|
49
|
+
"subscription.updated",
|
|
50
|
+
"subscription.canceled",
|
|
51
|
+
"subscription.past_due",
|
|
52
|
+
"subscription.update_failed",
|
|
53
|
+
"subscription.trial_will_end",
|
|
54
|
+
"invoice.created",
|
|
55
|
+
"invoice.paid",
|
|
56
|
+
"invoice.payment_failed",
|
|
57
|
+
"invoice.voided",
|
|
58
|
+
"invoice.updated",
|
|
59
|
+
"notice.sent",
|
|
60
|
+
"charge.refunded",
|
|
61
|
+
"invoice.fiscal_document.issued",
|
|
62
|
+
"invoice.fiscal_document.rejected",
|
|
63
|
+
"payment_method.attached",
|
|
64
|
+
"payment_method.detached",
|
|
65
|
+
"payment_method.suspended",
|
|
66
|
+
"payment_method.expiring",
|
|
67
|
+
"checkout.session.completed",
|
|
68
|
+
"checkout.session.expired",
|
|
69
|
+
"entitlements.updated",
|
|
70
|
+
"meter.threshold_reached",
|
|
71
|
+
"meter.exhausted",
|
|
72
|
+
"grant.created",
|
|
73
|
+
"grant.expired",
|
|
74
|
+
"grant.withdrawn",
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
#: A product's ``storefront.placement``: a card among the main plans, or a
|
|
78
|
+
#: line under them (sold, but not as a card).
|
|
79
|
+
PLACEMENT_MAIN = "main"
|
|
80
|
+
PLACEMENT_SECONDARY = "secondary"
|
|
81
|
+
#: A product's ``kind``, read by Bucli from its rules and prices.
|
|
82
|
+
PRODUCT_KIND_PLAN = "plan"
|
|
83
|
+
PRODUCT_KIND_ADDON = "addon"
|
|
84
|
+
PRODUCT_KIND_ONE_TIME = "one_time"
|
|
85
|
+
PRODUCT_KIND_TRIAL = "trial"
|
|
86
|
+
|
|
87
|
+
#: A customer's access in its entitlements.
|
|
88
|
+
ACCESS_FULL = "full"
|
|
89
|
+
ACCESS_READ_ONLY = "read_only"
|
|
90
|
+
ACCESS_NONE = "none"
|
|
91
|
+
#: ``-1`` in a limit or a balance: unlimited.
|
|
92
|
+
UNLIMITED = -1
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Optional integrations (``pip install bucli[django]``)."""
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""``bucli.contrib.django`` — the Django app ``bucli_billing``.
|
|
2
|
+
|
|
3
|
+
Add ``"bucli.contrib.django"`` to ``INSTALLED_APPS``; see the README for the
|
|
4
|
+
settings, the webhook URL and the services (``bucli.contrib.django.services``)
|
|
5
|
+
and the access rule (``bucli.contrib.django.access``).
|
|
6
|
+
"""
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""The access rule, the same in every SaaS that bills with Bucli.
|
|
2
|
+
|
|
3
|
+
========================================= ======================================
|
|
4
|
+
Estado en Bucli ``access_level``
|
|
5
|
+
========================================= ======================================
|
|
6
|
+
``trialing``, ``active`` ``FULL``
|
|
7
|
+
``past_due`` ``WARNING`` (completo, con aviso de
|
|
8
|
+
«actualiza tu tarjeta»); pasado
|
|
9
|
+
``BUCLI_GRACE`` desde el fin del
|
|
10
|
+
periodo, como un estado vencido
|
|
11
|
+
``paused``, ``canceled``, ``FREE`` o ``READ_ONLY`` según
|
|
12
|
+
``incomplete_expired``, sin suscripción ``BUCLI_LAPSED_ACCESS``
|
|
13
|
+
``incomplete`` ``NONE``: nada nuevo, todavía no pagó
|
|
14
|
+
========================================= ======================================
|
|
15
|
+
|
|
16
|
+
It reads only the local copy (``BillingAccount``): no call to Bucli. The plan's
|
|
17
|
+
limits (users, messages, documents) stay in the SaaS; Bucli only says which
|
|
18
|
+
plan it has and whether it is up to date.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import datetime
|
|
24
|
+
|
|
25
|
+
from django.utils import timezone
|
|
26
|
+
|
|
27
|
+
from bucli.constants import ACTIVE, INCOMPLETE, PAST_DUE, TRIALING
|
|
28
|
+
from bucli.contrib.django import conf
|
|
29
|
+
from bucli.contrib.django.models import BillingAccount
|
|
30
|
+
|
|
31
|
+
FULL = "full"
|
|
32
|
+
WARNING = "warning"
|
|
33
|
+
FREE = "free"
|
|
34
|
+
READ_ONLY = "read_only"
|
|
35
|
+
NONE = "none"
|
|
36
|
+
|
|
37
|
+
LEVELS = (FULL, WARNING, FREE, READ_ONLY, NONE)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def billing_account_of(account) -> BillingAccount | None:
|
|
41
|
+
"""The ``BillingAccount`` of an account of the SaaS (or itself), without creating it."""
|
|
42
|
+
if account is None:
|
|
43
|
+
return None
|
|
44
|
+
if isinstance(account, BillingAccount):
|
|
45
|
+
return account
|
|
46
|
+
try:
|
|
47
|
+
return account.bucli_billing
|
|
48
|
+
except BillingAccount.DoesNotExist:
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _lapsed() -> str:
|
|
53
|
+
return READ_ONLY if conf.lapsed_access() == conf.LAPSED_READ_ONLY else FREE
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def access_level(account, *, now: datetime.datetime | None = None) -> str:
|
|
57
|
+
"""One of ``FULL``, ``WARNING``, ``FREE``, ``READ_ONLY``, ``NONE``."""
|
|
58
|
+
billing = billing_account_of(account)
|
|
59
|
+
status = billing.status if billing else ""
|
|
60
|
+
if status in (TRIALING, ACTIVE):
|
|
61
|
+
return FULL
|
|
62
|
+
if status == PAST_DUE:
|
|
63
|
+
grace = conf.grace()
|
|
64
|
+
end = billing.current_period_end
|
|
65
|
+
if grace is not None and end is not None and (now or timezone.now()) > end + grace:
|
|
66
|
+
return _lapsed()
|
|
67
|
+
return WARNING
|
|
68
|
+
if status == INCOMPLETE:
|
|
69
|
+
return NONE
|
|
70
|
+
return _lapsed()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def has_access(account, *, now: datetime.datetime | None = None) -> bool:
|
|
74
|
+
"""The paid plan applies (``FULL`` or ``WARNING``)."""
|
|
75
|
+
return access_level(account, now=now) in (FULL, WARNING)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def needs_payment_update(account, *, now: datetime.datetime | None = None) -> bool:
|
|
79
|
+
"""Show the «actualiza tu tarjeta» notice (``past_due`` while it still has access)."""
|
|
80
|
+
return access_level(account, now=now) == WARNING
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def is_read_only(account, *, now: datetime.datetime | None = None) -> bool:
|
|
84
|
+
return access_level(account, now=now) == READ_ONLY
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def current_plan(account, *, now: datetime.datetime | None = None) -> str | None:
|
|
88
|
+
"""The plan whose limits apply now: the paid one, ``BUCLI_FREE_PLAN`` when the
|
|
89
|
+
rule falls back to free, or ``None`` (read-only).
|
|
90
|
+
|
|
91
|
+
``incomplete`` grants nothing new: it keeps the fallback (the free plan when
|
|
92
|
+
``BUCLI_LAPSED_ACCESS`` is ``"free"``), never the plan it has not paid yet."""
|
|
93
|
+
level = access_level(account, now=now)
|
|
94
|
+
if level in (FULL, WARNING):
|
|
95
|
+
billing = billing_account_of(account)
|
|
96
|
+
return (billing.plan or None) if billing else None
|
|
97
|
+
if level == FREE or (level == NONE and _lapsed() == FREE):
|
|
98
|
+
return conf.free_plan()
|
|
99
|
+
return None
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from django.contrib import admin
|
|
2
|
+
|
|
3
|
+
from bucli.contrib.django.models import BillingAccount, ProcessedEvent
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@admin.register(BillingAccount)
|
|
7
|
+
class BillingAccountAdmin(admin.ModelAdmin):
|
|
8
|
+
list_display = ("account", "plan", "status", "current_period_end", "cancel_at_period_end", "livemode")
|
|
9
|
+
list_filter = ("status", "plan", "livemode", "cancel_at_period_end")
|
|
10
|
+
search_fields = ("bucli_customer_id", "bucli_subscription_id")
|
|
11
|
+
readonly_fields = [field.name for field in BillingAccount._meta.fields if field.name != "account"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@admin.register(ProcessedEvent)
|
|
15
|
+
class ProcessedEventAdmin(admin.ModelAdmin):
|
|
16
|
+
list_display = ("event_id", "type", "outcome", "sequence", "livemode", "received_at")
|
|
17
|
+
list_filter = ("type", "outcome", "livemode")
|
|
18
|
+
search_fields = ("event_id",)
|
|
19
|
+
readonly_fields = [field.name for field in ProcessedEvent._meta.fields]
|