Metadata-Version: 2.5
Name: diotp
Version: 1.1.0
Summary: Official Python client for the DiOTP OTP API: send and verify one-time passwords by SMS or WhatsApp.
Project-URL: Homepage, https://diotp.diorbit.com/docs/sdks
Project-URL: Documentation, https://diotp.diorbit.com/docs
Project-URL: Repository, https://github.com/Diorbit-Technologies-LLP/diotp-python
Project-URL: Issues, https://github.com/Diorbit-Technologies-LLP/diotp-python/issues
Project-URL: Changelog, https://github.com/Diorbit-Technologies-LLP/diotp-python/blob/main/CHANGELOG.md
Author-email: Diorbit Technologies LLP <otp-support@diorbit.com>
License-Expression: MIT
License-File: LICENSE
Keywords: 2fa,diotp,india,otp,sms,verification,whatsapp
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Telephony
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.24
Description-Content-Type: text/markdown

# DiOTP Python SDK

[![PyPI version](https://img.shields.io/pypi/v/diotp.svg)](https://pypi.org/project/diotp/)
[![Python versions](https://img.shields.io/pypi/pyversions/diotp.svg)](https://pypi.org/project/diotp/)
[![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)
[![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)

The official Python client for the [DiOTP](https://diotp.diorbit.com) OTP API. Send a one-time password by SMS
(or WhatsApp, once it is switched on for your account) and verify the code your user types.

- Sync (`DiOTP`) and async (`AsyncDiOTP`) clients with the same methods.
- Typed, immutable results and a typed exception for every documented error code.
- Automatic retries with exponential backoff, and an `Idempotency-Key` on every send so a retry never sends a
  second code.
- Webhook signature verification.
- Python 3.9 or later. One dependency: [httpx](https://www.python-httpx.org/).

Documentation: [https://diotp.diorbit.com/docs](https://diotp.diorbit.com/docs) (SDK page:
[diotp.diorbit.com/docs/sdks](https://diotp.diorbit.com/docs/sdks)).

## Install

```bash
pip install diotp
```

## Quickstart

Keep your API key on the server, in the `DIOTP_API_KEY` environment variable.

```python
from diotp import DiOTP, InvalidCodeError

client = DiOTP()  # reads DIOTP_API_KEY
otp = client.send("9876543210")  # country code 91 by default; keep otp.request_id

try:
    client.verify(otp.request_id, "482913")  # the code the user typed
    print("verified")
except InvalidCodeError:
    print("wrong code, try again")
```

Async:

```python
import asyncio
from diotp import AsyncDiOTP


async def main() -> None:
    async with AsyncDiOTP() as client:
        otp = await client.send("9876543210")
        result = await client.verify(otp.request_id, "482913")
        print(result.verified_at)


asyncio.run(main())
```

## Methods

| Method | Endpoint | Returns |
|---|---|---|
| `send(to, *, country_code=91, channel="sms", purpose="login", template=None, digits=None, idempotency_key=None)` | `POST /v1/otp/send` | `SendResult` |
| `verify(request_id, code)` | `POST /v1/otp/verify` | `VerifyResult` |
| `resend(to, *, country_code=91, channel="sms", purpose="login", template=None, digits=None)` | `POST /v1/otp/send` (helper) | `SendResult` |
| `me()` | `GET /v1/me` | `Account` |
| `usage(period=None)` | `GET /v1/usage?period=YYYY-MM` | `Usage` |
| `is_test_mode()` | `GET /v1/me` | `bool` |

On `AsyncDiOTP` every method is a coroutine. `send_otp`, `verify_otp` and `resend_otp` are other names for
`send`, `verify` and `resend`.

The fields match [Send an OTP](https://diotp.diorbit.com/docs/send-otp) and
[Verify an OTP](https://diotp.diorbit.com/docs/verify-otp): `country_code` is an integer (default 91) and `code`
is a string of 4 to 10 characters.

- `to` is the mobile number, digits only (6 to 15). For India, the 10-digit number without +91.
- `SendResult` has `request_id`, `channel`, `expires_at` (a timezone-aware `datetime`, 5 minutes after sending)
  and `idempotency_key`.
- `VerifyResult` has `request_id`, `verified` (always `True`) and `verified_at`. Every failure raises instead.
- `Account` has `client` (`id`, `name`, `status`) and `key` (`id`, `name`, `last_four`).
- `Usage` has `period`, `attempts`, `accepted`, `billable_units` and `amount`. `amount` is a decimal string such
  as `"16.00"`, kept as a string so nothing is lost to floating point. Use `decimal.Decimal(usage.amount)`.
- Every result keeps the decoded JSON in `.raw`.

### Resending a code

`resend` is a helper, not a separate endpoint. There is no resend endpoint in the API. It calls
`POST /v1/otp/send` again with a new `Idempotency-Key`, so a new code is sent and you get a new `request_id`:
verify against that one. The API allows one code to the same number every 30 seconds. Call `resend` sooner
and it raises `RateLimitError` with code `resend_cooldown`, so show a 30-second resend timer in your app.

## Configuration

```python
from diotp import DiOTP

client = DiOTP(
    api_key="...",  # default: the DIOTP_API_KEY environment variable
    base_url="https://api-diotp.diorbit.com/v1",  # default
    timeout=10.0,  # seconds per attempt, default 10
    max_retries=2,  # default 2; 0 disables retries
    http_client=None,  # optional httpx.Client (httpx.AsyncClient for AsyncDiOTP)
)
```

If no key is passed and `DIOTP_API_KEY` is not set, the constructor raises `ConfigurationError`.

The key is never logged or included in error messages. `repr(client)` shows it masked, as `dio_...` and its last
four characters.

Use the client as a context manager, or call `close()` (`await aclose()` for `AsyncDiOTP`) when done. A client
you pass in through `http_client` is yours to close.

## Error handling

Every error derives from `DiOTPError`, which has:

- `code`: the stable error code, such as `invalid_code`. Branch on this.
- `status`: the HTTP status, or `None` when there was no response.
- `message`: a sentence for people. Its wording can change.
- `request_id`: the id of the request (also the `X-Request-Id` header). Quote it to support.

| Exception | Status and codes |
|---|---|
| `AuthenticationError` | 401 `unauthorized` |
| `InsufficientBalanceError` | 402 `insufficient_balance` |
| `PermissionDeniedError` | 403 `account_suspended` |
| `TrialError` | test mode: 402 `trial_used_up`, 403 `trial_restricted`, 429 `test_limit` |
| `InvalidCodeError` (a `ValidationError`) | 400 `invalid_code` |
| `ValidationError` | 422 `invalid_request`, `template_not_available` |
| `NotFoundError` | 404 `not_found` |
| `ConflictError` | 409 `already_verified`, `not_pending`, `idempotency_key_reused`, `channel_not_enabled` |
| `ExpiredError` | 410 `expired` |
| `RateLimitError` | 429 `resend_cooldown`, `phone_hourly_limit`, `phone_daily_limit`, `api_key_minute_limit`, `rate_limited`, `too_many_attempts` |
| `ServerError` | 5xx, such as 503 `sending_unavailable` |
| `NetworkError` | no response: timeout, DNS failure, connection reset |
| `ConfigurationError` | no API key, or an invalid setting |
| `WebhookSignatureError` | a webhook failed verification |

`TrialError` groups the three test-mode errors because they share a cause and a fix, even though their statuses
differ. It is not a subclass of `RateLimitError` or `PermissionDeniedError`; check `e.code` or `e.status` if you
need to tell them apart. A code this version does not know maps by HTTP status to the closest class and keeps
the raw `code`.

`RateLimitError.retry_after` is the number of seconds from the `Retry-After` header, or `None` when the header is
absent. The API does not send `Retry-After` today, so expect `None`.

```python
from diotp import (
    DiOTP,
    ConflictError,
    ExpiredError,
    InvalidCodeError,
    RateLimitError,
    TrialError,
)

client = DiOTP()

try:
    client.verify(request_id, code)
except InvalidCodeError:
    ...  # wrong code: let the user try again (5 attempts per code)
except ExpiredError:
    ...  # more than 5 minutes passed: send a new code
except RateLimitError as e:
    if e.code == "too_many_attempts":
        ...  # locked: send a new code
except ConflictError as e:
    if e.code == "already_verified":
        ...  # treat the number as verified
```

The full list of codes is on [API error codes](https://diotp.diorbit.com/docs/errors).

## Retries

The client retries automatically, with exponential backoff and full jitter (base 0.5 seconds, factor 2, capped at
8 seconds), up to `max_retries` times (default 2).

- It retries only on network errors and 5xx responses.
- It never retries a 4xx response, including 429. Read `RateLimitError.retry_after` and decide yourself.
- `send` retries are safe: the same `Idempotency-Key` is reused on every retry of one call, so the API
  returns the first response instead of sending a second code. Pass your own `idempotency_key` to make retries
  across calls or processes safe too.
- `verify` retries only on network errors and 502, 503 and 504. The server counts every verify attempt (five
  per code), so other 5xx responses are not retried.

## Webhooks

DiOTP signs every webhook delivery. Verify it against the raw request body, before parsing it:

```python
from diotp import WebhookSignatureError, verify_webhook_headers


# Flask
@app.post("/webhooks/diotp")
def diotp_webhook():
    try:
        event = verify_webhook_headers(request.get_data(), request.headers, WEBHOOK_SECRET)
    except WebhookSignatureError:
        return "", 400
    if event.event == "otp.verified":
        ...
    return "", 204
```

Or pass the headers yourself:

```python
from diotp import verify_webhook

event = verify_webhook(
    raw_body,  # bytes or str, exactly as received
    headers["X-Diorbit-Signature"],
    headers["X-Diorbit-Timestamp"],
    secret,
    tolerance=300,  # seconds, default 300
)
```

- The signature in `X-Diorbit-Signature` is the lowercase hex HMAC-SHA256 of `"{timestamp}.{raw_body}"`, keyed
  with your endpoint's signing secret. `X-Diorbit-Timestamp` is Unix seconds.
- The comparison is constant-time (`hmac.compare_digest`), and timestamps more than `tolerance` seconds from now
  are rejected.
- The result is a `WebhookEvent` with `event` (`otp.sent`, `otp.delivered`, `otp.failed` or `otp.verified`),
  `created_at`, `request_id`, and `channel` and `status` when the event has them.
- Any failure raises `WebhookSignatureError`.

## Sandbox / test mode

Every new account starts in test mode. Test mode is the real API with one restriction, not a simulator: codes go
only to the mobile number you verified at sign-up, as real SMS, with real request ids, expiry and attempt counting.

- Sending to any other number raises `TrialError` with code `trial_restricted` (403).
- When your free test messages are used up, sends raise `TrialError` with code `trial_used_up` (402).
- A live account switched back to test mode in the dashboard has a daily allowance; past it, sends raise
  `TrialError` with code `test_limit` (429).
- Rate limits apply in test mode too.

`client.is_test_mode()` returns `True` when `me().client.status` is `trial` or `pending_review`. A live account
switched back to test mode in the dashboard still reports `live`, so `is_test_mode()` returns `False` for it; check
the dashboard in that case. Going live needs no code change: the same key, base URL and requests keep working.
More on [test mode](https://diotp.diorbit.com/docs/sandbox).

## Tests

```bash
python -m venv .venv && . .venv/bin/activate
pip install -e . pytest pytest-asyncio
pytest                                         # unit tests, mocked HTTP, no API key needed
DIOTP_TEST_API_KEY=... pytest -m integration   # sandbox tests against the real API
```

The integration tests are deselected by default and skipped unless `DIOTP_TEST_API_KEY` is set. Without
`DIOTP_TEST_PHONE` they send nothing that uses a test message; with it (your verified sign-up number) one test
sends a real code.

## Documentation

Full API documentation: [https://diotp.diorbit.com/docs](https://diotp.diorbit.com/docs). Error codes:
[diotp.diorbit.com/docs/errors](https://diotp.diorbit.com/docs/errors).

## Licence

MIT. See [LICENSE](LICENSE). Copyright (c) 2026 Diorbit Technologies LLP.
