stablevoy 1.0.0__tar.gz

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.
Files changed (55) hide show
  1. stablevoy-1.0.0/.gitignore +9 -0
  2. stablevoy-1.0.0/CHANGELOG.md +7 -0
  3. stablevoy-1.0.0/LICENSE +21 -0
  4. stablevoy-1.0.0/PKG-INFO +114 -0
  5. stablevoy-1.0.0/README.md +93 -0
  6. stablevoy-1.0.0/pyproject.toml +57 -0
  7. stablevoy-1.0.0/src/stablevoy/__init__.py +63 -0
  8. stablevoy-1.0.0/src/stablevoy/_version.py +1 -0
  9. stablevoy-1.0.0/src/stablevoy/client.py +57 -0
  10. stablevoy-1.0.0/src/stablevoy/errors/__init__.py +0 -0
  11. stablevoy-1.0.0/src/stablevoy/errors/api_error.py +29 -0
  12. stablevoy-1.0.0/src/stablevoy/errors/authentication_error.py +5 -0
  13. stablevoy-1.0.0/src/stablevoy/errors/configuration_error.py +5 -0
  14. stablevoy-1.0.0/src/stablevoy/errors/maintenance_error.py +5 -0
  15. stablevoy-1.0.0/src/stablevoy/errors/not_found_error.py +5 -0
  16. stablevoy-1.0.0/src/stablevoy/errors/problem_issue.py +9 -0
  17. stablevoy-1.0.0/src/stablevoy/errors/rate_limited_error.py +5 -0
  18. stablevoy-1.0.0/src/stablevoy/errors/signature_error.py +5 -0
  19. stablevoy-1.0.0/src/stablevoy/errors/stablevoy_error.py +2 -0
  20. stablevoy-1.0.0/src/stablevoy/errors/transport_error.py +5 -0
  21. stablevoy-1.0.0/src/stablevoy/errors/unexpected_response_error.py +5 -0
  22. stablevoy-1.0.0/src/stablevoy/errors/validation_error.py +5 -0
  23. stablevoy-1.0.0/src/stablevoy/http/__init__.py +0 -0
  24. stablevoy-1.0.0/src/stablevoy/http/error_factory.py +59 -0
  25. stablevoy-1.0.0/src/stablevoy/http/http_answer.py +9 -0
  26. stablevoy-1.0.0/src/stablevoy/http/no_redirects.py +12 -0
  27. stablevoy-1.0.0/src/stablevoy/http/opener.py +10 -0
  28. stablevoy-1.0.0/src/stablevoy/http/retry_policy.py +26 -0
  29. stablevoy-1.0.0/src/stablevoy/http/transport.py +10 -0
  30. stablevoy-1.0.0/src/stablevoy/http/urllib_opener.py +22 -0
  31. stablevoy-1.0.0/src/stablevoy/http/urllib_transport.py +129 -0
  32. stablevoy-1.0.0/src/stablevoy/model/__init__.py +0 -0
  33. stablevoy-1.0.0/src/stablevoy/model/created_invoice.py +20 -0
  34. stablevoy-1.0.0/src/stablevoy/model/deposit_address.py +19 -0
  35. stablevoy-1.0.0/src/stablevoy/model/fields.py +100 -0
  36. stablevoy-1.0.0/src/stablevoy/model/invoice.py +52 -0
  37. stablevoy-1.0.0/src/stablevoy/model/invoice_page.py +18 -0
  38. stablevoy-1.0.0/src/stablevoy/model/invoice_status.py +22 -0
  39. stablevoy-1.0.0/src/stablevoy/model/limits.py +17 -0
  40. stablevoy-1.0.0/src/stablevoy/model/network.py +35 -0
  41. stablevoy-1.0.0/src/stablevoy/model/payment.py +35 -0
  42. stablevoy-1.0.0/src/stablevoy/model/pricing.py +18 -0
  43. stablevoy-1.0.0/src/stablevoy/model/store.py +37 -0
  44. stablevoy-1.0.0/src/stablevoy/model/token.py +18 -0
  45. stablevoy-1.0.0/src/stablevoy/py.typed +0 -0
  46. stablevoy-1.0.0/src/stablevoy/resources/__init__.py +0 -0
  47. stablevoy-1.0.0/src/stablevoy/resources/invoices.py +67 -0
  48. stablevoy-1.0.0/src/stablevoy/resources/platform.py +25 -0
  49. stablevoy-1.0.0/src/stablevoy/resources/stores.py +12 -0
  50. stablevoy-1.0.0/src/stablevoy/time/__init__.py +0 -0
  51. stablevoy-1.0.0/src/stablevoy/time/clock.py +7 -0
  52. stablevoy-1.0.0/src/stablevoy/time/system_clock.py +6 -0
  53. stablevoy-1.0.0/src/stablevoy/webhook/__init__.py +0 -0
  54. stablevoy-1.0.0/src/stablevoy/webhook/webhook_event.py +28 -0
  55. stablevoy-1.0.0/src/stablevoy/webhook/webhook_verifier.py +62 -0
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .coverage
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ First release: invoices (create with an idempotency key, read, list and walk all pages), the store of the API key, limits, pricing and networks, typed errors with retries where a repeat is safe, and webhook signature verification. No dependencies, Python 3.11 or newer, fully typed.
6
+
7
+ Security: the base URL must be https (http only for localhost) and only a host, invoice ids must be UUIDs, redirects are never followed and every request has a timeout, so the API key cannot leak or reach another path.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stablevoy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.5
2
+ Name: stablevoy
3
+ Version: 1.0.0
4
+ Summary: Python client for the Stablevoy API: non-custodial USDT and USDC payments, invoices and signed webhooks.
5
+ Project-URL: Homepage, https://stablevoy.com
6
+ Project-URL: Documentation, https://stablevoy.com/docs/
7
+ Project-URL: Source, https://github.com/stablevoy/stablevoy-python
8
+ Project-URL: Issues, https://github.com/stablevoy/stablevoy-python/issues
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: crypto payments,payment gateway,stablecoin,stablevoy,tether,trc20,tron,usdc,usdt,webhooks
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Office/Business :: Financial
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.11
20
+ Description-Content-Type: text/markdown
21
+
22
+ # Stablevoy Python SDK
23
+
24
+ [![CI](https://github.com/stablevoy/stablevoy-python/actions/workflows/ci.yml/badge.svg)](https://github.com/stablevoy/stablevoy-python/actions/workflows/ci.yml)
25
+ [![PyPI](https://img.shields.io/pypi/v/stablevoy)](https://pypi.org/project/stablevoy/)
26
+
27
+ Python client for [Stablevoy](https://stablevoy.com), the non-custodial gateway for USDT and USDC payments. Customers pay on chain and the money goes straight to your own wallet: USDC and USDT on Base, Arbitrum, Optimism, Avalanche, Polygon and BNB Chain, and USDT (TRC20) on Tron with no fee.
28
+
29
+ The library creates invoices, reads them, and verifies the signed webhooks that tell your shop an order is paid. It has no dependencies, needs Python 3.11 or newer and is fully typed.
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ pip install stablevoy
35
+ ```
36
+
37
+ ## Create an invoice and send the buyer to pay
38
+
39
+ Create an API key for your store in the [Stablevoy dashboard](https://stablevoy.com/app/).
40
+
41
+ ```python
42
+ import os
43
+
44
+ from stablevoy import Stablevoy
45
+
46
+ stablevoy = Stablevoy.create(os.environ["STABLEVOY_API_KEY"])
47
+
48
+ created = stablevoy.invoices.create(
49
+ 2599, # $25.99 in US cents
50
+ external_reference="order-1042", # your order id, sent back in webhooks
51
+ return_url="https://shop.example/orders/1042",
52
+ idempotency_key="order-1042", # a retry returns the same invoice, never a second one
53
+ )
54
+
55
+ # Send the buyer to created.checkout_url
56
+ ```
57
+
58
+ Read an invoice with `stablevoy.invoices.get(invoice_id)`, or walk them all:
59
+
60
+ ```python
61
+ for invoice in stablevoy.invoices.all(status="paid"):
62
+ print(invoice.external_reference, invoice.amount_usd_cents)
63
+ ```
64
+
65
+ ## Verify webhooks
66
+
67
+ Stablevoy posts an event to your webhook URL when an invoice is paid, overpaid, underpaid, expired, paid late or put on hold. Check the signature before you trust it, using the signing secret shown when you set the webhook in the dashboard. Pass the raw body, exactly as received.
68
+
69
+ Flask:
70
+
71
+ ```python
72
+ from flask import Flask, request
73
+
74
+ from stablevoy import SignatureError, WebhookVerifier
75
+
76
+ verifier = WebhookVerifier(os.environ["STABLEVOY_WEBHOOK_SECRET"])
77
+ app = Flask(__name__)
78
+
79
+
80
+ @app.post("/stablevoy/webhook")
81
+ def stablevoy_webhook():
82
+ try:
83
+ event = verifier.verify(request.get_data(), request.headers.get("X-Stablevoy-Signature"))
84
+ except SignatureError:
85
+ return "", 400
86
+ if event.invoice is not None and event.invoice.is_paid():
87
+ ... # mark the order event.invoice.external_reference as paid; use event.id to handle each event once
88
+ return "", 200
89
+ ```
90
+
91
+ Django: `verifier.verify(request.body, request.headers.get("X-Stablevoy-Signature"))`. FastAPI: `verifier.verify(await request.body(), request.headers.get("X-Stablevoy-Signature"))`.
92
+
93
+ ## Errors and retries
94
+
95
+ Every error extends `StablevoyError`. API errors are `ApiError` with the HTTP `status`, a stable `code`, a readable `detail` and a link to the [error catalog](https://stablevoy.com/docs/api/errors/); the ones you may want to handle on their own are `AuthenticationError`, `ValidationError` (with `issues`), `NotFoundError`, `RateLimitedError` and `MaintenanceError`. `TransportError` means no answer at all.
96
+
97
+ Reads, and creates that carry an idempotency key, are retried on rate limits, maintenance and failed connections, at most twice and only for waits of up to 10 seconds. Anything longer reaches you with `retry_after_seconds`, so a request never hangs. Every request times out after 30 seconds.
98
+
99
+ ```python
100
+ from stablevoy import RetryPolicy, Stablevoy
101
+
102
+ stablevoy = Stablevoy.create(api_key, retries=RetryPolicy(max_retries=3, max_wait_seconds=30), timeout_seconds=10)
103
+ ```
104
+
105
+ ## Links
106
+
107
+ - [API reference](https://stablevoy.com/docs/api/)
108
+ - [Docs](https://stablevoy.com/docs/)
109
+ - [PHP SDK](https://github.com/stablevoy/stablevoy-php), [Node.js SDK](https://github.com/stablevoy/stablevoy-node)
110
+ - [WooCommerce plugin](https://wordpress.org/plugins/stablevoy-for-woocommerce/)
111
+
112
+ ## License
113
+
114
+ MIT
@@ -0,0 +1,93 @@
1
+ # Stablevoy Python SDK
2
+
3
+ [![CI](https://github.com/stablevoy/stablevoy-python/actions/workflows/ci.yml/badge.svg)](https://github.com/stablevoy/stablevoy-python/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/stablevoy)](https://pypi.org/project/stablevoy/)
5
+
6
+ Python client for [Stablevoy](https://stablevoy.com), the non-custodial gateway for USDT and USDC payments. Customers pay on chain and the money goes straight to your own wallet: USDC and USDT on Base, Arbitrum, Optimism, Avalanche, Polygon and BNB Chain, and USDT (TRC20) on Tron with no fee.
7
+
8
+ The library creates invoices, reads them, and verifies the signed webhooks that tell your shop an order is paid. It has no dependencies, needs Python 3.11 or newer and is fully typed.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pip install stablevoy
14
+ ```
15
+
16
+ ## Create an invoice and send the buyer to pay
17
+
18
+ Create an API key for your store in the [Stablevoy dashboard](https://stablevoy.com/app/).
19
+
20
+ ```python
21
+ import os
22
+
23
+ from stablevoy import Stablevoy
24
+
25
+ stablevoy = Stablevoy.create(os.environ["STABLEVOY_API_KEY"])
26
+
27
+ created = stablevoy.invoices.create(
28
+ 2599, # $25.99 in US cents
29
+ external_reference="order-1042", # your order id, sent back in webhooks
30
+ return_url="https://shop.example/orders/1042",
31
+ idempotency_key="order-1042", # a retry returns the same invoice, never a second one
32
+ )
33
+
34
+ # Send the buyer to created.checkout_url
35
+ ```
36
+
37
+ Read an invoice with `stablevoy.invoices.get(invoice_id)`, or walk them all:
38
+
39
+ ```python
40
+ for invoice in stablevoy.invoices.all(status="paid"):
41
+ print(invoice.external_reference, invoice.amount_usd_cents)
42
+ ```
43
+
44
+ ## Verify webhooks
45
+
46
+ Stablevoy posts an event to your webhook URL when an invoice is paid, overpaid, underpaid, expired, paid late or put on hold. Check the signature before you trust it, using the signing secret shown when you set the webhook in the dashboard. Pass the raw body, exactly as received.
47
+
48
+ Flask:
49
+
50
+ ```python
51
+ from flask import Flask, request
52
+
53
+ from stablevoy import SignatureError, WebhookVerifier
54
+
55
+ verifier = WebhookVerifier(os.environ["STABLEVOY_WEBHOOK_SECRET"])
56
+ app = Flask(__name__)
57
+
58
+
59
+ @app.post("/stablevoy/webhook")
60
+ def stablevoy_webhook():
61
+ try:
62
+ event = verifier.verify(request.get_data(), request.headers.get("X-Stablevoy-Signature"))
63
+ except SignatureError:
64
+ return "", 400
65
+ if event.invoice is not None and event.invoice.is_paid():
66
+ ... # mark the order event.invoice.external_reference as paid; use event.id to handle each event once
67
+ return "", 200
68
+ ```
69
+
70
+ Django: `verifier.verify(request.body, request.headers.get("X-Stablevoy-Signature"))`. FastAPI: `verifier.verify(await request.body(), request.headers.get("X-Stablevoy-Signature"))`.
71
+
72
+ ## Errors and retries
73
+
74
+ Every error extends `StablevoyError`. API errors are `ApiError` with the HTTP `status`, a stable `code`, a readable `detail` and a link to the [error catalog](https://stablevoy.com/docs/api/errors/); the ones you may want to handle on their own are `AuthenticationError`, `ValidationError` (with `issues`), `NotFoundError`, `RateLimitedError` and `MaintenanceError`. `TransportError` means no answer at all.
75
+
76
+ Reads, and creates that carry an idempotency key, are retried on rate limits, maintenance and failed connections, at most twice and only for waits of up to 10 seconds. Anything longer reaches you with `retry_after_seconds`, so a request never hangs. Every request times out after 30 seconds.
77
+
78
+ ```python
79
+ from stablevoy import RetryPolicy, Stablevoy
80
+
81
+ stablevoy = Stablevoy.create(api_key, retries=RetryPolicy(max_retries=3, max_wait_seconds=30), timeout_seconds=10)
82
+ ```
83
+
84
+ ## Links
85
+
86
+ - [API reference](https://stablevoy.com/docs/api/)
87
+ - [Docs](https://stablevoy.com/docs/)
88
+ - [PHP SDK](https://github.com/stablevoy/stablevoy-php), [Node.js SDK](https://github.com/stablevoy/stablevoy-node)
89
+ - [WooCommerce plugin](https://wordpress.org/plugins/stablevoy-for-woocommerce/)
90
+
91
+ ## License
92
+
93
+ MIT
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["hatchling==1.32.4"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "stablevoy"
7
+ version = "1.0.0"
8
+ description = "Python client for the Stablevoy API: non-custodial USDT and USDC payments, invoices and signed webhooks."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ dependencies = []
14
+ keywords = ["stablevoy", "usdt", "usdc", "trc20", "stablecoin", "crypto payments", "payment gateway", "webhooks", "tether", "tron"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Topic :: Office/Business :: Financial",
22
+ "Typing :: Typed",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://stablevoy.com"
27
+ Documentation = "https://stablevoy.com/docs/"
28
+ Source = "https://github.com/stablevoy/stablevoy-python"
29
+ Issues = "https://github.com/stablevoy/stablevoy-python/issues"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/stablevoy"]
33
+
34
+ [tool.hatch.build.targets.sdist]
35
+ include = ["src/stablevoy", "README.md", "LICENSE", "CHANGELOG.md"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+ addopts = "--cov=stablevoy --cov-branch --cov-report=term-missing --cov-fail-under=100"
40
+ pythonpath = ["src"]
41
+
42
+ [tool.mypy]
43
+ strict = true
44
+ files = ["src", "tests"]
45
+ mypy_path = "src"
46
+
47
+ [tool.ruff]
48
+ line-length = 140
49
+ target-version = "py311"
50
+ src = ["src", "tests"]
51
+
52
+ [tool.ruff.lint]
53
+ select = ["E", "F", "W", "I", "B", "UP", "S", "RUF", "SIM", "PT", "N", "ANN", "TRY", "EM", "PL"]
54
+ ignore = ["TRY003", "PLR0913", "PLR2004", "EM101", "EM102"]
55
+
56
+ [tool.ruff.lint.per-file-ignores]
57
+ "tests/**" = ["S101", "S105", "S106", "ANN", "PLR2004", "SLF001"]
@@ -0,0 +1,63 @@
1
+ """Python client for the Stablevoy API: non-custodial USDT and USDC payments, invoices and signed webhooks."""
2
+
3
+ from stablevoy._version import __version__
4
+ from stablevoy.client import Stablevoy
5
+ from stablevoy.errors.api_error import ApiError
6
+ from stablevoy.errors.authentication_error import AuthenticationError
7
+ from stablevoy.errors.configuration_error import ConfigurationError
8
+ from stablevoy.errors.maintenance_error import MaintenanceError
9
+ from stablevoy.errors.not_found_error import NotFoundError
10
+ from stablevoy.errors.problem_issue import ProblemIssue
11
+ from stablevoy.errors.rate_limited_error import RateLimitedError
12
+ from stablevoy.errors.signature_error import SignatureError
13
+ from stablevoy.errors.stablevoy_error import StablevoyError
14
+ from stablevoy.errors.transport_error import TransportError
15
+ from stablevoy.errors.unexpected_response_error import UnexpectedResponseError
16
+ from stablevoy.errors.validation_error import ValidationError
17
+ from stablevoy.http.retry_policy import RetryPolicy
18
+ from stablevoy.http.transport import Transport
19
+ from stablevoy.model.created_invoice import CreatedInvoice
20
+ from stablevoy.model.deposit_address import DepositAddress
21
+ from stablevoy.model.invoice import Invoice
22
+ from stablevoy.model.invoice_page import InvoicePage
23
+ from stablevoy.model.invoice_status import InvoiceStatus
24
+ from stablevoy.model.limits import Limits
25
+ from stablevoy.model.network import Network
26
+ from stablevoy.model.payment import Payment
27
+ from stablevoy.model.pricing import Pricing
28
+ from stablevoy.model.store import Store
29
+ from stablevoy.model.token import Token
30
+ from stablevoy.webhook.webhook_event import WebhookEvent
31
+ from stablevoy.webhook.webhook_verifier import WebhookVerifier
32
+
33
+ __all__ = [
34
+ "ApiError",
35
+ "AuthenticationError",
36
+ "ConfigurationError",
37
+ "CreatedInvoice",
38
+ "DepositAddress",
39
+ "Invoice",
40
+ "InvoicePage",
41
+ "InvoiceStatus",
42
+ "Limits",
43
+ "MaintenanceError",
44
+ "Network",
45
+ "NotFoundError",
46
+ "Payment",
47
+ "Pricing",
48
+ "ProblemIssue",
49
+ "RateLimitedError",
50
+ "RetryPolicy",
51
+ "SignatureError",
52
+ "Stablevoy",
53
+ "StablevoyError",
54
+ "Store",
55
+ "Token",
56
+ "Transport",
57
+ "TransportError",
58
+ "UnexpectedResponseError",
59
+ "ValidationError",
60
+ "WebhookEvent",
61
+ "WebhookVerifier",
62
+ "__version__",
63
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ import platform
4
+ import time
5
+ from collections.abc import Callable
6
+
7
+ from stablevoy._version import __version__
8
+ from stablevoy.http.error_factory import ErrorFactory
9
+ from stablevoy.http.opener import Opener
10
+ from stablevoy.http.retry_policy import RetryPolicy
11
+ from stablevoy.http.transport import Transport
12
+ from stablevoy.http.urllib_opener import UrllibOpener
13
+ from stablevoy.http.urllib_transport import UrllibTransport
14
+ from stablevoy.resources.invoices import Invoices
15
+ from stablevoy.resources.platform import Platform
16
+ from stablevoy.resources.stores import Stores
17
+
18
+
19
+ class Stablevoy:
20
+ """The Stablevoy API: ``stablevoy = Stablevoy.create(os.environ["STABLEVOY_API_KEY"])``."""
21
+
22
+ def __init__(self, invoices: Invoices, stores: Stores, platform: Platform) -> None:
23
+ self.invoices = invoices
24
+ self.stores = stores
25
+ self.platform = platform
26
+
27
+ @classmethod
28
+ def create(
29
+ cls,
30
+ api_key: str,
31
+ *,
32
+ base_url: str = "https://api.stablevoy.com",
33
+ retries: RetryPolicy | None = None,
34
+ timeout_seconds: float = 30.0,
35
+ user_agent_suffix: str | None = None,
36
+ opener: Opener | None = None,
37
+ sleep: Callable[[float], None] = time.sleep,
38
+ ) -> Stablevoy:
39
+ user_agent = f"stablevoy-python/{__version__} Python/{platform.python_version()}"
40
+ if user_agent_suffix is not None:
41
+ user_agent += f" {user_agent_suffix}"
42
+ return cls.from_transport(
43
+ UrllibTransport(
44
+ api_key=api_key,
45
+ base_url=base_url,
46
+ user_agent=user_agent,
47
+ retries=retries if retries is not None else RetryPolicy(),
48
+ opener=opener if opener is not None else UrllibOpener(),
49
+ sleep=sleep,
50
+ errors=ErrorFactory(),
51
+ timeout_seconds=timeout_seconds,
52
+ )
53
+ )
54
+
55
+ @classmethod
56
+ def from_transport(cls, transport: Transport) -> Stablevoy:
57
+ return cls(Invoices(transport), Stores(transport), Platform(transport))
File without changes
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ from stablevoy.errors.problem_issue import ProblemIssue
4
+ from stablevoy.errors.stablevoy_error import StablevoyError
5
+
6
+
7
+ class ApiError(StablevoyError):
8
+ """
9
+ The API answered with an error: an RFC 7807 problem document with a stable code, a readable detail and a link to the
10
+ code's entry in the error catalog (https://stablevoy.com/docs/api/errors/).
11
+ """
12
+
13
+ def __init__(
14
+ self,
15
+ *,
16
+ status: int,
17
+ code: str,
18
+ detail: str,
19
+ type: str | None,
20
+ issues: tuple[ProblemIssue, ...],
21
+ retry_after_seconds: int | None,
22
+ ) -> None:
23
+ super().__init__(f"{detail} (HTTP {status}, {code})")
24
+ self.status = status
25
+ self.code = code
26
+ self.detail = detail
27
+ self.type = type
28
+ self.issues = issues
29
+ self.retry_after_seconds = retry_after_seconds
@@ -0,0 +1,5 @@
1
+ from stablevoy.errors.api_error import ApiError
2
+
3
+
4
+ class AuthenticationError(ApiError):
5
+ """The API key is missing, invalid or revoked (HTTP 401)."""
@@ -0,0 +1,5 @@
1
+ from stablevoy.errors.stablevoy_error import StablevoyError
2
+
3
+
4
+ class ConfigurationError(StablevoyError):
5
+ """The client cannot be built as asked, for example with an empty API key or an unsafe base URL."""
@@ -0,0 +1,5 @@
1
+ from stablevoy.errors.api_error import ApiError
2
+
3
+
4
+ class MaintenanceError(ApiError):
5
+ """Stablevoy is under maintenance (HTTP 503, code maintenance). Nothing was changed; retry after retry_after_seconds."""
@@ -0,0 +1,5 @@
1
+ from stablevoy.errors.api_error import ApiError
2
+
3
+
4
+ class NotFoundError(ApiError):
5
+ """The invoice or store does not exist for this API key (HTTP 404)."""
@@ -0,0 +1,9 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass(frozen=True)
5
+ class ProblemIssue:
6
+ """A field a validation error names."""
7
+
8
+ path: str
9
+ message: str
@@ -0,0 +1,5 @@
1
+ from stablevoy.errors.api_error import ApiError
2
+
3
+
4
+ class RateLimitedError(ApiError):
5
+ """Too many requests (HTTP 429); retry_after_seconds says when to try again."""
@@ -0,0 +1,5 @@
1
+ from stablevoy.errors.stablevoy_error import StablevoyError
2
+
3
+
4
+ class SignatureError(StablevoyError):
5
+ """A webhook did not pass the signature check; the message says why. Answer such a request with HTTP 400."""
@@ -0,0 +1,2 @@
1
+ class StablevoyError(Exception):
2
+ """Every error this library raises extends it, so one ``except StablevoyError`` covers them all."""
@@ -0,0 +1,5 @@
1
+ from stablevoy.errors.stablevoy_error import StablevoyError
2
+
3
+
4
+ class TransportError(StablevoyError):
5
+ """No answer from the API: the connection failed or timed out."""
@@ -0,0 +1,5 @@
1
+ from stablevoy.errors.stablevoy_error import StablevoyError
2
+
3
+
4
+ class UnexpectedResponseError(StablevoyError):
5
+ """The API answered something this library cannot read: not JSON, or a field missing or of the wrong type."""
@@ -0,0 +1,5 @@
1
+ from stablevoy.errors.api_error import ApiError
2
+
3
+
4
+ class ValidationError(ApiError):
5
+ """The request was refused because of its content (HTTP 400 or 422); issues names the fields."""
File without changes
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ from stablevoy.errors.api_error import ApiError
6
+ from stablevoy.errors.authentication_error import AuthenticationError
7
+ from stablevoy.errors.maintenance_error import MaintenanceError
8
+ from stablevoy.errors.not_found_error import NotFoundError
9
+ from stablevoy.errors.problem_issue import ProblemIssue
10
+ from stablevoy.errors.rate_limited_error import RateLimitedError
11
+ from stablevoy.errors.validation_error import ValidationError
12
+
13
+
14
+ class ErrorFactory:
15
+ """Turns an error answer of the API (an RFC 7807 problem document) into the matching error."""
16
+
17
+ def from_problem(self, status: int, body: bytes, retry_after_seconds: int | None) -> ApiError:
18
+ problem = self._parse(body)
19
+ code = problem.get("code")
20
+ code = code if isinstance(code, str) else f"http_{status}"
21
+ detail = problem.get("detail")
22
+ problem_type = problem.get("type")
23
+ error_class: type[ApiError] = ApiError
24
+ if status == 401:
25
+ error_class = AuthenticationError
26
+ elif status == 404:
27
+ error_class = NotFoundError
28
+ elif status == 429:
29
+ error_class = RateLimitedError
30
+ elif status == 503 and code == "maintenance":
31
+ error_class = MaintenanceError
32
+ elif status in (400, 422):
33
+ error_class = ValidationError
34
+ return error_class(
35
+ status=status,
36
+ code=code,
37
+ detail=detail if isinstance(detail, str) else f"The API answered HTTP {status}",
38
+ type=problem_type if isinstance(problem_type, str) else None,
39
+ issues=self._issues(problem.get("issues")),
40
+ retry_after_seconds=retry_after_seconds,
41
+ )
42
+
43
+ @staticmethod
44
+ def _parse(body: bytes) -> dict[str, object]:
45
+ try:
46
+ value = json.loads(body)
47
+ except ValueError:
48
+ return {}
49
+ return value if isinstance(value, dict) else {}
50
+
51
+ @staticmethod
52
+ def _issues(value: object) -> tuple[ProblemIssue, ...]:
53
+ if not isinstance(value, list):
54
+ return ()
55
+ return tuple(
56
+ ProblemIssue(issue["path"], issue["message"])
57
+ for issue in value
58
+ if isinstance(issue, dict) and isinstance(issue.get("path"), str) and isinstance(issue.get("message"), str)
59
+ )
@@ -0,0 +1,9 @@
1
+ from dataclasses import dataclass
2
+ from email.message import Message
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class HttpAnswer:
7
+ status: int
8
+ headers: Message
9
+ body: bytes
@@ -0,0 +1,12 @@
1
+ from __future__ import annotations
2
+
3
+ from email.message import Message
4
+ from typing import IO
5
+ from urllib.request import HTTPRedirectHandler, Request
6
+
7
+
8
+ class NoRedirects(HTTPRedirectHandler):
9
+ """The API never redirects; following one would carry the key wherever it points. The 3xx answer is returned as is."""
10
+
11
+ def redirect_request(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: Message, newurl: str) -> None: # noqa: PLR0917 - urllib defines this signature
12
+ return None
@@ -0,0 +1,10 @@
1
+ from typing import Protocol
2
+ from urllib.request import Request
3
+
4
+ from stablevoy.http.http_answer import HttpAnswer
5
+
6
+
7
+ class Opener(Protocol):
8
+ """Sends a request and returns the answer, whatever its status; raises OSError when there is no answer at all."""
9
+
10
+ def send(self, request: Request, timeout: float) -> HttpAnswer: ...