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.
@@ -0,0 +1,50 @@
1
+ """The webhook the SaaS exposes to Bucli: ``path("webhooks/bucli/", include("bucli.contrib.django.urls"))``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+
7
+ from django.db import transaction
8
+ from django.http import HttpRequest, JsonResponse
9
+ from django.utils.decorators import method_decorator
10
+ from django.views import View
11
+ from django.views.decorators.csrf import csrf_exempt
12
+
13
+ from bucli.constants import SIGNATURE_HEADER
14
+ from bucli.contrib.django import conf
15
+ from bucli.contrib.django.webhooks import handle_event
16
+ from bucli.errors import BucliError, SignatureVerificationError
17
+ from bucli.webhook import Webhook
18
+
19
+ logger = logging.getLogger("bucli.contrib.django")
20
+
21
+
22
+ @method_decorator(csrf_exempt, name="dispatch")
23
+ @method_decorator(transaction.non_atomic_requests, name="dispatch")
24
+ class BucliWebhookView(View):
25
+ """Verifies ``Bucli-Signature`` on the RAW body, deduplicates and stores.
26
+
27
+ * 400: bad signature, too old, not JSON (Bucli will not fix it by retrying).
28
+ * 503: Bucli could not be asked for the fresh object — nothing recorded, the
29
+ redelivery will do it.
30
+ * 200 otherwise (also for duplicates and events it ignores)."""
31
+
32
+ http_method_names = ["post"]
33
+
34
+ def post(self, request: HttpRequest, *args, **kwargs) -> JsonResponse:
35
+ header = request.headers.get(SIGNATURE_HEADER, "")
36
+ try:
37
+ event = Webhook.construct_event(
38
+ request.body, header, conf.webhook_secrets(), tolerance=conf.webhook_tolerance()
39
+ )
40
+ except SignatureVerificationError as error:
41
+ logger.warning("Bucli webhook refused: %s", error.message)
42
+ return JsonResponse({"error": "invalid_signature"}, status=400)
43
+ if not event.get("id") or not event.get("type"):
44
+ return JsonResponse({"error": "invalid_event"}, status=400)
45
+ try:
46
+ outcome = handle_event(event)
47
+ except BucliError as error:
48
+ logger.warning("Bucli webhook %s deferred: %r", event.get("id"), error)
49
+ return JsonResponse({"error": "bucli_unavailable"}, status=503)
50
+ return JsonResponse({"received": True, "outcome": outcome})
@@ -0,0 +1,236 @@
1
+ """Handling one verified Bucli event.
2
+
3
+ 1. **Deduplicated** by ``event.id`` (``ProcessedEvent``): a redelivery does nothing.
4
+ 2. **Never trusts the order** nor the payload's snapshot: it asks Bucli for the
5
+ object again (``GET /v1/subscriptions/{id}``…) and stores THAT; the
6
+ object's ``updated`` (then ``sequence``) keeps an older copy from
7
+ overwriting a newer one (``services.store_subscription``).
8
+ 3. **One transaction** records the event and updates the ``BillingAccount``;
9
+ signals go after the commit.
10
+
11
+ A failure talking to Bucli raises (``bucli.BucliError``): the view answers 503
12
+ and Bucli delivers the event again later, since nothing was recorded.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ from typing import Any
19
+
20
+ from django.apps import apps
21
+ from django.core.exceptions import ValidationError
22
+ from django.db import IntegrityError, transaction
23
+
24
+ from bucli.client import Bucli
25
+ from bucli.contrib.django import conf
26
+ from bucli.contrib.django.models import BillingAccount, ProcessedEvent
27
+ from bucli.contrib.django.services import ACCOUNT_METADATA_KEY, STALE, account_from_label, ref, store_subscription
28
+ from bucli.contrib.django.signals import event_processed
29
+ from bucli.errors import InvalidRequestError
30
+
31
+ logger = logging.getLogger("bucli.contrib.django")
32
+
33
+ SUBSCRIPTION_EVENTS = frozenset(
34
+ {
35
+ "subscription.created",
36
+ "subscription.updated",
37
+ "subscription.canceled",
38
+ "subscription.past_due",
39
+ "subscription.update_failed",
40
+ "subscription.trial_will_end",
41
+ }
42
+ )
43
+ INVOICE_EVENTS = frozenset(
44
+ {
45
+ "invoice.paid",
46
+ "invoice.payment_failed",
47
+ "invoice.fiscal_document.issued",
48
+ "invoice.fiscal_document.rejected",
49
+ }
50
+ )
51
+ CHECKOUT_EVENTS = frozenset({"checkout.session.completed"})
52
+ #: A refund (``charge.refunded``): its invoice is fetched and handed to the signal.
53
+ REFUND_EVENTS = frozenset({"charge.refunded"})
54
+ #: A notice Bucli sent the customer (``notice.sent``): matched to the account for
55
+ #: the signal (put it in the SaaS's bell); there is no endpoint to fetch it again.
56
+ NOTICE_EVENTS = frozenset({"notice.sent"})
57
+ #: The events the app acts on; subscribe your Bucli endpoint to these.
58
+ HANDLED_EVENTS = SUBSCRIPTION_EVENTS | INVOICE_EVENTS | CHECKOUT_EVENTS | REFUND_EVENTS | NOTICE_EVENTS
59
+
60
+ # Outcomes (``ProcessedEvent.outcome`` and the webhook's answer).
61
+ DUPLICATE = "duplicate"
62
+ IGNORED = "ignored"
63
+ WRONG_MODE = "wrong_mode"
64
+ UNMATCHED = "unmatched"
65
+ MISSING = "missing"
66
+
67
+
68
+ def _account_by_reference(reference: str) -> BillingAccount | None:
69
+ """``client_reference_id`` is the SaaS account's pk (``start_checkout``)."""
70
+ if not reference:
71
+ return None
72
+ try:
73
+ billing = BillingAccount.objects.filter(account_id=reference).first()
74
+ if billing is not None:
75
+ return billing
76
+ model = apps.get_model(conf.account_model_label())
77
+ account = model._default_manager.filter(pk=reference).first()
78
+ except (ValueError, TypeError, ValidationError):
79
+ return None
80
+ if account is None:
81
+ return None
82
+ billing, _ = BillingAccount.objects.get_or_create(account=account)
83
+ return billing
84
+
85
+
86
+ def find_billing_account(*, subscription_id: str = "", customer_id: str = "", reference: str = "", label: str = ""):
87
+ """Subscription id first, then the checkout's reference, then the
88
+ subscription's ``metadata.bucli_account`` (imported subscriptions), then the
89
+ customer (only when exactly one account has it: Bucli keeps one customer per
90
+ e-mail)."""
91
+ if subscription_id:
92
+ billing = BillingAccount.objects.filter(bucli_subscription_id=subscription_id).first()
93
+ if billing is not None:
94
+ return billing
95
+ billing = _account_by_reference(reference)
96
+ if billing is not None:
97
+ return billing
98
+ account = account_from_label(label)
99
+ if account is not None:
100
+ billing, _ = BillingAccount.objects.get_or_create(account=account)
101
+ return billing
102
+ if customer_id:
103
+ matches = list(BillingAccount.objects.filter(bucli_customer_id=customer_id)[:2])
104
+ if len(matches) == 1:
105
+ return matches[0]
106
+ return None
107
+
108
+
109
+ def _fetch(event: dict, api: Bucli) -> dict[str, Any]:
110
+ """The fresh objects behind ``event``: ``subscription``, ``invoice``,
111
+ ``customer_id``, ``reference``."""
112
+ event_type = event["type"]
113
+ obj = (event.get("data") or {}).get("object") or {}
114
+ found: dict[str, Any] = {"subscription": None, "invoice": None, "customer_id": "", "reference": ""}
115
+ subscription_id = ""
116
+ if event_type in SUBSCRIPTION_EVENTS:
117
+ subscription_id = obj.get("id") or ""
118
+ elif event_type in INVOICE_EVENTS:
119
+ invoice = api.invoices.retrieve(obj["id"])
120
+ found["invoice"] = invoice
121
+ found["customer_id"] = ref(invoice.get("customer"))
122
+ subscription_id = ref(invoice.get("subscription"))
123
+ elif event_type in CHECKOUT_EVENTS:
124
+ session = api.checkout_sessions.retrieve(obj["id"])
125
+ found["customer_id"] = ref(session.get("customer"))
126
+ found["reference"] = session.get("client_reference_id") or ""
127
+ subscription_id = ref(session.get("subscription"))
128
+ elif event_type in REFUND_EVENTS:
129
+ refund = api.refunds.retrieve(obj["id"])
130
+ invoice_id = ref(refund.get("invoice"))
131
+ if invoice_id:
132
+ invoice = api.invoices.retrieve(invoice_id)
133
+ found["invoice"] = invoice
134
+ found["customer_id"] = ref(invoice.get("customer"))
135
+ subscription_id = ref(refund.get("subscription"))
136
+ elif event_type in NOTICE_EVENTS:
137
+ # Frozen when sent: the payload is the notice; only its subscription is fetched.
138
+ found["customer_id"] = ref(obj.get("customer"))
139
+ subscription_id = ref(obj.get("subscription"))
140
+ if subscription_id:
141
+ subscription = api.subscriptions.retrieve(subscription_id)
142
+ found["subscription"] = subscription
143
+ found["customer_id"] = found["customer_id"] or ref(subscription.get("customer"))
144
+ return found
145
+
146
+
147
+ def _record(event: dict, outcome: str, billing: BillingAccount | None = None) -> ProcessedEvent | None:
148
+ try:
149
+ with transaction.atomic():
150
+ return ProcessedEvent.objects.create(
151
+ event_id=event["id"],
152
+ type=event.get("type") or "",
153
+ sequence=event.get("sequence"),
154
+ livemode=bool(event.get("livemode")),
155
+ billing_account=billing,
156
+ outcome=outcome,
157
+ )
158
+ except IntegrityError:
159
+ return None
160
+
161
+
162
+ def _notify(event: dict, billing: BillingAccount | None, invoice: Any, outcome: str) -> None:
163
+ def send() -> None:
164
+ results = event_processed.send_robust(
165
+ sender=BillingAccount,
166
+ event=event,
167
+ account=billing.account if billing else None,
168
+ billing_account=billing,
169
+ invoice=invoice,
170
+ outcome=outcome,
171
+ )
172
+ for receiver, result in results:
173
+ if isinstance(result, Exception):
174
+ logger.error("Bucli: event_processed receiver %r failed: %s", receiver, result)
175
+
176
+ transaction.on_commit(send)
177
+
178
+
179
+ def handle_event(event: dict, *, client: Bucli | None = None) -> str:
180
+ """Process a verified event; answers its outcome (``applied``, ``duplicate``…)."""
181
+ event_id = event.get("id")
182
+ event_type = event.get("type") or ""
183
+ if not event_id:
184
+ raise ValueError("El evento no trae id.")
185
+ if ProcessedEvent.objects.filter(event_id=event_id).exists():
186
+ return DUPLICATE
187
+ api = client or conf.get_client()
188
+
189
+ if bool(event.get("livemode")) != api.livemode:
190
+ # A test event reaching production (or the other way): never applied.
191
+ logger.warning("Bucli: event %s is from the other mode; ignored", event_id)
192
+ with transaction.atomic():
193
+ return WRONG_MODE if _record(event, WRONG_MODE) else DUPLICATE
194
+ if event_type not in HANDLED_EVENTS:
195
+ with transaction.atomic():
196
+ if _record(event, IGNORED) is None:
197
+ return DUPLICATE
198
+ _notify(event, None, None, IGNORED)
199
+ return IGNORED
200
+
201
+ try:
202
+ found = _fetch(event, api)
203
+ except InvalidRequestError as error:
204
+ if error.code != "resource_missing":
205
+ raise
206
+ logger.warning("Bucli: the object of event %s no longer exists", event_id)
207
+ with transaction.atomic():
208
+ return MISSING if _record(event, MISSING) else DUPLICATE
209
+
210
+ subscription = found["subscription"]
211
+ billing = find_billing_account(
212
+ subscription_id=subscription["id"] if subscription else "",
213
+ customer_id=found["customer_id"],
214
+ reference=found["reference"],
215
+ label=((subscription or {}).get("metadata") or {}).get(ACCOUNT_METADATA_KEY, ""),
216
+ )
217
+ with transaction.atomic():
218
+ processed = _record(event, UNMATCHED, billing)
219
+ if processed is None:
220
+ return DUPLICATE
221
+ if billing is None:
222
+ logger.info("Bucli: event %s (%s) matches no account", event_id, event_type)
223
+ outcome = UNMATCHED
224
+ elif subscription is None:
225
+ if found["customer_id"] and not billing.bucli_customer_id:
226
+ BillingAccount.objects.filter(pk=billing.pk).update(bucli_customer_id=found["customer_id"])
227
+ billing.bucli_customer_id = found["customer_id"]
228
+ outcome = IGNORED # e.g. a one-off invoice: nothing to copy, the signal tells the SaaS
229
+ else:
230
+ outcome = store_subscription(billing, subscription, sequence=event.get("sequence"))
231
+ if outcome != UNMATCHED:
232
+ ProcessedEvent.objects.filter(pk=processed.pk).update(outcome=outcome)
233
+ _notify(event, billing, found["invoice"], outcome)
234
+ if outcome == STALE:
235
+ logger.info("Bucli: event %s is older than the stored copy; kept the copy", event_id)
236
+ return outcome
bucli/errors.py ADDED
@@ -0,0 +1,193 @@
1
+ """Typed errors. Every refusal of ``/v1`` answers::
2
+
3
+ {"error": {"type", "code", "message", "param", "doc_url", "request_id"}}
4
+
5
+ ``type`` picks the class (what to do about it); ``code`` is the stable reason a
6
+ program branches on (``e.code == "resource_missing"``); ``message`` is the
7
+ Spanish sentence for a person. A replay that cannot repeat a secret or a URL
8
+ (``409 url_unavailable_on_replay`` / ``webhook_secret_unavailable_on_replay``)
9
+ also names the object: ``e.object_id`` (``cs_…``) and ``e.object_type``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any
15
+
16
+ from bucli.objects import BucliObject, convert
17
+
18
+
19
+ class BucliError(Exception):
20
+ """Base of every error this library raises."""
21
+
22
+ def __init__(
23
+ self,
24
+ message: str | None = None,
25
+ *,
26
+ type: str | None = None, # noqa: A002 — the API's own word
27
+ code: str | None = None,
28
+ param: str | None = None,
29
+ request_id: str | None = None,
30
+ http_status: int | None = None,
31
+ doc_url: str | None = None,
32
+ headers: dict[str, str] | None = None,
33
+ json_body: Any = None,
34
+ object_id: str | None = None,
35
+ object_type: str | None = None,
36
+ ) -> None:
37
+ super().__init__(message or "")
38
+ self.message = message or ""
39
+ self.type = type
40
+ self.code = code
41
+ self.param = param
42
+ self.request_id = request_id
43
+ self.http_status = http_status
44
+ self.doc_url = doc_url
45
+ self.headers = dict(headers or {})
46
+ self.json_body = json_body
47
+ #: The object a replay refusal names (``error.object_id``/``object_type``), else ``None``.
48
+ self.object_id = object_id
49
+ self.object_type = object_type
50
+
51
+ @property
52
+ def quote(self) -> BucliObject | None:
53
+ """The new quote a ``409 quote_changed`` carries (``error.quote``), else ``None``:
54
+ the same kind of object ``subscriptions.preview`` answers (``quote.amount``,
55
+ ``quote["amount"]``); show it and send its ``amount`` again as ``expected_amount``."""
56
+ payload = self.json_body.get("error") if isinstance(self.json_body, dict) else None
57
+ quote = payload.get("quote") if isinstance(payload, dict) else None
58
+ return convert(quote) if isinstance(quote, dict) else None
59
+
60
+ def __str__(self) -> str:
61
+ parts = [self.message or self.__class__.__name__]
62
+ if self.code:
63
+ parts.append(f"(code={self.code})")
64
+ if self.request_id:
65
+ parts.append(f"[{self.request_id}]")
66
+ return " ".join(parts)
67
+
68
+ def __repr__(self) -> str:
69
+ return (
70
+ f"{self.__class__.__name__}(message={self.message!r}, code={self.code!r}, "
71
+ f"http_status={self.http_status!r}, request_id={self.request_id!r})"
72
+ )
73
+
74
+
75
+ class APIConnectionError(BucliError):
76
+ """Bucli could not be reached (DNS, TLS, timeout, connection reset)."""
77
+
78
+
79
+ class AuthenticationError(BucliError):
80
+ """401: the key is missing, invalid or revoked."""
81
+
82
+
83
+ class PermissionError(BucliError): # noqa: A001 — Stripe's name, scoped to this package
84
+ """403: the plan, the key kind or the role does not allow it."""
85
+
86
+
87
+ class InvalidRequestError(BucliError):
88
+ """400/404/409/413/422: the request itself is wrong (``param`` says where)."""
89
+
90
+
91
+ class IdempotencyError(BucliError):
92
+ """409 ``idempotency_key_in_use`` / ``idempotency_key_reused``."""
93
+
94
+
95
+ class RateLimitError(BucliError):
96
+ """429: too many requests; ``retry_after`` says how long to wait."""
97
+
98
+ @property
99
+ def retry_after(self) -> float | None:
100
+ return parse_retry_after(self.headers.get("Retry-After"))
101
+
102
+
103
+ class BillingError(BucliError):
104
+ """402: Bucli's own plan of the merchant refuses it (limit, read-only)."""
105
+
106
+
107
+ class CardError(BillingError):
108
+ """402 ``payment_method_rejected``: Wompi refused the payment method."""
109
+
110
+
111
+ class APIError(BucliError):
112
+ """5xx or an answer that is not the API's error shape."""
113
+
114
+
115
+ class SignatureVerificationError(BucliError):
116
+ """A webhook whose ``Bucli-Signature`` does not verify, is too old or is not JSON."""
117
+
118
+ def __init__(self, message: str, sig_header: str | None = None) -> None:
119
+ super().__init__(message)
120
+ self.sig_header = sig_header
121
+
122
+
123
+ ERROR_TYPES: dict[str, type[BucliError]] = {
124
+ "authentication_error": AuthenticationError,
125
+ "permission_error": PermissionError,
126
+ "invalid_request_error": InvalidRequestError,
127
+ "idempotency_error": IdempotencyError,
128
+ "rate_limit_error": RateLimitError,
129
+ "billing_error": BillingError,
130
+ "api_error": APIError,
131
+ }
132
+
133
+ #: Codes that deserve a narrower class than their type's.
134
+ ERROR_CODES: dict[str, type[BucliError]] = {
135
+ "payment_method_rejected": CardError,
136
+ }
137
+
138
+
139
+ def _class_for(error_type: str | None, code: str | None, status: int) -> type[BucliError]:
140
+ if code in ERROR_CODES:
141
+ return ERROR_CODES[code]
142
+ if error_type in ERROR_TYPES:
143
+ return ERROR_TYPES[error_type]
144
+ if status == 401:
145
+ return AuthenticationError
146
+ if status == 403:
147
+ return PermissionError
148
+ if status == 402:
149
+ return BillingError
150
+ if status == 429:
151
+ return RateLimitError
152
+ if 400 <= status < 500:
153
+ return InvalidRequestError
154
+ return APIError
155
+
156
+
157
+ def error_from_response(status: int, body: Any, headers: dict[str, str]) -> BucliError:
158
+ """The typed error of an HTTP answer ``status`` >= 400."""
159
+ payload = body.get("error") if isinstance(body, dict) else None
160
+ if not isinstance(payload, dict):
161
+ payload = {}
162
+ error_type = payload.get("type")
163
+ code = payload.get("code")
164
+ message = payload.get("message") or f"Bucli respondió HTTP {status}."
165
+ cls = _class_for(error_type, code, status)
166
+ return cls(
167
+ message,
168
+ type=error_type,
169
+ code=code,
170
+ param=payload.get("param"),
171
+ request_id=payload.get("request_id") or headers.get("Request-Id"),
172
+ http_status=status,
173
+ doc_url=payload.get("doc_url"),
174
+ headers=headers,
175
+ json_body=body,
176
+ object_id=_text(payload.get("object_id")),
177
+ object_type=_text(payload.get("object_type")),
178
+ )
179
+
180
+
181
+ def _text(value: Any) -> str | None:
182
+ return value if isinstance(value, str) and value else None
183
+
184
+
185
+ def parse_retry_after(value: str | None) -> float | None:
186
+ """Seconds of a ``Retry-After`` header (Bucli sends whole seconds)."""
187
+ if value in (None, ""):
188
+ return None
189
+ try:
190
+ seconds = float(value)
191
+ except (TypeError, ValueError):
192
+ return None
193
+ return max(seconds, 0.0)
bucli/keys.py ADDED
@@ -0,0 +1,18 @@
1
+ """HTTP idempotency keys this library derives (no imports: used by resources and metering)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+
7
+ #: Bucli's ``Idempotency-Key`` limit.
8
+ MAX_LENGTH = 255
9
+
10
+
11
+ def reserve_request_key(meter: str, customer: str, idempotency_key: str) -> str:
12
+ """The header of a reservation, scoped to the meter and the customer:
13
+ Bucli scopes the header per account only, and one document key may be
14
+ reserved on two meters (or for two customers)."""
15
+ key = f"reserve:{meter}:{customer}:{idempotency_key}"
16
+ if len(key) <= MAX_LENGTH:
17
+ return key
18
+ return "reserve:" + hashlib.sha256(key.encode()).hexdigest()