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/webhook.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Verifying Bucli's webhooks.
|
|
2
|
+
|
|
3
|
+
Every delivery carries ``Bucli-Signature: t=<timestamp>,v1=<hex>`` where
|
|
4
|
+
``v1 = HMAC-SHA256(whsec_…, "<t>.<raw body>")``. For 24 hours after the
|
|
5
|
+
endpoint's secret is rolled the header carries TWO ``v1`` (the previous
|
|
6
|
+
secret's and, last, the new one's): any match is enough.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import hmac
|
|
13
|
+
import json
|
|
14
|
+
import time
|
|
15
|
+
from collections.abc import Iterable
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from bucli.constants import SIGNATURE_SCHEME, SIGNATURE_TOLERANCE_SECONDS
|
|
19
|
+
from bucli.errors import SignatureVerificationError
|
|
20
|
+
from bucli.objects import BucliObject, convert
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _as_bytes(payload: bytes | bytearray | str) -> bytes:
|
|
24
|
+
if isinstance(payload, bytes | bytearray):
|
|
25
|
+
return bytes(payload)
|
|
26
|
+
if isinstance(payload, str):
|
|
27
|
+
return payload.encode("utf-8")
|
|
28
|
+
raise TypeError("El cuerpo del webhook debe ser bytes (request.body), sin parsear.")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _secrets(secret: str | Iterable[str]) -> list[str]:
|
|
32
|
+
values = [secret] if isinstance(secret, str) else list(secret or [])
|
|
33
|
+
values = [value for value in values if isinstance(value, str) and value]
|
|
34
|
+
if not values:
|
|
35
|
+
raise ValueError("Falta el secreto del endpoint de webhooks (whsec_…).")
|
|
36
|
+
return values
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def compute_signature(payload: bytes | str, secret: str, timestamp: int | str) -> str:
|
|
40
|
+
"""``HMAC-SHA256(secret, "<timestamp>.<payload>")`` in hex."""
|
|
41
|
+
message = f"{timestamp}.".encode() + _as_bytes(payload)
|
|
42
|
+
return hmac.new(secret.encode("utf-8"), message, hashlib.sha256).hexdigest()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class WebhookSignature:
|
|
46
|
+
@staticmethod
|
|
47
|
+
def parse_header(header: str) -> tuple[int, list[str]]:
|
|
48
|
+
timestamp: int | None = None
|
|
49
|
+
signatures: list[str] = []
|
|
50
|
+
for item in (header or "").split(","):
|
|
51
|
+
key, sep, value = item.strip().partition("=")
|
|
52
|
+
if not sep:
|
|
53
|
+
continue
|
|
54
|
+
if key == "t":
|
|
55
|
+
try:
|
|
56
|
+
timestamp = int(value)
|
|
57
|
+
except ValueError:
|
|
58
|
+
raise SignatureVerificationError(
|
|
59
|
+
"El timestamp de Bucli-Signature no es un número.", header
|
|
60
|
+
) from None
|
|
61
|
+
elif key == SIGNATURE_SCHEME and value:
|
|
62
|
+
signatures.append(value)
|
|
63
|
+
if timestamp is None:
|
|
64
|
+
raise SignatureVerificationError("Bucli-Signature no trae el timestamp (t=…).", header)
|
|
65
|
+
if not signatures:
|
|
66
|
+
raise SignatureVerificationError("Bucli-Signature no trae ninguna firma v1.", header)
|
|
67
|
+
return timestamp, signatures
|
|
68
|
+
|
|
69
|
+
@classmethod
|
|
70
|
+
def verify_header(
|
|
71
|
+
cls,
|
|
72
|
+
payload: bytes | str,
|
|
73
|
+
header: str,
|
|
74
|
+
secret: str | Iterable[str],
|
|
75
|
+
tolerance: int | None = SIGNATURE_TOLERANCE_SECONDS,
|
|
76
|
+
*,
|
|
77
|
+
now: float | None = None,
|
|
78
|
+
) -> bool:
|
|
79
|
+
"""``True`` or ``SignatureVerificationError``. ``secret`` may be a list
|
|
80
|
+
(your own rotation of ``BUCLI_WEBHOOK_SECRET``)."""
|
|
81
|
+
if not header:
|
|
82
|
+
raise SignatureVerificationError("Falta la cabecera Bucli-Signature.", header)
|
|
83
|
+
timestamp, signatures = cls.parse_header(header)
|
|
84
|
+
if tolerance is not None:
|
|
85
|
+
age = (time.time() if now is None else now) - timestamp
|
|
86
|
+
if age > tolerance:
|
|
87
|
+
raise SignatureVerificationError("La firma es demasiado vieja: posible repetición.", header)
|
|
88
|
+
if age < -tolerance:
|
|
89
|
+
raise SignatureVerificationError("La firma viene del futuro: revisa el reloj.", header)
|
|
90
|
+
body = _as_bytes(payload)
|
|
91
|
+
for value in _secrets(secret):
|
|
92
|
+
expected = compute_signature(body, value, timestamp)
|
|
93
|
+
# Constant-time per pair; any v1 may match (two during a rotation).
|
|
94
|
+
if any(hmac.compare_digest(expected, candidate) for candidate in signatures):
|
|
95
|
+
return True
|
|
96
|
+
raise SignatureVerificationError("Ninguna firma v1 coincide con el cuerpo y el secreto.", header)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class Webhook:
|
|
100
|
+
@staticmethod
|
|
101
|
+
def construct_event(
|
|
102
|
+
payload: bytes | str,
|
|
103
|
+
sig_header: str,
|
|
104
|
+
secret: str | Iterable[str],
|
|
105
|
+
tolerance: int | None = SIGNATURE_TOLERANCE_SECONDS,
|
|
106
|
+
*,
|
|
107
|
+
now: float | None = None,
|
|
108
|
+
) -> BucliObject:
|
|
109
|
+
"""The verified ``event`` of a delivery.
|
|
110
|
+
|
|
111
|
+
``payload`` is the RAW body (Django: ``request.body``), never a parsed and
|
|
112
|
+
re-serialized one. Raises ``SignatureVerificationError`` when the header is
|
|
113
|
+
missing or malformed, no ``v1`` matches, ``t`` is older or newer than
|
|
114
|
+
``tolerance`` seconds, or the body is not a JSON object."""
|
|
115
|
+
body = _as_bytes(payload)
|
|
116
|
+
WebhookSignature.verify_header(body, sig_header, secret, tolerance, now=now)
|
|
117
|
+
try:
|
|
118
|
+
data: Any = json.loads(body.decode("utf-8"))
|
|
119
|
+
except (UnicodeDecodeError, ValueError):
|
|
120
|
+
raise SignatureVerificationError("El cuerpo del webhook no es JSON válido.", sig_header) from None
|
|
121
|
+
if not isinstance(data, dict):
|
|
122
|
+
raise SignatureVerificationError("El cuerpo del webhook no es un objeto JSON.", sig_header)
|
|
123
|
+
return convert(data)
|
|
124
|
+
|
|
125
|
+
@staticmethod
|
|
126
|
+
def generate_test_header(
|
|
127
|
+
payload: bytes | str,
|
|
128
|
+
secret: str | Iterable[str],
|
|
129
|
+
*,
|
|
130
|
+
timestamp: int | None = None,
|
|
131
|
+
) -> str:
|
|
132
|
+
"""A valid ``Bucli-Signature`` for your tests. A list of secrets yields
|
|
133
|
+
one ``v1`` per secret, as a rotation does."""
|
|
134
|
+
ts = int(time.time()) if timestamp is None else int(timestamp)
|
|
135
|
+
signatures = [compute_signature(payload, value, ts) for value in _secrets(secret)]
|
|
136
|
+
return ",".join([f"t={ts}", *(f"{SIGNATURE_SCHEME}={item}" for item in signatures)])
|
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: bucli
|
|
3
|
+
Version: 0.6.0
|
|
4
|
+
Summary: Librería oficial de Bucli para Python: cliente de la API /v1, verificación de webhooks e integración con Django.
|
|
5
|
+
Project-URL: Homepage, https://bucli.co
|
|
6
|
+
Project-URL: Documentation, https://github.com/bithaus-sas/bucli-python#readme
|
|
7
|
+
Project-URL: Source, https://github.com/bithaus-sas/bucli-python
|
|
8
|
+
Project-URL: Changelog, https://github.com/bithaus-sas/bucli-python/blob/main/CHANGELOG.md
|
|
9
|
+
Author: Bithaus SAS
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: billing,bucli,django,subscriptions,wompi
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Framework :: Django
|
|
15
|
+
Classifier: Framework :: Django :: 4.2
|
|
16
|
+
Classifier: Framework :: Django :: 5.2
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.11
|
|
26
|
+
Requires-Dist: requests<3,>=2.31
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
29
|
+
Requires-Dist: django>=4.2; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
31
|
+
Requires-Dist: responses>=0.25; extra == 'dev'
|
|
32
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
33
|
+
Provides-Extra: django
|
|
34
|
+
Requires-Dist: django>=4.2; extra == 'django'
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# bucli-python
|
|
38
|
+
|
|
39
|
+
La librería oficial de **Bucli** para Python. Sirve para que un SaaS cobre sus suscripciones con Bucli en vez de hablar directo con Wompi, y trae una integración completa para proyectos Django.
|
|
40
|
+
|
|
41
|
+
Trae tres piezas:
|
|
42
|
+
|
|
43
|
+
- **`bucli.Bucli`**: el cliente HTTP de la API pública `/v1`. Sigue las convenciones de Stripe: llaves `sk_`, `Idempotency-Key`, `Bucli-Version`, paginación por cursor, `expand[]` y errores tipados.
|
|
44
|
+
- **`bucli.Webhook`**: la verificación de la firma `Bucli-Signature` de los webhooks.
|
|
45
|
+
- **`bucli.contrib.django`** (opcional): la app `bucli_billing`. Trae los modelos, la vista del webhook, los servicios (suscribirse, portal, cambiar de plan, cancelar, sincronizar), la regla de acceso y el comando `bucli_sync`.
|
|
46
|
+
|
|
47
|
+
La referencia de la API está en OpenAPI 3.1 en `https://api.bucli.co/v1/openapi.json`.
|
|
48
|
+
|
|
49
|
+
- Python ≥ 3.11.
|
|
50
|
+
- La única dependencia del núcleo es `requests`. La parte de Django pide Django ≥ 4.2.
|
|
51
|
+
- Versión de la API: `2026-11-01`.
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## Instalación
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
pip install "bucli[django]"
|
|
59
|
+
|
|
60
|
+
# En el requirements de tu proyecto, fija la versión:
|
|
61
|
+
bucli[django]==0.6.0
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Sin Django basta con `pip install bucli`, sin el extra.
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## El cliente
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
import bucli
|
|
72
|
+
|
|
73
|
+
client = bucli.Bucli("sk_test_…") # la llave decide el modo: sk_test_ → sandbox de Wompi, sk_live_ → producción
|
|
74
|
+
client.livemode # False
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
| Parámetro | Por defecto | Para qué |
|
|
78
|
+
|---|---|---|
|
|
79
|
+
| `api_key` | — | Una llave **secreta** (`sk_test_…`/`sk_live_…`). Una `pk_` se rechaza: solo sirve en el navegador. |
|
|
80
|
+
| `base_url` | `https://api.bucli.co` | El host. El prefijo `/v1` lo pone la librería. |
|
|
81
|
+
| `api_version` | `2026-11-01` | Se envía en `Bucli-Version` en cada petición. |
|
|
82
|
+
| `timeout` | `30` | Segundos por intento. |
|
|
83
|
+
| `max_retries` | `2` | Reintentos con backoff exponencial y jitter. |
|
|
84
|
+
| `max_retry_after` | `20` | Un `Retry-After` más largo no se espera: se lanza el error. |
|
|
85
|
+
|
|
86
|
+
### Recursos
|
|
87
|
+
|
|
88
|
+
Cada método lleva los nombres de parámetro de la API como argumentos con nombre. Los `None` no se envían.
|
|
89
|
+
|
|
90
|
+
| Recurso | Métodos |
|
|
91
|
+
|---|---|
|
|
92
|
+
| `client.account` | `retrieve()` |
|
|
93
|
+
| `client.customers` | `create`, `list`, `retrieve`, `update`, `delete`, `list_payment_methods` |
|
|
94
|
+
| `client.products` | `create`, `list`, `retrieve`, `update`, `delete` |
|
|
95
|
+
| `client.prices` | `create` (`recurring` u `one_time`), `list`, `retrieve`, `update` |
|
|
96
|
+
| `client.subscriptions` | `create` (`items`, `billing_cycle_anchor`, `trial_end`, `trial_key`, `coupon`), `list`, `retrieve`, `update`, `preview`, `cancel`, `pause`, `resume`, `extend_period`, `extend_trial`, `end_trial`, `apply_discount`, `delete_discount`, `list_actions` |
|
|
97
|
+
| `client.subscription_items` | `create`, `list`, `retrieve`, `update`, `delete` |
|
|
98
|
+
| `client.payment_methods` | `create` / `import_wompi_source`, `retrieve`, `set_default`, `set_backup`, `delete` (`detach`), `list(customer=…)` |
|
|
99
|
+
| `client.invoices` | `create` (factura única), `list`, `retrieve`, `list_lines`, `pay`, `void`, `mark_paid` |
|
|
100
|
+
| `client.payments` | `list`, `retrieve`, `refund`, `void` |
|
|
101
|
+
| `client.refunds` | `list`, `retrieve` |
|
|
102
|
+
| `client.coupons` | `create`, `list`, `retrieve`, `update`, `delete` |
|
|
103
|
+
| `client.fixed_term_offers` | `create`, `list`, `retrieve`, `cancel` |
|
|
104
|
+
| `client.events` | `list`, `retrieve`, `resend` |
|
|
105
|
+
| `client.webhook_endpoints` | `create`, `list`, `retrieve`, `update`, `delete`, `roll_secret` |
|
|
106
|
+
| `client.checkout_sessions` | `create`, `retrieve`, `expire` |
|
|
107
|
+
| `client.payment_links` | `create`, `list`, `retrieve`, `update` |
|
|
108
|
+
| `client.portal_sessions` | `create` |
|
|
109
|
+
|
|
110
|
+
La librería tiene **solo** lo que la API documenta. Las actualizaciones son `PATCH`, como en Bucli. `resume` es lo contrario de `pause`, no de `cancel`: para deshacer una cancelación programada se usa `subscriptions.update(id, cancel_at_period_end=False)`. Una prueba de contrato compara cada ruta contra el registro de la API (ver «Pruebas»).
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
# Un plan: el producto se crea en el mismo paso
|
|
114
|
+
price = client.prices.create(product={"name": "Plan Pro"}, amount=89900, recurring={"interval": "month"})
|
|
115
|
+
|
|
116
|
+
# Un paquete de pago único
|
|
117
|
+
pack = client.prices.create(product="prod_…", amount=50000, type="one_time")
|
|
118
|
+
|
|
119
|
+
# Cliente y checkout hospedado
|
|
120
|
+
customer = client.customers.create(email="ana@tienda.co", name="Ana Pérez", metadata={"tenant": "42"})
|
|
121
|
+
session = client.checkout_sessions.create(
|
|
122
|
+
price=price.id,
|
|
123
|
+
customer=customer.id,
|
|
124
|
+
success_url="https://app.co/facturacion/listo",
|
|
125
|
+
cancel_url="https://app.co/planes",
|
|
126
|
+
client_reference_id="42",
|
|
127
|
+
)
|
|
128
|
+
# → redirige a session.url
|
|
129
|
+
|
|
130
|
+
# Checkout de varios ítems (plan base + puestos, mismo intervalo) y metadata de la suscripción
|
|
131
|
+
session = client.checkout_sessions.create(
|
|
132
|
+
line_items=[{"price": "price_PlanPro", "quantity": 1}, {"price": "price_Puesto", "quantity": 3}],
|
|
133
|
+
customer=customer.id,
|
|
134
|
+
success_url="https://app.co/facturacion/listo",
|
|
135
|
+
subscription_data={"metadata": {"tenant": "42"}},
|
|
136
|
+
)
|
|
137
|
+
# session.line_items, session.amount_total
|
|
138
|
+
|
|
139
|
+
# Suscripción con plan base + puestos, que nace active y cobra en el ancla (migración)
|
|
140
|
+
import datetime
|
|
141
|
+
sub = client.subscriptions.create(
|
|
142
|
+
customer=customer.id,
|
|
143
|
+
items=[{"price": "price_PlanPro", "quantity": 1}, {"price": "price_Puesto", "quantity": 3}],
|
|
144
|
+
billing_cycle_anchor=datetime.datetime(2026, 11, 15, 5, tzinfo=datetime.UTC), # con zona horaria
|
|
145
|
+
metadata={"legacy_id": "klopi-sub-1042"},
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
# Cambiar el plan sin prorrateo (aplica ya y se cobra desde el próximo periodo)
|
|
149
|
+
client.subscriptions.update(sub.id, price="price_PlanScale", proration_behavior="none")
|
|
150
|
+
|
|
151
|
+
# Con prorrateo: la vista previa dice cuánto se cobra AHORA y el cambio envía ese valor
|
|
152
|
+
quote = client.subscriptions.preview(sub.id, price="price_PlanScale")
|
|
153
|
+
try:
|
|
154
|
+
client.subscriptions.update(
|
|
155
|
+
sub.id, price="price_PlanScale", proration_behavior="create_prorations", expected_amount=quote.amount
|
|
156
|
+
)
|
|
157
|
+
except bucli.InvalidRequestError as e:
|
|
158
|
+
if e.code == "quote_changed":
|
|
159
|
+
quote = e.quote # la cotización nueva (como la de preview): muéstrala y confirma otra vez
|
|
160
|
+
|
|
161
|
+
client.subscriptions.cancel(sub.id, at_period_end=True, reason="requested_by_customer")
|
|
162
|
+
|
|
163
|
+
# Un cupón de una vez para un cliente, aplicado a su suscripción
|
|
164
|
+
coupon = client.coupons.create(name="Crédito Ana", amount_off=120000, duration="once", max_redemptions=1)
|
|
165
|
+
client.subscriptions.apply_discount(sub.id, coupon=coupon.id)
|
|
166
|
+
|
|
167
|
+
# Devolver parte de un pago
|
|
168
|
+
client.payments.refund("py_…", amount=20000, reason="Cobro doble")
|
|
169
|
+
|
|
170
|
+
# Factura única cobrada de una a la tarjeta guardada
|
|
171
|
+
client.invoices.create(customer=customer.id, lines=[{"price": pack.id, "quantity": 2}])
|
|
172
|
+
|
|
173
|
+
# Importar una tarjeta que ya está en TU cuenta de Wompi
|
|
174
|
+
client.payment_methods.import_wompi_source(customer=customer.id, wompi_payment_source_id=48213, make_default=True)
|
|
175
|
+
|
|
176
|
+
# El portal del cliente (válido una hora)
|
|
177
|
+
url = client.portal_sessions.create(customer=customer.id, return_url="https://app.co/cuenta").url
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### Objetos
|
|
181
|
+
|
|
182
|
+
Cada respuesta es un `BucliObject`. Es **el dict** que respondió la API (`json.dumps(obj)` funciona y `obj["status"]` también), y además se lee por atributo: `sub.status`, `sub.cancellation_details.reason`. Para guardarlo, `obj.to_dict()` devuelve una copia hecha solo de `dict` y `list` planos. `obj.last_response` trae `http_status`, `request_id`, `headers`, `idempotency_key` y `replayed`.
|
|
183
|
+
|
|
184
|
+
> Una clave que choca con un método de `dict` se lee con corchetes. La que importa es la de los ítems de una suscripción: **`sub["items"]`**, porque `sub.items` es `dict.items`.
|
|
185
|
+
|
|
186
|
+
### Idempotencia y reintentos
|
|
187
|
+
|
|
188
|
+
- **Cada POST** lleva un `Idempotency-Key` (un uuid4 si no le pasas `idempotency_key=`) y repite **la misma** clave en cada reintento. Un POST reintentado nunca hace la cosa dos veces: Bucli responde la respuesta guardada (`obj.last_response.replayed`).
|
|
189
|
+
- **Se reintenta solo** ante errores de red (conexión, timeout), `409 idempotency_key_in_use`, `429` (se respeta `Retry-After`) y `5xx`. **Nunca** ante otro 4xx.
|
|
190
|
+
- Un replay que traía una URL con token (checkout o portal) responde `409 url_unavailable_on_replay`, con el id del objeto en `error.object_id` (`e.object_id`, y su tipo en `e.object_type`). La librería lo resuelve sola: si fue un checkout, consulta la sesión por ese id; si fue el portal, crea otra sesión con una clave nueva (`portal_sessions.retrieve` no vuelve a mostrar la URL).
|
|
191
|
+
|
|
192
|
+
### Paginación y `expand[]`
|
|
193
|
+
|
|
194
|
+
```python
|
|
195
|
+
page = client.subscriptions.list(status="active", limit=100) # una página
|
|
196
|
+
page.data, page.has_more
|
|
197
|
+
|
|
198
|
+
for sub in client.subscriptions.list(customer="cus_…", limit=100).auto_paging_iter(): # todas
|
|
199
|
+
...
|
|
200
|
+
|
|
201
|
+
client.subscriptions.retrieve("sub_…", expand=["customer", "latest_invoice"])
|
|
202
|
+
client.invoices.list(expand=["data.customer"])
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
`auto_paging_iter()` conserva los filtros y el `expand[]`, y avanza con `starting_after`. Si la página se pidió con `ending_before`, recorre hacia atrás. También sirve en listas incrustadas, como `sub["items"]`.
|
|
206
|
+
|
|
207
|
+
### Errores
|
|
208
|
+
|
|
209
|
+
```python
|
|
210
|
+
try:
|
|
211
|
+
client.customers.create(email="ana@tienda.co")
|
|
212
|
+
except bucli.InvalidRequestError as e:
|
|
213
|
+
if e.code == "resource_already_exists":
|
|
214
|
+
...
|
|
215
|
+
print(e.http_status, e.type, e.code, e.message, e.param, e.request_id)
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
| Clase | Cuándo |
|
|
219
|
+
|---|---|
|
|
220
|
+
| `AuthenticationError` | 401: la llave falta, no existe o fue revocada |
|
|
221
|
+
| `PermissionError` | 403: el plan, el tipo de llave o el rol no lo permite |
|
|
222
|
+
| `InvalidRequestError` | 400/404/409/413/422: la petición está mal (`param` dice dónde) |
|
|
223
|
+
| `IdempotencyError` | 409 `idempotency_key_in_use` / `idempotency_key_reused` |
|
|
224
|
+
| `RateLimitError` | 429 (`e.retry_after`) |
|
|
225
|
+
| `BillingError` / `CardError` | 402: el plan de Bucli del comercio, o `payment_method_rejected` (Wompi rechazó el método) |
|
|
226
|
+
| `APIError` | 5xx o una respuesta que no es JSON |
|
|
227
|
+
| `APIConnectionError` | No se llegó a Bucli (DNS, TLS, timeout), ya agotados los reintentos |
|
|
228
|
+
|
|
229
|
+
Todas heredan de `bucli.BucliError`. El `code` es estable y es lo que conviene comparar en el código. El `message` está en español, para mostrárselo a una persona.
|
|
230
|
+
|
|
231
|
+
### Webhooks
|
|
232
|
+
|
|
233
|
+
```python
|
|
234
|
+
event = bucli.Webhook.construct_event(
|
|
235
|
+
payload=request.body, # el cuerpo CRUDO, en bytes
|
|
236
|
+
sig_header=request.headers["Bucli-Signature"],
|
|
237
|
+
secret="whsec_…", # o una lista durante tu propia rotación
|
|
238
|
+
tolerance=300,
|
|
239
|
+
)
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
La función:
|
|
243
|
+
- verifica `HMAC-SHA256(secreto, "<t>.<cuerpo crudo>")` en tiempo constante;
|
|
244
|
+
- acepta **cualquiera** de las firmas `v1`. Durante las 24 horas que siguen a `roll_secret`, Bucli manda dos: la del secreto anterior y la del nuevo;
|
|
245
|
+
- rechaza un `t` de hace más de `tolerance` segundos o que venga del futuro;
|
|
246
|
+
- rechaza un cuerpo que no sea un objeto JSON.
|
|
247
|
+
|
|
248
|
+
Si algo de eso falla, lanza `SignatureVerificationError`. Para tus pruebas, `bucli.Webhook.generate_test_header(body, secret)` arma una cabecera válida.
|
|
249
|
+
|
|
250
|
+
---
|
|
251
|
+
|
|
252
|
+
## Integrar un SaaS Django paso a paso
|
|
253
|
+
|
|
254
|
+
### 1. Settings
|
|
255
|
+
|
|
256
|
+
```python
|
|
257
|
+
INSTALLED_APPS = [
|
|
258
|
+
# …
|
|
259
|
+
"tenants",
|
|
260
|
+
"bucli.contrib.django", # app label: bucli_billing
|
|
261
|
+
]
|
|
262
|
+
|
|
263
|
+
BUCLI_SECRET_KEY = env("BUCLI_SECRET_KEY") # sk_test_… en staging, sk_live_… en producción
|
|
264
|
+
BUCLI_WEBHOOK_SECRET = env("BUCLI_WEBHOOK_SECRET") # el whsec_… del endpoint (una lista durante una rotación)
|
|
265
|
+
BUCLI_ACCOUNT_MODEL = "tenants.Tenant" # el modelo dueño de la suscripción
|
|
266
|
+
BUCLI_PRICE_PLANS = { # precios de Bucli → planes internos
|
|
267
|
+
"price_AbC…": "basic",
|
|
268
|
+
"price_DeF…": "pro",
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
# Opcionales
|
|
272
|
+
BUCLI_GRACE = None # past_due mantiene el acceso mientras Bucli reintenta; con timedelta/días, hasta ese plazo tras el fin del periodo
|
|
273
|
+
BUCLI_LAPSED_ACCESS = "free" # o "read_only": qué reciben paused / canceled / incomplete_expired / sin suscripción
|
|
274
|
+
BUCLI_FREE_PLAN = "free"
|
|
275
|
+
# BUCLI_API_BASE_URL, BUCLI_API_VERSION, BUCLI_TIMEOUT (15), BUCLI_MAX_RETRIES (2), BUCLI_WEBHOOK_TOLERANCE (300)
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
Las llaves viven solo en el servidor. **`BUCLI_ACCOUNT_MODEL` se fija antes del primer `migrate` y no se cambia después**, igual que `AUTH_USER_MODEL`.
|
|
279
|
+
|
|
280
|
+
### 2. URL del webhook y migraciones
|
|
281
|
+
|
|
282
|
+
```python
|
|
283
|
+
# urls.py
|
|
284
|
+
urlpatterns = [
|
|
285
|
+
path("webhooks/bucli/", include("bucli.contrib.django.urls")), # POST /webhooks/bucli/
|
|
286
|
+
]
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
```bash
|
|
290
|
+
python manage.py migrate bucli_billing
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Se crean dos tablas:
|
|
294
|
+
- `BillingAccount`: una fila por cuenta del SaaS, con `bucli_customer_id`, `bucli_subscription_id`, `price_id`, `plan`, `status`, `current_period_end`, `cancel_at_period_end`, `items`, `bucli_updated_at` (el `updated` de Bucli de la copia), `last_event_sequence` y `updated_at`. Es la copia del estado de Bucli que sirve para decidir el acceso sin llamar a Bucli. Se lee con `tenant.bucli_billing`.
|
|
295
|
+
- `ProcessedEvent`: los eventos ya procesados.
|
|
296
|
+
|
|
297
|
+
### 3. El botón «Suscribirme»
|
|
298
|
+
|
|
299
|
+
```python
|
|
300
|
+
from django.shortcuts import redirect
|
|
301
|
+
from bucli.contrib.django import services
|
|
302
|
+
from bucli.contrib.django.exceptions import AlreadySubscribed
|
|
303
|
+
|
|
304
|
+
def subscribe(request, price_id):
|
|
305
|
+
tenant = request.tenant
|
|
306
|
+
try:
|
|
307
|
+
session = services.start_checkout(
|
|
308
|
+
tenant,
|
|
309
|
+
price_id,
|
|
310
|
+
success_url=request.build_absolute_uri("/facturacion/procesando"),
|
|
311
|
+
cancel_url=request.build_absolute_uri("/planes"),
|
|
312
|
+
email=request.user.email,
|
|
313
|
+
name=tenant.name,
|
|
314
|
+
external_id=str(tenant.pk), # un cliente por cuenta, nunca por correo
|
|
315
|
+
phone="+573001234567", # E.164, o None
|
|
316
|
+
fiscal=billing_fiscal(tenant), # sus datos para la factura electrónica, o None
|
|
317
|
+
)
|
|
318
|
+
except AlreadySubscribed:
|
|
319
|
+
return redirect("billing-portal") # ya paga: que cambie de plan o use el portal
|
|
320
|
+
return redirect(session.url)
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
`start_checkout` hace tres cosas:
|
|
324
|
+
1. Crea el cliente de Bucli, o reusa el vinculado o el que ya tenga ese `external_id` (sin él, ese correo).
|
|
325
|
+
2. Guarda el vínculo en `BillingAccount`.
|
|
326
|
+
3. Abre la sesión con `client_reference_id = tenant.pk` y `metadata.bucli_account = "tenants.tenant:<pk>"`, y la suscripción que crea lleva lo mismo en su metadata (`subscription_data`).
|
|
327
|
+
|
|
328
|
+
Con varios ítems (plan base + puestos + adicionales), en vez de `price_id`:
|
|
329
|
+
|
|
330
|
+
```python
|
|
331
|
+
session = services.start_checkout(
|
|
332
|
+
tenant,
|
|
333
|
+
items=["price_PlanPro", ("price_Puesto", 3)], # o {"price": ..., "quantity": ...}
|
|
334
|
+
success_url=request.build_absolute_uri("/facturacion/procesando"),
|
|
335
|
+
email=request.user.email,
|
|
336
|
+
)
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
Al menos un precio debe estar en `BUCLI_PRICE_PLANS` (el que fija el plan).
|
|
340
|
+
|
|
341
|
+
**Los datos de la factura electrónica (`fiscal`).** Cuando el comercio tiene activa la facturación electrónica, Bucli emite la factura de cada cobro a nombre de quien paga, así que el cliente lleva sus datos fiscales completos: tipo de persona, documento con su DV, razón social o nombres, dirección y municipio DANE, y las responsabilidades del RUT. `fiscal` va entero; si la cuenta todavía no los tiene completos, no lo mandes. Cuando cambian los datos de la cuenta, mándalos otra vez desde una tarea, después del commit:
|
|
342
|
+
|
|
343
|
+
```python
|
|
344
|
+
services.sync_customer(tenant, name=tenant.name, email=owner_email, phone=phone, fiscal=billing_fiscal(tenant))
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
`sync_customer` envía solo lo que no sea `None` y no hace nada si la cuenta aún no tiene cliente en Bucli. `start_checkout` de una cuenta ya vinculada también manda el `phone` y el `fiscal` que reciba. Si `email` cambia, puede responder `409 resource_already_exists` cuando otro cliente sin `external_id` ya tiene ese correo.
|
|
348
|
+
|
|
349
|
+
**Si ya tenías clientes sin `external_id`:** con `external_id` el cliente se busca solo por él. Una cuenta sin vincular cuyo cliente viejo no tiene `external_id` recibe uno nuevo. Antes de pasar a `external_id`, vincúlalas con `services.link` o ponles su `external_id` (`client.customers.update(id, external_id=…)`).
|
|
350
|
+
|
|
351
|
+
**La página de `success_url` no activa nada.** Muestra «Estamos confirmando tu pago» y consulta `has_access(tenant)` cada pocos segundos. La activación llega por el webhook, o por `services.sync(tenant)` si quieres forzarla.
|
|
352
|
+
|
|
353
|
+
### 4. Portal, cambio de plan y cancelación
|
|
354
|
+
|
|
355
|
+
```python
|
|
356
|
+
return redirect(services.portal_url(tenant, return_url=request.build_absolute_uri("/cuenta"))) # tarjeta, facturas, datos
|
|
357
|
+
|
|
358
|
+
services.change_plan(tenant, "price_DeF…") # aplica ya y se cobra desde el próximo periodo
|
|
359
|
+
|
|
360
|
+
quote = services.preview_plan_change(tenant, "price_DeF…") # lo que cuesta AHORA, prorrateado
|
|
361
|
+
services.change_plan(tenant, "price_DeF…", proration_behavior="create_prorations", expected_amount=quote["amount"])
|
|
362
|
+
# subir se cobra ya y aplica cuando Wompi lo aprueba (llega por webhook); bajar espera la renovación
|
|
363
|
+
services.cancel(tenant) # al fin del periodo; cancel(tenant, at_period_end=False) = ya
|
|
364
|
+
services.reactivate(tenant) # deshace la cancelación programada
|
|
365
|
+
services.sync(tenant) # vuelve a leer de Bucli
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
Con varios ítems (plan base + puestos), `change_plan` cambia el ítem cuyo precio está en `BUCLI_PRICE_PLANS`. Los puestos se manejan con `client.subscription_items` (`bucli.contrib.django.conf.get_client()` da el cliente configurado).
|
|
369
|
+
|
|
370
|
+
### 5. La regla de acceso
|
|
371
|
+
|
|
372
|
+
```python
|
|
373
|
+
from bucli.contrib.django import access
|
|
374
|
+
|
|
375
|
+
access.has_access(tenant) # True con FULL o WARNING
|
|
376
|
+
access.access_level(tenant) # "full" | "warning" | "free" | "read_only" | "none"
|
|
377
|
+
access.current_plan(tenant) # "pro" | "free" | None → con esto aplicas TUS límites
|
|
378
|
+
access.needs_payment_update(tenant) # mostrar «actualiza tu tarjeta»
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
| Estado en Bucli | `access_level` | Acceso |
|
|
382
|
+
|---|---|---|
|
|
383
|
+
| `trialing`, `active` | `full` | Completo |
|
|
384
|
+
| `past_due` | `warning` | Completo mientras Bucli reintenta, con el aviso de «actualiza tu tarjeta». Si definiste `BUCLI_GRACE` y ya pasó ese plazo desde el fin del periodo, cae al acceso de suscripción vencida |
|
|
385
|
+
| `paused`, `canceled`, `incomplete_expired`, sin suscripción | `free` o `read_only` | Plan gratis o solo lectura, según `BUCLI_LAPSED_ACCESS` |
|
|
386
|
+
| `incomplete` | `none` | Nada nuevo: todavía no pagó. Se queda con el plan gratis si lo hay, nunca con el plan que compró |
|
|
387
|
+
|
|
388
|
+
Solo lee la copia local. Los límites de cada plan (usuarios, mensajes, documentos) siguen en el SaaS: Bucli solo dice qué plan tiene la cuenta y si está al día.
|
|
389
|
+
|
|
390
|
+
> Mientras migras, usa la regla solo para las cuentas que **cobra Bucli**. Una cuenta que todavía cobra el sistema viejo no tiene `BillingAccount` y la regla la vería como «sin suscripción».
|
|
391
|
+
|
|
392
|
+
### 6. Señales
|
|
393
|
+
|
|
394
|
+
```python
|
|
395
|
+
from django.dispatch import receiver
|
|
396
|
+
from bucli.contrib.django.signals import subscription_changed, event_processed
|
|
397
|
+
|
|
398
|
+
@receiver(subscription_changed)
|
|
399
|
+
def on_change(sender, account, billing_account, previous_status, status, previous_plan, plan, **kwargs):
|
|
400
|
+
... # recalcular límites, avisar al equipo
|
|
401
|
+
|
|
402
|
+
@receiver(event_processed)
|
|
403
|
+
def on_event(sender, event, account, billing_account, invoice, outcome, **kwargs):
|
|
404
|
+
if event["type"] == "invoice.fiscal_document.issued":
|
|
405
|
+
... # invoice["fiscal_document"]["pdf_url"]
|
|
406
|
+
elif event["type"] == "notice.sent":
|
|
407
|
+
... # a la campana de account: event["data"]["object"]["subject"], ["message"]
|
|
408
|
+
elif event["type"] == "subscription.update_failed":
|
|
409
|
+
... # el cambio prorrateado no se cobró: la suscripción quedó como estaba
|
|
410
|
+
elif event["type"] == "charge.refunded":
|
|
411
|
+
... # event["data"]["object"] es el refund; invoice, su factura
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
Las dos señales se envían **después del commit** con `send_robust`: si un receptor falla, se registra en el log y el webhook no se rompe.
|
|
415
|
+
|
|
416
|
+
### 7. El webhook en Bucli
|
|
417
|
+
|
|
418
|
+
Crea el endpoint desde el dashboard («Desarrolladores → Webhooks») o con la API. Necesita un plan con webhooks (Pro o superior).
|
|
419
|
+
|
|
420
|
+
```python
|
|
421
|
+
endpoint = client.webhook_endpoints.create(
|
|
422
|
+
url="https://api.tu-saas.co/webhooks/bucli/",
|
|
423
|
+
enabled_events=[
|
|
424
|
+
"checkout.session.completed",
|
|
425
|
+
"subscription.created", "subscription.updated", "subscription.canceled",
|
|
426
|
+
"subscription.past_due", "subscription.update_failed", "subscription.trial_will_end",
|
|
427
|
+
"invoice.paid", "invoice.payment_failed", "charge.refunded", "notice.sent",
|
|
428
|
+
"invoice.fiscal_document.issued", "invoice.fiscal_document.rejected",
|
|
429
|
+
],
|
|
430
|
+
description="Acceso del SaaS",
|
|
431
|
+
)
|
|
432
|
+
endpoint.secret # whsec_… — se muestra UNA vez: va a BUCLI_WEBHOOK_SECRET
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
`charge.refunded` hace que la app lea el refund y su factura: la llave necesita poder leer devoluciones y facturas (las llaves secretas completas pueden).
|
|
436
|
+
|
|
437
|
+
Ojo: Bucli no usa los nombres de Stripe. Sus eventos son **`subscription.*`**, no `customer.subscription.*`. La lista que la app procesa está en `bucli.contrib.django.webhooks.HANDLED_EVENTS`.
|
|
438
|
+
|
|
439
|
+
Qué hace la vista con cada entrega:
|
|
440
|
+
1. **Verifica la firma** sobre el cuerpo crudo. Si no pasa, responde `400`.
|
|
441
|
+
2. **Deduplica** por `event.id`. Una entrega repetida responde `200 duplicate`.
|
|
442
|
+
3. **No confía en el orden ni en el contenido del evento.** Vuelve a pedir el objeto (`GET /v1/subscriptions/{id}`; para `invoice.*` y `checkout.session.completed`, antes la factura o la sesión) y guarda **ese** estado. Una copia con `updated` más viejo que la guardada nunca la sobrescribe (`stale`), venga de un evento o de `sync`; cuando `updated` no lo decide (el mismo segundo, otra suscripción), un evento con `sequence` menor que el último aplicado tampoco.
|
|
443
|
+
4. **Una sola transacción** registra el evento y actualiza `BillingAccount`. Corre fuera de `ATOMIC_REQUESTS`.
|
|
444
|
+
5. Responde `200` rápido. Si Bucli no contesta al pedir el objeto, responde `503` sin registrar nada, y la reentrega de Bucli lo procesa después.
|
|
445
|
+
6. Ignora los eventos del otro modo, por ejemplo uno de test que llegue a producción (`wrong_mode`).
|
|
446
|
+
|
|
447
|
+
Para encontrar la cuenta busca, en este orden:
|
|
448
|
+
1. la suscripción ya vinculada;
|
|
449
|
+
2. el `client_reference_id` del checkout;
|
|
450
|
+
3. `metadata.bucli_account` de la suscripción;
|
|
451
|
+
4. el cliente, solo si una sola cuenta lo tiene. Bucli guarda un cliente por correo, así que dos empresas de la misma persona comparten cliente.
|
|
452
|
+
|
|
453
|
+
**Rotar el secreto:** `client.webhook_endpoints.roll_secret("we_…")` y despliega el nuevo antes de 24 horas. Mientras tanto, cada entrega trae dos `v1` y la verificación acepta cualquiera. Si prefieres desplegar primero, pon temporalmente `BUCLI_WEBHOOK_SECRET = ["whsec_viejo", "whsec_nuevo"]`.
|
|
454
|
+
|
|
455
|
+
### 8. Resincronizar
|
|
456
|
+
|
|
457
|
+
```bash
|
|
458
|
+
python manage.py bucli_sync 42 43 # cuentas por pk
|
|
459
|
+
python manage.py bucli_sync --all # todas las que tienen cliente en Bucli
|
|
460
|
+
python manage.py bucli_sync --discover # recorre las suscripciones de Bucli y vincula las que traen metadata.bucli_account
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
Conviene correr `bucli_sync --all` una vez al día como red de seguridad.
|
|
464
|
+
|
|
465
|
+
### 9. Pruebas en el SaaS
|
|
466
|
+
|
|
467
|
+
Para probar el webhook firma el cuerpo con `bucli.Webhook.generate_test_header(body, settings.BUCLI_WEBHOOK_SECRET)` y simula la API con `responses`. Así lo hacen las pruebas de esta librería (`tests/django_tests/`).
|
|
468
|
+
|
|
469
|
+
---
|
|
470
|
+
|
|
471
|
+
## Derechos y medidores
|
|
472
|
+
|
|
473
|
+
Bucli calcula los derechos de cada cliente (módulos, límites y `access`) y cuenta los cupos medidos. La copia local de
|
|
474
|
+
tu SaaS se actualiza con `entitlements.updated` y, de respaldo, con `client.customers.entitlements("cus_…")`.
|
|
475
|
+
|
|
476
|
+
Para gastar una unidad justo antes del acto que no se deshace, usa el guardián:
|
|
477
|
+
|
|
478
|
+
```python
|
|
479
|
+
from bucli.contrib.django.metering import guard
|
|
480
|
+
|
|
481
|
+
reservation = guard().reserve("documents", customer=account.bucli_customer_id, idempotency_key=f"doc-{document.pk}")
|
|
482
|
+
if not reservation.allowed:
|
|
483
|
+
raise QuotaExhausted(reservation.refusal) # "quota_exhausted" o "entitlement_access_denied"
|
|
484
|
+
...
|
|
485
|
+
if dian_rejected:
|
|
486
|
+
guard().release(reservation.usage_id) # vuelve a su origen (si no fue offline)
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
- `BUCLI_METER_ON_UNAVAILABLE = {"documents": "allow"}`: si Bucli no responde en 2 s (`BUCLI_METER_TIMEOUT`), la unidad
|
|
490
|
+
pasa, queda en `PendingUsage` y `manage.py bucli_flush_usage` (cada minuto) la reporta con su fecha. Bucli nunca la
|
|
491
|
+
niega: lo que pase del cupo queda como exceso en su tablero.
|
|
492
|
+
- Cada respuesta trae `remaining`; con el saldo en cero el guardián niega sin llamar durante `BUCLI_METER_CACHE_SECONDS`.
|
|
493
|
+
Llama `guard().forget(customer_id)` al recibir `grant.created` o `entitlements.updated`.
|
|
494
|
+
|
|
495
|
+
## Migrar los clientes existentes
|
|
496
|
+
|
|
497
|
+
Si tu SaaS ya cobra con Wompi, puedes pasar a Bucli por fases, sin pedirles la tarjeta otra vez a tus clientes.
|
|
498
|
+
|
|
499
|
+
**Fase 0. Un solo webhook de Wompi, sin tocar el código.**
|
|
500
|
+
1. En Bucli crea tu organización y conecta las mismas llaves de Wompi.
|
|
501
|
+
2. En «Cobros en línea → Reenvío de eventos» crea una regla por **prefijo de referencia** que lleve los eventos de tus cobros actuales a tu webhook de hoy (más una ruta por defecto).
|
|
502
|
+
3. Cambia la URL de eventos en el panel de Wompi por la de Bucli.
|
|
503
|
+
|
|
504
|
+
Tu SaaS sigue recibiendo los eventos de sus cobros viejos con el cuerpo y el `X-Event-Checksum` originales.
|
|
505
|
+
|
|
506
|
+
**Fase 1. Los clientes nuevos entran por Bucli.** Integra esta librería (pasos 1 a 8). Los clientes antiguos siguen con el cobro viejo.
|
|
507
|
+
|
|
508
|
+
**Fase 2. Los clientes antiguos pasan a Bucli.** Bucli puede importar sus suscripciones con la fuente de pago que ya tienen en Wompi: nacen `active`, con la próxima fecha de cobro de tu sistema como `billing_cycle_anchor`, y no cobran en el acto. Escríbele al soporte de Bucli para hacerlo.
|
|
509
|
+
|
|
510
|
+
Para que tu SaaS reconozca a cada cliente importado, pon en la `metadata` de cada suscripción el `bucli_account` de su cuenta (`{"bucli_account": "tenants.tenant:42"}`) y corre `python manage.py bucli_sync --discover`. También el primer webhook de esa suscripción la vincula. Sin esa metadata, vincúlala con sus ids: `services.link(tenant, customer_id="cus_…", subscription_id="sub_…")`.
|
|
511
|
+
|
|
512
|
+
**El corte, cliente por cliente y en este orden:**
|
|
513
|
+
1. la suscripción ya está en Bucli;
|
|
514
|
+
2. marca «cobra Bucli» en tu SaaS. Desde ahí la regla de acceso de esa cuenta sale de `BillingAccount`;
|
|
515
|
+
3. apaga ese cliente en el cobro viejo.
|
|
516
|
+
|
|
517
|
+
Nunca deben cobrar los dos sistemas al mismo cliente. Si el sistema viejo cobra antes del ancla, Bucli cobra igual en el ancla: alinea las fechas antes de pasar.
|
|
518
|
+
|
|
519
|
+
---
|
|
520
|
+
|
|
521
|
+
## Desarrollo
|
|
522
|
+
|
|
523
|
+
```bash
|
|
524
|
+
python3 -m venv .venv
|
|
525
|
+
.venv/bin/python -m pip install -e ".[dev]"
|
|
526
|
+
.venv/bin/python -m pytest # sin red: responses simula la API y un guard corta cualquier socket
|
|
527
|
+
.venv/bin/ruff check . && .venv/bin/ruff format --check .
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
- `tests/test_client.py`, `test_resources.py` y `test_objects_and_pagination.py` prueban el cliente: cabeceras, idempotencia, reintentos, errores, cada recurso y la paginación.
|
|
531
|
+
- `tests/test_webhook.py` prueba la firma: válida, doble `v1`, vieja, del futuro, alterada y cuerpos que no son JSON.
|
|
532
|
+
- `tests/django_tests/` corre un proyecto mínimo en sqlite. Prueba la vista, la deduplicación, el orden invertido, los servicios, `sync`, el comando, `has_access`, que las migraciones coincidan con los modelos y los checks de Django.
|
|
533
|
+
- `tests/test_contract.py` es la prueba de contrato contra el registro de documentación de la API de Bucli (un repositorio privado). Lo lee con `ast`, sin Django, y falla si la librería llama un método y una ruta que la API no documenta, o si la API documenta una que la librería no tiene. También falla si cambian la versión, los tipos de evento, la firma, los tipos de error o los estados. Busca ese repositorio en `$BUCLI_API_DIR` o en `../bucli-api`; si no está, se salta.
|
|
534
|
+
|
|
535
|
+
## Publicar una versión
|
|
536
|
+
|
|
537
|
+
Se publica en PyPI sola al subir su etiqueta `vX.Y.Z` (`.github/workflows/publish.yml`); los detalles están en los comentarios de los workflows.
|
|
538
|
+
|
|
539
|
+
## Licencia
|
|
540
|
+
|
|
541
|
+
MIT. © 2026 Bithaus SAS. Ver [`LICENSE`](https://github.com/bithaus-sas/bucli-python/blob/main/LICENSE).
|