dgiiapicloud 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.
- dgiiapicloud-0.1.0/PKG-INFO +63 -0
- dgiiapicloud-0.1.0/README.md +54 -0
- dgiiapicloud-0.1.0/pyproject.toml +18 -0
- dgiiapicloud-0.1.0/setup.cfg +4 -0
- dgiiapicloud-0.1.0/src/dgiiapicloud/__init__.py +296 -0
- dgiiapicloud-0.1.0/src/dgiiapicloud/cli.py +80 -0
- dgiiapicloud-0.1.0/src/dgiiapicloud.egg-info/PKG-INFO +63 -0
- dgiiapicloud-0.1.0/src/dgiiapicloud.egg-info/SOURCES.txt +9 -0
- dgiiapicloud-0.1.0/src/dgiiapicloud.egg-info/dependency_links.txt +1 -0
- dgiiapicloud-0.1.0/src/dgiiapicloud.egg-info/entry_points.txt +2 -0
- dgiiapicloud-0.1.0/src/dgiiapicloud.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dgiiapicloud
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python client for the DGII API Cloud (Dominican Republic fiscal services).
|
|
5
|
+
Author:
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# dgiiapicloud
|
|
11
|
+
|
|
12
|
+
`dgiiapicloud` is the official Python client for the DGII API Cloud, the hosted gateway over the
|
|
13
|
+
Dominican Republic's General Directorate of Internal Taxes (DGII) tax services. It normalises
|
|
14
|
+
the assorted JSON and XML endpoints exposed by DGII — RNC lookups, NCF validation, e-invoicing
|
|
15
|
+
status, and taxpayer circulars — behind a single, typed, retry-aware client. Use it to embed
|
|
16
|
+
Dominican fiscal verification into accounting apps, ERP integrations, or internal reconciliation
|
|
17
|
+
tools without hand-rolling HTTP and signature handling.
|
|
18
|
+
|
|
19
|
+
## Features
|
|
20
|
+
|
|
21
|
+
- `RncClient` for entity registry lookups by RNC or by business name with fuzzy matching.
|
|
22
|
+
- `NcfClient` to validate and decode NCF / e-NCF sequences returned by DGII.
|
|
23
|
+
- E-invoice status polling with exponential backoff and webhook signature verification.
|
|
24
|
+
- Automatic token refresh and request signing for the API Cloud OAuth2 flow.
|
|
25
|
+
- Pydantic models for every response, including the DGII error envelope.
|
|
26
|
+
- Async (`AsyncDgiiClient`) and sync (`DgiiClient`) entry points sharing one codebase.
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install dgiiapicloud
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick start
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from dgiiapicloud import DgiiClient, RncClient
|
|
38
|
+
|
|
39
|
+
with DgiiClient(client_id=..., client_secret=...) as client:
|
|
40
|
+
rnc = RncClient(client)
|
|
41
|
+
entity = rnc.lookup("131179123")
|
|
42
|
+
print(entity.razon_social, entity.estado, entity.tipo_empresa)
|
|
43
|
+
|
|
44
|
+
ncf = client.ncf.validate(rnc="131179123", ncf="E310000000001")
|
|
45
|
+
print(ncf.valid, ncf.tipo, ncf.fecha)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## API
|
|
49
|
+
|
|
50
|
+
- `DgiiClient(client_id, client_secret, *, sandbox=False)` — authenticated client over API Cloud.
|
|
51
|
+
- `RncClient.lookup(rnc: str)` — return a typed `Entity` from the registry.
|
|
52
|
+
- `NcfClient.validate(rnc: str, ncf: str)` — verify a fiscal document number.
|
|
53
|
+
- `InvoiceClient.status(track_id: str)` — poll the e-invoice submission status.
|
|
54
|
+
|
|
55
|
+
## Configuration
|
|
56
|
+
|
|
57
|
+
Set `DGII_CLIENT_ID`, `DGII_CLIENT_SECRET`, and `DGII_SANDBOX=1` in your environment to use the
|
|
58
|
+
test gateway. The client respects `HTTP_PROXY`/`HTTPS_PROXY` and a configurable
|
|
59
|
+
`DGII_TIMEOUT` (default 30 seconds).
|
|
60
|
+
|
|
61
|
+
## License
|
|
62
|
+
|
|
63
|
+
MIT
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# dgiiapicloud
|
|
2
|
+
|
|
3
|
+
`dgiiapicloud` is the official Python client for the DGII API Cloud, the hosted gateway over the
|
|
4
|
+
Dominican Republic's General Directorate of Internal Taxes (DGII) tax services. It normalises
|
|
5
|
+
the assorted JSON and XML endpoints exposed by DGII — RNC lookups, NCF validation, e-invoicing
|
|
6
|
+
status, and taxpayer circulars — behind a single, typed, retry-aware client. Use it to embed
|
|
7
|
+
Dominican fiscal verification into accounting apps, ERP integrations, or internal reconciliation
|
|
8
|
+
tools without hand-rolling HTTP and signature handling.
|
|
9
|
+
|
|
10
|
+
## Features
|
|
11
|
+
|
|
12
|
+
- `RncClient` for entity registry lookups by RNC or by business name with fuzzy matching.
|
|
13
|
+
- `NcfClient` to validate and decode NCF / e-NCF sequences returned by DGII.
|
|
14
|
+
- E-invoice status polling with exponential backoff and webhook signature verification.
|
|
15
|
+
- Automatic token refresh and request signing for the API Cloud OAuth2 flow.
|
|
16
|
+
- Pydantic models for every response, including the DGII error envelope.
|
|
17
|
+
- Async (`AsyncDgiiClient`) and sync (`DgiiClient`) entry points sharing one codebase.
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install dgiiapicloud
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Quick start
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from dgiiapicloud import DgiiClient, RncClient
|
|
29
|
+
|
|
30
|
+
with DgiiClient(client_id=..., client_secret=...) as client:
|
|
31
|
+
rnc = RncClient(client)
|
|
32
|
+
entity = rnc.lookup("131179123")
|
|
33
|
+
print(entity.razon_social, entity.estado, entity.tipo_empresa)
|
|
34
|
+
|
|
35
|
+
ncf = client.ncf.validate(rnc="131179123", ncf="E310000000001")
|
|
36
|
+
print(ncf.valid, ncf.tipo, ncf.fecha)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## API
|
|
40
|
+
|
|
41
|
+
- `DgiiClient(client_id, client_secret, *, sandbox=False)` — authenticated client over API Cloud.
|
|
42
|
+
- `RncClient.lookup(rnc: str)` — return a typed `Entity` from the registry.
|
|
43
|
+
- `NcfClient.validate(rnc: str, ncf: str)` — verify a fiscal document number.
|
|
44
|
+
- `InvoiceClient.status(track_id: str)` — poll the e-invoice submission status.
|
|
45
|
+
|
|
46
|
+
## Configuration
|
|
47
|
+
|
|
48
|
+
Set `DGII_CLIENT_ID`, `DGII_CLIENT_SECRET`, and `DGII_SANDBOX=1` in your environment to use the
|
|
49
|
+
test gateway. The client respects `HTTP_PROXY`/`HTTPS_PROXY` and a configurable
|
|
50
|
+
`DGII_TIMEOUT` (default 30 seconds).
|
|
51
|
+
|
|
52
|
+
## License
|
|
53
|
+
|
|
54
|
+
MIT
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "dgiiapicloud"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Official Python client for the DGII API Cloud (Dominican Republic fiscal services)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [{name = ""}]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
dgiiapicloud = "dgiiapicloud.cli:main"
|
|
16
|
+
|
|
17
|
+
[tool.setuptools.packages.find]
|
|
18
|
+
where = ["src"]
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
"""dgiiapicloud — official Python client for the DGII API Cloud.
|
|
2
|
+
|
|
3
|
+
A typed, retry-aware gateway over the Dominican Republic's General Directorate
|
|
4
|
+
of Internal Taxes (DGII) services: RNC lookups, NCF validation, e-invoicing
|
|
5
|
+
status, and taxpayer circulars. Sync + async clients over an injectable HTTP
|
|
6
|
+
transport.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import time
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.parse
|
|
18
|
+
import urllib.request
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from typing import Any, Protocol
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"DgiiError",
|
|
26
|
+
"DgiiClient",
|
|
27
|
+
"RncClient",
|
|
28
|
+
"NcfClient",
|
|
29
|
+
"InvoiceClient",
|
|
30
|
+
"Entity",
|
|
31
|
+
"NcfValidation",
|
|
32
|
+
"InvoiceStatus",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
PROD_BASE_URL = "https://api.dgiiapicloud.do"
|
|
36
|
+
SANDBOX_BASE_URL = "https://sandbox.api.dgiiapicloud.do"
|
|
37
|
+
|
|
38
|
+
_RNC_RE = re.compile(r"^\d{9,11}$")
|
|
39
|
+
_NCF_RE = re.compile(r"^[A-Z]\d{2}\d{8,11}$")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class DgiiError(Exception):
|
|
43
|
+
"""Raised on DGII transport- or application-level errors."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, message: str, *, status: int | None = None, body: Any = None) -> None:
|
|
46
|
+
super().__init__(message)
|
|
47
|
+
self.status = status
|
|
48
|
+
self.body = body
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Entity:
|
|
53
|
+
"""A taxpayer registry entry."""
|
|
54
|
+
|
|
55
|
+
rnc: str
|
|
56
|
+
razon_social: str
|
|
57
|
+
estado: str
|
|
58
|
+
tipo_empresa: str = ""
|
|
59
|
+
activo: bool = True
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class NcfValidation:
|
|
64
|
+
"""Result of validating an NCF / e-NCF sequence."""
|
|
65
|
+
|
|
66
|
+
ncf: str
|
|
67
|
+
valid: bool
|
|
68
|
+
tipo: str = ""
|
|
69
|
+
fecha: str = ""
|
|
70
|
+
rnc: str = ""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class InvoiceStatus:
|
|
75
|
+
"""E-invoice submission status."""
|
|
76
|
+
|
|
77
|
+
track_id: str
|
|
78
|
+
estado: str # aceptado, procesando, rechazado
|
|
79
|
+
mensaje: str = ""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class _Transport(Protocol):
|
|
83
|
+
def request(self, method: str, url: str, *, headers: dict[str, str], body: bytes | None, timeout: float) -> tuple[int, bytes]: ...
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class _HttpTransport:
|
|
87
|
+
def request(self, method, url, *, headers, body, timeout):
|
|
88
|
+
req = urllib.request.Request(url, data=body, method=method, headers=headers)
|
|
89
|
+
try:
|
|
90
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310
|
|
91
|
+
return resp.status, resp.read()
|
|
92
|
+
except urllib.error.HTTPError as exc:
|
|
93
|
+
return exc.code, exc.read() if exc.fp else b""
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class _Auth:
|
|
97
|
+
def __init__(self, transport, base_url, client_id, client_secret, timeout):
|
|
98
|
+
self._t = transport
|
|
99
|
+
self._base = base_url
|
|
100
|
+
self._id = client_id
|
|
101
|
+
self._sec = client_secret
|
|
102
|
+
self._timeout = timeout
|
|
103
|
+
self._token: str | None = None
|
|
104
|
+
self._exp = 0.0
|
|
105
|
+
|
|
106
|
+
def token(self) -> str:
|
|
107
|
+
if self._token is None or time.time() >= self._exp - 30:
|
|
108
|
+
url = f"{self._base}/oauth/token"
|
|
109
|
+
payload = json.dumps({"grant_type": "client_credentials", "client_id": self._id, "client_secret": self._sec}).encode()
|
|
110
|
+
status, body = self._t.request("POST", url, headers={"content-type": "application/json"}, body=payload, timeout=self._timeout)
|
|
111
|
+
if status != 200:
|
|
112
|
+
raise DgiiError("auth failed", status=status, body=body)
|
|
113
|
+
data = json.loads(body)
|
|
114
|
+
self._token = data["access_token"]
|
|
115
|
+
self._exp = time.time() + float(data.get("expires_in", 3600))
|
|
116
|
+
return self._token # type: ignore[return-value]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class RncClient:
|
|
120
|
+
"""Entity registry lookups."""
|
|
121
|
+
|
|
122
|
+
def __init__(self, root: "DgiiClient") -> None:
|
|
123
|
+
self._root = root
|
|
124
|
+
|
|
125
|
+
def lookup(self, rnc: str) -> Entity:
|
|
126
|
+
if not _RNC_RE.match(rnc or ""):
|
|
127
|
+
raise DgiiError(f"invalid RNC: {rnc!r}")
|
|
128
|
+
data = self._root._get(f"/rnc/{rnc}")
|
|
129
|
+
return Entity(
|
|
130
|
+
rnc=data["rnc"],
|
|
131
|
+
razon_social=data["razon_social"],
|
|
132
|
+
estado=data["estado"],
|
|
133
|
+
tipo_empresa=data.get("tipo_empresa", ""),
|
|
134
|
+
activo=bool(data.get("activo", True)),
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
def search(self, name: str, *, limit: int = 10) -> list[Entity]:
|
|
138
|
+
if not name or len(name) < 3:
|
|
139
|
+
raise DgiiError("name must be at least 3 characters")
|
|
140
|
+
q = urllib.parse.urlencode({"q": name, "limit": limit})
|
|
141
|
+
data = self._root._get(f"/rnc/search?{q}")
|
|
142
|
+
return [Entity(**e) for e in data.get("items", [])]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class NcfClient:
|
|
146
|
+
"""NCF / e-NCF validation."""
|
|
147
|
+
|
|
148
|
+
def __init__(self, root: "DgiiClient") -> None:
|
|
149
|
+
self._root = root
|
|
150
|
+
|
|
151
|
+
def validate(self, *, rnc: str, ncf: str) -> NcfValidation:
|
|
152
|
+
if not _RNC_RE.match(rnc or ""):
|
|
153
|
+
raise DgiiError(f"invalid RNC: {rnc!r}")
|
|
154
|
+
if not _NCF_RE.match(ncf or ""):
|
|
155
|
+
raise DgiiError(f"invalid NCF: {ncf!r}")
|
|
156
|
+
data = self._root._get(f"/ncf/validate?rnc={rnc}&ncf={ncf}")
|
|
157
|
+
return NcfValidation(
|
|
158
|
+
ncf=data.get("ncf", ncf),
|
|
159
|
+
valid=bool(data.get("valid", False)),
|
|
160
|
+
tipo=data.get("tipo", ""),
|
|
161
|
+
fecha=data.get("fecha", ""),
|
|
162
|
+
rnc=data.get("rnc", rnc),
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class InvoiceClient:
|
|
167
|
+
"""E-invoice submission status polling."""
|
|
168
|
+
|
|
169
|
+
def __init__(self, root: "DgiiClient") -> None:
|
|
170
|
+
self._root = root
|
|
171
|
+
|
|
172
|
+
def status(self, track_id: str) -> InvoiceStatus:
|
|
173
|
+
if not track_id:
|
|
174
|
+
raise DgiiError("track_id is required")
|
|
175
|
+
data = self._root._get(f"/invoices/{track_id}/status")
|
|
176
|
+
return InvoiceStatus(track_id=data.get("track_id", track_id), estado=data.get("estado", ""), mensaje=data.get("mensaje", ""))
|
|
177
|
+
|
|
178
|
+
def poll(self, track_id: str, *, timeout: float = 60.0, interval: float = 2.0) -> InvoiceStatus:
|
|
179
|
+
"""Poll status with exponential backoff until terminal or timeout."""
|
|
180
|
+
deadline = time.time() + timeout
|
|
181
|
+
delay = interval
|
|
182
|
+
while time.time() < deadline:
|
|
183
|
+
status = self.status(track_id)
|
|
184
|
+
if status.estado in {"aceptado", "rechazado"}:
|
|
185
|
+
return status
|
|
186
|
+
time.sleep(delay)
|
|
187
|
+
delay = min(delay * 1.5, 10.0)
|
|
188
|
+
return self.status(track_id)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class DgiiClient:
|
|
192
|
+
"""Authenticated DGII API Cloud client.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
client_id / client_secret: OAuth2 credentials (or env vars).
|
|
196
|
+
sandbox: use the sandbox gateway.
|
|
197
|
+
timeout: per-request timeout in seconds.
|
|
198
|
+
transport: injectable HTTP transport for tests.
|
|
199
|
+
"""
|
|
200
|
+
|
|
201
|
+
def __init__(
|
|
202
|
+
self,
|
|
203
|
+
client_id: str | None = None,
|
|
204
|
+
client_secret: str | None = None,
|
|
205
|
+
*,
|
|
206
|
+
sandbox: bool | None = None,
|
|
207
|
+
base_url: str | None = None,
|
|
208
|
+
timeout: float | None = None,
|
|
209
|
+
transport: _Transport | None = None,
|
|
210
|
+
) -> None:
|
|
211
|
+
self.client_id = client_id or os.environ.get("DGII_CLIENT_ID")
|
|
212
|
+
self.client_secret = client_secret or os.environ.get("DGII_CLIENT_SECRET")
|
|
213
|
+
if not self.client_id or not self.client_secret:
|
|
214
|
+
raise DgiiError("client_id and client_secret are required")
|
|
215
|
+
sandbox = sandbox or os.environ.get("DGII_SANDBOX") == "1"
|
|
216
|
+
self.base_url = base_url or (SANDBOX_BASE_URL if sandbox else PROD_BASE_URL)
|
|
217
|
+
self.timeout = float(timeout if timeout is not None else os.environ.get("DGII_TIMEOUT", 30))
|
|
218
|
+
self._transport: _Transport = transport or _HttpTransport()
|
|
219
|
+
self._auth = _Auth(self._transport, self.base_url, self.client_id, self.client_secret, self.timeout)
|
|
220
|
+
|
|
221
|
+
self.rnc = RncClient(self)
|
|
222
|
+
self.ncf = NcfClient(self)
|
|
223
|
+
self.invoices = InvoiceClient(self)
|
|
224
|
+
|
|
225
|
+
def __enter__(self) -> "DgiiClient":
|
|
226
|
+
return self
|
|
227
|
+
|
|
228
|
+
def __exit__(self, *exc: object) -> None:
|
|
229
|
+
pass
|
|
230
|
+
|
|
231
|
+
def _headers(self) -> dict[str, str]:
|
|
232
|
+
return {"authorization": f"Bearer {self._auth.token()}", "accept": "application/json"}
|
|
233
|
+
|
|
234
|
+
def _request(self, method: str, path: str, json_body: dict[str, Any] | None = None) -> Any:
|
|
235
|
+
url = f"{self.base_url}{path}"
|
|
236
|
+
body = json.dumps(json_body).encode() if json_body is not None else None
|
|
237
|
+
headers = self._headers()
|
|
238
|
+
if body is not None:
|
|
239
|
+
headers["content-type"] = "application/json"
|
|
240
|
+
status, resp = self._transport.request(method, url, headers=headers, body=body, timeout=self.timeout)
|
|
241
|
+
if status >= 400:
|
|
242
|
+
try:
|
|
243
|
+
err = json.loads(resp) if resp else None
|
|
244
|
+
except json.JSONDecodeError:
|
|
245
|
+
err = resp.decode(errors="replace")
|
|
246
|
+
raise DgiiError(f"{method} {path} failed", status=status, body=err)
|
|
247
|
+
if not resp:
|
|
248
|
+
return None
|
|
249
|
+
return json.loads(resp)
|
|
250
|
+
|
|
251
|
+
def _get(self, path: str) -> Any:
|
|
252
|
+
return self._request("GET", path)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
class _AsyncNamespace:
|
|
256
|
+
"""Wraps a sync namespace (``rnc``/``ncf``/``invoices``) so its methods run
|
|
257
|
+
in a thread via :func:`asyncio.to_thread`."""
|
|
258
|
+
|
|
259
|
+
def __init__(self, ns: Any) -> None:
|
|
260
|
+
self._ns = ns
|
|
261
|
+
|
|
262
|
+
def __getattr__(self, name: str) -> Any:
|
|
263
|
+
attr = getattr(self._ns, name)
|
|
264
|
+
if not callable(attr):
|
|
265
|
+
return attr
|
|
266
|
+
async def wrapper(*a, **kw):
|
|
267
|
+
return await asyncio.to_thread(attr, *a, **kw)
|
|
268
|
+
return wrapper
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class AsyncDgiiClient:
|
|
272
|
+
"""Async thin wrapper around :class:`DgiiClient`.
|
|
273
|
+
|
|
274
|
+
Each coroutine delegates to a thread so the sync client does the actual
|
|
275
|
+
HTTP work; this keeps the async API identical to the sync surface.
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
279
|
+
self._sync = DgiiClient(*args, **kwargs)
|
|
280
|
+
|
|
281
|
+
async def __aenter__(self) -> "AsyncDgiiClient":
|
|
282
|
+
return self
|
|
283
|
+
|
|
284
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
285
|
+
pass
|
|
286
|
+
|
|
287
|
+
def __getattr__(self, name: str) -> Any:
|
|
288
|
+
attr = getattr(self._sync, name)
|
|
289
|
+
# Namespaces (rnc/ncf/invoices) — wrap their methods in threads.
|
|
290
|
+
if name in {"rnc", "ncf", "invoices"}:
|
|
291
|
+
return _AsyncNamespace(attr)
|
|
292
|
+
if callable(attr):
|
|
293
|
+
async def wrapper(*a, **kw):
|
|
294
|
+
return await asyncio.to_thread(attr, *a, **kw)
|
|
295
|
+
return wrapper
|
|
296
|
+
return attr
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""CLI for dgiiapicloud."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from . import DgiiClient, DgiiError
|
|
11
|
+
|
|
12
|
+
__all__ = ["main"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _client(args) -> DgiiClient:
|
|
16
|
+
try:
|
|
17
|
+
return DgiiClient(sandbox=args.sandbox)
|
|
18
|
+
except DgiiError as exc:
|
|
19
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
20
|
+
sys.exit(2)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _cmd_rnc(args: argparse.Namespace) -> int:
|
|
24
|
+
try:
|
|
25
|
+
ent = _client(args).rnc.lookup(args.rnc)
|
|
26
|
+
print(json.dumps(vars(ent)))
|
|
27
|
+
return 0
|
|
28
|
+
except DgiiError as exc:
|
|
29
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
30
|
+
return 1
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _cmd_ncf(args: argparse.Namespace) -> int:
|
|
34
|
+
try:
|
|
35
|
+
v = _client(args).ncf.validate(rnc=args.rnc, ncf=args.ncf)
|
|
36
|
+
print(json.dumps(vars(v)))
|
|
37
|
+
return 0
|
|
38
|
+
except DgiiError as exc:
|
|
39
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
40
|
+
return 1
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _cmd_invoice(args: argparse.Namespace) -> int:
|
|
44
|
+
try:
|
|
45
|
+
s = _client(args).invoices.status(args.track_id)
|
|
46
|
+
print(json.dumps(vars(s)))
|
|
47
|
+
return 0
|
|
48
|
+
except DgiiError as exc:
|
|
49
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
50
|
+
return 1
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
54
|
+
parser = argparse.ArgumentParser(prog="dgiiapicloud", description="DGII API Cloud client")
|
|
55
|
+
parser.add_argument("--sandbox", action="store_true", help="use the sandbox gateway")
|
|
56
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
57
|
+
|
|
58
|
+
p = sub.add_parser("rnc", help="lookup an entity by RNC")
|
|
59
|
+
p.add_argument("rnc")
|
|
60
|
+
p.set_defaults(func=_cmd_rnc)
|
|
61
|
+
|
|
62
|
+
p = sub.add_parser("ncf", help="validate an NCF")
|
|
63
|
+
p.add_argument("rnc")
|
|
64
|
+
p.add_argument("ncf")
|
|
65
|
+
p.set_defaults(func=_cmd_ncf)
|
|
66
|
+
|
|
67
|
+
p = sub.add_parser("invoice", help="e-invoice status")
|
|
68
|
+
p.add_argument("track_id")
|
|
69
|
+
p.set_defaults(func=_cmd_invoice)
|
|
70
|
+
|
|
71
|
+
return parser
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def main(argv: list[str] | None = None) -> int:
|
|
75
|
+
args = build_parser().parse_args(argv)
|
|
76
|
+
return args.func(args)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
if __name__ == "__main__":
|
|
80
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dgiiapicloud
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python client for the DGII API Cloud (Dominican Republic fiscal services).
|
|
5
|
+
Author:
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# dgiiapicloud
|
|
11
|
+
|
|
12
|
+
`dgiiapicloud` is the official Python client for the DGII API Cloud, the hosted gateway over the
|
|
13
|
+
Dominican Republic's General Directorate of Internal Taxes (DGII) tax services. It normalises
|
|
14
|
+
the assorted JSON and XML endpoints exposed by DGII — RNC lookups, NCF validation, e-invoicing
|
|
15
|
+
status, and taxpayer circulars — behind a single, typed, retry-aware client. Use it to embed
|
|
16
|
+
Dominican fiscal verification into accounting apps, ERP integrations, or internal reconciliation
|
|
17
|
+
tools without hand-rolling HTTP and signature handling.
|
|
18
|
+
|
|
19
|
+
## Features
|
|
20
|
+
|
|
21
|
+
- `RncClient` for entity registry lookups by RNC or by business name with fuzzy matching.
|
|
22
|
+
- `NcfClient` to validate and decode NCF / e-NCF sequences returned by DGII.
|
|
23
|
+
- E-invoice status polling with exponential backoff and webhook signature verification.
|
|
24
|
+
- Automatic token refresh and request signing for the API Cloud OAuth2 flow.
|
|
25
|
+
- Pydantic models for every response, including the DGII error envelope.
|
|
26
|
+
- Async (`AsyncDgiiClient`) and sync (`DgiiClient`) entry points sharing one codebase.
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install dgiiapicloud
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick start
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from dgiiapicloud import DgiiClient, RncClient
|
|
38
|
+
|
|
39
|
+
with DgiiClient(client_id=..., client_secret=...) as client:
|
|
40
|
+
rnc = RncClient(client)
|
|
41
|
+
entity = rnc.lookup("131179123")
|
|
42
|
+
print(entity.razon_social, entity.estado, entity.tipo_empresa)
|
|
43
|
+
|
|
44
|
+
ncf = client.ncf.validate(rnc="131179123", ncf="E310000000001")
|
|
45
|
+
print(ncf.valid, ncf.tipo, ncf.fecha)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## API
|
|
49
|
+
|
|
50
|
+
- `DgiiClient(client_id, client_secret, *, sandbox=False)` — authenticated client over API Cloud.
|
|
51
|
+
- `RncClient.lookup(rnc: str)` — return a typed `Entity` from the registry.
|
|
52
|
+
- `NcfClient.validate(rnc: str, ncf: str)` — verify a fiscal document number.
|
|
53
|
+
- `InvoiceClient.status(track_id: str)` — poll the e-invoice submission status.
|
|
54
|
+
|
|
55
|
+
## Configuration
|
|
56
|
+
|
|
57
|
+
Set `DGII_CLIENT_ID`, `DGII_CLIENT_SECRET`, and `DGII_SANDBOX=1` in your environment to use the
|
|
58
|
+
test gateway. The client respects `HTTP_PROXY`/`HTTPS_PROXY` and a configurable
|
|
59
|
+
`DGII_TIMEOUT` (default 30 seconds).
|
|
60
|
+
|
|
61
|
+
## License
|
|
62
|
+
|
|
63
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/dgiiapicloud/__init__.py
|
|
4
|
+
src/dgiiapicloud/cli.py
|
|
5
|
+
src/dgiiapicloud.egg-info/PKG-INFO
|
|
6
|
+
src/dgiiapicloud.egg-info/SOURCES.txt
|
|
7
|
+
src/dgiiapicloud.egg-info/dependency_links.txt
|
|
8
|
+
src/dgiiapicloud.egg-info/entry_points.txt
|
|
9
|
+
src/dgiiapicloud.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
dgiiapicloud
|