diotp 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.
diotp-1.0.0/.gitignore ADDED
@@ -0,0 +1,19 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .eggs/
5
+ build/
6
+ dist/
7
+ .venv*/
8
+ venv/
9
+ .env
10
+ .coverage
11
+ .coverage.*
12
+ coverage.xml
13
+ htmlcov/
14
+ .pytest_cache/
15
+ .mypy_cache/
16
+ .ruff_cache/
17
+ .DS_Store
18
+ .idea/
19
+ .vscode/
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [1.0.0] - 2026-12-03
8
+
9
+ ### Added
10
+
11
+ - `DiOTP` (sync) and `AsyncDiOTP` (async) clients built on httpx, usable as context managers.
12
+ - `send`, `verify`, `resend` (a helper over `POST /otp/send`), `me`, `usage` and `is_test_mode`.
13
+ `send_otp`, `verify_otp` and `resend_otp` are other names for the first three.
14
+ - Typed, frozen dataclass results: `SendResult`, `VerifyResult`, `Account`, `Usage`, `WebhookEvent`.
15
+ - A typed exception for every documented error code, under `DiOTPError`, and `ERROR_CODES` mapping each
16
+ code to its class.
17
+ - Automatic retries with exponential backoff and full jitter on network errors and 5xx responses; `verify`
18
+ retries only on network errors and 502, 503 and 504.
19
+ - An `Idempotency-Key` (UUID v4) on every send, reused across that call's retries.
20
+ - API key from the `DIOTP_API_KEY` environment variable, masked in every repr.
21
+ - Webhook verification: `verify_webhook` and `verify_webhook_headers`, with a constant-time compare and a
22
+ timestamp tolerance.
23
+
24
+ [1.0.0]: https://github.com/Diorbit-Technologies-LLP/diotp-python/releases/tag/v1.0.0
diotp-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Diorbit Technologies LLP
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.
diotp-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,301 @@
1
+ Metadata-Version: 2.5
2
+ Name: diotp
3
+ Version: 1.0.0
4
+ Summary: Official Python client for the DiOTP OTP API: send and verify one-time passwords by SMS or WhatsApp.
5
+ Project-URL: Homepage, https://diotp.diorbit.com/docs/sdks
6
+ Project-URL: Documentation, https://diotp.diorbit.com/docs
7
+ Project-URL: Repository, https://github.com/Diorbit-Technologies-LLP/diotp-python
8
+ Project-URL: Issues, https://github.com/Diorbit-Technologies-LLP/diotp-python/issues
9
+ Project-URL: Changelog, https://github.com/Diorbit-Technologies-LLP/diotp-python/blob/main/CHANGELOG.md
10
+ Author-email: Diorbit Technologies LLP <otp-support@diorbit.com>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: 2fa,diotp,india,otp,sms,verification,whatsapp
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Communications :: Telephony
25
+ Classifier: Topic :: Security
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: >=3.9
29
+ Requires-Dist: httpx<1,>=0.24
30
+ Description-Content-Type: text/markdown
31
+
32
+ # DiOTP Python SDK
33
+
34
+ [![PyPI version](https://img.shields.io/pypi/v/diotp.svg)](https://pypi.org/project/diotp/)
35
+ [![Python versions](https://img.shields.io/pypi/pyversions/diotp.svg)](https://pypi.org/project/diotp/)
36
+ [![CI](https://github.com/Diorbit-Technologies-LLP/diotp-python/actions/workflows/ci.yml/badge.svg)](https://github.com/Diorbit-Technologies-LLP/diotp-python/actions/workflows/ci.yml)
37
+ [![License: MIT](https://img.shields.io/github/license/Diorbit-Technologies-LLP/diotp-python.svg)](https://github.com/Diorbit-Technologies-LLP/diotp-python/blob/main/LICENSE)
38
+
39
+ The official Python client for the [DiOTP](https://diotp.diorbit.com) OTP API. Send a one-time password by SMS
40
+ (or WhatsApp, once it is switched on for your account) and verify the code your user types.
41
+
42
+ - Sync (`DiOTP`) and async (`AsyncDiOTP`) clients with the same methods.
43
+ - Typed, immutable results and a typed exception for every documented error code.
44
+ - Automatic retries with exponential backoff, and an `Idempotency-Key` on every send so a retry never sends a
45
+ second code.
46
+ - Webhook signature verification.
47
+ - Python 3.9 or later. One dependency: [httpx](https://www.python-httpx.org/).
48
+
49
+ Documentation: [https://diotp.diorbit.com/docs](https://diotp.diorbit.com/docs) (SDK page:
50
+ [diotp.diorbit.com/docs/sdks](https://diotp.diorbit.com/docs/sdks)).
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ pip install diotp
56
+ ```
57
+
58
+ ## Quickstart
59
+
60
+ Keep your API key on the server, in the `DIOTP_API_KEY` environment variable.
61
+
62
+ ```python
63
+ from diotp import DiOTP, InvalidCodeError
64
+
65
+ client = DiOTP() # reads DIOTP_API_KEY
66
+ otp = client.send("9876543210") # country code 91 by default; keep otp.request_id
67
+
68
+ try:
69
+ client.verify(otp.request_id, "482913") # the code the user typed
70
+ print("verified")
71
+ except InvalidCodeError:
72
+ print("wrong code, try again")
73
+ ```
74
+
75
+ Async:
76
+
77
+ ```python
78
+ import asyncio
79
+ from diotp import AsyncDiOTP
80
+
81
+
82
+ async def main() -> None:
83
+ async with AsyncDiOTP() as client:
84
+ otp = await client.send("9876543210")
85
+ result = await client.verify(otp.request_id, "482913")
86
+ print(result.verified_at)
87
+
88
+
89
+ asyncio.run(main())
90
+ ```
91
+
92
+ ## Methods
93
+
94
+ | Method | Endpoint | Returns |
95
+ |---|---|---|
96
+ | `send(to, *, country_code=91, channel="sms", purpose="login", template=None, idempotency_key=None)` | `POST /v1/otp/send` | `SendResult` |
97
+ | `verify(request_id, code)` | `POST /v1/otp/verify` | `VerifyResult` |
98
+ | `resend(to, *, country_code=91, channel="sms", purpose="login", template=None)` | `POST /v1/otp/send` (helper) | `SendResult` |
99
+ | `me()` | `GET /v1/me` | `Account` |
100
+ | `usage(period=None)` | `GET /v1/usage?period=YYYY-MM` | `Usage` |
101
+ | `is_test_mode()` | `GET /v1/me` | `bool` |
102
+
103
+ On `AsyncDiOTP` every method is a coroutine. `send_otp`, `verify_otp` and `resend_otp` are other names for
104
+ `send`, `verify` and `resend`.
105
+
106
+ The fields match [Send an OTP](https://diotp.diorbit.com/docs/send-otp) and
107
+ [Verify an OTP](https://diotp.diorbit.com/docs/verify-otp): `country_code` is an integer (default 91) and `code`
108
+ is a string of 4 to 10 characters.
109
+
110
+ - `to` is the mobile number, digits only (6 to 15). For India, the 10-digit number without +91.
111
+ - `SendResult` has `request_id`, `channel`, `expires_at` (a timezone-aware `datetime`, 5 minutes after sending)
112
+ and `idempotency_key`.
113
+ - `VerifyResult` has `request_id`, `verified` (always `True`) and `verified_at`. Every failure raises instead.
114
+ - `Account` has `client` (`id`, `name`, `status`) and `key` (`id`, `name`, `last_four`).
115
+ - `Usage` has `period`, `attempts`, `accepted`, `billable_units` and `amount`. `amount` is a decimal string such
116
+ as `"16.00"`, kept as a string so nothing is lost to floating point. Use `decimal.Decimal(usage.amount)`.
117
+ - Every result keeps the decoded JSON in `.raw`.
118
+
119
+ ### Resending a code
120
+
121
+ `resend` is a helper, not a separate endpoint. There is no resend endpoint in the API. It calls
122
+ `POST /v1/otp/send` again with a new `Idempotency-Key`, so a new code is sent and you get a new `request_id`:
123
+ verify against that one. The API allows one code to the same number every 30 seconds. Call `resend` sooner
124
+ and it raises `RateLimitError` with code `resend_cooldown`, so show a 30-second resend timer in your app.
125
+
126
+ ## Configuration
127
+
128
+ ```python
129
+ from diotp import DiOTP
130
+
131
+ client = DiOTP(
132
+ api_key="...", # default: the DIOTP_API_KEY environment variable
133
+ base_url="https://api-diotp.diorbit.com/v1", # default
134
+ timeout=10.0, # seconds per attempt, default 10
135
+ max_retries=2, # default 2; 0 disables retries
136
+ http_client=None, # optional httpx.Client (httpx.AsyncClient for AsyncDiOTP)
137
+ )
138
+ ```
139
+
140
+ If no key is passed and `DIOTP_API_KEY` is not set, the constructor raises `ConfigurationError`.
141
+
142
+ The key is never logged or included in error messages. `repr(client)` shows it masked, as `dio_...` and its last
143
+ four characters.
144
+
145
+ Use the client as a context manager, or call `close()` (`await aclose()` for `AsyncDiOTP`) when done. A client
146
+ you pass in through `http_client` is yours to close.
147
+
148
+ ## Error handling
149
+
150
+ Every error derives from `DiOTPError`, which has:
151
+
152
+ - `code`: the stable error code, such as `invalid_code`. Branch on this.
153
+ - `status`: the HTTP status, or `None` when there was no response.
154
+ - `message`: a sentence for people. Its wording can change.
155
+ - `request_id`: the id of the request (also the `X-Request-Id` header). Quote it to support.
156
+
157
+ | Exception | Status and codes |
158
+ |---|---|
159
+ | `AuthenticationError` | 401 `unauthorized` |
160
+ | `InsufficientBalanceError` | 402 `insufficient_balance` |
161
+ | `PermissionDeniedError` | 403 `account_suspended` |
162
+ | `TrialError` | test mode: 402 `trial_used_up`, 403 `trial_restricted`, 429 `test_limit` |
163
+ | `InvalidCodeError` (a `ValidationError`) | 400 `invalid_code` |
164
+ | `ValidationError` | 422 `invalid_request`, `template_not_available` |
165
+ | `NotFoundError` | 404 `not_found` |
166
+ | `ConflictError` | 409 `already_verified`, `not_pending`, `idempotency_key_reused`, `channel_not_enabled` |
167
+ | `ExpiredError` | 410 `expired` |
168
+ | `RateLimitError` | 429 `resend_cooldown`, `phone_hourly_limit`, `phone_daily_limit`, `api_key_minute_limit`, `rate_limited`, `too_many_attempts` |
169
+ | `ServerError` | 5xx, such as 503 `sending_unavailable` |
170
+ | `NetworkError` | no response: timeout, DNS failure, connection reset |
171
+ | `ConfigurationError` | no API key, or an invalid setting |
172
+ | `WebhookSignatureError` | a webhook failed verification |
173
+
174
+ `TrialError` groups the three test-mode errors because they share a cause and a fix, even though their statuses
175
+ differ. It is not a subclass of `RateLimitError` or `PermissionDeniedError`; check `e.code` or `e.status` if you
176
+ need to tell them apart. A code this version does not know maps by HTTP status to the closest class and keeps
177
+ the raw `code`.
178
+
179
+ `RateLimitError.retry_after` is the number of seconds from the `Retry-After` header, or `None` when the header is
180
+ absent. The API does not send `Retry-After` today, so expect `None`.
181
+
182
+ ```python
183
+ from diotp import (
184
+ DiOTP,
185
+ ConflictError,
186
+ ExpiredError,
187
+ InvalidCodeError,
188
+ RateLimitError,
189
+ TrialError,
190
+ )
191
+
192
+ client = DiOTP()
193
+
194
+ try:
195
+ client.verify(request_id, code)
196
+ except InvalidCodeError:
197
+ ... # wrong code: let the user try again (5 attempts per code)
198
+ except ExpiredError:
199
+ ... # more than 5 minutes passed: send a new code
200
+ except RateLimitError as e:
201
+ if e.code == "too_many_attempts":
202
+ ... # locked: send a new code
203
+ except ConflictError as e:
204
+ if e.code == "already_verified":
205
+ ... # treat the number as verified
206
+ ```
207
+
208
+ The full list of codes is on [API error codes](https://diotp.diorbit.com/docs/errors).
209
+
210
+ ## Retries
211
+
212
+ The client retries automatically, with exponential backoff and full jitter (base 0.5 seconds, factor 2, capped at
213
+ 8 seconds), up to `max_retries` times (default 2).
214
+
215
+ - It retries only on network errors and 5xx responses.
216
+ - It never retries a 4xx response, including 429. Read `RateLimitError.retry_after` and decide yourself.
217
+ - `send` retries are safe: the same `Idempotency-Key` is reused on every retry of one call, so the API
218
+ returns the first response instead of sending a second code. Pass your own `idempotency_key` to make retries
219
+ across calls or processes safe too.
220
+ - `verify` retries only on network errors and 502, 503 and 504. The server counts every verify attempt (five
221
+ per code), so other 5xx responses are not retried.
222
+
223
+ ## Webhooks
224
+
225
+ DiOTP signs every webhook delivery. Verify it against the raw request body, before parsing it:
226
+
227
+ ```python
228
+ from diotp import WebhookSignatureError, verify_webhook_headers
229
+
230
+
231
+ # Flask
232
+ @app.post("/webhooks/diotp")
233
+ def diotp_webhook():
234
+ try:
235
+ event = verify_webhook_headers(request.get_data(), request.headers, WEBHOOK_SECRET)
236
+ except WebhookSignatureError:
237
+ return "", 400
238
+ if event.event == "otp.verified":
239
+ ...
240
+ return "", 204
241
+ ```
242
+
243
+ Or pass the headers yourself:
244
+
245
+ ```python
246
+ from diotp import verify_webhook
247
+
248
+ event = verify_webhook(
249
+ raw_body, # bytes or str, exactly as received
250
+ headers["X-Diorbit-Signature"],
251
+ headers["X-Diorbit-Timestamp"],
252
+ secret,
253
+ tolerance=300, # seconds, default 300
254
+ )
255
+ ```
256
+
257
+ - The signature in `X-Diorbit-Signature` is the lowercase hex HMAC-SHA256 of `"{timestamp}.{raw_body}"`, keyed
258
+ with your endpoint's signing secret. `X-Diorbit-Timestamp` is Unix seconds.
259
+ - The comparison is constant-time (`hmac.compare_digest`), and timestamps more than `tolerance` seconds from now
260
+ are rejected.
261
+ - The result is a `WebhookEvent` with `event` (`otp.sent`, `otp.delivered`, `otp.failed` or `otp.verified`),
262
+ `created_at`, `request_id`, and `channel` and `status` when the event has them.
263
+ - Any failure raises `WebhookSignatureError`.
264
+
265
+ ## Sandbox / test mode
266
+
267
+ Every new account starts in test mode. Test mode is the real API with one restriction, not a simulator: codes go
268
+ only to the mobile number you verified at sign-up, as real SMS, with real request ids, expiry and attempt counting.
269
+
270
+ - Sending to any other number raises `TrialError` with code `trial_restricted` (403).
271
+ - When your free test messages are used up, sends raise `TrialError` with code `trial_used_up` (402).
272
+ - A live account switched back to test mode in the dashboard has a daily allowance; past it, sends raise
273
+ `TrialError` with code `test_limit` (429).
274
+ - Rate limits apply in test mode too.
275
+
276
+ `client.is_test_mode()` returns `True` when `me().client.status` is `trial` or `pending_review`. A live account
277
+ switched back to test mode in the dashboard still reports `live`, so `is_test_mode()` returns `False` for it; check
278
+ the dashboard in that case. Going live needs no code change: the same key, base URL and requests keep working.
279
+ More on [test mode](https://diotp.diorbit.com/docs/sandbox).
280
+
281
+ ## Tests
282
+
283
+ ```bash
284
+ python -m venv .venv && . .venv/bin/activate
285
+ pip install -e . pytest pytest-asyncio
286
+ pytest # unit tests, mocked HTTP, no API key needed
287
+ DIOTP_TEST_API_KEY=... pytest -m integration # sandbox tests against the real API
288
+ ```
289
+
290
+ The integration tests are deselected by default and skipped unless `DIOTP_TEST_API_KEY` is set. Without
291
+ `DIOTP_TEST_PHONE` they send nothing that uses a test message; with it (your verified sign-up number) one test
292
+ sends a real code.
293
+
294
+ ## Documentation
295
+
296
+ Full API documentation: [https://diotp.diorbit.com/docs](https://diotp.diorbit.com/docs). Error codes:
297
+ [diotp.diorbit.com/docs/errors](https://diotp.diorbit.com/docs/errors).
298
+
299
+ ## Licence
300
+
301
+ MIT. See [LICENSE](LICENSE). Copyright (c) 2026 Diorbit Technologies LLP.
diotp-1.0.0/README.md ADDED
@@ -0,0 +1,270 @@
1
+ # DiOTP Python SDK
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/diotp.svg)](https://pypi.org/project/diotp/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/diotp.svg)](https://pypi.org/project/diotp/)
5
+ [![CI](https://github.com/Diorbit-Technologies-LLP/diotp-python/actions/workflows/ci.yml/badge.svg)](https://github.com/Diorbit-Technologies-LLP/diotp-python/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/github/license/Diorbit-Technologies-LLP/diotp-python.svg)](https://github.com/Diorbit-Technologies-LLP/diotp-python/blob/main/LICENSE)
7
+
8
+ The official Python client for the [DiOTP](https://diotp.diorbit.com) OTP API. Send a one-time password by SMS
9
+ (or WhatsApp, once it is switched on for your account) and verify the code your user types.
10
+
11
+ - Sync (`DiOTP`) and async (`AsyncDiOTP`) clients with the same methods.
12
+ - Typed, immutable results and a typed exception for every documented error code.
13
+ - Automatic retries with exponential backoff, and an `Idempotency-Key` on every send so a retry never sends a
14
+ second code.
15
+ - Webhook signature verification.
16
+ - Python 3.9 or later. One dependency: [httpx](https://www.python-httpx.org/).
17
+
18
+ Documentation: [https://diotp.diorbit.com/docs](https://diotp.diorbit.com/docs) (SDK page:
19
+ [diotp.diorbit.com/docs/sdks](https://diotp.diorbit.com/docs/sdks)).
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install diotp
25
+ ```
26
+
27
+ ## Quickstart
28
+
29
+ Keep your API key on the server, in the `DIOTP_API_KEY` environment variable.
30
+
31
+ ```python
32
+ from diotp import DiOTP, InvalidCodeError
33
+
34
+ client = DiOTP() # reads DIOTP_API_KEY
35
+ otp = client.send("9876543210") # country code 91 by default; keep otp.request_id
36
+
37
+ try:
38
+ client.verify(otp.request_id, "482913") # the code the user typed
39
+ print("verified")
40
+ except InvalidCodeError:
41
+ print("wrong code, try again")
42
+ ```
43
+
44
+ Async:
45
+
46
+ ```python
47
+ import asyncio
48
+ from diotp import AsyncDiOTP
49
+
50
+
51
+ async def main() -> None:
52
+ async with AsyncDiOTP() as client:
53
+ otp = await client.send("9876543210")
54
+ result = await client.verify(otp.request_id, "482913")
55
+ print(result.verified_at)
56
+
57
+
58
+ asyncio.run(main())
59
+ ```
60
+
61
+ ## Methods
62
+
63
+ | Method | Endpoint | Returns |
64
+ |---|---|---|
65
+ | `send(to, *, country_code=91, channel="sms", purpose="login", template=None, idempotency_key=None)` | `POST /v1/otp/send` | `SendResult` |
66
+ | `verify(request_id, code)` | `POST /v1/otp/verify` | `VerifyResult` |
67
+ | `resend(to, *, country_code=91, channel="sms", purpose="login", template=None)` | `POST /v1/otp/send` (helper) | `SendResult` |
68
+ | `me()` | `GET /v1/me` | `Account` |
69
+ | `usage(period=None)` | `GET /v1/usage?period=YYYY-MM` | `Usage` |
70
+ | `is_test_mode()` | `GET /v1/me` | `bool` |
71
+
72
+ On `AsyncDiOTP` every method is a coroutine. `send_otp`, `verify_otp` and `resend_otp` are other names for
73
+ `send`, `verify` and `resend`.
74
+
75
+ The fields match [Send an OTP](https://diotp.diorbit.com/docs/send-otp) and
76
+ [Verify an OTP](https://diotp.diorbit.com/docs/verify-otp): `country_code` is an integer (default 91) and `code`
77
+ is a string of 4 to 10 characters.
78
+
79
+ - `to` is the mobile number, digits only (6 to 15). For India, the 10-digit number without +91.
80
+ - `SendResult` has `request_id`, `channel`, `expires_at` (a timezone-aware `datetime`, 5 minutes after sending)
81
+ and `idempotency_key`.
82
+ - `VerifyResult` has `request_id`, `verified` (always `True`) and `verified_at`. Every failure raises instead.
83
+ - `Account` has `client` (`id`, `name`, `status`) and `key` (`id`, `name`, `last_four`).
84
+ - `Usage` has `period`, `attempts`, `accepted`, `billable_units` and `amount`. `amount` is a decimal string such
85
+ as `"16.00"`, kept as a string so nothing is lost to floating point. Use `decimal.Decimal(usage.amount)`.
86
+ - Every result keeps the decoded JSON in `.raw`.
87
+
88
+ ### Resending a code
89
+
90
+ `resend` is a helper, not a separate endpoint. There is no resend endpoint in the API. It calls
91
+ `POST /v1/otp/send` again with a new `Idempotency-Key`, so a new code is sent and you get a new `request_id`:
92
+ verify against that one. The API allows one code to the same number every 30 seconds. Call `resend` sooner
93
+ and it raises `RateLimitError` with code `resend_cooldown`, so show a 30-second resend timer in your app.
94
+
95
+ ## Configuration
96
+
97
+ ```python
98
+ from diotp import DiOTP
99
+
100
+ client = DiOTP(
101
+ api_key="...", # default: the DIOTP_API_KEY environment variable
102
+ base_url="https://api-diotp.diorbit.com/v1", # default
103
+ timeout=10.0, # seconds per attempt, default 10
104
+ max_retries=2, # default 2; 0 disables retries
105
+ http_client=None, # optional httpx.Client (httpx.AsyncClient for AsyncDiOTP)
106
+ )
107
+ ```
108
+
109
+ If no key is passed and `DIOTP_API_KEY` is not set, the constructor raises `ConfigurationError`.
110
+
111
+ The key is never logged or included in error messages. `repr(client)` shows it masked, as `dio_...` and its last
112
+ four characters.
113
+
114
+ Use the client as a context manager, or call `close()` (`await aclose()` for `AsyncDiOTP`) when done. A client
115
+ you pass in through `http_client` is yours to close.
116
+
117
+ ## Error handling
118
+
119
+ Every error derives from `DiOTPError`, which has:
120
+
121
+ - `code`: the stable error code, such as `invalid_code`. Branch on this.
122
+ - `status`: the HTTP status, or `None` when there was no response.
123
+ - `message`: a sentence for people. Its wording can change.
124
+ - `request_id`: the id of the request (also the `X-Request-Id` header). Quote it to support.
125
+
126
+ | Exception | Status and codes |
127
+ |---|---|
128
+ | `AuthenticationError` | 401 `unauthorized` |
129
+ | `InsufficientBalanceError` | 402 `insufficient_balance` |
130
+ | `PermissionDeniedError` | 403 `account_suspended` |
131
+ | `TrialError` | test mode: 402 `trial_used_up`, 403 `trial_restricted`, 429 `test_limit` |
132
+ | `InvalidCodeError` (a `ValidationError`) | 400 `invalid_code` |
133
+ | `ValidationError` | 422 `invalid_request`, `template_not_available` |
134
+ | `NotFoundError` | 404 `not_found` |
135
+ | `ConflictError` | 409 `already_verified`, `not_pending`, `idempotency_key_reused`, `channel_not_enabled` |
136
+ | `ExpiredError` | 410 `expired` |
137
+ | `RateLimitError` | 429 `resend_cooldown`, `phone_hourly_limit`, `phone_daily_limit`, `api_key_minute_limit`, `rate_limited`, `too_many_attempts` |
138
+ | `ServerError` | 5xx, such as 503 `sending_unavailable` |
139
+ | `NetworkError` | no response: timeout, DNS failure, connection reset |
140
+ | `ConfigurationError` | no API key, or an invalid setting |
141
+ | `WebhookSignatureError` | a webhook failed verification |
142
+
143
+ `TrialError` groups the three test-mode errors because they share a cause and a fix, even though their statuses
144
+ differ. It is not a subclass of `RateLimitError` or `PermissionDeniedError`; check `e.code` or `e.status` if you
145
+ need to tell them apart. A code this version does not know maps by HTTP status to the closest class and keeps
146
+ the raw `code`.
147
+
148
+ `RateLimitError.retry_after` is the number of seconds from the `Retry-After` header, or `None` when the header is
149
+ absent. The API does not send `Retry-After` today, so expect `None`.
150
+
151
+ ```python
152
+ from diotp import (
153
+ DiOTP,
154
+ ConflictError,
155
+ ExpiredError,
156
+ InvalidCodeError,
157
+ RateLimitError,
158
+ TrialError,
159
+ )
160
+
161
+ client = DiOTP()
162
+
163
+ try:
164
+ client.verify(request_id, code)
165
+ except InvalidCodeError:
166
+ ... # wrong code: let the user try again (5 attempts per code)
167
+ except ExpiredError:
168
+ ... # more than 5 minutes passed: send a new code
169
+ except RateLimitError as e:
170
+ if e.code == "too_many_attempts":
171
+ ... # locked: send a new code
172
+ except ConflictError as e:
173
+ if e.code == "already_verified":
174
+ ... # treat the number as verified
175
+ ```
176
+
177
+ The full list of codes is on [API error codes](https://diotp.diorbit.com/docs/errors).
178
+
179
+ ## Retries
180
+
181
+ The client retries automatically, with exponential backoff and full jitter (base 0.5 seconds, factor 2, capped at
182
+ 8 seconds), up to `max_retries` times (default 2).
183
+
184
+ - It retries only on network errors and 5xx responses.
185
+ - It never retries a 4xx response, including 429. Read `RateLimitError.retry_after` and decide yourself.
186
+ - `send` retries are safe: the same `Idempotency-Key` is reused on every retry of one call, so the API
187
+ returns the first response instead of sending a second code. Pass your own `idempotency_key` to make retries
188
+ across calls or processes safe too.
189
+ - `verify` retries only on network errors and 502, 503 and 504. The server counts every verify attempt (five
190
+ per code), so other 5xx responses are not retried.
191
+
192
+ ## Webhooks
193
+
194
+ DiOTP signs every webhook delivery. Verify it against the raw request body, before parsing it:
195
+
196
+ ```python
197
+ from diotp import WebhookSignatureError, verify_webhook_headers
198
+
199
+
200
+ # Flask
201
+ @app.post("/webhooks/diotp")
202
+ def diotp_webhook():
203
+ try:
204
+ event = verify_webhook_headers(request.get_data(), request.headers, WEBHOOK_SECRET)
205
+ except WebhookSignatureError:
206
+ return "", 400
207
+ if event.event == "otp.verified":
208
+ ...
209
+ return "", 204
210
+ ```
211
+
212
+ Or pass the headers yourself:
213
+
214
+ ```python
215
+ from diotp import verify_webhook
216
+
217
+ event = verify_webhook(
218
+ raw_body, # bytes or str, exactly as received
219
+ headers["X-Diorbit-Signature"],
220
+ headers["X-Diorbit-Timestamp"],
221
+ secret,
222
+ tolerance=300, # seconds, default 300
223
+ )
224
+ ```
225
+
226
+ - The signature in `X-Diorbit-Signature` is the lowercase hex HMAC-SHA256 of `"{timestamp}.{raw_body}"`, keyed
227
+ with your endpoint's signing secret. `X-Diorbit-Timestamp` is Unix seconds.
228
+ - The comparison is constant-time (`hmac.compare_digest`), and timestamps more than `tolerance` seconds from now
229
+ are rejected.
230
+ - The result is a `WebhookEvent` with `event` (`otp.sent`, `otp.delivered`, `otp.failed` or `otp.verified`),
231
+ `created_at`, `request_id`, and `channel` and `status` when the event has them.
232
+ - Any failure raises `WebhookSignatureError`.
233
+
234
+ ## Sandbox / test mode
235
+
236
+ Every new account starts in test mode. Test mode is the real API with one restriction, not a simulator: codes go
237
+ only to the mobile number you verified at sign-up, as real SMS, with real request ids, expiry and attempt counting.
238
+
239
+ - Sending to any other number raises `TrialError` with code `trial_restricted` (403).
240
+ - When your free test messages are used up, sends raise `TrialError` with code `trial_used_up` (402).
241
+ - A live account switched back to test mode in the dashboard has a daily allowance; past it, sends raise
242
+ `TrialError` with code `test_limit` (429).
243
+ - Rate limits apply in test mode too.
244
+
245
+ `client.is_test_mode()` returns `True` when `me().client.status` is `trial` or `pending_review`. A live account
246
+ switched back to test mode in the dashboard still reports `live`, so `is_test_mode()` returns `False` for it; check
247
+ the dashboard in that case. Going live needs no code change: the same key, base URL and requests keep working.
248
+ More on [test mode](https://diotp.diorbit.com/docs/sandbox).
249
+
250
+ ## Tests
251
+
252
+ ```bash
253
+ python -m venv .venv && . .venv/bin/activate
254
+ pip install -e . pytest pytest-asyncio
255
+ pytest # unit tests, mocked HTTP, no API key needed
256
+ DIOTP_TEST_API_KEY=... pytest -m integration # sandbox tests against the real API
257
+ ```
258
+
259
+ The integration tests are deselected by default and skipped unless `DIOTP_TEST_API_KEY` is set. Without
260
+ `DIOTP_TEST_PHONE` they send nothing that uses a test message; with it (your verified sign-up number) one test
261
+ sends a real code.
262
+
263
+ ## Documentation
264
+
265
+ Full API documentation: [https://diotp.diorbit.com/docs](https://diotp.diorbit.com/docs). Error codes:
266
+ [diotp.diorbit.com/docs/errors](https://diotp.diorbit.com/docs/errors).
267
+
268
+ ## Licence
269
+
270
+ MIT. See [LICENSE](LICENSE). Copyright (c) 2026 Diorbit Technologies LLP.