# hbank (Python)

Client for the HBank merchant API. Python 3.8+, no dependencies.

```sh
pip install --index-url https://bank.thehsi.cloud/hbank/pip/simple/ hbank
pip install ./sdks/python    # or from the folder
```

```python
import os
from decimal import Decimal
import hbank

bank = hbank.HBank(api_key=os.environ["HBANK_API_KEY"])  # base_url="http://localhost:8000" for a local instance

tid = bank.create_payment(Decimal("24.90"), "EUR", description="Order 1042",
                          callback_url="https://shop.example.com/hbank/callback")
checkout = bank.checkout_url(tid)                 # hosted checkout (card + PIN)
qr = bank.create_payment_code(tid)                # or a QR code: qr.url, qr.qr_svg

payment = bank.get_payment(tid)
if payment.completed:
    ship(order)

result = bank.refund(tid, "10.00", reason="Returned one item")
print(result.refund.reference, result.payment.refundable)

sub = bank.create_subscription("9.99", "EUR", "month", description="Pro plan")
send_to_customer(sub.url)
bank.cancel_subscription(sub.id)

# Several subscriptions in one checkout: offers you made and new ones, one payment starts them all
both = bank.create_subscriptions_checkout([sub.id, {"amount": "2.50", "currency": "EUR", "interval": "week"}])

bank.convert(100, "EUR", "USD")                   # Decimal("108.37")
bank.rate("EUR", "USD").to_rate
```

Amounts may be `Decimal`, `int`, `str` or `float`; answers use `Decimal` and timezone-aware `datetime`s. Each model
keeps the full JSON in `.raw`.

## Errors

```python
try:
    bank.refund(tid)
except hbank.AuthenticationError:          # missing_api_key / invalid_api_key
    ...
except hbank.HBankConnectionError:         # connection_failed: may or may not have reached HBank
    ...
except hbank.HBankError as e:
    print(e.code, e.status, e.message)     # "not_refundable", 409, "..."
```

## Callbacks

HBank POSTs `{id, amount, currency, status, description}` to the payment's `callback_url` before charging, and charges
only if you answer `{"resume": true}`. It's signed: check `hbank.verify_signature(secret, request.headers.get("HBank-Signature"), raw_body)`
with your signing secret (business settings → Callback URLs) before you approve, and check it against your own order.

**Flask**

```python
@app.post("/hbank/callback")
def hbank_callback():
    cb = hbank.parse_callback(request.get_data())
    order = Order.by_transaction(cb.id)
    return jsonify(hbank.approve() if order and order.total == cb.amount else hbank.refuse("Out of stock"))
```

**Django**

```python
@csrf_exempt
@require_POST
def hbank_callback(request):
    cb = hbank.parse_callback(request.body)
    ok = Order.objects.filter(hbank_transaction_id=cb.id, total=cb.amount).exists()
    return JsonResponse(hbank.approve() if ok else hbank.refuse("This order is no longer available"))
```

**FastAPI** (the client is synchronous: call it from plain `def` endpoints, which FastAPI runs in a thread pool,
or wrap calls in `run_in_threadpool` inside `async def`)

```python
@app.post("/hbank/callback")
async def hbank_callback(request: Request):
    cb = hbank.parse_callback(await request.body())
    return hbank.approve() if await orders.matches(cb.id, cb.amount) else hbank.refuse("Out of stock")

@app.get("/checkout/hbank")
def start_checkout(cart: int):
    tid = bank.create_payment(carts[cart].total, "EUR", callback_url="https://shop.example.com/hbank/callback")
    return RedirectResponse(bank.checkout_url(tid))
```

## Tests

```sh
python -m unittest discover -s tests      # starts ../testing/mock_server.py in-process
```
