payrudder 0.2.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.
@@ -0,0 +1,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .mypy_cache/
7
+ .pytest_cache/
8
+ .ruff_cache/
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ All notable changes to the Payrudder Python SDK (`payrudder`). The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), the version numbers follow [Semantic Versioning](https://semver.org/).
4
+ The four SDKs share one version number and are released together.
5
+
6
+ ## [Unreleased]
7
+
8
+ ## [0.2.0] - 2026-11-23
9
+
10
+ ### Added
11
+ - `connect`: creates or updates a customer by your own id (an organisation with its signed-in member) and returns the link to its customer page.
12
+ - `access`: subscription, payment and limits in one check, with `allowed`, `reason` and `notices` to show in your app.
13
+ - The client's cache option: `access`, `record_usage`/`recordUsage` and `handle_webhook`/`handleWebhook` on the client go through a `PayrudderCache`, which gains `access` and an access TTL (default 5 s).
14
+
15
+ ### Changed
16
+ - `PayrudderCache` also invalidates the customer on `invoice.paid`, `invoice.uncollectible` and `invoice.voided`.
17
+
18
+ ## [0.1.0] - 2026-11-20
19
+
20
+ ### Added
21
+ - `PayrudderCache`: entitlement checks and the catalog kept in a store your instances share (`RedisStore` over redis-py, or `MemoryStore`), invalidated by webhooks through `handle_webhook`, with usage recorded through it counted into the cache. `client.environment` says whether the key is a test or a live one.
22
+ - A sync client (`Payrudder`) and an async client (`AsyncPayrudder`) for every operation of the tenant API (`/v1/*`): retries with backoff, typed errors, pagination iterators, a batching `events.ingest`, and webhook verification. Typed (`py.typed`); Python 3.10 or newer; one dependency, `httpx`.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,291 @@
1
+ Metadata-Version: 2.5
2
+ Name: payrudder
3
+ Version: 0.2.0
4
+ Summary: Python SDK for the Payrudder billing platform (tenant API and webhook verification).
5
+ Project-URL: Homepage, https://github.com/nafrucom/payrudder-sdks/tree/main/python
6
+ Project-URL: Repository, https://github.com/nafrucom/payrudder-sdks
7
+ Project-URL: Changelog, https://github.com/nafrucom/payrudder-sdks/blob/main/python/CHANGELOG.md
8
+ Project-URL: Issues, https://github.com/nafrucom/payrudder-sdks/issues
9
+ Author: Payrudder
10
+ License: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: billing,payrudder,sdk,usage-based-billing
13
+ Classifier: Development Status :: 2 - Pre-Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: Other/Proprietary License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: httpx<1,>=0.27
24
+ Provides-Extra: dev
25
+ Requires-Dist: build; extra == 'dev'
26
+ Requires-Dist: mypy>=1.11; extra == 'dev'
27
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
28
+ Requires-Dist: pytest>=8; extra == 'dev'
29
+ Requires-Dist: pyyaml>=6; extra == 'dev'
30
+ Requires-Dist: redis>=5; extra == 'dev'
31
+ Requires-Dist: ruff>=0.6; extra == 'dev'
32
+ Requires-Dist: types-pyyaml; extra == 'dev'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # payrudder (Python SDK)
36
+
37
+ Python client for the [Payrudder](https://payrudder.com) tenant API (`/v1/*`) and for verifying webhook deliveries.
38
+
39
+ Install from this repository: `pip install ./sdk/python` (or `pip install -e ./sdk/python[dev]` to work on it).
40
+
41
+ - Python 3.10+, fully typed (`py.typed`, checked with `mypy --strict`).
42
+ - A sync client (`Payrudder`) and an async client (`AsyncPayrudder`) with the same methods.
43
+ - One runtime dependency: [`httpx`](https://www.python-httpx.org/).
44
+ - Models are `TypedDict`s with the wire's snake_case names; money (`*_minor`) is a Python `int`. A key the API always sends is required in a response model,
45
+ a timestamp or nested object that is not set is `None`; a request object that is also a response has a twin without the server-filled fields
46
+ (`AddressInput`, `CouponInput`, `PriceInput`, ...).
47
+
48
+ Scope: the tenant API authenticated with an API key (`prk_test_...` for the sandbox, `prk_live_...` for live). The operator
49
+ (`/admin/v1`) and console (`/app/v1`, `/auth`) routes are not part of this SDK.
50
+
51
+ Runnable programs (send a usage event, create a customer, list invoices, verify a webhook) are in [`examples/`](examples/README.md).
52
+
53
+ ## Quickstart
54
+
55
+ ```python
56
+ from payrudder import Payrudder
57
+
58
+ client = Payrudder(api_key="prk_test_...", base_url="http://localhost:42800")
59
+ # or set PAYRUDDER_API_KEY and PAYRUDDER_BASE_URL and call Payrudder()
60
+
61
+ client.customers.create_customer({"external_id": "cus_42", "name": "Acme", "email": "billing@acme.test"})
62
+
63
+ results = client.events.ingest(
64
+ [
65
+ {
66
+ "customer_external_id": "cus_42",
67
+ "meter_code": "ai_tokens",
68
+ "quantity": "1500",
69
+ "event_time": "2026-11-03T10:15:00Z",
70
+ }
71
+ ]
72
+ )
73
+ print(results[0]["status"]) # accepted | duplicate | rejected
74
+
75
+ usage = client.customers.get_customer_usage("cus_42", period="2026-11")
76
+ ```
77
+
78
+ Async:
79
+
80
+ ```python
81
+ import asyncio
82
+ from payrudder import AsyncPayrudder
83
+
84
+
85
+ async def main() -> None:
86
+ async with AsyncPayrudder() as client:
87
+ invoice = await client.invoices.get_invoice("0192...")
88
+ async for customer in client.customers.iter_customers(page_size=200):
89
+ print(customer["external_id"])
90
+
91
+
92
+ asyncio.run(main())
93
+ ```
94
+
95
+ ### Client options
96
+
97
+ | Option | Default | |
98
+ |---|---|---|
99
+ | `api_key` | `PAYRUDDER_API_KEY` | required one way or the other |
100
+ | `base_url` | `PAYRUDDER_BASE_URL`, else `http://localhost:42800` | |
101
+ | `timeout` | `30` seconds | per request |
102
+ | `max_retries` | `2` | see [Retries](#retries) |
103
+ | `http_client` / `transport` | | your own `httpx.Client` / `httpx.AsyncClient`, or a transport (tests, proxy, mTLS) |
104
+ | `user_agent` | `payrudder-python/0.0.0` | |
105
+ | `default_headers` | | sent on every request |
106
+
107
+ Every method also takes `options={"timeout": ..., "max_retries": ..., "idempotency_key": ..., "headers": {...}}`.
108
+ Use the client as a context manager (`with` / `async with`) or call `close()` / `await aclose()`.
109
+
110
+ ## Methods
111
+
112
+ One method per `operationId` of the Payrudder OpenAPI spec, named `snake_case(operationId)` and grouped
113
+ under the first path segment: `POST /v1/customers` (`createCustomer`) is `client.customers.create_customer(...)`,
114
+ `GET /v1/e-invoices/{id}` (`getEInvoice`) is `client.e_invoices.get_e_invoice(id)`. Path parameters are positional, a JSON
115
+ body is the next positional argument (a `TypedDict` from `payrudder.models`), query parameters are keyword-only (`from` is
116
+ `from_`). Responses are the typed dicts of the spec; a CSV export returns `str`, the inbox file `bytes`, a `204` `None`.
117
+
118
+ A test (`tests/test_spec_sync.py`) parses the OpenAPI file and fails if an operation has no method or a method has no
119
+ operation, so the SDK cannot drift. The models, the resources and the int64 table are generated:
120
+
121
+ ```sh
122
+ python tools/generate.py # rewrite src/payrudder/{models,resources,_wire_tables,_opids}.py
123
+ python tools/generate.py --check # what the test and CI run
124
+ ```
125
+
126
+ ### Money and decimals
127
+
128
+ `*_minor` values are int64 strings on the wire and `int` in Python, in both directions (never a float). Quantities and
129
+ prices are decimal strings: pass a `str`, `int` or `Decimal`; a `float` is refused with `TypeError`. `datetime` / `date`
130
+ are accepted where the API takes a timestamp or a date (a naive `datetime` is taken as UTC).
131
+
132
+ ### Ingesting events
133
+
134
+ `client.events.ingest(events)` takes any number of events, splits them into valid batches (1 to 500 events, under 1 MiB),
135
+ fills a missing `idempotency_key` with a generated one, and returns one result per event in input order. A single rejected
136
+ event is `{"status": "rejected", "error_code": ...}` in the list, not an exception; a whole-batch failure (401, 429, 503, ...)
137
+ raises. `client.events.ingest_events({"events": [...]})` is the raw one-request call.
138
+
139
+ Live keys require an `idempotency_key` per event, and the generated one is stable across the automatic retries of a batch.
140
+ If you need to resume a half-done multi-batch call safely, pass your own keys.
141
+
142
+ ### Pagination
143
+
144
+ Every list operation that returns `next_page_token` has a lazy generator next to the raw call:
145
+
146
+ ```python
147
+ page = client.invoices.list_invoices(page_size=100) # one page, with next_page_token
148
+ for invoice in client.invoices.iter_invoices(): # every invoice
149
+ ...
150
+ async for payout in client.affiliates.iter_affiliate_payouts(): # async client
151
+ ...
152
+ ```
153
+
154
+ ## Connecting customers and checking access
155
+
156
+ `connect` creates the customer by your own id, or updates its name, e-mail and language when they changed, and returns the link to its customer page (valid for a day: ask for one at every visit). The customer chooses a plan, pays and cancels there; your code never manages a subscription. With a plan, the page opens with that plan chosen. For an organisation, pass your organisation id and the signed-in person as the member: the first member manages payment, and the others get no link (`url` is null, `billing_owner` false).
157
+
158
+ `access` answers whether the customer may use the service now: `allowed`, the `reason` that decided (`ok`, `trialing`, `past_due`, or `no_subscription`, `awaiting_payment`, `unpaid`, `limit_reached`, ...), the subscription and the meters asked for. For an organisation, ask with the organisation id: every member gets the same answer. `notices` is what to show the customer, ready for a banner, most serious first:
159
+
160
+ ```python
161
+ client = Payrudder(cache={}) # optional: answer most checks from a store, e.g. cache={"store": RedisStore(redis)}
162
+
163
+ session = client.connect(id=user.id, name=user.name, email=user.email)
164
+ # redirect to session["url"]
165
+
166
+ access = client.access(user.id, "api_calls")
167
+ if not access["allowed"]:
168
+ abort(402, access["reason"])
169
+ for n in access["notices"]:
170
+ banner(n["severity"], n["code"], n["meter_code"], n["at"])
171
+ ```
172
+
173
+ | `code` | `severity` | |
174
+ |---|---|---|
175
+ | `suspended` | critical | you suspended the customer's service |
176
+ | `payment_required` | critical | the first payment is not made, or an invoice became uncollectible |
177
+ | `payment_overdue` | warning | a renewal is being retried |
178
+ | `trial_ending` | info | the trial ends within 7 days (`at`) |
179
+ | `subscription_ending` | info | cancelled at the end of the paid period (`at` when known) |
180
+ | `limit_reached` | critical | a hard limit of `meter_code` is reached |
181
+ | `limit_exceeded` | warning | a soft or notify limit of `meter_code` is passed |
182
+ | `limit_near` | warning | 80 % of the limit of `meter_code` is used |
183
+
184
+ With `cache`, `access`, `record_usage` and `handle_webhook` on the client go through the cache below (`access_ttl_ms` defaults to 5000); `member=` also checks membership. `AsyncPayrudder` has `connect` and `access` without a cache.
185
+
186
+ ## Caching entitlements and the catalog in Redis
187
+
188
+ `PayrudderCache` keeps entitlement checks and the catalog (plans with their current prices, active credit packs, running campaigns) in a store every instance of your app shares. Pass the redis-py client you already have; without a store it uses a `MemoryStore` in the process. Forward verified webhooks to it, so a change in Payrudder invalidates the cached answers at once.
189
+
190
+ ```python
191
+ import redis
192
+ from payrudder import PayrudderCache, RedisStore, construct_event
193
+
194
+ cache = PayrudderCache(client, store=RedisStore(redis.Redis()), on_error=logger.warning)
195
+
196
+ status = cache.entitlement(customer, "api_calls") # also cache.entitlements(customer), cache.catalog()
197
+ cache.record_usage({"customer_external_id": customer, "meter_code": "api_calls", "quantity": "1", "event_time": now})
198
+
199
+ # in your webhook view, after verifying the delivery
200
+ cache.handle_webhook(construct_event(body, signature, secret))
201
+ ```
202
+
203
+ - Entitlements are served for `entitlement_ttl_ms` (default 60 s), the catalog for `catalog_ttl_ms` (default 10 min); with webhooks wired a change shows at once, without them it can be that stale.
204
+ - `record_usage` counts the event into the cached entitlement, so a hard limit is enforced without a refetch after every event.
205
+ - Keys start with `prefix` (default `payrudder:`) and the key's environment (`client.environment`), so test and live never share entries. A store error never fails a call: it reads through to the API and goes to `on_error`.
206
+ - The cache works with the sync `Payrudder` client.
207
+
208
+ ## Errors
209
+
210
+ ```python
211
+ from payrudder import APIError, NotFoundError, RateLimitError, ValidationError, APIConnectionError
212
+
213
+ try:
214
+ client.customers.get_customer("nope")
215
+ except NotFoundError as e:
216
+ print(e.status_code, e.code, e.key, e.message, e.request_id) # 404 NOT_FOUND common.not_found ...
217
+ except ValidationError as e:
218
+ print(e.details) # [{"field": "email", "description": "..."}]
219
+ except RateLimitError as e:
220
+ print(e.retry_after) # seconds, from Retry-After
221
+ except APIError as e: # any other error status
222
+ ...
223
+ except APIConnectionError: # no answer (APITimeoutError is a subclass)
224
+ ...
225
+ ```
226
+
227
+ All errors derive from `PayrudderError`. `APIError` carries `status_code`, `code` (gRPC style), `key` (the stable,
228
+ translatable error key such as `billing.credit_note.nothing_to_refund`: translate the key, not the message), `message`,
229
+ `details`, `request_id`, `retry_after`, `headers` and `body`. Subclasses: `AuthenticationError` (401),
230
+ `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `ValidationError` (400, 422),
231
+ `RateLimitError` (429), `ServerError` (5xx).
232
+
233
+ ## Retries
234
+
235
+ Automatic, with exponential backoff (0.5 s doubling, capped at 8 s, jittered):
236
+
237
+ - network errors: a connection that never opened is always retried; one that may have carried the request (read timeout,
238
+ dropped connection) only when the call can safely repeat;
239
+ - `429`, honouring `Retry-After` (a value over 60 s is not waited for: you get the `RateLimitError`);
240
+ - `502`, `503`, `504`;
241
+ - `500` only for idempotent calls: `GET`, `PUT`, `DELETE`, and a `POST` that carries an idempotency key.
242
+
243
+ Other `4xx` are never retried. `max_retries=0` turns it all off.
244
+
245
+ ## Idempotency
246
+
247
+ Pass `options={"idempotency_key": "order-77"}` to send an `Idempotency-Key` header (the API honours it on payment links
248
+ and upload sessions, which also accept `idempotency_key` in the body). A POST with a key is retried after a `500`, and the
249
+ same key is sent on every attempt. Event ingestion has a key per event (see above).
250
+
251
+ ## Webhooks
252
+
253
+ Verify the **raw** request body before parsing it (a re-serialised JSON will not match). `construct_event` verifies and
254
+ parses; a bad, missing or stale (more than 5 minutes) signature raises `WebhookSignatureError`.
255
+
256
+ ```python
257
+ from payrudder import EventType, WebhookSignatureError, construct_event
258
+
259
+
260
+ # Flask
261
+ @app.post("/webhooks/payrudder")
262
+ def hook():
263
+ try:
264
+ event = construct_event(request.get_data(), request.headers.get("Payrudder-Signature"), WEBHOOK_SECRET)
265
+ except WebhookSignatureError:
266
+ return "", 400
267
+ if event["type"] == EventType.INVOICE_PAID:
268
+ total = event["data"]["total_minor"] # int
269
+ return "", 200
270
+ ```
271
+
272
+ `verify_webhook(payload, header, secret, tolerance=300)` only verifies. A delivery signed while a secret rotates carries two
273
+ `v1` signatures and verifies with either the new or the old secret. Deliveries are at least once and unordered: ignore a
274
+ repeated `event["id"]`. `EVENT_TYPES` and `EventType` list the event names of the webhook documentation.
275
+ `InvoiceEventData`, `CreditNoteEventData`, `SubscriptionEventData`, `PaymentLinkEventData`, `CreditsPurchasedEventData` and
276
+ `CreditsLowEventData` type `event["data"]` per event family; narrow with `typing.cast(InvoiceEventData, event["data"])`.
277
+
278
+ ## Development
279
+
280
+ ```sh
281
+ python -m venv .venv && .venv/bin/pip install -e '.[dev]'
282
+ .venv/bin/ruff check . && .venv/bin/ruff format --check .
283
+ .venv/bin/mypy # strict
284
+ .venv/bin/pytest # unit tests against a local fake gateway; no network, no stack needed
285
+ PAYRUDDER_API_KEY=prk_test_... .venv/bin/pytest tests/test_integration.py # optional smoke test against a running stack
286
+ .venv/bin/python -m build # sdist and wheel in dist/
287
+ ```
288
+
289
+ ## Licence
290
+
291
+ Apache License 2.0: see [LICENSE](LICENSE).