flashpi 0.1.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 (99) hide show
  1. flashpi-0.1.0/.gitignore +16 -0
  2. flashpi-0.1.0/CHANGELOG.md +46 -0
  3. flashpi-0.1.0/LICENSE +21 -0
  4. flashpi-0.1.0/PKG-INFO +472 -0
  5. flashpi-0.1.0/README.en.md +436 -0
  6. flashpi-0.1.0/README.md +441 -0
  7. flashpi-0.1.0/openapi/openapi.json +12892 -0
  8. flashpi-0.1.0/pyproject.toml +98 -0
  9. flashpi-0.1.0/scripts/__init__.py +0 -0
  10. flashpi-0.1.0/scripts/installed_check.py +70 -0
  11. flashpi-0.1.0/scripts/openapi.py +645 -0
  12. flashpi-0.1.0/scripts/package_check.py +145 -0
  13. flashpi-0.1.0/scripts/readme.py +216 -0
  14. flashpi-0.1.0/src/flashpi/__init__.py +74 -0
  15. flashpi-0.1.0/src/flashpi/_client.py +405 -0
  16. flashpi-0.1.0/src/flashpi/_errors.py +249 -0
  17. flashpi-0.1.0/src/flashpi/_http.py +666 -0
  18. flashpi-0.1.0/src/flashpi/_network.py +114 -0
  19. flashpi-0.1.0/src/flashpi/_pagination.py +130 -0
  20. flashpi-0.1.0/src/flashpi/_resource.py +100 -0
  21. flashpi-0.1.0/src/flashpi/_response.py +95 -0
  22. flashpi-0.1.0/src/flashpi/_validate.py +89 -0
  23. flashpi-0.1.0/src/flashpi/_version.py +3 -0
  24. flashpi-0.1.0/src/flashpi/_webhooks.py +264 -0
  25. flashpi-0.1.0/src/flashpi/py.typed +0 -0
  26. flashpi-0.1.0/src/flashpi/resources/__init__.py +80 -0
  27. flashpi-0.1.0/src/flashpi/resources/documents.py +320 -0
  28. flashpi-0.1.0/src/flashpi/resources/events.py +73 -0
  29. flashpi-0.1.0/src/flashpi/resources/issuer_onboardings.py +130 -0
  30. flashpi-0.1.0/src/flashpi/resources/issuers.py +604 -0
  31. flashpi-0.1.0/src/flashpi/resources/status.py +47 -0
  32. flashpi-0.1.0/src/flashpi/resources/uploads.py +117 -0
  33. flashpi-0.1.0/src/flashpi/resources/webhook_endpoints.py +341 -0
  34. flashpi-0.1.0/src/flashpi/types/__init__.py +336 -0
  35. flashpi-0.1.0/src/flashpi/types/_generated.py +2841 -0
  36. flashpi-0.1.0/tests/__init__.py +0 -0
  37. flashpi-0.1.0/tests/conftest.py +46 -0
  38. flashpi-0.1.0/tests/examples/readme/_context.py +39 -0
  39. flashpi-0.1.0/tests/examples/readme/en_01.py +38 -0
  40. flashpi-0.1.0/tests/examples/readme/en_02.py +22 -0
  41. flashpi-0.1.0/tests/examples/readme/en_03.py +18 -0
  42. flashpi-0.1.0/tests/examples/readme/en_04.py +16 -0
  43. flashpi-0.1.0/tests/examples/readme/en_05.py +21 -0
  44. flashpi-0.1.0/tests/examples/readme/en_06.py +10 -0
  45. flashpi-0.1.0/tests/examples/readme/en_07.py +17 -0
  46. flashpi-0.1.0/tests/examples/readme/en_08.py +32 -0
  47. flashpi-0.1.0/tests/examples/readme/en_09.py +31 -0
  48. flashpi-0.1.0/tests/examples/readme/en_10.py +32 -0
  49. flashpi-0.1.0/tests/examples/readme/en_11.py +49 -0
  50. flashpi-0.1.0/tests/examples/readme/en_12.py +17 -0
  51. flashpi-0.1.0/tests/examples/readme/en_13.py +10 -0
  52. flashpi-0.1.0/tests/examples/readme/en_14.py +11 -0
  53. flashpi-0.1.0/tests/examples/readme/en_15.py +12 -0
  54. flashpi-0.1.0/tests/examples/readme/es_01.py +38 -0
  55. flashpi-0.1.0/tests/examples/readme/es_02.py +22 -0
  56. flashpi-0.1.0/tests/examples/readme/es_03.py +18 -0
  57. flashpi-0.1.0/tests/examples/readme/es_04.py +16 -0
  58. flashpi-0.1.0/tests/examples/readme/es_05.py +21 -0
  59. flashpi-0.1.0/tests/examples/readme/es_06.py +10 -0
  60. flashpi-0.1.0/tests/examples/readme/es_07.py +17 -0
  61. flashpi-0.1.0/tests/examples/readme/es_08.py +32 -0
  62. flashpi-0.1.0/tests/examples/readme/es_09.py +31 -0
  63. flashpi-0.1.0/tests/examples/readme/es_10.py +32 -0
  64. flashpi-0.1.0/tests/examples/readme/es_11.py +49 -0
  65. flashpi-0.1.0/tests/examples/readme/es_12.py +17 -0
  66. flashpi-0.1.0/tests/examples/readme/es_13.py +10 -0
  67. flashpi-0.1.0/tests/examples/readme/es_14.py +11 -0
  68. flashpi-0.1.0/tests/examples/readme/es_15.py +12 -0
  69. flashpi-0.1.0/tests/examples/typings/django/__init__.pyi +2 -0
  70. flashpi-0.1.0/tests/examples/typings/django/http/__init__.pyi +32 -0
  71. flashpi-0.1.0/tests/examples/typings/django/views/__init__.pyi +0 -0
  72. flashpi-0.1.0/tests/examples/typings/django/views/decorators/__init__.pyi +0 -0
  73. flashpi-0.1.0/tests/examples/typings/django/views/decorators/csrf.pyi +6 -0
  74. flashpi-0.1.0/tests/examples/typings/django/views/decorators/http.pyi +6 -0
  75. flashpi-0.1.0/tests/examples/typings/fastapi/__init__.pyi +29 -0
  76. flashpi-0.1.0/tests/examples/typings/fastapi/responses.pyi +14 -0
  77. flashpi-0.1.0/tests/examples/typings/flask/__init__.pyi +38 -0
  78. flashpi-0.1.0/tests/live/__init__.py +0 -0
  79. flashpi-0.1.0/tests/live/test_live.py +191 -0
  80. flashpi-0.1.0/tests/support.py +466 -0
  81. flashpi-0.1.0/tests/test_cancellation.py +73 -0
  82. flashpi-0.1.0/tests/test_client.py +436 -0
  83. flashpi-0.1.0/tests/test_deadline.py +175 -0
  84. flashpi-0.1.0/tests/test_errors.py +150 -0
  85. flashpi-0.1.0/tests/test_headers.py +222 -0
  86. flashpi-0.1.0/tests/test_http.py +163 -0
  87. flashpi-0.1.0/tests/test_network.py +372 -0
  88. flashpi-0.1.0/tests/test_openapi.py +440 -0
  89. flashpi-0.1.0/tests/test_operations.py +355 -0
  90. flashpi-0.1.0/tests/test_package_check.py +156 -0
  91. flashpi-0.1.0/tests/test_pagination.py +124 -0
  92. flashpi-0.1.0/tests/test_readme.py +190 -0
  93. flashpi-0.1.0/tests/test_resource_types.py +83 -0
  94. flashpi-0.1.0/tests/test_resources.py +896 -0
  95. flashpi-0.1.0/tests/test_retries.py +316 -0
  96. flashpi-0.1.0/tests/test_review_fixes.py +422 -0
  97. flashpi-0.1.0/tests/test_types.py +123 -0
  98. flashpi-0.1.0/tests/test_version.py +34 -0
  99. flashpi-0.1.0/tests/test_webhooks.py +489 -0
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .coverage
8
+ .coverage.*
9
+ htmlcov/
10
+ coverage.xml
11
+ .pytest_cache/
12
+ .ruff_cache/
13
+ .env
14
+ .env.*
15
+ !.env.example
16
+ .DS_Store
@@ -0,0 +1,46 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-13)
4
+
5
+
6
+ ### Features
7
+
8
+ * add issuer onboardings ([d053103](https://github.com/flashpi1/flashpi-python/commit/d053103a06360c91c0ed21f6a9beec751d5bd3ac))
9
+ * add issuers with their establishments, emission points and certificates ([82a94d2](https://github.com/flashpi1/flashpi-python/commit/82a94d2b2d257b4ec3c121023426623d8bdc1e4f))
10
+ * add pagination to list operations ([470f23f](https://github.com/flashpi1/flashpi-python/commit/470f23f0706024dadf3def628558d5a2f26ae08b))
11
+ * add the error classes ([79e3073](https://github.com/flashpi1/flashpi-python/commit/79e3073e358a7d6e5bad0925c7b326b39426e0af))
12
+ * add the Flashpi and AsyncFlashpi clients with safe retries ([2b51b92](https://github.com/flashpi1/flashpi-python/commit/2b51b92282a7df08b4f2d69fd17ff6a9a2b1b28c))
13
+ * add the package skeleton with its version and typing marker ([dd5460c](https://github.com/flashpi1/flashpi-python/commit/dd5460cca9a19420830485c62ef24c858f8d638f))
14
+ * add the status and events resources ([9c22f49](https://github.com/flashpi1/flashpi-python/commit/9c22f496dcf8e348a9ec5e053f41d4d076e6bc85))
15
+ * add webhook endpoints and their deliveries ([4cf8635](https://github.com/flashpi1/flashpi-python/commit/4cf86351fadf1e68442bafd243926ab0a9e15ed9))
16
+ * issue documents and read them back ([0874000](https://github.com/flashpi1/flashpi-python/commit/0874000d922f00a0ad05b5b55f27c7c7d0950fc9))
17
+ * the Python SDK ([e1f2983](https://github.com/flashpi1/flashpi-python/commit/e1f29836e01cb79ac53219b0fcda5c6dd0d6ef0c))
18
+ * **types:** add the public types module ([d73c59d](https://github.com/flashpi1/flashpi-python/commit/d73c59d65dd2076d92ae8e010de9c6d2e2502235))
19
+ * **types:** generate TypedDicts from the API's OpenAPI document ([60f6787](https://github.com/flashpi1/flashpi-python/commit/60f6787172846479774ab4df734bca4178540874))
20
+ * verify webhook signatures ([0aa315f](https://github.com/flashpi1/flashpi-python/commit/0aa315f18deecfbaa391f4d1c40f287ee58e786b))
21
+
22
+
23
+ ### Bug fixes
24
+
25
+ * check header names and values before sending anything ([e197f98](https://github.com/flashpi1/flashpi-python/commit/e197f9818491d9536799d2c8c9cc143fe70b1b3c))
26
+ * check the deadline once the answer is read, also after response hooks ([5a0d475](https://github.com/flashpi1/flashpi-python/commit/5a0d47575ef816bbbc334784662309f14850ae2e))
27
+ * do not retry a request httpx refuses, nor show why ([cf7d38d](https://github.com/flashpi1/flashpi-python/commit/cf7d38d7f213a78953827bfbc2e565ba02aeaf3f))
28
+ * give each attempt one deadline that covers reading the answer ([48cfd71](https://github.com/flashpi1/flashpi-python/commit/48cfd71cbafb8fef57f1d9841864d3b4471d6c3b))
29
+ * keep a certificate and its password out of the multipart repr ([cc34bcf](https://github.com/flashpi1/flashpi-python/commit/cc34bcf1d4a2ae4ed864fb464a2787707ae82231))
30
+ * keep httpx's own limits when its internals are not there ([eed5ea8](https://github.com/flashpi1/flashpi-python/commit/eed5ea888cbd09589f9e1cf56c2debe9218b9955))
31
+ * keep the .p12 and its password out of the frames of an upload error ([9ac950f](https://github.com/flashpi1/flashpi-python/commit/9ac950f3ca913b87d51b5d9e8cc53ed2c8a98536))
32
+ * keep the API key out of the frames of request and settings errors ([b7c90ae](https://github.com/flashpi1/flashpi-python/commit/b7c90ae3253544a3968943c1464084684f411da8))
33
+ * keep the webhook signing key out of the frames of a verification error ([de4d6f8](https://github.com/flashpi1/flashpi-python/commit/de4d6f8b4fee9bf95db3798b6117c3a33382a7df))
34
+ * limit every network operation of a Flashpi attempt to its time left ([3b868b5](https://github.com/flashpi1/flashpi-python/commit/3b868b5d5a46b2d517ecd6966d0e80731b9215b9))
35
+ * read a certificate file only up to one byte past the limit ([5254a47](https://github.com/flashpi1/flashpi-python/commit/5254a47905acacc8b2460a3367f44fa7094a27af))
36
+ * refuse a body that is not text or bytes before the webhook-id check ([91591dc](https://github.com/flashpi1/flashpi-python/commit/91591dc9232a08bb2cda82e2f4631c104afbcd25))
37
+ * refuse a Content-Length or Transfer-Encoding header ([e4bc63e](https://github.com/flashpi1/flashpi-python/commit/e4bc63e08221e4e4e85758e8f20de14c35bc357a))
38
+ * refuse a malformed base_url with a FlashpiError ([ebce4f0](https://github.com/flashpi1/flashpi-python/commit/ebce4f018621212e74743ee660519b927c288e32))
39
+ * refuse a non-blocking certificate stream that has no data ready ([f57f518](https://github.com/flashpi1/flashpi-python/commit/f57f51867505d6ee069e586134e8ca43199ba9ef))
40
+ * refuse an API key with spaces or control characters ([8c51ee5](https://github.com/flashpi1/flashpi-python/commit/8c51ee5ffbfecf9d4c55ef7816fb88b22bdbbc7b))
41
+ * refuse header values that are not text on every httpx version ([04f6fb6](https://github.com/flashpi1/flashpi-python/commit/04f6fb6c7d22bc826433fd62f3bf149f011d116f))
42
+ * reject a webhook-id that is not UTF-8 as an unmatched signature ([1a0b3dd](https://github.com/flashpi1/flashpi-python/commit/1a0b3ddc86fb5d5ae52f11740742282e9a84b70c))
43
+ * **scripts:** refuse a redirect to plain HTTP when syncing the contract ([65a4cca](https://github.com/flashpi1/flashpi-python/commit/65a4cca1e0cf4512bb00d884623a1a285569e17b))
44
+ * send header values outside ASCII as UTF-8 on every request ([5bdf182](https://github.com/flashpi1/flashpi-python/commit/5bdf18227fb57f5a033858fd984056090b136813))
45
+ * trim a byte order mark around the API key, as Node does ([559a278](https://github.com/flashpi1/flashpi-python/commit/559a2783a271fc49fd3ff956f3afd8f61afd8f8f))
46
+ * **types:** type async with_response methods as coroutines ([5975f2c](https://github.com/flashpi1/flashpi-python/commit/5975f2c06821265d979b16a1babb75e50268244c))
flashpi-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SIGNIADIGITAL S.A.
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.
flashpi-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,472 @@
1
+ Metadata-Version: 2.5
2
+ Name: flashpi
3
+ Version: 0.1.0
4
+ Summary: The official Python SDK for Flashpi, the electronic invoicing API for Ecuador's SRI.
5
+ Project-URL: Homepage, https://flashpi.com.ec
6
+ Project-URL: Documentation, https://flashpi.com.ec/docs/sdks/
7
+ Project-URL: Repository, https://github.com/flashpi1/flashpi-python
8
+ Project-URL: Issues, https://github.com/flashpi1/flashpi-python/issues
9
+ Project-URL: Changelog, https://github.com/flashpi1/flashpi-python/blob/main/CHANGELOG.md
10
+ Author: SIGNIADIGITAL S.A.
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: e-invoicing,ecuador,facturacion electronica,flashpi,invoices,sdk,sri
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Programming Language :: Python :: 3.15
25
+ Classifier: Topic :: Office/Business :: Financial :: Accounting
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: >=3.11
29
+ Requires-Dist: httpx<1,>=0.27
30
+ Description-Content-Type: text/markdown
31
+
32
+ # Flashpi para Python
33
+
34
+ SDK oficial de [Flashpi](https://flashpi.com.ec), la API de facturación electrónica del SRI de
35
+ Ecuador, para Python.
36
+
37
+ [English](https://github.com/flashpi1/flashpi-python/blob/main/README.en.md)
38
+
39
+ - Las 45 operaciones de la API: los seis comprobantes, documentos (XML, RIDE en PDF, correo),
40
+ emisores con establecimientos, puntos de emisión y certificados .p12, webhooks y eventos.
41
+ - Un cliente síncrono (`Flashpi`) y uno asíncrono (`AsyncFlashpi`, asyncio) con los mismos
42
+ métodos.
43
+ - Tipos (`TypedDict`) generados del documento OpenAPI de la API: tu editor y tu verificador de
44
+ tipos conocen cada campo.
45
+ - Reintentos seguros: cada emisión lleva un `Idempotency-Key`, así un reintento nunca emite dos
46
+ veces.
47
+ - Errores tipados (RFC 9457) con su `code`, los errores por campo y el `request_id`.
48
+ - Paginación automática con `for` y `async for`.
49
+ - Verificación de firmas de webhooks (Standard Webhooks) para Django, Flask, FastAPI o cualquier
50
+ framework.
51
+ - Python 3.11 o superior. Una sola dependencia: [httpx](https://www.python-httpx.org/).
52
+
53
+ ## Instalación
54
+
55
+ ```bash
56
+ pip install flashpi
57
+ ```
58
+
59
+ También con `uv add flashpi` o `poetry add flashpi`.
60
+
61
+ ## Primeros pasos
62
+
63
+ Crea una clave de API en la [consola](https://flashpi.com.ec/app/) y guárdala en la variable de
64
+ entorno `FLASHPI_API_KEY`. Una clave `fp_test_` emite en el ambiente de pruebas del SRI; una
65
+ `fp_live_` emite comprobantes reales en producción.
66
+
67
+ ```python
68
+ from flashpi import Flashpi
69
+
70
+ # Lee FLASHPI_API_KEY; también puedes pasarla: Flashpi("fp_test_...")
71
+ flashpi = Flashpi()
72
+
73
+ invoice = flashpi.invoices.create(
74
+ {
75
+ "issuerId": "<id del emisor demo o del tuyo>",
76
+ "establishment": "001",
77
+ "emissionPoint": "001",
78
+ "customer": {
79
+ "idType": "ruc",
80
+ "id": "1760013210001",
81
+ "name": "PRUEBAS SERVICIO DE RENTAS INTERNAS",
82
+ "address": "Av. Amazonas y Villalengua, Quito",
83
+ },
84
+ "items": [
85
+ {
86
+ "code": "P-001",
87
+ "description": "Servicio de prueba",
88
+ "quantity": "1",
89
+ "unitPrice": "1.00",
90
+ "taxes": [{"type": "vat", "rate": "15"}],
91
+ }
92
+ ],
93
+ "payments": [{"method": "cash", "amount": "1.15"}],
94
+ "options": {"waitForAuthorization": True},
95
+ }
96
+ )
97
+
98
+ print(invoice["status"], invoice["accessKey"])
99
+ ```
100
+
101
+ Las peticiones y las respuestas son diccionarios con las claves de la API, en camelCase
102
+ (`invoice["accessKey"]`), tipados con los `TypedDict` de `flashpi.types`
103
+ (`from flashpi.types import CreateInvoice, Document`). Los montos y cantidades son **textos**
104
+ (`"1.15"`), nunca números, para no perder decimales.
105
+
106
+ Con el **emisor demo** puedes emitir en pruebas sin subir un certificado: su id está en el
107
+ Resumen de la consola (hasta 50 comprobantes al día). Más en
108
+ [Sandbox y emisor demo](https://flashpi.com.ec/docs/sandbox/).
109
+
110
+ Un cliente mantiene un grupo de conexiones: crea uno y reutilízalo. Ciérralo con
111
+ `flashpi.close()` o úsalo en un bloque `with`.
112
+
113
+ ## Asíncrono
114
+
115
+ `AsyncFlashpi` tiene los mismos recursos y métodos; espéralos con `await`.
116
+
117
+ ```python
118
+ import asyncio
119
+
120
+ from flashpi import AsyncFlashpi
121
+
122
+
123
+ async def main() -> None:
124
+ async with AsyncFlashpi() as flashpi:
125
+ status = await flashpi.status.get()
126
+ print(status["status"])
127
+
128
+ async for document in flashpi.documents.list({"status": "authorized"}):
129
+ print(document["accessKey"])
130
+
131
+
132
+ asyncio.run(main())
133
+ ```
134
+
135
+ Funciona sobre asyncio. Para cancelar una llamada, cancela su tarea (por ejemplo con
136
+ `asyncio.timeout()`). Sin `async with`, cierra el cliente con `await flashpi.aclose()`.
137
+
138
+ ## Emitir comprobantes
139
+
140
+ | Comprobante | Método |
141
+ | --------------------- | ------------------------------------------- |
142
+ | Factura | `flashpi.invoices.create(body)` |
143
+ | Nota de crédito | `flashpi.credit_notes.create(body)` |
144
+ | Nota de débito | `flashpi.debit_notes.create(body)` |
145
+ | Liquidación de compra | `flashpi.purchase_settlements.create(body)` |
146
+ | Guía de remisión | `flashpi.waybills.create(body)` |
147
+ | Retención | `flashpi.withholdings.create(body)` |
148
+
149
+ Todos devuelven el documento. Por defecto la respuesta llega enseguida con el estado
150
+ `processing` y el resultado del SRI llega por webhook. Con
151
+ `"options": {"waitForAuthorization": True}` la API espera la respuesta del SRI (15 s por defecto,
152
+ hasta 30 s con `waitTimeoutSeconds`) y devuelve `authorized`, `rejected` o `failed`; si el SRI
153
+ tarda más, devuelve `processing` o `pending_sri` y el documento sigue su curso.
154
+
155
+ ## Documentos
156
+
157
+ ```python
158
+ from pathlib import Path
159
+
160
+ document = flashpi.documents.get(invoice["id"])
161
+
162
+ xml = flashpi.documents.xml(invoice["id"]) # xml["kind"]: "authorized" cuando ya lo autorizó el SRI
163
+ pdf = flashpi.documents.pdf(invoice["id"]) # el RIDE, en bytes
164
+ Path(f"{invoice['accessKey']}.pdf").write_bytes(pdf)
165
+
166
+ flashpi.documents.send_email(invoice["id"]) # reenvía RIDE y XML al correo del comprador
167
+ ```
168
+
169
+ ## Listas y paginación
170
+
171
+ Una lista devuelve una página. Con `for` recorres todas las páginas, que se piden a medida que
172
+ avanzas:
173
+
174
+ ```python
175
+ for document in flashpi.documents.list({"status": "authorized", "issueDateFrom": "2026-11-01"}):
176
+ print(document["accessKey"])
177
+
178
+ page = flashpi.documents.list({"limit": 50})
179
+ print(len(page.data)) # los documentos de esta página
180
+ if page.has_next_page():
181
+ page = page.next_page()
182
+ ```
183
+
184
+ Los filtros usan los nombres de la API (`issueDateFrom`, `issuerId`). Con `AsyncFlashpi`,
185
+ `async for` recorre todas las páginas y `await flashpi.documents.list()` devuelve la primera
186
+ (`await page.next_page()` la siguiente).
187
+
188
+ ## Errores
189
+
190
+ Cada error de la API es una subclase de `APIError` según su estado HTTP. Decide según `code`,
191
+ que es estable y en inglés; `message` sigue el idioma pedido.
192
+
193
+ ```python
194
+ from flashpi import APIError, UnprocessableEntityError
195
+
196
+ try:
197
+ flashpi.invoices.create(body)
198
+ except UnprocessableEntityError as error:
199
+ print(error.code) # "validation_failed", "total_mismatch", ...
200
+ for field in error.errors:
201
+ print(field["field"], field["message"])
202
+ raise
203
+ except APIError as error:
204
+ print(error.status, error.code, error.request_id) # comparte request_id con soporte
205
+ raise
206
+ ```
207
+
208
+ | Clase | Estado | Ejemplos de `code` |
209
+ | -------------------------- | ------ | ----------------------------------------------------------- |
210
+ | `BadRequestError` | 400 | `malformed_json`, `invalid_idempotency_key` |
211
+ | `AuthenticationError` | 401 | `authentication_required`, `invalid_api_key` |
212
+ | `PermissionDeniedError` | 403 | `key_read_only`, `key_scope_mismatch`, `ip_not_allowed` |
213
+ | `NotFoundError` | 404 | `not_found` |
214
+ | `ConflictError` | 409 | `sequential_already_used`, `ride_not_available` |
215
+ | `UnprocessableEntityError` | 422 | `validation_failed`, `total_mismatch` |
216
+ | `RateLimitError` | 429 | `demo_issuer_quota_exceeded`, `account_email_limit_reached` |
217
+ | `InternalServerError` | 5xx | `internal_error` |
218
+ | `APIConnectionError` | — | sin respuesta (red); `APITimeoutError` si se agotó el plazo |
219
+
220
+ Todas derivan de `FlashpiError`. Algunos errores traen datos extra en `error.problem`, por
221
+ ejemplo `documentId`, `limit`, `resetsAt` o `rideStatus`. Para recibir los mensajes en español:
222
+ `Flashpi(language="es")`.
223
+
224
+ ## Reintentos e idempotencia
225
+
226
+ El SDK reintenta hasta 2 veces, con espera creciente, los errores de red, los tiempos agotados,
227
+ las respuestas 408, 429 (si piden esperar 60 s o menos) y 5xx. Cada POST lleva un
228
+ `Idempotency-Key` que se repite en sus reintentos, así que la API nunca emite dos veces:
229
+
230
+ - Si un reintento descubre que el primer intento sí creó el documento, el SDK devuelve ese
231
+ documento.
232
+ - Si el primer intento sigue en curso en la API (por ejemplo, se cortó la conexión mientras
233
+ esperaba al SRI), el SDK espera a que termine con la misma clave, hasta el tiempo límite de la
234
+ llamada, sin gastar reintentos.
235
+
236
+ Para usar tu propia clave (por ejemplo el id de tu pedido), pásala a la llamada:
237
+
238
+ ```python
239
+ flashpi.invoices.create(body, idempotency_key=f"pedido-{order.id}")
240
+ ```
241
+
242
+ Si una emisión falla igual, el error (un `FlashpiError`) trae la clave que usó en
243
+ `error.idempotency_key`. Reintentar con `idempotency_key=error.idempotency_key` nunca emite un
244
+ segundo documento: dentro de 24 horas la API devuelve la primera respuesta; después (o si la API
245
+ perdió el primer intento), la llamada falla con un 422 `idempotency_key_reused` cuyo
246
+ `error.problem["documentId"]` es el documento que ya existe (léelo con `flashpi.documents.get`).
247
+
248
+ ```python
249
+ from flashpi import FlashpiError
250
+
251
+ try:
252
+ flashpi.invoices.create(body)
253
+ except FlashpiError as error:
254
+ if error.idempotency_key:
255
+ save_for_retry(body, error.idempotency_key) # tu cola de reintentos
256
+ raise
257
+ ```
258
+
259
+ Una llamada de `AsyncFlashpi` cuya tarea se cancela lanza `asyncio.CancelledError`, que no es un
260
+ `FlashpiError` ni trae clave: si cancelas emisiones, pasa tu propio `idempotency_key`.
261
+
262
+ Los límites diarios (como la cuota del emisor demo) no se reintentan: se lanzan como
263
+ `RateLimitError` con `retry_after` en segundos.
264
+
265
+ ## Webhooks
266
+
267
+ Verifica cada webhook con el cuerpo **tal cual llegó** (sin parsear) y el secreto `whsec_` del
268
+ endpoint. `unwrap_webhook` no necesita clave de API (también está en `flashpi.webhooks.unwrap`).
269
+ No hace E/S, así que se llama sin `await` también en vistas asíncronas.
270
+
271
+ Con Django:
272
+
273
+ ```python
274
+ import os
275
+
276
+ from django.http import HttpRequest, HttpResponse, JsonResponse
277
+ from django.views.decorators.csrf import csrf_exempt
278
+ from django.views.decorators.http import require_POST
279
+
280
+ from flashpi import WebhookVerificationError, unwrap_webhook
281
+
282
+
283
+ @csrf_exempt
284
+ @require_POST
285
+ def flashpi_webhook(request: HttpRequest) -> HttpResponse:
286
+ try:
287
+ event = unwrap_webhook(request.body, request.headers, os.environ["FLASHPI_WEBHOOK_SECRET"])
288
+ except WebhookVerificationError:
289
+ return HttpResponse(status=400)
290
+
291
+ if event["type"] == "webhook_endpoint.verification":
292
+ # La activación del endpoint: responde el desafío.
293
+ return JsonResponse({"challenge": event["data"]["challenge"]})
294
+ if event["type"] == "invoice.authorized":
295
+ print("Autorizada", event["data"]["accessKey"]) # event["data"] es el documento
296
+ elif event["type"] == "invoice.rejected":
297
+ print("Rechazada", event["data"]["sriMessages"])
298
+ return HttpResponse(status=204)
299
+ ```
300
+
301
+ Con Flask (su `request.headers` no es un `Mapping`, así que pasa `dict(request.headers)`):
302
+
303
+ ```python
304
+ import os
305
+
306
+ from flask import Flask, request
307
+
308
+ from flashpi import WebhookVerificationError, unwrap_webhook
309
+
310
+ app = Flask(__name__)
311
+
312
+
313
+ @app.post("/webhooks/flashpi")
314
+ def flashpi_webhook():
315
+ try:
316
+ event = unwrap_webhook(
317
+ request.get_data(), dict(request.headers), os.environ["FLASHPI_WEBHOOK_SECRET"]
318
+ )
319
+ except WebhookVerificationError:
320
+ return "", 400
321
+
322
+ if event["type"] == "webhook_endpoint.verification":
323
+ return {"challenge": event["data"]["challenge"]}
324
+ handle_event(event) # tu código, como las ramas del ejemplo de Django
325
+ return "", 204
326
+ ```
327
+
328
+ Con FastAPI:
329
+
330
+ ```python
331
+ import os
332
+
333
+ from fastapi import FastAPI, Request, Response
334
+ from fastapi.responses import JSONResponse
335
+
336
+ from flashpi import WebhookVerificationError, unwrap_webhook
337
+
338
+ app = FastAPI()
339
+
340
+
341
+ @app.post("/webhooks/flashpi")
342
+ async def flashpi_webhook(request: Request) -> Response:
343
+ try:
344
+ event = unwrap_webhook(
345
+ await request.body(), request.headers, os.environ["FLASHPI_WEBHOOK_SECRET"]
346
+ )
347
+ except WebhookVerificationError:
348
+ return Response(status_code=400)
349
+
350
+ if event["type"] == "webhook_endpoint.verification":
351
+ return JSONResponse({"challenge": event["data"]["challenge"]})
352
+ handle_event(event) # tu código, como las ramas del ejemplo de Django
353
+ return Response(status_code=204)
354
+ ```
355
+
356
+ Guarda el `event["id"]` y descarta los repetidos: un evento puede llegar más de una vez. Durante
357
+ una rotación del secreto, Flashpi firma con el nuevo y el anterior, así que cualquiera de los dos
358
+ sirve. Si el endpoint usa el modo `thin` (sin `data`), usa
359
+ `cast(ThinWebhookEvent, unwrap_webhook(...))` y pide el evento con
360
+ `flashpi.events.get(event["id"])`.
361
+
362
+ ## Emisores y certificados
363
+
364
+ Estas operaciones necesitan una clave de toda la cuenta con acceso de lectura y escritura.
365
+
366
+ Un emisor nace de su firma electrónica (.p12): Flashpi la verifica, lee el RUC y consulta al SRI,
367
+ y te devuelve un `prefill` con lo que encontró para que armes el emisor.
368
+
369
+ ```python
370
+ import os
371
+ import time
372
+ from pathlib import Path
373
+
374
+ onboarding = flashpi.issuer_onboardings.create(
375
+ {"file": Path("firma.p12").read_bytes(), "password": os.environ["P12_PASSWORD"]}
376
+ )
377
+ while onboarding["status"] == "verifying":
378
+ time.sleep(2)
379
+ onboarding = flashpi.issuer_onboardings.get(onboarding["id"])
380
+ if onboarding["status"] != "ready":
381
+ rejection = onboarding["rejection"]
382
+ raise RuntimeError(rejection["message"] if rejection else onboarding["status"])
383
+
384
+ prefill = onboarding["prefill"]
385
+ if onboarding["existingIssuer"]:
386
+ # Ya tienes ese RUC: el certificado se agrega a ese emisor (una renovación).
387
+ completed = flashpi.issuer_onboardings.complete(onboarding["id"])
388
+ else:
389
+ # Un RUC nuevo: tú confirmas los datos del emisor, partiendo del prefill.
390
+ legal_name = prefill and prefill["legalName"]
391
+ address = prefill and prefill["headOfficeAddress"]
392
+ tax_profile = prefill and prefill["taxProfile"]
393
+ rimpe_regime = tax_profile and tax_profile["rimpeRegime"]
394
+ completed = flashpi.issuer_onboardings.complete(
395
+ onboarding["id"],
396
+ {
397
+ "legalName": legal_name or "MI EMPRESA S.A.",
398
+ "headOfficeAddress": address or "Av. Amazonas N24-100, Quito",
399
+ "taxProfile": {
400
+ "keepsAccounting": bool(tax_profile and tax_profile["keepsAccounting"]),
401
+ "rimpeRegime": None if rimpe_regime == "general" else rimpe_regime,
402
+ # Si es contribuyente especial o agente de retención, agrega sus resoluciones.
403
+ },
404
+ # Si onboarding["rucNeedsConfirmation"] es True, envía también "ruc".
405
+ },
406
+ )
407
+
408
+ for establishment in flashpi.issuers.establishments.list(completed["issuer"]["id"]):
409
+ print(establishment["code"])
410
+ ```
411
+
412
+ El `file` puede ser el contenido del .p12 en bytes o un archivo abierto en modo binario
413
+ (`open("firma.p12", "rb")`), de hasta 1 MiB.
414
+
415
+ Para **renovar la firma** de un emisor, para pruebas y producción a la vez, repite el mismo
416
+ flujo con el .p12 nuevo: Flashpi reconoce el RUC (`existingIssuer`) y `complete()` sin datos
417
+ agrega el certificado. En cambio,
418
+ `flashpi.issuers.certificates.upload(issuer_id, {"file": ..., "password": ...})` sube un
419
+ certificado solo para el modo de la clave que usas (pruebas o producción).
420
+
421
+ ## Opciones
422
+
423
+ ```python
424
+ import os
425
+
426
+ from flashpi import Flashpi
427
+
428
+ flashpi = Flashpi(
429
+ api_key=os.environ["FLASHPI_API_KEY"], # por defecto, la variable FLASHPI_API_KEY
430
+ language="es", # idioma de los mensajes: "en" (por defecto) o "es"
431
+ timeout=60, # segundos por intento (con waitForAuthorization, al menos la espera + 15 s)
432
+ max_retries=2, # 0 desactiva los reintentos
433
+ )
434
+ ```
435
+
436
+ Cada método acepta además, como argumentos con nombre, opciones de esa petición:
437
+ `idempotency_key`, `timeout`, `max_retries`, `language`, `correlation_id` (tu propio id, que
438
+ Flashpi registra) y `extra_headers`.
439
+
440
+ ```python
441
+ document = flashpi.documents.get(document_id, timeout=10, language="es", correlation_id="pedido-42")
442
+ ```
443
+
444
+ Para ver la respuesta HTTP y el id de la petición, llama al método a través de `with_response`:
445
+
446
+ ```python
447
+ result = flashpi.documents.with_response.get(document_id)
448
+ print(result.data["status"], result.response.status_code, result.request_id)
449
+ ```
450
+
451
+ Para enviar las peticiones con tu propio `httpx.Client` (`httpx.AsyncClient` con `AsyncFlashpi`),
452
+ por ejemplo con un proxy o un transporte de pruebas, pásalo en `http_client`. Tú lo cierras; el
453
+ SDK nunca sigue redirecciones.
454
+
455
+ ```python
456
+ import httpx
457
+
458
+ from flashpi import Flashpi
459
+
460
+ flashpi = Flashpi(http_client=httpx.Client(proxy="http://proxy.interno:3128"))
461
+ ```
462
+
463
+ En las pruebas, un `httpx.MockTransport` responde en lugar de la API.
464
+
465
+ ## Solo en el servidor
466
+
467
+ Tu clave de API es secreta: usa el SDK en tus servidores, nunca en código que corre en los
468
+ dispositivos de tus usuarios. `repr(flashpi)` muestra el ambiente y la URL, nunca la clave.
469
+
470
+ ## Licencia
471
+
472
+ [MIT](https://github.com/flashpi1/flashpi-python/blob/main/LICENSE) © 2026 SIGNIADIGITAL S.A.