stableops 0.7.1__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.
stableops/webhooks.py ADDED
@@ -0,0 +1,378 @@
1
+ """Webhooks API and signature verification."""
2
+
3
+ import hashlib
4
+ import hmac
5
+ import time
6
+ from typing import Any, Dict, List, NamedTuple, Optional, Sequence, Tuple, Union
7
+
8
+ from stableops.http import AsyncHttpClient, HttpClient
9
+ from stableops.types import (
10
+ ReplayDeadLettersResult,
11
+ ReplayDeliveryResult,
12
+ WebhookDelivery,
13
+ WebhookDeliveryStatus,
14
+ WebhookEndpoint,
15
+ WebhookEventType,
16
+ )
17
+
18
+ # ---- Signature verification constants ----
19
+
20
+ SIGNATURE_HEADER = "x-product-signature"
21
+ EVENT_ID_HEADER = "x-event-id"
22
+ DELIVERY_ID_HEADER = "x-delivery-id"
23
+
24
+ DEFAULT_TOLERANCE_SECONDS = 300 # 5 minutes
25
+
26
+
27
+ class VerificationResult(NamedTuple):
28
+ """Result of webhook signature verification."""
29
+
30
+ valid: bool
31
+ reason: str
32
+
33
+
34
+ def verify_webhook_signature(
35
+ body: Union[str, bytes],
36
+ signature: Optional[str] = None,
37
+ timestamp: Optional[str] = None,
38
+ secret: Optional[str] = None,
39
+ tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
40
+ *,
41
+ header: Optional[str] = None,
42
+ secrets: Optional[Sequence[str]] = None,
43
+ now: Optional[int] = None,
44
+ ) -> VerificationResult:
45
+ """Verify webhook signature.
46
+
47
+ Args:
48
+ body: Raw request body (string)
49
+ header: X-Product-Signature header value (t=<unix_ts>,v1=<hmac>[,v1=<hmac>...])
50
+ secret: Webhook secret from dashboard
51
+ secrets: Optional rotation set of acceptable secrets
52
+ tolerance_seconds: Maximum age of webhook (default 300 seconds)
53
+ now: Current unix timestamp in seconds, primarily for tests
54
+ signature/timestamp: Backward-compatible legacy arguments
55
+
56
+ Returns:
57
+ VerificationResult with valid flag and reason
58
+
59
+ Example:
60
+ >>> result = verify_webhook_signature(
61
+ ... body=request.body,
62
+ ... header=request.headers["X-Product-Signature"],
63
+ ... secret="whsec_...",
64
+ ... )
65
+ >>> if not result.valid:
66
+ ... return {"error": result.reason}, 401
67
+ """
68
+ legacy_mode = header is None and (signature is not None or timestamp is not None)
69
+ if header is None:
70
+ if legacy_mode:
71
+ if not signature:
72
+ return VerificationResult(False, "missing_signature")
73
+ if not timestamp:
74
+ return VerificationResult(False, "missing_timestamp")
75
+ header = f"t={timestamp},v1={signature}"
76
+ else:
77
+ return VerificationResult(False, "missing_header")
78
+ if not header:
79
+ return VerificationResult(False, "missing_header")
80
+
81
+ valid_secrets = [value for value in (secrets or ([secret] if secret else [])) if value]
82
+ if not valid_secrets:
83
+ return VerificationResult(False, "missing_secret")
84
+
85
+ parsed = _parse_signature_header(header)
86
+ if parsed is None:
87
+ return VerificationResult(False, "invalid_timestamp" if legacy_mode else "invalid_format")
88
+ ts, signatures = parsed
89
+
90
+ current_time = int(time.time()) if now is None else now
91
+ if abs(current_time - ts) > tolerance_seconds:
92
+ return VerificationResult(False, "timestamp_too_old" if legacy_mode else "timestamp_expired")
93
+
94
+ raw_body = body.decode("utf-8") if isinstance(body, bytes) else body
95
+ signed_payload = f"{ts}.{raw_body}"
96
+ for candidate_secret in valid_secrets:
97
+ expected_signature = hmac.new(
98
+ candidate_secret.encode("utf-8"),
99
+ signed_payload.encode("utf-8"),
100
+ hashlib.sha256,
101
+ ).hexdigest()
102
+
103
+ for candidate_signature in signatures:
104
+ if hmac.compare_digest(candidate_signature, expected_signature):
105
+ return VerificationResult(True, "valid")
106
+
107
+ return VerificationResult(False, "invalid_signature")
108
+
109
+
110
+ def _parse_signature_header(header: str) -> Optional[Tuple[int, List[str]]]:
111
+ timestamp: Optional[int] = None
112
+ signatures: List[str] = []
113
+ for segment in header.split(","):
114
+ key, _, value = segment.strip().partition("=")
115
+ if not key or not value:
116
+ continue
117
+ if key == "t":
118
+ try:
119
+ timestamp = int(value)
120
+ except ValueError:
121
+ return None
122
+ elif key == "v1":
123
+ signatures.append(value)
124
+ if timestamp is None or not signatures:
125
+ return None
126
+ return timestamp, signatures
127
+
128
+
129
+ # ---- Webhook endpoints API ----
130
+
131
+ class WebhooksApi:
132
+ """Webhooks API (synchronous)."""
133
+
134
+ def __init__(self, http: HttpClient) -> None:
135
+ """Initialize Webhooks API."""
136
+ self.http = http
137
+
138
+ def create_endpoint(
139
+ self,
140
+ url: str,
141
+ description: Optional[str] = None,
142
+ enabled_events: Optional[List[WebhookEventType]] = None,
143
+ redact_metadata: Optional[bool] = None,
144
+ ) -> WebhookEndpoint:
145
+ """Create a webhook endpoint."""
146
+ body: Dict[str, Any] = {"url": url}
147
+ if description:
148
+ body["description"] = description
149
+ if enabled_events:
150
+ body["enabled_events"] = enabled_events
151
+ if redact_metadata is not None:
152
+ body["redact_metadata"] = redact_metadata
153
+
154
+ response = self.http.request(
155
+ method="POST",
156
+ path="/v1/webhook-endpoints",
157
+ body=body,
158
+ )
159
+ return WebhookEndpoint(**response)
160
+
161
+ def list_endpoints(self) -> List[WebhookEndpoint]:
162
+ """List webhook endpoints."""
163
+ response = self.http.request(
164
+ method="GET",
165
+ path="/v1/webhook-endpoints",
166
+ )
167
+ return [WebhookEndpoint(**item) for item in response["items"]]
168
+
169
+ def update_endpoint(
170
+ self,
171
+ endpoint_id: str,
172
+ description: Optional[str] = None,
173
+ enabled_events: Optional[List[WebhookEventType]] = None,
174
+ redact_metadata: Optional[bool] = None,
175
+ ) -> WebhookEndpoint:
176
+ """Update a webhook endpoint."""
177
+ body: Dict[str, Any] = {}
178
+ if description is not None:
179
+ body["description"] = description
180
+ if enabled_events is not None:
181
+ body["enabled_events"] = enabled_events
182
+ if redact_metadata is not None:
183
+ body["redact_metadata"] = redact_metadata
184
+
185
+ response = self.http.request(
186
+ method="PATCH",
187
+ path=f"/v1/webhook-endpoints/{endpoint_id}",
188
+ body=body,
189
+ )
190
+ return WebhookEndpoint(**response)
191
+
192
+ def rotate_secret(self, endpoint_id: str) -> WebhookEndpoint:
193
+ """Rotate webhook endpoint secret."""
194
+ response = self.http.request(
195
+ method="POST",
196
+ path=f"/v1/webhook-endpoints/{endpoint_id}/rotate-secret",
197
+ )
198
+ return WebhookEndpoint(**response)
199
+
200
+ def replay(self, endpoint_id: str, event_id: str) -> ReplayDeliveryResult:
201
+ """Replay an event to a specific endpoint (creates a fresh delivery)."""
202
+ response = self.http.request(
203
+ method="POST",
204
+ path=f"/v1/webhook-endpoints/{endpoint_id}/replay",
205
+ body={"event_id": event_id},
206
+ )
207
+ return ReplayDeliveryResult(**response)
208
+
209
+ def list_deliveries(
210
+ self,
211
+ status: Optional[WebhookDeliveryStatus] = None,
212
+ endpoint_id: Optional[str] = None,
213
+ payment_order_id: Optional[str] = None,
214
+ limit: Optional[int] = None,
215
+ ) -> List[WebhookDelivery]:
216
+ """List webhook deliveries."""
217
+ response = self.http.request(
218
+ method="GET",
219
+ path="/v1/webhook-deliveries",
220
+ query={
221
+ "status": status,
222
+ "endpoint_id": endpoint_id,
223
+ "payment_order_id": payment_order_id,
224
+ "limit": limit,
225
+ },
226
+ )
227
+ return [WebhookDelivery(**item) for item in response["items"]]
228
+
229
+ def replay_delivery(self, delivery_id: str) -> ReplayDeliveryResult:
230
+ """Replay a single delivery by its ID."""
231
+ response = self.http.request(
232
+ method="POST",
233
+ path=f"/v1/webhook-deliveries/{delivery_id}/replay",
234
+ )
235
+ return ReplayDeliveryResult(**response)
236
+
237
+ def replay_dead_letters(
238
+ self,
239
+ endpoint_id: Optional[str] = None,
240
+ limit: Optional[int] = None,
241
+ ) -> ReplayDeadLettersResult:
242
+ """Batch replay dead-lettered deliveries."""
243
+ body: Dict[str, Any] = {}
244
+ if endpoint_id is not None:
245
+ body["endpoint_id"] = endpoint_id
246
+ if limit is not None:
247
+ body["limit"] = limit
248
+ response = self.http.request(
249
+ method="POST",
250
+ path="/v1/webhook-deliveries/replay-dead-letters",
251
+ body=body,
252
+ )
253
+ return ReplayDeadLettersResult(**response)
254
+
255
+
256
+ class AsyncWebhooksApi:
257
+ """Webhooks API (asynchronous)."""
258
+
259
+ def __init__(self, http: AsyncHttpClient) -> None:
260
+ """Initialize async Webhooks API."""
261
+ self.http = http
262
+
263
+ async def create_endpoint(
264
+ self,
265
+ url: str,
266
+ description: Optional[str] = None,
267
+ enabled_events: Optional[List[WebhookEventType]] = None,
268
+ redact_metadata: Optional[bool] = None,
269
+ ) -> WebhookEndpoint:
270
+ """Create a webhook endpoint (async)."""
271
+ body: Dict[str, Any] = {"url": url}
272
+ if description:
273
+ body["description"] = description
274
+ if enabled_events:
275
+ body["enabled_events"] = enabled_events
276
+ if redact_metadata is not None:
277
+ body["redact_metadata"] = redact_metadata
278
+
279
+ response = await self.http.request(
280
+ method="POST",
281
+ path="/v1/webhook-endpoints",
282
+ body=body,
283
+ )
284
+ return WebhookEndpoint(**response)
285
+
286
+ async def list_endpoints(self) -> List[WebhookEndpoint]:
287
+ """List webhook endpoints (async)."""
288
+ response = await self.http.request(
289
+ method="GET",
290
+ path="/v1/webhook-endpoints",
291
+ )
292
+ return [WebhookEndpoint(**item) for item in response["items"]]
293
+
294
+ async def update_endpoint(
295
+ self,
296
+ endpoint_id: str,
297
+ description: Optional[str] = None,
298
+ enabled_events: Optional[List[WebhookEventType]] = None,
299
+ redact_metadata: Optional[bool] = None,
300
+ ) -> WebhookEndpoint:
301
+ """Update a webhook endpoint (async)."""
302
+ body: Dict[str, Any] = {}
303
+ if description is not None:
304
+ body["description"] = description
305
+ if enabled_events is not None:
306
+ body["enabled_events"] = enabled_events
307
+ if redact_metadata is not None:
308
+ body["redact_metadata"] = redact_metadata
309
+
310
+ response = await self.http.request(
311
+ method="PATCH",
312
+ path=f"/v1/webhook-endpoints/{endpoint_id}",
313
+ body=body,
314
+ )
315
+ return WebhookEndpoint(**response)
316
+
317
+ async def rotate_secret(self, endpoint_id: str) -> WebhookEndpoint:
318
+ """Rotate webhook endpoint secret (async)."""
319
+ response = await self.http.request(
320
+ method="POST",
321
+ path=f"/v1/webhook-endpoints/{endpoint_id}/rotate-secret",
322
+ )
323
+ return WebhookEndpoint(**response)
324
+
325
+ async def replay(self, endpoint_id: str, event_id: str) -> ReplayDeliveryResult:
326
+ """Replay an event to a specific endpoint (async)."""
327
+ response = await self.http.request(
328
+ method="POST",
329
+ path=f"/v1/webhook-endpoints/{endpoint_id}/replay",
330
+ body={"event_id": event_id},
331
+ )
332
+ return ReplayDeliveryResult(**response)
333
+
334
+ async def list_deliveries(
335
+ self,
336
+ status: Optional[WebhookDeliveryStatus] = None,
337
+ endpoint_id: Optional[str] = None,
338
+ payment_order_id: Optional[str] = None,
339
+ limit: Optional[int] = None,
340
+ ) -> List[WebhookDelivery]:
341
+ """List webhook deliveries (async)."""
342
+ response = await self.http.request(
343
+ method="GET",
344
+ path="/v1/webhook-deliveries",
345
+ query={
346
+ "status": status,
347
+ "endpoint_id": endpoint_id,
348
+ "payment_order_id": payment_order_id,
349
+ "limit": limit,
350
+ },
351
+ )
352
+ return [WebhookDelivery(**item) for item in response["items"]]
353
+
354
+ async def replay_delivery(self, delivery_id: str) -> ReplayDeliveryResult:
355
+ """Replay a single delivery by its ID (async)."""
356
+ response = await self.http.request(
357
+ method="POST",
358
+ path=f"/v1/webhook-deliveries/{delivery_id}/replay",
359
+ )
360
+ return ReplayDeliveryResult(**response)
361
+
362
+ async def replay_dead_letters(
363
+ self,
364
+ endpoint_id: Optional[str] = None,
365
+ limit: Optional[int] = None,
366
+ ) -> ReplayDeadLettersResult:
367
+ """Batch replay dead-lettered deliveries (async)."""
368
+ body: Dict[str, Any] = {}
369
+ if endpoint_id is not None:
370
+ body["endpoint_id"] = endpoint_id
371
+ if limit is not None:
372
+ body["limit"] = limit
373
+ response = await self.http.request(
374
+ method="POST",
375
+ path="/v1/webhook-deliveries/replay-dead-letters",
376
+ body=body,
377
+ )
378
+ return ReplayDeadLettersResult(**response)
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.4
2
+ Name: stableops
3
+ Version: 0.7.1
4
+ Summary: Official Python SDK for StableOps - Stablecoin payment infrastructure
5
+ Project-URL: Homepage, https://stableops.dev
6
+ Project-URL: Documentation, https://docs.stableops.dev
7
+ Project-URL: Repository, https://github.com/stableops/stableops
8
+ Project-URL: Bug Tracker, https://github.com/stableops/stableops/issues
9
+ Author-email: StableOps <hello@stableops.dev>
10
+ License: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: blockchain,crypto,payments,stablecoin,stableops,usdc,usdt
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Office/Business :: Financial
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Requires-Python: >=3.8
25
+ Requires-Dist: httpx>=0.24.0
26
+ Requires-Dist: pydantic>=2.0.0
27
+ Requires-Dist: typing-extensions>=4.5.0; python_version < '3.11'
28
+ Provides-Extra: dev
29
+ Requires-Dist: mypy>=1.0.0; extra == 'dev'
30
+ Requires-Dist: pylint>=3.0.0; extra == 'dev'
31
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
32
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
33
+ Requires-Dist: pytest>=7.0.0; extra == 'dev'
34
+ Requires-Dist: respx>=0.20.0; extra == 'dev'
35
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # StableOps Python SDK
39
+
40
+ [![PyPI version](https://img.shields.io/pypi/v/stableops)](https://pypi.org/project/stableops/) [![PyPI downloads](https://img.shields.io/pypi/dm/stableops)](https://pypi.org/project/stableops/) [![License](https://img.shields.io/pypi/l/stableops)](./LICENSE) [![Python](https://img.shields.io/badge/Python-%3E%3D3.8-3776AB)](https://www.python.org)
41
+
42
+ [中文文档](./README.zh-CN.md)
43
+
44
+ StableOps turns on-chain stablecoin transfers into familiar payment primitives:
45
+ payment orders, deterministic status transitions, signed webhooks, retries, and
46
+ confirmation tracking. StableOps watches supported chains, matches transfers,
47
+ tracks confirmations, checks reorgs, and delivers webhook events to your app.
48
+
49
+ This SDK is for server-side Python applications that create payment orders and
50
+ checkout sessions, manage webhook endpoints, and verify webhook signatures.
51
+
52
+ ## Features
53
+
54
+ - Type-safe client (Pydantic v2 models) for payment orders, checkout sessions, and webhooks.
55
+ - Sync (`StableOps`) and async (`AsyncStableOps`) clients with an identical API.
56
+ - Built-in request retries and explicit idempotency for write operations.
57
+ - Constant-time webhook signature verification.
58
+
59
+ ## Requirements
60
+
61
+ - Python 3.8 or newer.
62
+ - A StableOps API key.
63
+ - A server-side environment. Do not expose your API key in browser code.
64
+
65
+ ## Installation
66
+
67
+ ```bash
68
+ pip install stableops
69
+ ```
70
+
71
+ ## Quick Start
72
+
73
+ ```python
74
+ import os
75
+
76
+ from stableops import StableOps
77
+
78
+ client = StableOps(api_key=os.environ["STABLEOPS_API_KEY"])
79
+
80
+ order = client.payment_orders.create(
81
+ merchant_order_id="order_123",
82
+ amount="49.00",
83
+ accepted_assets=[
84
+ {"chain": "base", "asset": "USDC"},
85
+ {"chain": "tron", "asset": "USDT"},
86
+ ],
87
+ expires_at="2026-12-31T23:59:59Z",
88
+ )
89
+
90
+ print(order.payment_instructions)
91
+ ```
92
+
93
+ The environment (sandbox / live) is determined by the API key prefix
94
+ (`sk_sandbox_…` / `sk_live_…`). Return only the order id, amount, and
95
+ `payment_instructions` to your frontend; the API key stays on your server.
96
+
97
+ ## Documentation
98
+
99
+ For complete guides, configuration, checkout sessions, webhook verification, and
100
+ the full API reference, see the official documentation:
101
+
102
+ - English docs: https://stableops.dev/en/docs/sdk/python-api-sdk
103
+ - Chinese docs: https://stableops.dev/zh/docs/sdk/python-api-sdk
104
+
105
+ ## Supported Chains and Assets
106
+
107
+ - Chains: Ethereum, Base, Arbitrum, Polygon, Optimism, BSC, TRON, Solana, and supported testnets.
108
+ - Assets: USDC and USDT.
109
+
110
+ ## License
111
+
112
+ This SDK is licensed under `Apache-2.0`. See [LICENSE](./LICENSE).
@@ -0,0 +1,13 @@
1
+ stableops/__init__.py,sha256=u1VR2vAk20B6COmv9EOSCfNOut8WKICroUovmsJ6ajM,2089
2
+ stableops/addresses.py,sha256=gPgI06x4uP9Ckv3tsYGFbGEwgB5HXryxXFP2PGqvy6g,7304
3
+ stableops/checkout_sessions.py,sha256=VCysaOOuj-7grpzPr9bqWBNpNEA2QUFz4qfpl-RmD8I,5832
4
+ stableops/client.py,sha256=V9wgRxNgHonqduZevtaXZjWD7p1VCAqX7ZY_mXLITKg,4809
5
+ stableops/errors.py,sha256=4HsB6Y1JN9zrvq5uXuVjZxpK4i2PiOYz_81cVb2O6Eg,1155
6
+ stableops/http.py,sha256=j5_lV__K9ttyWEsSkNkzV0ImKfUxfVaRESPCcCNDdbE,18505
7
+ stableops/payment_orders.py,sha256=iq6C9cbHkD9agIoDE8L8DpZnd0wrXgN6RqPVAwPFqh0,7470
8
+ stableops/types.py,sha256=jLy_Nu6jNKgcvHG-RLl1zOnw72VqHNSxJ6KiY5oovG8,6935
9
+ stableops/webhooks.py,sha256=AtI3-0NfQkFhFjP2YfkgO8GD0LtMVWrtv6EZ_0LMABg,13004
10
+ stableops-0.7.1.dist-info/METADATA,sha256=xf3GpyAdQdcYto_3QojIaC-Xz5oxYHikAwYR2E_LNsE,4176
11
+ stableops-0.7.1.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
12
+ stableops-0.7.1.dist-info/licenses/LICENSE,sha256=9UvCRVWzRHKobc7nTnRGxBq6N9DFjB8MGPydV4Bqx9k,10413
13
+ stableops-0.7.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any