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.
@@ -0,0 +1 @@
1
+ """Official integrations maintained by the PyJS project."""
@@ -0,0 +1,15 @@
1
+ """Backend-neutral Stripe interfaces for PyJS applications."""
2
+
3
+ from .server import (
4
+ CheckoutRequest,
5
+ HostedSession,
6
+ StripeGateway,
7
+ WebhookEvent,
8
+ )
9
+
10
+ __all__ = [
11
+ "CheckoutRequest",
12
+ "HostedSession",
13
+ "StripeGateway",
14
+ "WebhookEvent",
15
+ ]
@@ -0,0 +1,193 @@
1
+ """Typed declarations for Stripe.js and its current payment widgets."""
2
+
3
+ from collections.abc import Awaitable, Callable
4
+ from typing import Final, Literal, NotRequired, TypedDict, overload
5
+
6
+ from pyjs import JS, js
7
+ from pyjs.web.dom import Element
8
+
9
+
10
+ class StripeConstructorOptions(TypedDict):
11
+ stripeAccount: NotRequired[str]
12
+ apiVersion: NotRequired[str]
13
+ locale: NotRequired[str]
14
+ betas: NotRequired[list[str]]
15
+
16
+
17
+ class ElementsOptions(TypedDict):
18
+ clientSecret: NotRequired[str]
19
+ mode: NotRequired[Literal["payment", "setup", "subscription"]]
20
+ amount: NotRequired[int]
21
+ currency: NotRequired[str]
22
+ locale: NotRequired[str]
23
+ appearance: NotRequired[object]
24
+
25
+
26
+ class ElementOptions(TypedDict):
27
+ mode: NotRequired[Literal["billing", "shipping"]]
28
+ layout: NotRequired[str]
29
+ defaultValues: NotRequired[object]
30
+ fields: NotRequired[object]
31
+ wallets: NotRequired[object]
32
+ terms: NotRequired[object]
33
+
34
+
35
+ class ConfirmParams(TypedDict):
36
+ return_url: NotRequired[str]
37
+ receipt_email: NotRequired[str]
38
+
39
+
40
+ class ConfirmPaymentOptions(TypedDict):
41
+ elements: NotRequired[StripeElements]
42
+ clientSecret: NotRequired[str]
43
+ confirmParams: NotRequired[ConfirmParams]
44
+ redirect: NotRequired[Literal["always", "if_required"]]
45
+
46
+
47
+ class EmbeddedCheckoutOptions(TypedDict):
48
+ clientSecret: NotRequired[str]
49
+ fetchClientSecret: NotRequired[Callable[[], Awaitable[str]]]
50
+ onComplete: NotRequired[Callable[[], None]]
51
+
52
+
53
+ class StripeError(TypedDict):
54
+ type: str
55
+ message: str
56
+ code: NotRequired[str]
57
+ decline_code: NotRequired[str]
58
+
59
+
60
+ class PaymentResult(TypedDict):
61
+ error: NotRequired[StripeError]
62
+ paymentIntent: NotRequired[object]
63
+
64
+
65
+ class ElementChangeEvent(TypedDict):
66
+ elementType: str
67
+ empty: bool
68
+ complete: bool
69
+ error: NotRequired[StripeError]
70
+
71
+
72
+ ElementType = Literal[
73
+ "address",
74
+ "expressCheckout",
75
+ "linkAuthentication",
76
+ "payment",
77
+ "paymentMethodMessaging",
78
+ ]
79
+
80
+
81
+ @js.native
82
+ class StripeElement:
83
+ def mount(self, target: str | Element) -> None: ...
84
+
85
+ def unmount(self) -> None: ...
86
+
87
+ def destroy(self) -> None: ...
88
+
89
+ def focus(self) -> None: ...
90
+
91
+ def blur(self) -> None: ...
92
+
93
+ def clear(self) -> None: ...
94
+
95
+ def on(
96
+ self,
97
+ event_type: Literal["change", "ready", "focus", "blur", "escape"],
98
+ handler: Callable[[ElementChangeEvent], None],
99
+ ) -> None: ...
100
+
101
+
102
+ @js.native
103
+ class PaymentElement(StripeElement): ...
104
+
105
+
106
+ @js.native
107
+ class AddressElement(StripeElement): ...
108
+
109
+
110
+ @js.native
111
+ class ExpressCheckoutElement(StripeElement): ...
112
+
113
+
114
+ @js.native
115
+ class LinkAuthenticationElement(StripeElement): ...
116
+
117
+
118
+ @js.native
119
+ class StripeElements:
120
+ @overload
121
+ def create(
122
+ self,
123
+ element_type: Literal["payment"],
124
+ options: ElementOptions,
125
+ ) -> PaymentElement: ...
126
+
127
+ @overload
128
+ def create(
129
+ self,
130
+ element_type: Literal["address"],
131
+ options: ElementOptions,
132
+ ) -> AddressElement: ...
133
+
134
+ @overload
135
+ def create(
136
+ self,
137
+ element_type: Literal["expressCheckout"],
138
+ options: ElementOptions,
139
+ ) -> ExpressCheckoutElement: ...
140
+
141
+ @overload
142
+ def create(
143
+ self,
144
+ element_type: Literal["linkAuthentication"],
145
+ options: ElementOptions,
146
+ ) -> LinkAuthenticationElement: ...
147
+
148
+ def create(
149
+ self,
150
+ element_type: ElementType,
151
+ options: ElementOptions,
152
+ ) -> StripeElement: ...
153
+
154
+ async def update(self, options: ElementsOptions) -> None: ...
155
+
156
+ async def submit(self) -> object: ...
157
+
158
+ async def fetchUpdates(self) -> object: ...
159
+
160
+
161
+ @js.native
162
+ class EmbeddedCheckout:
163
+ def mount(self, target: str | Element) -> None: ...
164
+
165
+ def unmount(self) -> None: ...
166
+
167
+ def destroy(self) -> None: ...
168
+
169
+
170
+ @js.native
171
+ class StripeClient:
172
+ def elements(self, options: ElementsOptions) -> StripeElements: ...
173
+
174
+ async def confirmPayment(
175
+ self,
176
+ options: ConfirmPaymentOptions,
177
+ ) -> PaymentResult: ...
178
+
179
+ async def initEmbeddedCheckout(
180
+ self,
181
+ options: EmbeddedCheckoutOptions,
182
+ ) -> EmbeddedCheckout: ...
183
+
184
+
185
+ @js.native
186
+ def Stripe(
187
+ publishable_key: str,
188
+ options: StripeConstructorOptions | None = None,
189
+ ) -> StripeClient: ...
190
+
191
+
192
+ STRIPE_JS_URL: Final[JS[str]] = "https://js.stripe.com/v3/"
193
+ PRICING_TABLE_JS_URL: Final[JS[str]] = "https://js.stripe.com/v3/pricing-table.js"
@@ -0,0 +1,184 @@
1
+ """Framework-neutral server adapter for the official Stripe Python SDK."""
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass, field
5
+ from typing import Any, Literal, Protocol
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class CheckoutRequest:
10
+ """Values needed to create a hosted Stripe Checkout subscription."""
11
+
12
+ price_id: str
13
+ success_url: str
14
+ cancel_url: str
15
+ client_reference_id: str = ""
16
+ customer_id: str = ""
17
+ customer_email: str = ""
18
+ quantity: int = 1
19
+ metadata: Mapping[str, str] = field(default_factory=dict)
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class PaymentRequest:
24
+ """Values needed to create a one-time hosted Stripe Checkout payment."""
25
+
26
+ amount_cents: int
27
+ name: str
28
+ success_url: str
29
+ cancel_url: str
30
+ currency: str = "usd"
31
+ client_reference_id: str = ""
32
+ customer_email: str = ""
33
+ idempotency_key: str = ""
34
+ metadata: Mapping[str, str] = field(default_factory=dict)
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class HostedSession:
39
+ id: str
40
+ kind: Literal["checkout", "portal"]
41
+ url: str
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class WebhookEvent:
46
+ id: str
47
+ type: str
48
+ data: object
49
+ created: int = 0
50
+
51
+
52
+ class StripeClientProtocol(Protocol):
53
+ v1: Any
54
+
55
+ def construct_event(
56
+ self,
57
+ payload: bytes | str,
58
+ signature: str,
59
+ secret: str,
60
+ ) -> Any: ...
61
+
62
+
63
+ def _new_client(
64
+ secret_key: str,
65
+ max_network_retries: int,
66
+ api_base: str,
67
+ ) -> StripeClientProtocol:
68
+ try:
69
+ from stripe import StripeClient
70
+ except ImportError as error:
71
+ raise RuntimeError(
72
+ "Stripe server support requires `pyjs-extras[stripe]`."
73
+ ) from error
74
+ options: dict[str, object] = {
75
+ "max_network_retries": max_network_retries,
76
+ }
77
+ if api_base:
78
+ options["base_addresses"] = {"api": api_base.rstrip("/")}
79
+ return StripeClient(secret_key, **options)
80
+
81
+
82
+ class StripeGateway:
83
+ """Small stable facade over the generated Stripe SDK service tree."""
84
+
85
+ def __init__(
86
+ self,
87
+ secret_key: str,
88
+ *,
89
+ webhook_secret: str = "",
90
+ api_base: str = "",
91
+ max_network_retries: int = 2,
92
+ client: StripeClientProtocol | None = None,
93
+ ):
94
+ if not secret_key and client is None:
95
+ raise ValueError("a Stripe secret key is required")
96
+ self.client = client or _new_client(
97
+ secret_key,
98
+ max_network_retries,
99
+ api_base,
100
+ )
101
+ self.webhook_secret = webhook_secret
102
+
103
+ def create_checkout(self, request: CheckoutRequest) -> HostedSession:
104
+ params: dict[str, object] = {
105
+ "mode": "subscription",
106
+ "line_items": [{"price": request.price_id, "quantity": request.quantity}],
107
+ "success_url": request.success_url,
108
+ "cancel_url": request.cancel_url,
109
+ }
110
+ if request.client_reference_id:
111
+ params["client_reference_id"] = request.client_reference_id
112
+ if request.customer_id:
113
+ params["customer"] = request.customer_id
114
+ elif request.customer_email:
115
+ params["customer_email"] = request.customer_email
116
+ if request.metadata:
117
+ params["metadata"] = dict(request.metadata)
118
+ params["subscription_data"] = {"metadata": dict(request.metadata)}
119
+ session = self.client.v1.checkout.sessions.create(params)
120
+ return HostedSession(session.id, "checkout", session.url)
121
+
122
+ def create_payment(self, request: PaymentRequest) -> HostedSession:
123
+ if request.amount_cents < 1:
124
+ raise ValueError("a positive payment amount is required")
125
+ params: dict[str, object] = {
126
+ "mode": "payment",
127
+ "line_items": [
128
+ {
129
+ "price_data": {
130
+ "currency": request.currency,
131
+ "product_data": {"name": request.name},
132
+ "unit_amount": request.amount_cents,
133
+ },
134
+ "quantity": 1,
135
+ }
136
+ ],
137
+ "success_url": request.success_url,
138
+ "cancel_url": request.cancel_url,
139
+ }
140
+ if request.client_reference_id:
141
+ params["client_reference_id"] = request.client_reference_id
142
+ if request.customer_email:
143
+ params["customer_email"] = request.customer_email
144
+ if request.metadata:
145
+ params["metadata"] = dict(request.metadata)
146
+ if request.idempotency_key:
147
+ session = self.client.v1.checkout.sessions.create(
148
+ params,
149
+ options={"idempotency_key": request.idempotency_key},
150
+ )
151
+ else:
152
+ session = self.client.v1.checkout.sessions.create(params)
153
+ return HostedSession(session.id, "checkout", session.url)
154
+
155
+ def create_portal(
156
+ self,
157
+ customer_id: str,
158
+ return_url: str,
159
+ ) -> HostedSession:
160
+ if not customer_id:
161
+ raise ValueError("a Stripe customer ID is required")
162
+ session = self.client.v1.billing_portal.sessions.create(
163
+ {"customer": customer_id, "return_url": return_url}
164
+ )
165
+ return HostedSession(session.id, "portal", session.url)
166
+
167
+ def construct_event(
168
+ self,
169
+ payload: bytes | str,
170
+ signature: str,
171
+ ) -> WebhookEvent:
172
+ if not self.webhook_secret:
173
+ raise ValueError("a Stripe webhook secret is required")
174
+ event = self.client.construct_event(
175
+ payload,
176
+ signature,
177
+ self.webhook_secret,
178
+ )
179
+ return WebhookEvent(
180
+ event.id,
181
+ event.type,
182
+ event.data.object,
183
+ int(getattr(event, "created", 0)),
184
+ )