Metadata-Version: 2.5
Name: izipay
Version: 0.2.0b1
Summary: Official Python SDK for the IZI Pay payment API (Angola): MULTICAIXA Express, payment references, refunds and webhooks.
Project-URL: Homepage, https://developer.izipay.ao
Project-URL: Documentation, https://developer.izipay.ao
Project-URL: Source, https://gitlab.com/suplitel/izipay-sdk-python
Project-URL: Changelog, https://gitlab.com/suplitel/izipay-sdk-python/-/blob/main/CHANGELOG.md
Author: Suplitel
License-Expression: MIT
License-File: LICENSE
Keywords: angola,emis,izipay,kwanza,multicaixa,payments
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
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.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Office/Business :: Financial
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx<1,>=0.25
Description-Content-Type: text/markdown

# IZI Pay Python SDK

Official Python client for the IZI Pay payment API (Angola). It handles access tokens, safe retries, errors and
webhooks for you, so your code only deals with payments.

> **Beta (0.x).** The API can still change between 0.x versions. Version 1.0 will follow once the IZI Pay API
> itself is stable. Pin the exact version you test with.

- Python 3.11 or later
- A sync client (`IziPay`: Django, Flask, Odoo, scripts) and an asyncio client (`AsyncIziPay`: FastAPI) with the
  same methods
- Sandbox and production
- MULTICAIXA Express (Webframe, mobile purchase, authorization and capture, QR Code), payment references,
  refunds, terminals, billing (read only) and webhooks
