8,117 bytes · the Python implementation · view raw
from dataclasses import replace
from typing import Any, Optional
from .subscriptions_stripe_state_types import SubscriptionState
_STATUSES = ("incomplete", "incomplete_expired", "trialing", "active", "past_due", "canceled", "unpaid", "paused")
_SUBSCRIPTION_EVENTS = (
"customer.subscription.created",
"customer.subscription.updated",
"customer.subscription.deleted",
"customer.subscription.paused",
"customer.subscription.resumed",
"customer.subscription.trial_will_end",
)
_PAID_EVENTS = ("invoice.paid", "invoice.payment_succeeded")
_FAILED_EVENT = "invoice.payment_failed"def _field(o: Any, key: str) -> Any:
return o.get(key) if isinstance(o, dict) elseNonedef _id_of(v: Any) -> Optional[str]:
# An id Stripe sends either as a string or, when expanded, as an object with one.if isinstance(v, str) and v != "":
return v
i = _field(v, "id")
return i if isinstance(i, str) and i != ""elseNonedef _is_int(v: Any) -> bool:
return isinstance(v, int) andnot isinstance(v, bool)
def _opt_int(o: Any, key: str) -> Optional[int]:
v = _field(o, key)
if v isNone:
returnNoneifnot _is_int(v):
raise ValueError("subscription field %s must be a whole number or null" % key)
return v
def _entitled(status: str) -> bool:
return status in ("active", "trialing", "past_due")
def _with_invoice_effect(status: str, payment_failed: bool) -> str:
# Where an invoice event happened after a snapshot was taken, the snapshot# does not know about the payment yet: keep the invoice's effect on top.ifnot payment_failed and status in ("incomplete", "past_due", "unpaid"):
return"active"if payment_failed and status == "active":
return"past_due"return status
def _invoice_subscription(invoice: dict) -> Optional[str]:
direct = _id_of(invoice.get("subscription"))
if direct isnotNone:
return direct
# API versions from 2025 move it under parent.subscription_details.return _id_of(_field(_field(invoice.get("parent"), "subscription_details"), "subscription"))
def apply_stripe_event(state: Optional[SubscriptionState], event: Any) -> Optional[SubscriptionState]:
"""Folds one verified Stripe webhook event into the stored state of one subscription. Stripe does not promise delivery order or delivery once, so subscription snapshots and invoice events each keep their own clock and an older one is ignored, a redelivered event changes nothing, and a cancelled subscription stays cancelled."""ifnot isinstance(event, dict):
raise ValueError("event must be a JSON object")
event_id = event.get("id")
event_type = event.get("type")
created = event.get("created")
ifnot isinstance(event_id, str) or event_id == "":
raise ValueError("event id must be a non-empty string")
ifnot isinstance(event_type, str) or event_type == "":
raise ValueError("event type must be a non-empty string")
ifnot _is_int(created) or created < 0:
raise ValueError("event created must be a whole number of seconds")
obj = event.get("object")
ifnot isinstance(obj, dict):
raise ValueError("event object must be a JSON object")
if state isnotNoneand event_id == state.last_event_id:
return state
if event_type in _SUBSCRIPTION_EVENTS:
sid = _id_of(obj.get("id"))
customer = _id_of(obj.get("customer"))
raw_status = obj.get("status")
if sid isNoneor customer isNoneornot isinstance(raw_status, str):
raise ValueError("subscription object needs id, customer and status")
if raw_status notin _STATUSES:
raise ValueError('unknown subscription status "%s"' % raw_status)
if state isnotNoneand sid != state.subscription_id:
raise ValueError("event is for subscription %s, not %s" % (sid, state.subscription_id))
snapshot_status = "canceled"if event_type == "customer.subscription.deleted"else raw_status
# Cancelled is final in Stripe: a late snapshot never revives it.if state isnotNoneand state.status == "canceled"and snapshot_status != "canceled":
return state
if state isnotNoneand created < state.subscription_event_at:
return state
items = _field(obj.get("items"), "data")
item = items[0] if isinstance(items, list) and items and isinstance(items[0], dict) else {}
quantity = _opt_int(item, "quantity")
period_start = _opt_int(obj, "current_period_start")
if period_start isNone:
period_start = _opt_int(item, "current_period_start")
period_end = _opt_int(obj, "current_period_end")
if period_end isNone:
period_end = _opt_int(item, "current_period_end")
cape = obj.get("cancel_at_period_end")
if cape isnotNoneandnot isinstance(cape, bool):
raise ValueError("subscription field cancel_at_period_end must be true or false")
payment_failed = state.payment_failed if state isnotNoneelseFalse
invoice_event_at = state.invoice_event_at if state isnotNoneelse0
status = snapshot_status
if invoice_event_at > created:
status = _with_invoice_effect(status, payment_failed)
latest = _id_of(obj.get("latest_invoice"))
if latest isNoneand state isnotNone:
latest = state.latest_invoice_id
return SubscriptionState(
subscription_id=sid,
customer_id=customer,
status=status,
price_id=_id_of(item.get("price")),
quantity=1if quantity isNoneelse quantity,
current_period_start=period_start,
current_period_end=period_end,
cancel_at_period_end=cape isTrue,
cancel_at=_opt_int(obj, "cancel_at"),
canceled_at=_opt_int(obj, "canceled_at"),
ended_at=_opt_int(obj, "ended_at"),
trial_end=_opt_int(obj, "trial_end"),
latest_invoice_id=latest,
payment_failed=payment_failed,
entitled=_entitled(status),
subscription_event_at=created,
invoice_event_at=invoice_event_at,
last_event_id=event_id,
)
paid = event_type in _PAID_EVENTS
if paid or event_type == _FAILED_EVENT:
sub = _invoice_subscription(obj)
if sub isNone:
return state
invoice_id = _id_of(obj.get("id"))
if state isNone:
customer = _id_of(obj.get("customer"))
if customer isNone:
raise ValueError("invoice object needs customer")
status = "active"if paid else"incomplete"return SubscriptionState(
subscription_id=sub,
customer_id=customer,
status=status,
price_id=None,
quantity=1,
current_period_start=None,
current_period_end=None,
cancel_at_period_end=False,
cancel_at=None,
canceled_at=None,
ended_at=None,
trial_end=None,
latest_invoice_id=invoice_id,
payment_failed=not paid,
entitled=_entitled(status),
subscription_event_at=0,
invoice_event_at=created,
last_event_id=event_id,
)
if sub != state.subscription_id:
raise ValueError("event is for subscription %s, not %s" % (sub, state.subscription_id))
if created < state.invoice_event_at:
return state
status = _with_invoice_effect(state.status, not paid)
return replace(
state,
status=status,
latest_invoice_id=invoice_id if invoice_id isnotNoneelse state.latest_invoice_id,
payment_failed=not paid,
entitled=_entitled(status),
invoice_event_at=created,
last_event_id=event_id,
)
return state