pyjs-extras 0.4.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.
- pyjs_extras/__init__.py +1 -0
- pyjs_extras/stripe/__init__.py +15 -0
- pyjs_extras/stripe/browser.py +193 -0
- pyjs_extras/stripe/server.py +184 -0
- pyjs_extras/stripe/simulator.py +1213 -0
- pyjs_extras/stripe/simulator_delivery.py +210 -0
- pyjs_extras/stripe/simulator_store.py +288 -0
- pyjs_extras/stripe/simulator_types.py +50 -0
- pyjs_extras/stripe/simulator_ui.py +653 -0
- pyjs_extras/stripe/testing.py +226 -0
- pyjs_extras/stripe/web.py +41 -0
- pyjs_extras-0.4.0.dist-info/METADATA +88 -0
- pyjs_extras-0.4.0.dist-info/RECORD +17 -0
- pyjs_extras-0.4.0.dist-info/WHEEL +5 -0
- pyjs_extras-0.4.0.dist-info/entry_points.txt +2 -0
- pyjs_extras-0.4.0.dist-info/licenses/LICENSE +28 -0
- pyjs_extras-0.4.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1213 @@
|
|
|
1
|
+
"""Stateful local simulator for Stripe subscription billing workflows."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import threading
|
|
6
|
+
from collections.abc import Iterable, Mapping
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from html import escape
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Self
|
|
11
|
+
from urllib.parse import parse_qs
|
|
12
|
+
|
|
13
|
+
from pyjs.server.dev import Application, Server
|
|
14
|
+
|
|
15
|
+
from .simulator_delivery import WebhookDelivery
|
|
16
|
+
from .simulator_store import SimulatorStore
|
|
17
|
+
from .simulator_types import (
|
|
18
|
+
AUTHENTICATION_CARD,
|
|
19
|
+
DECLINED_CARD,
|
|
20
|
+
RENEWAL_BEHAVIORS,
|
|
21
|
+
RENEWAL_FAILURE_CARD,
|
|
22
|
+
SUCCESS_CARD,
|
|
23
|
+
SimulatorHTTPError,
|
|
24
|
+
SimulatorOptions,
|
|
25
|
+
status_text,
|
|
26
|
+
)
|
|
27
|
+
from .simulator_ui import (
|
|
28
|
+
DashboardView,
|
|
29
|
+
EventView,
|
|
30
|
+
InvoiceView,
|
|
31
|
+
SubscriptionView,
|
|
32
|
+
)
|
|
33
|
+
from .simulator_ui import (
|
|
34
|
+
document as simulator_document,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class StripeSimulator:
|
|
39
|
+
"""WSGI application implementing the Stripe subset used by PyJS Extras."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, store: SimulatorStore, options: SimulatorOptions):
|
|
42
|
+
self.store = store
|
|
43
|
+
self.options = options
|
|
44
|
+
self._state_lock = threading.RLock()
|
|
45
|
+
self.delivery = WebhookDelivery(
|
|
46
|
+
store,
|
|
47
|
+
options.webhook_url,
|
|
48
|
+
options.webhook_secret,
|
|
49
|
+
)
|
|
50
|
+
self._seed_catalog()
|
|
51
|
+
|
|
52
|
+
def _seed_catalog(self) -> None:
|
|
53
|
+
product = {
|
|
54
|
+
"id": self.options.product_id,
|
|
55
|
+
"object": "product",
|
|
56
|
+
"active": True,
|
|
57
|
+
"name": self.options.product_name,
|
|
58
|
+
"description": "Local subscription used by the Stripe simulator.",
|
|
59
|
+
}
|
|
60
|
+
price = {
|
|
61
|
+
"id": self.options.price_id,
|
|
62
|
+
"object": "price",
|
|
63
|
+
"active": True,
|
|
64
|
+
"currency": self.options.currency,
|
|
65
|
+
"unit_amount": self.options.unit_amount,
|
|
66
|
+
"product": product["id"],
|
|
67
|
+
"recurring": {"interval": "month", "interval_count": 1},
|
|
68
|
+
"type": "recurring",
|
|
69
|
+
}
|
|
70
|
+
if self.store.get("product", product["id"]) is None:
|
|
71
|
+
self.store.put("product", product)
|
|
72
|
+
if self.store.get("price", price["id"]) is None:
|
|
73
|
+
self.store.put("price", price)
|
|
74
|
+
|
|
75
|
+
def __call__(self, environ, start_response):
|
|
76
|
+
method = environ.get("REQUEST_METHOD", "GET").upper()
|
|
77
|
+
path = environ.get("PATH_INFO", "/").rstrip("/") or "/"
|
|
78
|
+
try:
|
|
79
|
+
if self._delivers_webhook(method, path):
|
|
80
|
+
result = self._request(method, path, environ)
|
|
81
|
+
else:
|
|
82
|
+
with self._state_lock:
|
|
83
|
+
result = self._request(method, path, environ)
|
|
84
|
+
except SimulatorHTTPError as error:
|
|
85
|
+
result = self._json(
|
|
86
|
+
{
|
|
87
|
+
"error": {
|
|
88
|
+
"type": error.error_type,
|
|
89
|
+
"message": error.message,
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
error.status,
|
|
93
|
+
)
|
|
94
|
+
status, headers, body = result
|
|
95
|
+
start_response(status, headers)
|
|
96
|
+
return [body]
|
|
97
|
+
|
|
98
|
+
def _request(self, method: str, path: str, environ):
|
|
99
|
+
if path.startswith("/v1/"):
|
|
100
|
+
self._authenticate(environ)
|
|
101
|
+
if api_version := environ.get("HTTP_STRIPE_VERSION"):
|
|
102
|
+
self.store.set_metadata("api_version", api_version)
|
|
103
|
+
return self._dispatch(method, path, environ)
|
|
104
|
+
|
|
105
|
+
@staticmethod
|
|
106
|
+
def _delivers_webhook(method: str, path: str) -> bool:
|
|
107
|
+
if method != "POST":
|
|
108
|
+
return False
|
|
109
|
+
return path.startswith("/_simulator/events/") or path.startswith(
|
|
110
|
+
"/_simulator/delivery/pending/"
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
def _authenticate(self, environ) -> None:
|
|
114
|
+
authorization = environ.get("HTTP_AUTHORIZATION", "")
|
|
115
|
+
if authorization != f"Bearer {self.options.api_key}":
|
|
116
|
+
raise SimulatorHTTPError(401, "invalid_api_key", "Invalid API Key")
|
|
117
|
+
|
|
118
|
+
def _dispatch(self, method: str, path: str, environ):
|
|
119
|
+
if method == "GET" and path == "/":
|
|
120
|
+
return self._html(self._home())
|
|
121
|
+
if method == "GET" and path == "/v1/products":
|
|
122
|
+
return self._json(self._list("product"))
|
|
123
|
+
if method == "GET" and path.startswith("/v1/products/"):
|
|
124
|
+
return self._object("product", path.rsplit("/", 1)[-1])
|
|
125
|
+
if method == "GET" and path == "/v1/prices":
|
|
126
|
+
return self._json(self._list("price"))
|
|
127
|
+
if method == "GET" and path.startswith("/v1/prices/"):
|
|
128
|
+
return self._object("price", path.rsplit("/", 1)[-1])
|
|
129
|
+
if method == "POST" and path == "/v1/checkout/sessions":
|
|
130
|
+
return self._create_checkout(path, environ)
|
|
131
|
+
if method == "GET" and path.startswith("/v1/checkout/sessions/"):
|
|
132
|
+
return self._object("checkout.session", path.rsplit("/", 1)[-1])
|
|
133
|
+
if method == "POST" and path == "/v1/billing_portal/sessions":
|
|
134
|
+
return self._create_portal(path, environ)
|
|
135
|
+
if method == "GET" and path == "/v1/customers":
|
|
136
|
+
return self._json(self._list("customer"))
|
|
137
|
+
if method == "GET" and path.startswith("/v1/customers/"):
|
|
138
|
+
return self._object("customer", path.rsplit("/", 1)[-1])
|
|
139
|
+
if method == "GET" and path == "/v1/subscriptions":
|
|
140
|
+
params = self._query(environ)
|
|
141
|
+
values = self.store.list("subscription")
|
|
142
|
+
if params.get("customer"):
|
|
143
|
+
values = [
|
|
144
|
+
item for item in values if item["customer"] == params["customer"]
|
|
145
|
+
]
|
|
146
|
+
return self._json(self._list_values(values))
|
|
147
|
+
if path.startswith("/v1/subscriptions/"):
|
|
148
|
+
subscription_id = path.rsplit("/", 1)[-1]
|
|
149
|
+
if method == "GET":
|
|
150
|
+
return self._object("subscription", subscription_id)
|
|
151
|
+
if method == "POST":
|
|
152
|
+
return self._update_subscription(subscription_id, environ)
|
|
153
|
+
if method == "GET" and path.startswith("/checkout/"):
|
|
154
|
+
return self._checkout_page(path.rsplit("/", 1)[-1])
|
|
155
|
+
if (
|
|
156
|
+
method == "POST"
|
|
157
|
+
and path.startswith("/checkout/")
|
|
158
|
+
and path.endswith("/complete")
|
|
159
|
+
):
|
|
160
|
+
session_id = path.removeprefix("/checkout/").removesuffix("/complete")
|
|
161
|
+
return self._complete_checkout(session_id, environ)
|
|
162
|
+
if (
|
|
163
|
+
method == "POST"
|
|
164
|
+
and path.startswith("/checkout/")
|
|
165
|
+
and path.endswith("/authenticate")
|
|
166
|
+
):
|
|
167
|
+
session_id = path.removeprefix("/checkout/").removesuffix("/authenticate")
|
|
168
|
+
return self._complete_checkout(session_id, environ, authenticated=True)
|
|
169
|
+
if method == "GET" and path.startswith("/portal/"):
|
|
170
|
+
return self._portal_page(path.rsplit("/", 1)[-1])
|
|
171
|
+
if method == "POST" and path.startswith("/portal/"):
|
|
172
|
+
parts = path.split("/")
|
|
173
|
+
if len(parts) != 4:
|
|
174
|
+
raise SimulatorHTTPError(404, "invalid_request_error", "No such endpoint")
|
|
175
|
+
_, _, session_id, action = parts
|
|
176
|
+
return self._portal_action(session_id, action)
|
|
177
|
+
if method == "GET" and path == "/_test/state":
|
|
178
|
+
return self._json(self._state())
|
|
179
|
+
if method == "POST" and path == "/_test/reset":
|
|
180
|
+
self.reset()
|
|
181
|
+
return self._json({"reset": True})
|
|
182
|
+
if method == "POST" and path == "/_test/clock/advance":
|
|
183
|
+
return self._advance_clock(environ)
|
|
184
|
+
if method == "POST" and path == "/_simulator/reset":
|
|
185
|
+
self.reset()
|
|
186
|
+
return self._redirect("/")
|
|
187
|
+
if method == "POST" and path == "/_simulator/clock/advance":
|
|
188
|
+
self._advance_clock(environ)
|
|
189
|
+
return self._redirect("/")
|
|
190
|
+
if method == "POST" and path == "/_simulator/delivery/mode":
|
|
191
|
+
return self._delivery_mode(environ)
|
|
192
|
+
if method == "POST" and path.startswith("/_simulator/delivery/pending/"):
|
|
193
|
+
return self._deliver_pending(path.rsplit("/", 1)[-1])
|
|
194
|
+
if method == "POST" and path.startswith("/_simulator/subscriptions/"):
|
|
195
|
+
return self._subscription_action(path, environ)
|
|
196
|
+
if method == "POST" and path.startswith("/_simulator/events/"):
|
|
197
|
+
return self._event_action(path)
|
|
198
|
+
raise SimulatorHTTPError(404, "invalid_request_error", "No such endpoint")
|
|
199
|
+
|
|
200
|
+
def _create_checkout(self, path: str, environ):
|
|
201
|
+
key = environ.get("HTTP_IDEMPOTENCY_KEY", "")
|
|
202
|
+
if existing := self.store.idempotent(path, key):
|
|
203
|
+
return self._json(existing)
|
|
204
|
+
form = self._form(environ)
|
|
205
|
+
price_id = form.get("line_items[0][price]", "")
|
|
206
|
+
if self.store.get("price", price_id) is None:
|
|
207
|
+
raise SimulatorHTTPError(
|
|
208
|
+
400,
|
|
209
|
+
"invalid_request_error",
|
|
210
|
+
f"No such price: '{price_id}'",
|
|
211
|
+
)
|
|
212
|
+
session_id = self.store.new_id("cs")
|
|
213
|
+
metadata = self._nested(form, "metadata")
|
|
214
|
+
subscription_metadata = self._nested(form, "subscription_data[metadata]")
|
|
215
|
+
value = {
|
|
216
|
+
"id": session_id,
|
|
217
|
+
"object": "checkout.session",
|
|
218
|
+
"mode": form.get("mode", "subscription"),
|
|
219
|
+
"client_reference_id": form.get("client_reference_id"),
|
|
220
|
+
"customer": form.get("customer") or None,
|
|
221
|
+
"customer_email": form.get("customer_email"),
|
|
222
|
+
"subscription": None,
|
|
223
|
+
"metadata": metadata,
|
|
224
|
+
"payment_status": "unpaid",
|
|
225
|
+
"status": "open",
|
|
226
|
+
"success_url": form.get("success_url", ""),
|
|
227
|
+
"cancel_url": form.get("cancel_url", ""),
|
|
228
|
+
"price_id": price_id,
|
|
229
|
+
"subscription_metadata": subscription_metadata,
|
|
230
|
+
"url": f"{self.options.public_url}/checkout/{session_id}",
|
|
231
|
+
}
|
|
232
|
+
self.store.put("checkout.session", value)
|
|
233
|
+
self.store.remember(path, key, value)
|
|
234
|
+
return self._json(value)
|
|
235
|
+
|
|
236
|
+
def _create_portal(self, path: str, environ):
|
|
237
|
+
key = environ.get("HTTP_IDEMPOTENCY_KEY", "")
|
|
238
|
+
if existing := self.store.idempotent(path, key):
|
|
239
|
+
return self._json(existing)
|
|
240
|
+
form = self._form(environ)
|
|
241
|
+
customer_id = form.get("customer", "")
|
|
242
|
+
if self.store.get("customer", customer_id) is None:
|
|
243
|
+
raise SimulatorHTTPError(
|
|
244
|
+
400,
|
|
245
|
+
"invalid_request_error",
|
|
246
|
+
f"No such customer: '{customer_id}'",
|
|
247
|
+
)
|
|
248
|
+
session_id = self.store.new_id("bps")
|
|
249
|
+
value = {
|
|
250
|
+
"id": session_id,
|
|
251
|
+
"object": "billing_portal.session",
|
|
252
|
+
"customer": customer_id,
|
|
253
|
+
"return_url": form.get("return_url", ""),
|
|
254
|
+
"url": f"{self.options.public_url}/portal/{session_id}",
|
|
255
|
+
}
|
|
256
|
+
self.store.put("billing_portal.session", value)
|
|
257
|
+
self.store.remember(path, key, value)
|
|
258
|
+
return self._json(value)
|
|
259
|
+
|
|
260
|
+
def _complete_checkout(
|
|
261
|
+
self,
|
|
262
|
+
session_id: str,
|
|
263
|
+
environ,
|
|
264
|
+
*,
|
|
265
|
+
authenticated: bool = False,
|
|
266
|
+
):
|
|
267
|
+
session = self._required("checkout.session", session_id)
|
|
268
|
+
form = self._form(environ)
|
|
269
|
+
card_number = form.get("card_number", session.get("card_number", ""))
|
|
270
|
+
card_number = card_number.replace(" ", "")
|
|
271
|
+
if session["status"] == "complete":
|
|
272
|
+
return self._redirect(self._success_url(session))
|
|
273
|
+
if card_number == DECLINED_CARD:
|
|
274
|
+
return self._checkout_page(session_id, "Your card was declined.", 402)
|
|
275
|
+
if card_number == AUTHENTICATION_CARD and not authenticated:
|
|
276
|
+
session["card_number"] = card_number
|
|
277
|
+
self.store.put("checkout.session", session)
|
|
278
|
+
return self._authentication_page(session)
|
|
279
|
+
if card_number not in {
|
|
280
|
+
SUCCESS_CARD,
|
|
281
|
+
AUTHENTICATION_CARD,
|
|
282
|
+
RENEWAL_FAILURE_CARD,
|
|
283
|
+
}:
|
|
284
|
+
return self._checkout_page(
|
|
285
|
+
session_id,
|
|
286
|
+
"Use a supported Stripe test card number.",
|
|
287
|
+
402,
|
|
288
|
+
)
|
|
289
|
+
customer = self._customer_for_checkout(session)
|
|
290
|
+
subscription = self._subscription_for_checkout(session, customer, card_number)
|
|
291
|
+
session.update(
|
|
292
|
+
{
|
|
293
|
+
"customer": customer["id"],
|
|
294
|
+
"subscription": subscription["id"],
|
|
295
|
+
"payment_status": "paid",
|
|
296
|
+
"status": "complete",
|
|
297
|
+
}
|
|
298
|
+
)
|
|
299
|
+
session.pop("card_number", None)
|
|
300
|
+
self.store.put("checkout.session", session)
|
|
301
|
+
invoice = self._new_invoice(subscription, "subscription_create")
|
|
302
|
+
self._emit("invoice.created", invoice)
|
|
303
|
+
invoice = self._finalize_invoice(invoice)
|
|
304
|
+
self._emit("invoice.finalized", invoice)
|
|
305
|
+
invoice.update(
|
|
306
|
+
{
|
|
307
|
+
"status": "paid",
|
|
308
|
+
"paid": True,
|
|
309
|
+
"attempted": True,
|
|
310
|
+
"amount_paid": invoice["amount_due"],
|
|
311
|
+
"attempt_count": 1,
|
|
312
|
+
"paid_at": self.store.now(),
|
|
313
|
+
}
|
|
314
|
+
)
|
|
315
|
+
self.store.put("invoice", invoice)
|
|
316
|
+
for event_type, source in (
|
|
317
|
+
("checkout.session.completed", session),
|
|
318
|
+
("customer.subscription.created", subscription),
|
|
319
|
+
("invoice.paid", invoice),
|
|
320
|
+
):
|
|
321
|
+
self._emit(event_type, source)
|
|
322
|
+
return self._redirect(self._success_url(session))
|
|
323
|
+
|
|
324
|
+
def _customer_for_checkout(self, session: Mapping[str, Any]) -> dict[str, Any]:
|
|
325
|
+
customer_id = session.get("customer")
|
|
326
|
+
if customer_id:
|
|
327
|
+
return self._required("customer", customer_id)
|
|
328
|
+
customer_id = self.store.new_id("cus")
|
|
329
|
+
return self.store.put(
|
|
330
|
+
"customer",
|
|
331
|
+
{
|
|
332
|
+
"id": customer_id,
|
|
333
|
+
"object": "customer",
|
|
334
|
+
"email": session.get("customer_email", ""),
|
|
335
|
+
"metadata": dict(session.get("metadata", {})),
|
|
336
|
+
},
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
def _subscription_for_checkout(
|
|
340
|
+
self,
|
|
341
|
+
session: Mapping[str, Any],
|
|
342
|
+
customer: Mapping[str, Any],
|
|
343
|
+
card_number: str,
|
|
344
|
+
) -> dict[str, Any]:
|
|
345
|
+
price = self._required("price", session["price_id"])
|
|
346
|
+
now = self.store.now()
|
|
347
|
+
subscription_id = self.store.new_id("sub")
|
|
348
|
+
subscription = self.store.put(
|
|
349
|
+
"subscription",
|
|
350
|
+
{
|
|
351
|
+
"id": subscription_id,
|
|
352
|
+
"object": "subscription",
|
|
353
|
+
"customer": customer["id"],
|
|
354
|
+
"status": "active",
|
|
355
|
+
"cancel_at_period_end": False,
|
|
356
|
+
"current_period_start": now,
|
|
357
|
+
"current_period_end": now + 30 * 24 * 60 * 60,
|
|
358
|
+
"livemode": False,
|
|
359
|
+
"metadata": dict(session.get("subscription_metadata", {})),
|
|
360
|
+
"default_payment_method": {
|
|
361
|
+
"id": self.store.new_id("pm"),
|
|
362
|
+
"object": "payment_method",
|
|
363
|
+
"type": "card",
|
|
364
|
+
"card": {
|
|
365
|
+
"brand": "visa",
|
|
366
|
+
"last4": card_number[-4:],
|
|
367
|
+
},
|
|
368
|
+
},
|
|
369
|
+
"items": {
|
|
370
|
+
"object": "list",
|
|
371
|
+
"data": [
|
|
372
|
+
{
|
|
373
|
+
"id": self.store.new_id("si"),
|
|
374
|
+
"object": "subscription_item",
|
|
375
|
+
"price": price,
|
|
376
|
+
"quantity": 1,
|
|
377
|
+
}
|
|
378
|
+
],
|
|
379
|
+
},
|
|
380
|
+
},
|
|
381
|
+
)
|
|
382
|
+
if card_number == RENEWAL_FAILURE_CARD:
|
|
383
|
+
self.set_renewal_behavior(subscription_id, "soft_decline")
|
|
384
|
+
return subscription
|
|
385
|
+
|
|
386
|
+
def _new_invoice(
|
|
387
|
+
self,
|
|
388
|
+
subscription: Mapping[str, Any],
|
|
389
|
+
billing_reason: str,
|
|
390
|
+
) -> dict[str, Any]:
|
|
391
|
+
now = self.store.now()
|
|
392
|
+
return self.store.put(
|
|
393
|
+
"invoice",
|
|
394
|
+
{
|
|
395
|
+
"id": self.store.new_id("in"),
|
|
396
|
+
"object": "invoice",
|
|
397
|
+
"customer": subscription["customer"],
|
|
398
|
+
"subscription": subscription["id"],
|
|
399
|
+
"status": "draft",
|
|
400
|
+
"paid": False,
|
|
401
|
+
"amount_due": self.options.unit_amount,
|
|
402
|
+
"amount_paid": 0,
|
|
403
|
+
"currency": self.options.currency,
|
|
404
|
+
"attempt_count": 0,
|
|
405
|
+
"attempted": False,
|
|
406
|
+
"auto_advance": True,
|
|
407
|
+
"billing_reason": billing_reason,
|
|
408
|
+
"collection_method": "charge_automatically",
|
|
409
|
+
"created": now,
|
|
410
|
+
"finalized_at": None,
|
|
411
|
+
"paid_at": None,
|
|
412
|
+
"period_start": subscription["current_period_start"],
|
|
413
|
+
"period_end": subscription["current_period_end"],
|
|
414
|
+
"next_payment_attempt": None,
|
|
415
|
+
"last_payment_error": None,
|
|
416
|
+
},
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
def _finalize_invoice(self, invoice: dict[str, Any]) -> dict[str, Any]:
|
|
420
|
+
invoice.update(
|
|
421
|
+
{
|
|
422
|
+
"status": "open",
|
|
423
|
+
"finalized_at": self.store.now(),
|
|
424
|
+
}
|
|
425
|
+
)
|
|
426
|
+
return self.store.put("invoice", invoice)
|
|
427
|
+
|
|
428
|
+
def renewal_behavior(self, subscription_id: str) -> str:
|
|
429
|
+
return self.store.metadata(f"renewal_behavior:{subscription_id}") or "success"
|
|
430
|
+
|
|
431
|
+
def set_renewal_behavior(self, subscription_id: str, behavior: str) -> None:
|
|
432
|
+
self._required("subscription", subscription_id)
|
|
433
|
+
if behavior not in RENEWAL_BEHAVIORS:
|
|
434
|
+
raise SimulatorHTTPError(
|
|
435
|
+
400,
|
|
436
|
+
"invalid_request_error",
|
|
437
|
+
f"Unsupported renewal behavior: '{behavior}'",
|
|
438
|
+
)
|
|
439
|
+
self.store.set_metadata(f"renewal_behavior:{subscription_id}", behavior)
|
|
440
|
+
|
|
441
|
+
def renew_subscription(self, subscription_id: str) -> dict[str, Any]:
|
|
442
|
+
subscription = self._required("subscription", subscription_id)
|
|
443
|
+
if subscription["status"] in {"canceled", "unpaid"}:
|
|
444
|
+
raise SimulatorHTTPError(
|
|
445
|
+
400,
|
|
446
|
+
"invalid_request_error",
|
|
447
|
+
"A terminal subscription cannot renew",
|
|
448
|
+
)
|
|
449
|
+
if subscription["cancel_at_period_end"]:
|
|
450
|
+
subscription["status"] = "canceled"
|
|
451
|
+
self.store.put("subscription", subscription)
|
|
452
|
+
self._emit("customer.subscription.deleted", subscription)
|
|
453
|
+
return subscription
|
|
454
|
+
if self._open_invoice(subscription_id) is not None:
|
|
455
|
+
raise SimulatorHTTPError(
|
|
456
|
+
400,
|
|
457
|
+
"invalid_request_error",
|
|
458
|
+
"Retry the subscription's open invoice before renewing",
|
|
459
|
+
)
|
|
460
|
+
return self._attempt_subscription_payment(subscription, renewal=True)
|
|
461
|
+
|
|
462
|
+
def retry_subscription(self, subscription_id: str) -> dict[str, Any]:
|
|
463
|
+
subscription = self._required("subscription", subscription_id)
|
|
464
|
+
invoice = self._open_invoice(subscription_id)
|
|
465
|
+
if invoice is None:
|
|
466
|
+
raise SimulatorHTTPError(
|
|
467
|
+
400,
|
|
468
|
+
"invalid_request_error",
|
|
469
|
+
"The subscription has no open invoice to retry",
|
|
470
|
+
)
|
|
471
|
+
return self._attempt_subscription_payment(
|
|
472
|
+
subscription,
|
|
473
|
+
renewal=False,
|
|
474
|
+
invoice=invoice,
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
def _open_invoice(self, subscription_id: str) -> dict[str, Any] | None:
|
|
478
|
+
invoices = [
|
|
479
|
+
invoice
|
|
480
|
+
for invoice in self.store.list("invoice")
|
|
481
|
+
if invoice["subscription"] == subscription_id and invoice["status"] == "open"
|
|
482
|
+
]
|
|
483
|
+
return invoices[-1] if invoices else None
|
|
484
|
+
|
|
485
|
+
def _attempt_subscription_payment(
|
|
486
|
+
self,
|
|
487
|
+
subscription: dict[str, Any],
|
|
488
|
+
*,
|
|
489
|
+
renewal: bool,
|
|
490
|
+
invoice: dict[str, Any] | None = None,
|
|
491
|
+
) -> dict[str, Any]:
|
|
492
|
+
behavior = self.renewal_behavior(subscription["id"])
|
|
493
|
+
if renewal:
|
|
494
|
+
period_start = max(self.store.now(), subscription["current_period_end"])
|
|
495
|
+
subscription["current_period_start"] = period_start
|
|
496
|
+
subscription["current_period_end"] = period_start + 30 * 24 * 60 * 60
|
|
497
|
+
if invoice is not None:
|
|
498
|
+
invoice["attempt_count"] = int(invoice.get("attempt_count", 0)) + 1
|
|
499
|
+
if invoice is None:
|
|
500
|
+
invoice = self._new_invoice(subscription, "subscription_cycle")
|
|
501
|
+
self._emit("invoice.created", invoice)
|
|
502
|
+
invoice = self._finalize_invoice(invoice)
|
|
503
|
+
self._emit("invoice.finalized", invoice)
|
|
504
|
+
invoice["attempt_count"] = 1
|
|
505
|
+
invoice["attempted"] = True
|
|
506
|
+
if behavior == "success":
|
|
507
|
+
invoice.update(
|
|
508
|
+
{
|
|
509
|
+
"status": "paid",
|
|
510
|
+
"paid": True,
|
|
511
|
+
"amount_paid": invoice["amount_due"],
|
|
512
|
+
"next_payment_attempt": None,
|
|
513
|
+
"last_payment_error": None,
|
|
514
|
+
"paid_at": self.store.now(),
|
|
515
|
+
}
|
|
516
|
+
)
|
|
517
|
+
self.store.put("invoice", invoice)
|
|
518
|
+
|
|
519
|
+
if behavior == "success":
|
|
520
|
+
subscription["status"] = "active"
|
|
521
|
+
self.store.put("subscription", subscription)
|
|
522
|
+
self._emit("invoice.paid", invoice)
|
|
523
|
+
self._emit("customer.subscription.updated", subscription)
|
|
524
|
+
return subscription
|
|
525
|
+
|
|
526
|
+
error = {
|
|
527
|
+
"type": "card_error",
|
|
528
|
+
"code": "authentication_required"
|
|
529
|
+
if behavior == "authentication_required"
|
|
530
|
+
else "card_declined",
|
|
531
|
+
"decline_code": "do_not_honor"
|
|
532
|
+
if behavior == "hard_decline"
|
|
533
|
+
else "insufficient_funds",
|
|
534
|
+
}
|
|
535
|
+
attempts = int(invoice["attempt_count"])
|
|
536
|
+
exhausted = (
|
|
537
|
+
behavior == "soft_decline" and attempts >= self.options.max_payment_attempts
|
|
538
|
+
)
|
|
539
|
+
retry_days = 1 if attempts == 1 else 3
|
|
540
|
+
invoice.update(
|
|
541
|
+
{
|
|
542
|
+
"status": "uncollectible" if exhausted else "open",
|
|
543
|
+
"paid": False,
|
|
544
|
+
"amount_paid": 0,
|
|
545
|
+
"last_payment_error": error,
|
|
546
|
+
"next_payment_attempt": (
|
|
547
|
+
self.store.now() + retry_days * 24 * 60 * 60
|
|
548
|
+
if behavior == "soft_decline" and not exhausted
|
|
549
|
+
else None
|
|
550
|
+
),
|
|
551
|
+
}
|
|
552
|
+
)
|
|
553
|
+
self.store.put("invoice", invoice)
|
|
554
|
+
subscription["status"] = "unpaid" if exhausted else "past_due"
|
|
555
|
+
self.store.put("subscription", subscription)
|
|
556
|
+
event_type = (
|
|
557
|
+
"invoice.payment_action_required"
|
|
558
|
+
if behavior == "authentication_required"
|
|
559
|
+
else "invoice.payment_failed"
|
|
560
|
+
)
|
|
561
|
+
self._emit(event_type, invoice)
|
|
562
|
+
if exhausted:
|
|
563
|
+
self._emit("invoice.marked_uncollectible", invoice)
|
|
564
|
+
self._emit("customer.subscription.updated", subscription)
|
|
565
|
+
return subscription
|
|
566
|
+
|
|
567
|
+
def replace_payment_method(
|
|
568
|
+
self,
|
|
569
|
+
subscription_id: str,
|
|
570
|
+
card_number: str = SUCCESS_CARD,
|
|
571
|
+
*,
|
|
572
|
+
retry: bool = True,
|
|
573
|
+
) -> dict[str, Any]:
|
|
574
|
+
subscription = self._required("subscription", subscription_id)
|
|
575
|
+
behavior = {
|
|
576
|
+
DECLINED_CARD: "hard_decline",
|
|
577
|
+
AUTHENTICATION_CARD: "authentication_required",
|
|
578
|
+
RENEWAL_FAILURE_CARD: "soft_decline",
|
|
579
|
+
}.get(card_number, "success")
|
|
580
|
+
payment_method = {
|
|
581
|
+
"id": self.store.new_id("pm"),
|
|
582
|
+
"object": "payment_method",
|
|
583
|
+
"type": "card",
|
|
584
|
+
"card": {"brand": "visa", "last4": card_number[-4:]},
|
|
585
|
+
}
|
|
586
|
+
subscription["default_payment_method"] = payment_method
|
|
587
|
+
self.store.put("subscription", subscription)
|
|
588
|
+
self.set_renewal_behavior(subscription_id, behavior)
|
|
589
|
+
self._emit("payment_method.attached", payment_method)
|
|
590
|
+
self._emit("customer.subscription.updated", subscription)
|
|
591
|
+
if retry and self._open_invoice(subscription_id) is not None:
|
|
592
|
+
return self.retry_subscription(subscription_id)
|
|
593
|
+
return subscription
|
|
594
|
+
|
|
595
|
+
def _update_subscription(self, subscription_id: str, environ):
|
|
596
|
+
subscription = self._required("subscription", subscription_id)
|
|
597
|
+
form = self._form(environ)
|
|
598
|
+
if "cancel_at_period_end" in form:
|
|
599
|
+
subscription["cancel_at_period_end"] = self._boolean(
|
|
600
|
+
form["cancel_at_period_end"]
|
|
601
|
+
)
|
|
602
|
+
self.store.put("subscription", subscription)
|
|
603
|
+
self._emit("customer.subscription.updated", subscription)
|
|
604
|
+
return self._json(subscription)
|
|
605
|
+
|
|
606
|
+
def _checkout_page(
|
|
607
|
+
self,
|
|
608
|
+
session_id: str,
|
|
609
|
+
error: str = "",
|
|
610
|
+
status: int = 200,
|
|
611
|
+
):
|
|
612
|
+
session = self._required("checkout.session", session_id)
|
|
613
|
+
price = self._required("price", session["price_id"])
|
|
614
|
+
if session["status"] == "complete":
|
|
615
|
+
return self._redirect(self._success_url(session))
|
|
616
|
+
error_html = f'<p class="error">{escape(error)}</p>' if error else ""
|
|
617
|
+
body = f"""
|
|
618
|
+
<main>
|
|
619
|
+
<p class="eyebrow">Local Stripe simulator</p>
|
|
620
|
+
<h1>Subscribe to Gencourt</h1>
|
|
621
|
+
<p class="price">${price["unit_amount"] / 100:.2f} per month</p>
|
|
622
|
+
<p>{escape(session.get("customer_email", ""))}</p>
|
|
623
|
+
{error_html}
|
|
624
|
+
<form method="post" action="/checkout/{escape(session_id)}/complete">
|
|
625
|
+
<label>Card number
|
|
626
|
+
<input name="card_number" inputmode="numeric"
|
|
627
|
+
autocomplete="cc-number" value="{SUCCESS_CARD}" required>
|
|
628
|
+
</label>
|
|
629
|
+
<label>Expiration <input value="12/34" autocomplete="cc-exp"></label>
|
|
630
|
+
<label>CVC <input value="123" autocomplete="cc-csc"></label>
|
|
631
|
+
<button type="submit">Subscribe</button>
|
|
632
|
+
</form>
|
|
633
|
+
<p class="hint">Success: 4242 4242 4242 4242</p>
|
|
634
|
+
<p class="hint">Decline: 4000 0000 0000 0002</p>
|
|
635
|
+
<p class="hint">Authentication: 4000 0025 0000 3155</p>
|
|
636
|
+
<a href="{escape(session["cancel_url"])}">Cancel</a>
|
|
637
|
+
</main>
|
|
638
|
+
"""
|
|
639
|
+
return self._html(self._document("Stripe Checkout", body), status)
|
|
640
|
+
|
|
641
|
+
def _authentication_page(self, session: Mapping[str, Any]):
|
|
642
|
+
body = f"""
|
|
643
|
+
<main>
|
|
644
|
+
<p class="eyebrow">Local Stripe simulator</p>
|
|
645
|
+
<h1>Confirm this payment</h1>
|
|
646
|
+
<p>This test card requires additional authentication.</p>
|
|
647
|
+
<form method="post"
|
|
648
|
+
action="/checkout/{escape(session["id"])}/authenticate">
|
|
649
|
+
<button type="submit">Complete authentication</button>
|
|
650
|
+
</form>
|
|
651
|
+
<a href="{escape(session["cancel_url"])}">Fail authentication</a>
|
|
652
|
+
</main>
|
|
653
|
+
"""
|
|
654
|
+
return self._html(self._document("Payment authentication", body))
|
|
655
|
+
|
|
656
|
+
def _portal_page(self, session_id: str):
|
|
657
|
+
session = self._required("billing_portal.session", session_id)
|
|
658
|
+
subscriptions = [
|
|
659
|
+
item
|
|
660
|
+
for item in self.store.list("subscription")
|
|
661
|
+
if item["customer"] == session["customer"] and item["status"] != "canceled"
|
|
662
|
+
]
|
|
663
|
+
if not subscriptions:
|
|
664
|
+
raise SimulatorHTTPError(
|
|
665
|
+
400, "invalid_request_error", "Customer has no subscription"
|
|
666
|
+
)
|
|
667
|
+
subscription = subscriptions[-1]
|
|
668
|
+
action = "resume" if subscription["cancel_at_period_end"] else "cancel"
|
|
669
|
+
label = "Resume subscription" if action == "resume" else "Cancel at period end"
|
|
670
|
+
body = f"""
|
|
671
|
+
<main>
|
|
672
|
+
<p class="eyebrow">Local Stripe simulator</p>
|
|
673
|
+
<h1>Manage subscription</h1>
|
|
674
|
+
<p>Status: {escape(subscription["status"])}</p>
|
|
675
|
+
<p>Visa ending in
|
|
676
|
+
{escape(subscription["default_payment_method"]["card"]["last4"])}</p>
|
|
677
|
+
<form method="post"
|
|
678
|
+
action="/portal/{escape(session_id)}/{action}">
|
|
679
|
+
<button type="submit">{label}</button>
|
|
680
|
+
</form>
|
|
681
|
+
<a href="{escape(session["return_url"])}">Return to Gencourt</a>
|
|
682
|
+
</main>
|
|
683
|
+
"""
|
|
684
|
+
return self._html(self._document("Stripe Customer Portal", body))
|
|
685
|
+
|
|
686
|
+
def _portal_action(self, session_id: str, action: str):
|
|
687
|
+
session = self._required("billing_portal.session", session_id)
|
|
688
|
+
if action not in {"cancel", "resume"}:
|
|
689
|
+
raise SimulatorHTTPError(404, "invalid_request_error", "Unknown action")
|
|
690
|
+
subscriptions = [
|
|
691
|
+
item
|
|
692
|
+
for item in self.store.list("subscription")
|
|
693
|
+
if item["customer"] == session["customer"] and item["status"] != "canceled"
|
|
694
|
+
]
|
|
695
|
+
if not subscriptions:
|
|
696
|
+
raise SimulatorHTTPError(
|
|
697
|
+
400, "invalid_request_error", "Customer has no subscription"
|
|
698
|
+
)
|
|
699
|
+
subscription = subscriptions[-1]
|
|
700
|
+
subscription["cancel_at_period_end"] = action == "cancel"
|
|
701
|
+
self.store.put("subscription", subscription)
|
|
702
|
+
self._emit("customer.subscription.updated", subscription)
|
|
703
|
+
status = "canceled" if action == "cancel" else "resumed"
|
|
704
|
+
separator = "&" if "?" in session["return_url"] else "?"
|
|
705
|
+
return self._redirect(f"{session['return_url']}{separator}status={status}")
|
|
706
|
+
|
|
707
|
+
def _advance_clock(self, environ):
|
|
708
|
+
form = self._form(environ)
|
|
709
|
+
try:
|
|
710
|
+
days = int(form.get("days", "30"))
|
|
711
|
+
except ValueError:
|
|
712
|
+
raise SimulatorHTTPError(
|
|
713
|
+
400, "invalid_request_error", "days must be an integer"
|
|
714
|
+
) from None
|
|
715
|
+
return self._json(self.advance_clock(days))
|
|
716
|
+
|
|
717
|
+
def advance_clock(self, days: int) -> dict[str, Any]:
|
|
718
|
+
if days < 1 or days > 366:
|
|
719
|
+
raise SimulatorHTTPError(
|
|
720
|
+
400, "invalid_request_error", "days must be between 1 and 366"
|
|
721
|
+
)
|
|
722
|
+
now = self.store.advance(days * 24 * 60 * 60)
|
|
723
|
+
changed: list[str] = []
|
|
724
|
+
for subscription in self.store.list("subscription"):
|
|
725
|
+
if subscription["status"] in {"canceled", "unpaid"}:
|
|
726
|
+
continue
|
|
727
|
+
if subscription["status"] == "past_due":
|
|
728
|
+
if (
|
|
729
|
+
subscription["cancel_at_period_end"]
|
|
730
|
+
and subscription["current_period_end"] <= now
|
|
731
|
+
):
|
|
732
|
+
self.renew_subscription(subscription["id"])
|
|
733
|
+
changed.append(subscription["id"])
|
|
734
|
+
continue
|
|
735
|
+
invoice = self._open_invoice(subscription["id"])
|
|
736
|
+
if (
|
|
737
|
+
invoice is not None
|
|
738
|
+
and invoice.get("next_payment_attempt") is not None
|
|
739
|
+
and invoice["next_payment_attempt"] <= now
|
|
740
|
+
):
|
|
741
|
+
self.retry_subscription(subscription["id"])
|
|
742
|
+
changed.append(subscription["id"])
|
|
743
|
+
continue
|
|
744
|
+
if subscription["current_period_end"] > now:
|
|
745
|
+
continue
|
|
746
|
+
if subscription["cancel_at_period_end"]:
|
|
747
|
+
self.renew_subscription(subscription["id"])
|
|
748
|
+
changed.append(subscription["id"])
|
|
749
|
+
continue
|
|
750
|
+
self.renew_subscription(subscription["id"])
|
|
751
|
+
changed.append(subscription["id"])
|
|
752
|
+
return {"now": now, "subscriptions": changed}
|
|
753
|
+
|
|
754
|
+
def _subscription_action(self, path: str, environ):
|
|
755
|
+
parts = path.removeprefix("/_simulator/subscriptions/").split("/")
|
|
756
|
+
if len(parts) != 2:
|
|
757
|
+
raise SimulatorHTTPError(404, "invalid_request_error", "Unknown action")
|
|
758
|
+
subscription_id, action = parts
|
|
759
|
+
if action == "behavior":
|
|
760
|
+
self.set_renewal_behavior(
|
|
761
|
+
subscription_id,
|
|
762
|
+
self._form(environ).get("behavior", ""),
|
|
763
|
+
)
|
|
764
|
+
elif action == "renew":
|
|
765
|
+
self.renew_subscription(subscription_id)
|
|
766
|
+
elif action == "retry":
|
|
767
|
+
self.retry_subscription(subscription_id)
|
|
768
|
+
elif action == "payment":
|
|
769
|
+
form = self._form(environ)
|
|
770
|
+
self.replace_payment_method(
|
|
771
|
+
subscription_id,
|
|
772
|
+
form.get("card_number", SUCCESS_CARD).replace(" ", ""),
|
|
773
|
+
retry=self._boolean(form.get("retry", "true")),
|
|
774
|
+
)
|
|
775
|
+
else:
|
|
776
|
+
raise SimulatorHTTPError(404, "invalid_request_error", "Unknown action")
|
|
777
|
+
return self._redirect("/")
|
|
778
|
+
|
|
779
|
+
def _event_action(self, path: str):
|
|
780
|
+
parts = path.removeprefix("/_simulator/events/").split("/")
|
|
781
|
+
if len(parts) != 2 or parts[1] not in {"resend", "invalid", "stale"}:
|
|
782
|
+
raise SimulatorHTTPError(404, "invalid_request_error", "Unknown action")
|
|
783
|
+
event = self.store.event(parts[0])
|
|
784
|
+
if event is None:
|
|
785
|
+
raise SimulatorHTTPError(404, "invalid_request_error", "No such event")
|
|
786
|
+
signature_mode = {
|
|
787
|
+
"resend": "valid",
|
|
788
|
+
"invalid": "invalid",
|
|
789
|
+
"stale": "stale",
|
|
790
|
+
}[parts[1]]
|
|
791
|
+
self.delivery.deliver(event, signature_mode=signature_mode)
|
|
792
|
+
return self._redirect("/")
|
|
793
|
+
|
|
794
|
+
def _delivery_mode(self, environ):
|
|
795
|
+
mode = self._form(environ).get("mode", "")
|
|
796
|
+
try:
|
|
797
|
+
self.delivery.set_mode(mode)
|
|
798
|
+
except ValueError as error:
|
|
799
|
+
raise SimulatorHTTPError(400, "invalid_request_error", str(error)) from error
|
|
800
|
+
return self._redirect("/")
|
|
801
|
+
|
|
802
|
+
def _deliver_pending(self, order: str):
|
|
803
|
+
if order not in {"oldest", "newest"}:
|
|
804
|
+
raise SimulatorHTTPError(404, "invalid_request_error", "Unknown action")
|
|
805
|
+
events = [
|
|
806
|
+
event
|
|
807
|
+
for event in self.store.events()
|
|
808
|
+
if event["delivery_state"] in {"pending", "failed"}
|
|
809
|
+
]
|
|
810
|
+
if order == "newest":
|
|
811
|
+
events.reverse()
|
|
812
|
+
for event in events:
|
|
813
|
+
self.delivery.deliver(event)
|
|
814
|
+
return self._redirect("/")
|
|
815
|
+
|
|
816
|
+
def _emit(self, event_type: str, source: Mapping[str, Any]) -> None:
|
|
817
|
+
event = {
|
|
818
|
+
"id": self.store.new_id("evt"),
|
|
819
|
+
"object": "event",
|
|
820
|
+
"api_version": self.store.metadata("api_version") or "2026-02-25.clover",
|
|
821
|
+
"created": self.store.now(),
|
|
822
|
+
"livemode": False,
|
|
823
|
+
"pending_webhooks": 1 if self.options.webhook_url else 0,
|
|
824
|
+
"type": event_type,
|
|
825
|
+
"data": {"object": dict(source)},
|
|
826
|
+
}
|
|
827
|
+
self.delivery.record(event)
|
|
828
|
+
|
|
829
|
+
def _deliver(self, event: Mapping[str, Any]) -> None:
|
|
830
|
+
self.delivery.deliver(event)
|
|
831
|
+
|
|
832
|
+
def wait_for_deliveries(self, timeout: float = 5) -> bool:
|
|
833
|
+
return self.delivery.wait_for_idle(timeout)
|
|
834
|
+
|
|
835
|
+
def reset(self) -> None:
|
|
836
|
+
if not self.delivery.prepare_reset():
|
|
837
|
+
raise SimulatorHTTPError(
|
|
838
|
+
400,
|
|
839
|
+
"simulator_busy",
|
|
840
|
+
"Wait for the active webhook delivery before resetting",
|
|
841
|
+
)
|
|
842
|
+
self.store.reset()
|
|
843
|
+
self._seed_catalog()
|
|
844
|
+
|
|
845
|
+
def close(self) -> None:
|
|
846
|
+
self.delivery.close()
|
|
847
|
+
|
|
848
|
+
def _success_url(self, session: Mapping[str, Any]) -> str:
|
|
849
|
+
return session["success_url"].replace("{CHECKOUT_SESSION_ID}", session["id"])
|
|
850
|
+
|
|
851
|
+
def _state(self) -> dict[str, Any]:
|
|
852
|
+
return {
|
|
853
|
+
"clock": self.store.now(),
|
|
854
|
+
"products": self.store.list("product"),
|
|
855
|
+
"prices": self.store.list("price"),
|
|
856
|
+
"customers": self.store.list("customer"),
|
|
857
|
+
"checkout_sessions": self.store.list("checkout.session"),
|
|
858
|
+
"subscriptions": self.store.list("subscription"),
|
|
859
|
+
"invoices": self.store.list("invoice"),
|
|
860
|
+
"events": self.store.events(),
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
def _home(self) -> str:
|
|
864
|
+
state = self._state()
|
|
865
|
+
customers = {customer["id"]: customer for customer in state["customers"]}
|
|
866
|
+
invoices_by_subscription: dict[str, list[dict[str, Any]]] = {}
|
|
867
|
+
for invoice in state["invoices"]:
|
|
868
|
+
invoices_by_subscription.setdefault(invoice["subscription"], []).append(
|
|
869
|
+
invoice
|
|
870
|
+
)
|
|
871
|
+
subscriptions: list[SubscriptionView] = []
|
|
872
|
+
for subscription in state["subscriptions"]:
|
|
873
|
+
customer = customers.get(subscription["customer"], {})
|
|
874
|
+
invoices = invoices_by_subscription.get(subscription["id"], [])
|
|
875
|
+
invoice = invoices[-1] if invoices else {}
|
|
876
|
+
card = subscription["default_payment_method"]["card"]
|
|
877
|
+
subscriptions.append(
|
|
878
|
+
SubscriptionView(
|
|
879
|
+
id=subscription["id"],
|
|
880
|
+
customer_email=customer.get("email", ""),
|
|
881
|
+
status=subscription["status"],
|
|
882
|
+
period_end=self._format_time(subscription["current_period_end"]),
|
|
883
|
+
cancel_at_period_end=subscription["cancel_at_period_end"],
|
|
884
|
+
payment_method=(
|
|
885
|
+
card["brand"].title() + " ending in " + card["last4"]
|
|
886
|
+
),
|
|
887
|
+
renewal_behavior=self.renewal_behavior(subscription["id"]),
|
|
888
|
+
invoice_id=invoice.get("id", ""),
|
|
889
|
+
invoice_status=invoice.get("status", ""),
|
|
890
|
+
invoice_attempts=int(invoice.get("attempt_count", 0)),
|
|
891
|
+
)
|
|
892
|
+
)
|
|
893
|
+
events: list[EventView] = []
|
|
894
|
+
for event in reversed(state["events"][-50:]):
|
|
895
|
+
attempts = int(event["delivery_attempts"])
|
|
896
|
+
payload = {
|
|
897
|
+
name: value
|
|
898
|
+
for name, value in event.items()
|
|
899
|
+
if name
|
|
900
|
+
not in {
|
|
901
|
+
"delivered",
|
|
902
|
+
"delivery_attempts",
|
|
903
|
+
"last_attempt_at",
|
|
904
|
+
"last_error",
|
|
905
|
+
"last_status",
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
delivery = event["delivery_state"].replace("_", " ")
|
|
909
|
+
last_response = ""
|
|
910
|
+
if event["last_status"] is not None:
|
|
911
|
+
last_response = "HTTP " + str(event["last_status"])
|
|
912
|
+
elif event["last_error"]:
|
|
913
|
+
last_response = event["last_error"]
|
|
914
|
+
events.append(
|
|
915
|
+
EventView(
|
|
916
|
+
id=event["id"],
|
|
917
|
+
type=event["type"],
|
|
918
|
+
created=self._format_time(event["created"]),
|
|
919
|
+
delivery=delivery,
|
|
920
|
+
attempts=attempts,
|
|
921
|
+
payload=json.dumps(payload, indent=2, sort_keys=True),
|
|
922
|
+
can_resend=bool(self.options.webhook_url),
|
|
923
|
+
last_response=last_response,
|
|
924
|
+
attempt_history=tuple(
|
|
925
|
+
self._format_attempt(attempt)
|
|
926
|
+
for attempt in self.store.delivery_attempts(event["id"])
|
|
927
|
+
),
|
|
928
|
+
)
|
|
929
|
+
)
|
|
930
|
+
invoices = tuple(
|
|
931
|
+
InvoiceView(
|
|
932
|
+
id=invoice["id"],
|
|
933
|
+
subscription_id=invoice["subscription"],
|
|
934
|
+
status=invoice["status"],
|
|
935
|
+
billing_reason=invoice.get("billing_reason", ""),
|
|
936
|
+
attempt_count=int(invoice.get("attempt_count", 0)),
|
|
937
|
+
next_attempt=(
|
|
938
|
+
self._format_time(invoice["next_payment_attempt"])
|
|
939
|
+
if invoice.get("next_payment_attempt")
|
|
940
|
+
else ""
|
|
941
|
+
),
|
|
942
|
+
error_code=(invoice.get("last_payment_error") or {}).get("code", ""),
|
|
943
|
+
)
|
|
944
|
+
for invoice in reversed(state["invoices"])
|
|
945
|
+
)
|
|
946
|
+
return simulator_document(
|
|
947
|
+
DashboardView(
|
|
948
|
+
clock=self._format_time(state["clock"]),
|
|
949
|
+
api_base=self.options.public_url + "/v1",
|
|
950
|
+
webhook_url=self.options.webhook_url,
|
|
951
|
+
retry_policy=(
|
|
952
|
+
str(self.options.max_payment_attempts) + " payment attempts"
|
|
953
|
+
),
|
|
954
|
+
customer_count=len(state["customers"]),
|
|
955
|
+
subscription_count=len(state["subscriptions"]),
|
|
956
|
+
invoice_count=len(state["invoices"]),
|
|
957
|
+
delivery_mode=self.delivery.mode,
|
|
958
|
+
pending_count=sum(
|
|
959
|
+
event["delivery_state"] in {"pending", "failed"}
|
|
960
|
+
for event in state["events"]
|
|
961
|
+
),
|
|
962
|
+
subscriptions=tuple(subscriptions),
|
|
963
|
+
invoices=invoices,
|
|
964
|
+
events=tuple(events),
|
|
965
|
+
)
|
|
966
|
+
)
|
|
967
|
+
|
|
968
|
+
@staticmethod
|
|
969
|
+
def _format_time(timestamp: int) -> str:
|
|
970
|
+
return datetime.fromtimestamp(timestamp, UTC).strftime("%Y-%m-%d %H:%M UTC")
|
|
971
|
+
|
|
972
|
+
@classmethod
|
|
973
|
+
def _format_attempt(cls, attempt: Mapping[str, Any]) -> str:
|
|
974
|
+
result = cls._format_time(int(attempt["attempted_at"]))
|
|
975
|
+
result += " · " + str(attempt["signature_mode"])
|
|
976
|
+
if attempt["status"] is not None:
|
|
977
|
+
result += " · HTTP " + str(attempt["status"])
|
|
978
|
+
elif attempt["error"]:
|
|
979
|
+
result += " · " + str(attempt["error"])
|
|
980
|
+
return result
|
|
981
|
+
|
|
982
|
+
@staticmethod
|
|
983
|
+
def _document(title: str, body: str) -> str:
|
|
984
|
+
return f"""<!doctype html>
|
|
985
|
+
<html lang="en"><head><meta charset="utf-8">
|
|
986
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
987
|
+
<title>{escape(title)}</title><style>
|
|
988
|
+
body {{ background:#f6f9fc; color:#30313d; font:16px system-ui;
|
|
989
|
+
margin:0; padding:3rem 1rem; }}
|
|
990
|
+
main {{ background:white; border-radius:12px; box-shadow:0 7px 14px
|
|
991
|
+
rgba(50,50,93,.1); margin:auto; max-width:460px; padding:2rem; }}
|
|
992
|
+
h1 {{ margin:.25rem 0 1rem; }} .eyebrow {{ color:#635bff; font-weight:700; }}
|
|
993
|
+
label {{ display:block; margin:1rem 0; }} input {{ box-sizing:border-box;
|
|
994
|
+
display:block; font:inherit; margin-top:.35rem; padding:.7rem;
|
|
995
|
+
width:100%; }} button {{ background:#635bff; border:0;
|
|
996
|
+
border-radius:6px; color:white; cursor:pointer; font:inherit;
|
|
997
|
+
font-weight:700; padding:.8rem 1rem; width:100%; }}
|
|
998
|
+
a {{ color:#635bff; display:inline-block; margin-top:1rem; }}
|
|
999
|
+
.error {{ color:#b42318; }} .hint {{ color:#697386; font-size:.85rem; }}
|
|
1000
|
+
.price {{ font-size:1.35rem; font-weight:700; }}
|
|
1001
|
+
</style></head><body>{body}</body></html>"""
|
|
1002
|
+
|
|
1003
|
+
def _required(self, kind: str, object_id: str) -> dict[str, Any]:
|
|
1004
|
+
value = self.store.get(kind, object_id)
|
|
1005
|
+
if value is None:
|
|
1006
|
+
raise SimulatorHTTPError(
|
|
1007
|
+
404,
|
|
1008
|
+
"invalid_request_error",
|
|
1009
|
+
f"No such {kind}: '{object_id}'",
|
|
1010
|
+
)
|
|
1011
|
+
return value
|
|
1012
|
+
|
|
1013
|
+
def _object(self, kind: str, object_id: str):
|
|
1014
|
+
return self._json(self._required(kind, object_id))
|
|
1015
|
+
|
|
1016
|
+
def _list(self, kind: str) -> dict[str, Any]:
|
|
1017
|
+
return self._list_values(self.store.list(kind))
|
|
1018
|
+
|
|
1019
|
+
@staticmethod
|
|
1020
|
+
def _list_values(values: Iterable[Mapping[str, Any]]) -> dict[str, Any]:
|
|
1021
|
+
return {
|
|
1022
|
+
"object": "list",
|
|
1023
|
+
"data": [dict(value) for value in values],
|
|
1024
|
+
"has_more": False,
|
|
1025
|
+
"url": "/v1",
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
@staticmethod
|
|
1029
|
+
def _nested(form: Mapping[str, str], prefix: str) -> dict[str, str]:
|
|
1030
|
+
start = prefix + "["
|
|
1031
|
+
return {
|
|
1032
|
+
key.removeprefix(start).removesuffix("]"): value
|
|
1033
|
+
for key, value in form.items()
|
|
1034
|
+
if key.startswith(start)
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
@staticmethod
|
|
1038
|
+
def _boolean(value: str) -> bool:
|
|
1039
|
+
return value.lower() in {"1", "true", "yes", "on"}
|
|
1040
|
+
|
|
1041
|
+
@staticmethod
|
|
1042
|
+
def _query(environ) -> dict[str, str]:
|
|
1043
|
+
return {
|
|
1044
|
+
key: values[-1]
|
|
1045
|
+
for key, values in parse_qs(
|
|
1046
|
+
environ.get("QUERY_STRING", ""), keep_blank_values=True
|
|
1047
|
+
).items()
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
@staticmethod
|
|
1051
|
+
def _form(environ) -> dict[str, str]:
|
|
1052
|
+
size = int(environ.get("CONTENT_LENGTH") or 0)
|
|
1053
|
+
body = environ["wsgi.input"].read(size).decode()
|
|
1054
|
+
return {
|
|
1055
|
+
key: values[-1]
|
|
1056
|
+
for key, values in parse_qs(body, keep_blank_values=True).items()
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
@staticmethod
|
|
1060
|
+
def _json(value: Mapping[str, Any], status: int = 200):
|
|
1061
|
+
body = json.dumps(dict(value), separators=(",", ":")).encode()
|
|
1062
|
+
return (
|
|
1063
|
+
f"{status} {status_text(status)}",
|
|
1064
|
+
[
|
|
1065
|
+
("Content-Type", "application/json"),
|
|
1066
|
+
("Content-Length", str(len(body))),
|
|
1067
|
+
("Request-Id", "req_local"),
|
|
1068
|
+
],
|
|
1069
|
+
body,
|
|
1070
|
+
)
|
|
1071
|
+
|
|
1072
|
+
@classmethod
|
|
1073
|
+
def _html(cls, value: str, status: int = 200):
|
|
1074
|
+
body = value.encode()
|
|
1075
|
+
return (
|
|
1076
|
+
f"{status} {status_text(status)}",
|
|
1077
|
+
[
|
|
1078
|
+
("Content-Type", "text/html; charset=utf-8"),
|
|
1079
|
+
("Content-Length", str(len(body))),
|
|
1080
|
+
],
|
|
1081
|
+
body,
|
|
1082
|
+
)
|
|
1083
|
+
|
|
1084
|
+
@staticmethod
|
|
1085
|
+
def _redirect(url: str):
|
|
1086
|
+
return (
|
|
1087
|
+
"303 See Other",
|
|
1088
|
+
[("Location", url), ("Content-Length", "0")],
|
|
1089
|
+
b"",
|
|
1090
|
+
)
|
|
1091
|
+
|
|
1092
|
+
|
|
1093
|
+
class SimulatorServer:
|
|
1094
|
+
"""Start a simulator in a background thread for application tests."""
|
|
1095
|
+
|
|
1096
|
+
def __init__(
|
|
1097
|
+
self,
|
|
1098
|
+
*,
|
|
1099
|
+
host: str = "127.0.0.1",
|
|
1100
|
+
port: int = 0,
|
|
1101
|
+
database: str | Path = ":memory:",
|
|
1102
|
+
webhook_url: str = "",
|
|
1103
|
+
webhook_secret: str = "whsec_local",
|
|
1104
|
+
api_key: str = "sk_test_local",
|
|
1105
|
+
product_id: str = "prod_local_membership",
|
|
1106
|
+
price_id: str = "price_local_monthly",
|
|
1107
|
+
product_name: str = "Example membership",
|
|
1108
|
+
unit_amount: int = 500,
|
|
1109
|
+
currency: str = "usd",
|
|
1110
|
+
max_payment_attempts: int = 3,
|
|
1111
|
+
):
|
|
1112
|
+
self.store = SimulatorStore(database)
|
|
1113
|
+
self.development_app = Application(
|
|
1114
|
+
name="Local Stripe simulator",
|
|
1115
|
+
)
|
|
1116
|
+
self.httpd = Server(
|
|
1117
|
+
self.development_app,
|
|
1118
|
+
host=host,
|
|
1119
|
+
port=port,
|
|
1120
|
+
quiet=True,
|
|
1121
|
+
)
|
|
1122
|
+
public_url = self.httpd.url
|
|
1123
|
+
self.app = StripeSimulator(
|
|
1124
|
+
self.store,
|
|
1125
|
+
SimulatorOptions(
|
|
1126
|
+
public_url=public_url,
|
|
1127
|
+
webhook_url=webhook_url,
|
|
1128
|
+
webhook_secret=webhook_secret,
|
|
1129
|
+
api_key=api_key,
|
|
1130
|
+
product_id=product_id,
|
|
1131
|
+
price_id=price_id,
|
|
1132
|
+
product_name=product_name,
|
|
1133
|
+
unit_amount=unit_amount,
|
|
1134
|
+
currency=currency,
|
|
1135
|
+
max_payment_attempts=max_payment_attempts,
|
|
1136
|
+
),
|
|
1137
|
+
)
|
|
1138
|
+
self.development_app.mount_wsgi(self.app)
|
|
1139
|
+
|
|
1140
|
+
@property
|
|
1141
|
+
def url(self) -> str:
|
|
1142
|
+
return self.app.options.public_url
|
|
1143
|
+
|
|
1144
|
+
def start(self) -> Self:
|
|
1145
|
+
self.httpd.start()
|
|
1146
|
+
return self
|
|
1147
|
+
|
|
1148
|
+
def close(self) -> None:
|
|
1149
|
+
self.httpd.close()
|
|
1150
|
+
self.app.close()
|
|
1151
|
+
self.store.close()
|
|
1152
|
+
|
|
1153
|
+
def __enter__(self) -> Self:
|
|
1154
|
+
return self.start()
|
|
1155
|
+
|
|
1156
|
+
def __exit__(self, *args: object) -> None:
|
|
1157
|
+
self.close()
|
|
1158
|
+
|
|
1159
|
+
|
|
1160
|
+
def main(argv: list[str] | None = None) -> None:
|
|
1161
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
1162
|
+
parser.add_argument("--host", default="127.0.0.1")
|
|
1163
|
+
parser.add_argument("--port", type=int, default=12111)
|
|
1164
|
+
parser.add_argument("--database", default=".pyjs-stripe.sqlite3")
|
|
1165
|
+
parser.add_argument("--webhook-url", default="")
|
|
1166
|
+
parser.add_argument("--webhook-secret", default="whsec_local")
|
|
1167
|
+
parser.add_argument("--api-key", default="sk_test_local")
|
|
1168
|
+
parser.add_argument("--product-id", default="prod_local_membership")
|
|
1169
|
+
parser.add_argument("--price-id", default="price_local_monthly")
|
|
1170
|
+
parser.add_argument("--product-name", default="Example membership")
|
|
1171
|
+
parser.add_argument("--unit-amount", type=int, default=500)
|
|
1172
|
+
parser.add_argument("--currency", default="usd")
|
|
1173
|
+
parser.add_argument("--max-payment-attempts", type=int, default=3)
|
|
1174
|
+
parser.add_argument("--allow-remote", action="store_true")
|
|
1175
|
+
args = parser.parse_args(argv)
|
|
1176
|
+
store = SimulatorStore(args.database)
|
|
1177
|
+
development_app = Application(name="Local Stripe simulator")
|
|
1178
|
+
server = Server(
|
|
1179
|
+
development_app,
|
|
1180
|
+
host=args.host,
|
|
1181
|
+
port=args.port,
|
|
1182
|
+
allow_remote=args.allow_remote,
|
|
1183
|
+
)
|
|
1184
|
+
app = StripeSimulator(
|
|
1185
|
+
store,
|
|
1186
|
+
SimulatorOptions(
|
|
1187
|
+
public_url=server.url,
|
|
1188
|
+
webhook_url=args.webhook_url,
|
|
1189
|
+
webhook_secret=args.webhook_secret,
|
|
1190
|
+
api_key=args.api_key,
|
|
1191
|
+
product_id=args.product_id,
|
|
1192
|
+
price_id=args.price_id,
|
|
1193
|
+
product_name=args.product_name,
|
|
1194
|
+
unit_amount=args.unit_amount,
|
|
1195
|
+
currency=args.currency,
|
|
1196
|
+
max_payment_attempts=args.max_payment_attempts,
|
|
1197
|
+
),
|
|
1198
|
+
)
|
|
1199
|
+
development_app.mount_wsgi(app)
|
|
1200
|
+
if args.webhook_url:
|
|
1201
|
+
print(f"Forwarding signed webhooks to {args.webhook_url}", flush=True)
|
|
1202
|
+
try:
|
|
1203
|
+
server.serve_forever()
|
|
1204
|
+
except KeyboardInterrupt:
|
|
1205
|
+
pass
|
|
1206
|
+
finally:
|
|
1207
|
+
server.close()
|
|
1208
|
+
app.close()
|
|
1209
|
+
store.close()
|
|
1210
|
+
|
|
1211
|
+
|
|
1212
|
+
if __name__ == "__main__":
|
|
1213
|
+
main()
|