- One dependency: [httpx](https://www.python-httpx.org). Fully typed (`py.typed`), plain frozen dataclasses

## Install

```bash
pip install --pre izipay
```

## Start

```python
import os
from decimal import Decimal

from izipay import IziPay

with IziPay(
    environment="sandbox",  # required: "sandbox" or "production"
    client_id=os.environ["IZIPAY_CLIENT_ID"],
    client_secret=os.environ["IZIPAY_CLIENT_SECRET"],
) as izipay:
    payment = izipay.payments.create_reference(
        amount=Decimal("1500"),
        description="Order 1042",
        customer_email="customer@example.com",
    )
    print(f"Pay entity {payment.entity}, reference {payment.reference}")
```

With asyncio, use `AsyncIziPay` and `await` every call:

```python
from izipay import AsyncIziPay

async with AsyncIziPay(environment="sandbox", client_id=..., client_secret=...) as izipay:
    payment = await izipay.payments.create_reference(amount=Decimal("1500"))
```

Create one client per set of credentials and reuse it (for example at application start-up): it keeps the access
token and the HTTP connections. `IziPay` is thread-safe; `AsyncIziPay` is safe to share between tasks of one event
loop. Only one token request runs at a time. Never put the secret in source control.

## Environments

| Environment | Address | Credentials |
| --- | --- | --- |
| `"sandbox"` / `Environment.SANDBOX` | `https://pay-sandbox.izipay.ao` | Sandbox Client App |
| `"production"` / `Environment.PRODUCTION` | `https://pay.izipay.ao` | Production Client App |

There is no default environment, so test code can never reach production by accident. Sandbox and production
credentials are different; using one in the other fails with an `AuthenticationError` that names the environment.
Ask for credentials at suporte@izipay.ao.

## Payments

| Method | What the customer does |
| --- | --- |
| `create_webframe` | Pays on a provider-hosted page; open `payment.payment_url` |
| `create_mobile` | Approves a one-time purchase on their phone |
| `create_authorization` / `capture` | Approves a reservation; you collect it later with the `authorization_id` |
| `create_qr_code` | Scans `payment.qr_code_png` or opens `payment.deep_link` |
| `create_reference` | Pays `entity` + `reference` at an ATM or in their banking app |

```python
from izipay import PaymentStatus

purchase = izipay.payments.create_mobile(
    amount=Decimal("2500"),
    reference="ORDER-1042",
    phone_number="923000000",
)

if purchase.status is PaymentStatus.COMPLETED:
    ...  # paid
elif purchase.status is PaymentStatus.FAILED:
    ...  # declined: purchase.error_code, purchase.error_message
else:
    ...  # pending: wait for the webhook or read it later with get()
```

A declined payment is **returned** with status `FAILED`, not raised. Always check `status`.

Amounts are in kwanzas, not cents: `Decimal("2500.50")`, `2500` or `"2500.50"`. A `float` is refused (it cannot
hold cents exactly), and so is more than 2 decimals. Amounts in answers are always `Decimal`.

For a payment by reference, `payment.id` is the reference number, which `get()` and `request_status_sync()` accept.

Other operations: `get`, `list`, `request_status_sync` (re-check with the provider when a webhook was missed) and
`cancel_authorization` (release a reservation; takes the `internal_id`, not the `authorization_id`).

## Time-outs

A mobile payment can take up to 90 seconds while the customer approves it on their phone. The SDK waits up to
120 seconds per attempt (`timeout=`). Check that your own limits are longer: gunicorn's default worker time-out is
30 seconds (`--timeout`), and your web server, load balancer or task queue may have their own.

Opening the connection gets at most 15 seconds of that time, so if IZI Pay cannot be reached a call fails within
about 45 seconds (3 attempts) instead of hanging. Nothing is sent before the connection opens, so this is always
safe to retry.

## Safe retries and idempotency

The SDK retries temporary failures (connection problems, time-outs, HTTP 502/503/504, rate limits) **only when
repeating the request cannot do anything twice**:

| Operation | Retried after it was sent? | Why |
| --- | --- | --- |
| Reads, token requests, status sync | Yes | They change nothing |
| Creating a payment (any method) | Yes, with the same idempotency key | IZI Pay returns the existing payment for a repeated key |
| Refunds, references, cancellations, opening/closing terminals | **No** | There is no idempotency key, so a repeat could do it twice |

Every request is retried when it certainly never reached IZI Pay (connection refused, DNS, TLS, connect time-out)
or was refused by the rate limiter (HTTP 429), because nothing was processed. When IZI Pay itself answers a change
with an error code and HTTP 5xx, the SDK does not repeat it.

Each payment gets an idempotency key. Pass your own (`idempotency_key=str(order.id)`) or store the one the SDK made
(`payment.idempotency_key`). If no clear answer comes back, you get an `OutcomeUnknownError`:

```python
from izipay import OutcomeUnknownError

try:
    payment = izipay.payments.create_mobile(amount=amount, reference=ref, phone_number=phone)
except OutcomeUnknownError as error:
    if error.idempotency_key is not None:
        # The payment may exist. Sending the same request with the same key later is safe:
        # IZI Pay returns the existing payment instead of charging again.
        payment = izipay.payments.create_mobile(
            amount=amount, reference=ref, phone_number=phone, idempotency_key=error.idempotency_key
        )
    else:
        ...  # refund, reference or terminal operation: look it up before trying again
```

Defaults: up to 2 retries (`max_retries=`, 0–5) and 120 seconds per attempt.

## Errors

Every failure from IZI Pay is an `izipay.IziPayError`. Catch a subclass, or check `error.kind`:

| Error | `kind` | Meaning |
| --- | --- | --- |
| `AuthenticationError` | `AUTHENTICATION` | Credentials or token rejected |
| `PermissionDeniedError` | `PERMISSION` | These credentials may not do this (HTTP 403) |
| `ValidationError` | `VALIDATION` | Something in the request is wrong (HTTP 400); see `error.details` |
| `NotFoundError` | `NOT_FOUND` | It does not exist for your merchant |
| `ConflictError` | `CONFLICT` | Clashes with the current state (HTTP 409) |
| `NotAvailableError` | `NOT_AVAILABLE` | Feature switched off for your merchant, for example `CHECKOUT_DISABLED` |
| `RateLimitedError` | `RATE_LIMITED` | Too many requests, even after waiting. Nothing was processed |
| `ConnectionFailedError` | `CONNECTION` | IZI Pay could not be reached. Nothing was sent |
| `ServerError` | `SERVER` | IZI Pay had an error while reading data |
| `OutcomeUnknownError` | `OUTCOME_UNKNOWN` | Sent, but no clear answer came back |
| `InvalidResponseError` | `INVALID_RESPONSE` | An answer the SDK could not read |

(`PermissionDeniedError` and `ConnectionFailedError` are named so they do not clash with Python's built-in
`PermissionError` and `ConnectionError`.)

Other attributes: `status_code`, `error_code` (IZI Pay's own code, such as `INVALID_OPERATION`), `details`,
`trace_id` (quote it to support) and `is_safe_to_retry`. Errors can be pickled with their fields (Celery,
multiprocessing).

Mistakes the SDK can see before sending (a missing phone number, a negative amount, a `float` amount, a date
without a time zone, ...) raise `ValueError` or `TypeError` and nothing is sent.

## Webhooks

IZI Pay sends the `Access-Key` you chose during onboarding with every notification. It only stops resending when your
endpoint answers HTTP 2xx with `"Success": true`.

```python
from izipay import Webhooks

webhooks = Webhooks(os.environ["IZIPAY_WEBHOOK_ACCESS_KEY"])


# FastAPI
@app.post("/izipay/reference-payments")
async def reference_payment(request: Request) -> Response:
    if not webhooks.is_authentic(request.headers.get("Access-Key")):
        return Response(status_code=401)

    payment = webhooks.parse_reference_payment(await request.body())

    # Notifications can arrive more than once: use payment.id to process each only once.
    order_id = await orders.mark_paid(payment.reference, payment.amount_paid, payment.id)

    return Response(Webhooks.acknowledge(order_id), media_type="application/json")
```

In Django, read the key with `request.headers.get("Access-Key")` and the body with `request.body`. Use
`parse_qr_code_payment` on your QR Code webhook URL. The key is compared in constant time.

## Other areas

```python
from izipay import CreateReferenceRequest

izipay.references.create(amount=Decimal("1000"))
izipay.references.create_bulk([CreateReferenceRequest(amount=5), CreateReferenceRequest(amount=6)])
izipay.references.get("584923109")
izipay.refunds.create(payment_id=payment_id, amount=Decimal("500"), supervisor_id="...")
izipay.terminals.get_status("POS-ID")
izipay.billing.get_current_usage()
```

## Dates

The gateway writes most dates in Luanda time without an offset. The SDK reads them as UTC+01:00 and returns
timezone-aware `datetime` values, so they are correct whatever time zone your server uses. Dates you pass in
(`expiry_date`, `start_date`, ...) must be timezone-aware too, for example
`datetime(2026, 12, 31, 23, 59, tzinfo=izipay.LUANDA)`.

## Logging

The SDK logs timings (DEBUG) and retries (WARNING) to the `izipay` logger, or to the `logger=` you pass. It never
logs request or response bodies, tokens, secrets or phone numbers.

## Your own HTTP client

Pass `http_client=httpx.Client(...)` (or `httpx.AsyncClient` for `AsyncIziPay`) to use a proxy or your own
connection settings. The SDK still applies its time-out to each request, never follows redirects, and does not
close a client you passed in.

## Development

```bash
python -m venv .venv
.venv/bin/pip install -e . --group dev
.venv/bin/pytest                 # unit tests (sync and async) and integration tests with a local server
.venv/bin/mypy                   # strict, checked as Python 3.11
.venv/bin/ruff check . && .venv/bin/ruff format --check .
.venv/bin/python tools/sandbox_check.py   # against the real sandbox; needs sandbox credentials
```

## Versions and support

Versions follow [Semantic Versioning](https://semver.org/). Before 1.0, a new minor version (0.1 to 0.2) can need code
changes; a new beta or preview of the same minor version only fixes problems. From 1.0, only a major version can remove
or change something, after it was marked as deprecated in a minor version. The SDK supports the Python versions that
still get security fixes from their maintainers. Fixes go to the newest version. What changed in each version:
[SDK updates](https://developer.izipay.ao/sdks/updates).

Problems with the SDK: email suporte@izipay.ao with the SDK version, the environment, and the error's message and
trace ID. Never send secrets, tokens or your webhook Access-Key.

## Releasing

1. Set the new version in `src/izipay/_version.py` and add it at the top of `CHANGELOG.md` (a test fails if they differ).
   If you changed the public API on purpose, run `python tools/api_surface.py --update` (a test fails until you do)
   and describe the change in the CHANGELOG.
2. Push to `main` and wait for the pipeline to pass.
3. Tag and push: `git tag -a v<version> -m "..." && git push origin v<version>`. GitLab CI tests again and publishes to
   PyPI with Trusted Publishing; the tag must match `_version.py`.
4. Check the version on https://pypi.org/project/izipay/ and install it in a clean environment.
5. Add the version to the **SDK updates** page of the docs (`izipay-v2-docs`: `pages/sdks/updates.mdx` and `pages/pt/sdks/updates.mdx`: date, what changed, whether code changes are needed) and update the version named on the SDK's overview pages.
