Metadata-Version: 2.4
Name: hisarpay
Version: 1.0.0
Summary: Official Python client for the HisarPay API (TRX and USDT-TRC20 payments on TRON).
Project-URL: Homepage, https://hisarpay.com
Project-URL: Documentation, https://hisarpay.com/en/docs
Author-email: HisarPay <support@hisarpay.com>
License-Expression: MIT
License-File: LICENSE
Keywords: hisarpay,payments,crypto,tron,trx,usdt,trc20,webhooks
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 :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx>=0.23,<1
Description-Content-Type: text/markdown

# HisarPay Python SDK

The official Python client for the [HisarPay](https://hisarpay.com) API: accept **TRX** and
**USDT (TRC20)** payments on TRON, manage payment links, withdraw your balance, and verify webhooks.

- Sync (`HisarPay`) and async (`AsyncHisarPay`) clients built on [`httpx`](https://www.python-httpx.org/)
- Automatic retries with exponential backoff and an `Idempotency-Key` on every `POST`, so a retry
  can never create a duplicate
- Typed request and response shapes (`TypedDict`), shipped with `py.typed`
- Webhook signature verification with support for secret rotation

## Requirements

Python 3.9 or newer. The only dependency is `httpx`.

## Installation

The package is downloaded from HisarPay; it is not on PyPI.

```bash
pip install https://hisarpay.com/downloads/hisarpay-1.0.0-py3-none-any.whl
```

## Quick start

Create an API key in the dashboard. Keys starting with `hp_test_` work in test mode (no real
money moves, and you can simulate payments). Keys starting with `hp_live_` are for production.
Keep keys on the server and read them from the environment, never from source code.

```python
import os
from hisarpay import HisarPay

client = HisarPay(os.environ["HISARPAY_API_KEY"])

invoice = client.invoices.create({
    "price_usd": "49.90",
    "order_id": "order_1001",
    "description": "Pro plan, 1 month",
    "metadata": {"user_id": "42"},
})
print(invoice["id"], invoice["status"], invoice["payment_url"])
```

Redirect your customer to `payment_url`. Then wait for the `invoice.paid` webhook (see
[Webhooks](#webhooks)) before fulfilling the order.

### Async

```python
import asyncio, os
from hisarpay import AsyncHisarPay

async def main() -> None:
    async with AsyncHisarPay(os.environ["HISARPAY_API_KEY"]) as client:
        invoice = await client.invoices.create({"price_usd": "49.90"})
        print(invoice["payment_url"])

asyncio.run(main())
```

Every method of the sync client exists on the async client with the same name and arguments.

## Configuration

```python
client = HisarPay(
    "hp_live_...",
    base_url="https://hisarpay.com",  # default
    timeout=30.0,                   # seconds, per network step (connect, each read/write)
    max_retries=2,                  # retries after the first attempt
    http_client=None,               # or your own httpx.Client (proxies, mTLS, custom transport)
)
```

Use the client as a context manager (`with HisarPay(...) as client:`), or call `client.close()`
(`await client.aclose()` for async). The SDK never closes an `http_client` you pass in.

Every method also accepts per-request keyword options: `timeout`, `max_retries` and
`extra_headers`. `POST` methods also accept `idempotency_key`.

```python
client.invoices.retrieve(invoice_id, timeout=5, max_retries=0)
```

Responses are plain `dict`s decoded from JSON. Their shapes are documented in `hisarpay.types`
(`Invoice`, `PaymentLink`, `Withdrawal`, ...). **Amounts are decimal strings** such as `"25.00"`.
Convert them with `decimal.Decimal`, never with `float`.

## Invoices

```python
# Price in USD; the customer picks TRX or USDT on the payment page
inv = client.invoices.create({"price_usd": "25.00", "order_id": "A-1001"})

# Fix the coin
inv = client.invoices.create({"price_usd": "25.00", "token": "USDT"})

# An exact amount in the coin
inv = client.invoices.create({"token": "TRX", "amount": "150"})

client.invoices.retrieve(inv["id"])            # includes inv["payments"]
client.invoices.retrieve_by_order("A-1001")    # look up by your own order id
client.invoices.cancel(inv["id"])              # only pending invoices with nothing received

page = client.invoices.list({"status": ["paid", "overpaid"], "limit": 50})
for invoice in page["data"]:
    print(invoice["id"], invoice["paid_amount"])

found = client.invoices.list({"q": "A-1001", "created_from": "2026-12-01", "source": "api"})
```

Creating an invoice again with the same `order_id` returns the existing invoice. With `customer_email` the
payer gets a receipt once the payment is final, if your account sends receipts.

Amounts can be passed as `decimal.Decimal` (`Decimal("49.90")` is sent as `"49.90"`). Timezone-aware
`datetime` values, for example `from` and `to` of a report or the `before` cursor of events, are sent as
UTC ISO 8601 strings.

### Simulating payments in test mode

With a test key you can drive an invoice through the real state machine, and real webhooks are
sent:

```python
test = HisarPay(os.environ["HISARPAY_TEST_KEY"])
inv = test.invoices.create({"price_usd": "25.00", "token": "USDT"})
paid = test.invoices.simulate(inv["id"], {"outcome": "paid"})
assert paid["status"] == "paid"

# Other outcomes: "partial" (optionally with "amount"), "overpaid", "expired"
```

## Payment links

Payment links are reusable payment pages with a fixed price, or an open amount the customer
chooses:

```python
link = client.payment_links.create({
    "title": "Workshop, 12 December",
    "kind": "fixed",
    "price_usd": "45.00",
    "max_uses": 24,                                   # an end, a number of uses
    "expires_at": "2026-12-12T09:00:00Z",
    "ask": {"name": "required", "email": "optional"}, # and questions to the payer
})
print(link["url"], link["qr_png_url"], link["qr_card_url"])  # the card is a printable A6 PDF

client.payment_links.update(link["id"], {"active": False})   # pause
client.payment_links.update(link["id"], {"archived": True})  # put away
client.payment_links.retrieve(link["id"])["stats"]           # uses, paid_count, paid_usd

donations = client.payment_links.create({
    "title": "Tip jar",
    "kind": "open",
    "min_usd": "10.00",
    "suggested_amounts": ["10.00", "25.00", "50.00"],
})
```

## Webhooks

HisarPay sends events such as `invoice.paid` or `withdrawal.completed` to your
webhook endpoints as signed `POST` requests. Each request carries:

- `X-HisarPay-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256>`, where the HMAC covers
  `f"{t}.{raw_body}"`. While you rotate a secret there are two `v1` values, and the request is
  valid if any of them matches.
- `X-HisarPay-Event-Id`: the event id. Deliveries can be retried, so use it to process each event
  only once.

**Always verify the raw request body, byte for byte.** If you parse the JSON and serialise it
again, the bytes change and the signature no longer matches. `construct_event` verifies the
signature, checks the timestamp is within 5 minutes (the `tolerance` argument) and returns the
decoded event:

### Flask

```python
import os
from flask import Flask, abort, request
from hisarpay import SignatureVerificationError, webhooks

app = Flask(__name__)
WEBHOOK_SECRET = os.environ["HISARPAY_WEBHOOK_SECRET"]  # whsec_...
# An endpoint gets test and live events, and anyone can mark a test invoice as paid.
LIVE = os.environ["HISARPAY_API_KEY"].startswith("hp_live_")

@app.post("/webhooks/hisarpay")
def hisarpay_webhook():
    try:
        event = webhooks.construct_event(
            request.get_data(),  # raw bytes, NOT request.json
            request.headers.get(webhooks.SIGNATURE_HEADER),
            WEBHOOK_SECRET,
        )
    except SignatureVerificationError:
        abort(400)

    if event["livemode"] is LIVE and event["type"] == "invoice.paid":
        invoice = event["data"]["invoice"]
        fulfil_order(invoice["order_id"], invoice["paid_amount"])
    return "", 204
```

### FastAPI

```python
import os
from fastapi import FastAPI, HTTPException, Request, Response
from hisarpay import SignatureVerificationError, webhooks

app = FastAPI()
WEBHOOK_SECRET = os.environ["HISARPAY_WEBHOOK_SECRET"]
LIVE = os.environ["HISARPAY_API_KEY"].startswith("hp_live_")

@app.post("/webhooks/hisarpay")
async def hisarpay_webhook(request: Request) -> Response:
    payload = await request.body()  # raw bytes
    try:
        event = webhooks.construct_event(
            payload, request.headers.get("x-hisarpay-signature"), WEBHOOK_SECRET
        )
    except SignatureVerificationError as exc:
        raise HTTPException(status_code=400, detail=str(exc))

    if event["livemode"] is LIVE and event["type"] in ("invoice.paid", "invoice.overpaid"):
        ...
    return Response(status_code=204)
```

Respond with a 2xx status quickly, and move slow work to a background job. If you only need a yes
or no, use `webhooks.verify(payload, header, secret)`, which returns a `bool`.

To test your handler, sign a payload yourself with `webhooks.generate_test_header(payload, secret)`.

**Rotating secrets.** `client.webhook_endpoints.rotate_secret(endpoint_id)` returns a new secret.
For 24 hours, deliveries are signed with both the old and the new secret, so you can deploy the
new one without missing events.

**Managing endpoints.** Creating, updating, deleting and rotating endpoints requires a **live** key
with the `webhooks` scope, because endpoints receive both live and test events. `list` and `retrieve`
only need the `read` scope. The `secret` is returned only once, by `create`:

```python
endpoint = live.webhook_endpoints.create({
    "url": "https://example.com/webhooks/hisarpay",
    "events": ["invoice.paid", "invoice.expired"],  # omit to receive every event type
})
store_secret(endpoint["secret"])
```

## Withdrawals

Withdrawals send funds from your HisarPay balance to a **trusted address that you saved in the
dashboard**. You need a **live** key with the `withdrawals` scope.

```python
live = HisarPay(os.environ["HISARPAY_LIVE_KEY"])

w = live.withdrawals.create({
    "token": "USDT",
    "amount": "250",
    "to_address": "TQ5...your saved address",
    "idempotency_key": "payout-2026-10-23-001",  # optional, generated if omitted
})
print(w["status"])  # pending_review, queued, processing, completed, failed or rejected

live.withdrawals.retrieve(w["id"])
live.balances.retrieve()                                # {"data": [{"token", "available", ...}]}
live.balances.transactions({"token": "USDT", "limit": 50})
```

Use a stable `idempotency_key` derived from your own payout record. A retry, even from a
different process, will then return the original withdrawal instead of paying out twice. Listen
for the `withdrawal.completed`, `withdrawal.failed` and `withdrawal.rejected` webhooks.

## Errors

Every exception derives from `hisarpay.HisarPayError`:

| Exception | When |
| --- | --- |
| `ValidationError` | 400 / 422: invalid parameters (`validation_error`, `amount_too_small`, ...) |
| `AuthenticationError` | 401: missing or invalid API key |
| `PermissionDeniedError` | 403: missing scope, or a test key used for a live-only action (`test_key`) and vice versa |
| `NotFoundError` | 404 |
| `ConflictError` | 409: e.g. `not_cancellable`, `insufficient_balance` |
| `IdempotencyError` | 409 `idempotency_conflict`: the key was reused with a different body |
| `RateLimitError` | 429 (has `retry_after`) |
| `ServerError` | 5xx |
| `APIConnectionError` / `APITimeoutError` | no response (network failure, timeout) |
| `SignatureVerificationError` | webhook verification failed |

Each error has `message`, `status`, `code`, `request_id` (quote it when contacting support),
`raw` (the decoded error body) and `headers`.

```python
from hisarpay import ConflictError, HisarPayError, ValidationError

try:
    client.invoices.cancel(invoice_id)
except ConflictError as e:
    print("cannot cancel:", e.code, e.message)
except ValidationError as e:
    print("bad request:", e.message)
except HisarPayError as e:
    print("HisarPay error", e.status, e.code, e.request_id)
    raise
```

## Idempotency

Every `POST` request carries an `Idempotency-Key` header. The SDK generates a UUID4 for each call
and reuses it for that call's automatic retries, so a retried create can never produce a
duplicate. The API stores the first response for 24 hours and replays it for repeated requests
with the same key and the same body. A repeated request with a different body fails with
`IdempotencyError`.

Pass your own key when a retry may come from somewhere else, such as a job queue or a restarted
process:

```python
client.invoices.create({"price_usd": "25.00"}, idempotency_key=f"invoice-for-order-{order.id}")
```

## Retries

These are retried automatically: network errors, timeouts, `408`, `429` and `5xx`. The SDK makes
up to `max_retries` retries (default 2), waiting with exponential backoff and jitter
(0.5 s, 1 s, 2 s, ... capped at 8 s). On a `429` it waits for the time given in the
`Retry-After` header. A `409` with the code `request_in_progress` is retried too: an earlier
attempt with the same `Idempotency-Key` is still running, so the retry receives its stored result.
Other `409`s and `4xx` responses are never retried. Set `max_retries=0` to
disable retries, on the client or per call.

## Pagination

List methods return one page: `{"data": [...], "next_before": cursor_or_None}`. Pass
`next_before` back as `before` to get the next page, or let `list_all()` do it for you:

```python
for invoice in client.invoices.list_all({"status": "paid", "limit": 100}):
    print(invoice["id"])            # walks every page lazily; limit is the page size

for page in client.invoices.list_all({"limit": 100}).pages():
    print(len(page["data"]), page["next_before"])

# async
async for invoice in async_client.invoices.list_all():
    ...
```

`list_all()` is available on `invoices`, `payment_links`, `withdrawals`
and `events`.

## Response metadata

`client.last_response` describes the most recent HTTP response:

```python
client.invoices.create({"price_usd": "25.00"}, idempotency_key="order-1001")
meta = client.last_response
meta.status                # 201
meta.request_id            # "req_..."
meta.idempotency_key       # "order-1001"
meta.idempotent_replayed   # True when the API replayed a stored response
meta.rate_limit            # RateLimitInfo(limit=300, remaining=297, reset=41)
```

If you send requests concurrently on one client, `last_response` holds whichever response
arrived last.

## Reports

Exports of up to 10 000 rows, rendered in the background and kept for 7 days (the key needs the `reports`
scope). Kinds: `invoices`, `withdrawals`, `balance_transactions`, `webhook_deliveries`.

```python
report = client.reports.create_and_wait(
    {"kind": "invoices", "format": "xlsx", "lang": "tr", "from": "2026-10-01T00:00:00Z", "status": ["paid"]}
)
if report["status"] == "ready":
    file = client.reports.download(report["id"])  # {"data": bytes, "content_type": ..., "filename": ...}
    with open(file["filename"] or "report.xlsx", "wb") as fh:
        fh.write(file["data"])
```

## Other endpoints

```python
client.webhook_endpoints.retrieve(endpoint_id)
client.events.list({"type": "invoice.paid"})
client.events.resend(event_id)                       # live key with the `webhooks` scope
client.rates()                                       # {"rates": {"TRX": "0.31", "USDT": "1"}, ...}
client.tokens()                                      # coins, fees, minimums
client.status()                                      # processing status
client.chain.transaction(txid)
client.chain.address("T...")
```

## Testing

To work on the SDK itself:

```bash
python -m venv .venv
.venv/bin/pip install -e '.[dev]'
.venv/bin/pytest
```

The integration tests in `tests/test_integration.py` call a real API. They are skipped unless
both `HISARPAY_API_BASE` and `HISARPAY_TEST_KEY` are set:

```bash
HISARPAY_API_BASE=http://127.0.0.1:4000 HISARPAY_TEST_KEY=hp_test_... .venv/bin/pytest
```

## License

MIT
