| 1 | import json |
| 2 | import socket |
| 3 | import urllib.error |
| 4 | import urllib.parse |
| 5 | import urllib.request |
| 6 | from decimal import Decimal |
| 7 | from typing import Any, Dict, List, Optional, Union |
| 8 | |
| 9 | from .errors import AuthenticationError, HBankConnectionError, HBankError |
| 10 | from .models import (Payment, PaymentCode, Rate, Refund, RefundResult, Subscription, SubscriptionCheckout, |
| 11 | SubscriptionsCheckout, _dec) |
| 12 | |
| 13 | DEFAULT_BASE_URL = "https://bank.thehsi.cloud" |
| 14 | Amount = Union[Decimal, int, str, float] |
| 15 | |
| 16 | |
| 17 | def _amount(value: Amount) -> str: |
| 18 | """Amounts go over the wire as strings, which the API accepts, so no digits are lost to floats.""" |
| 19 | if isinstance(value, bool): |
| 20 | raise TypeError("amount must be a number") |
| 21 | if isinstance(value, float): |
| 22 | value = repr(value) # shortest round-trip text: 24.9 -> "24.9" |
| 23 | return str(value) |
| 24 | |
| 25 | |
| 26 | class HBank: |
| 27 | """Client for the HBank merchant API (v1). |
| 28 | |
| 29 | >>> bank = HBank(api_key=os.environ["HBANK_API_KEY"]) |
| 30 | >>> tid = bank.create_payment("24.90", "EUR", description="Order 1042", |
| 31 | ... callback_url="https://shop.example.com/hbank/callback") |
| 32 | >>> redirect(bank.checkout_url(tid)) |
| 33 | |
| 34 | Thread-safe: one instance can be shared by the whole app. |
| 35 | """ |
| 36 | |
| 37 | def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0, |
| 38 | user_agent: str = "hbank-python/1.0"): |
| 39 | if not api_key: |
| 40 | raise ValueError("api_key is required") |
| 41 | self.api_key = api_key |
| 42 | self.base_url = base_url.rstrip("/") |
| 43 | self.timeout = timeout |
| 44 | self.user_agent = user_agent |
| 45 | |
| 46 | # ── Payments ───────────────────────────────────────────── |
| 47 | |
| 48 | def create_payment(self, amount: Amount, currency: str, description: Optional[str] = None, |
| 49 | callback_url: Optional[str] = None) -> str: |
| 50 | """Creates a pending payment request and returns its transaction id: a random string like |
| 51 | ``tx_8fK2mQ7xRb4Tn9WcYz3LpH6v`` (store it as text). It stays payable for one hour.""" |
| 52 | body = {"amount": _amount(amount), "currency": currency} |
| 53 | _put(body, description=description, callback_url=callback_url) |
| 54 | return self._post("payment/request", body)["transaction_id"] |
| 55 | |
| 56 | def create_payment_code(self, transaction_id: str) -> PaymentCode: |
| 57 | """A QR code / link for a pending payment. Calling it again returns the same code.""" |
| 58 | d = self._post("payment/code", {"transaction_id": transaction_id}) |
| 59 | return PaymentCode(code=d["code"], url=d["url"], qr_svg=d["qr_svg"]) |
| 60 | |
| 61 | def get_payment(self, transaction_id: str) -> Payment: |
| 62 | """The current state of one of your payments. Check ``.completed`` here before handing out goods.""" |
| 63 | return Payment.from_json(self._post("payment/details", {"transaction_id": transaction_id})["transaction"]) |
| 64 | |
| 65 | def refund(self, transaction_id: str, amount: Optional[Amount] = None, reason: Optional[str] = None) -> RefundResult: |
| 66 | """Refunds a completed payment: ``amount`` in its currency, or everything that's left if omitted. |
| 67 | |
| 68 | Not safe to blindly retry after a timeout: check ``get_payment(id).refunded`` first. |
| 69 | """ |
| 70 | body: Dict[str, Any] = {"transaction_id": transaction_id} |
| 71 | if amount is not None: |
| 72 | body["amount"] = _amount(amount) |
| 73 | _put(body, reason=reason) |
| 74 | d = self._post("payment/refund", body) |
| 75 | r = d["refund"] |
| 76 | return RefundResult( |
| 77 | refund=Refund(id=r["id"], amount=_dec(r["amount"]), currency=r["currency"], reference=r["reference"], |
| 78 | reason=r.get("reason")), |
| 79 | payment=Payment.from_json(d["transaction"])) |
| 80 | |
| 81 | def checkout_url(self, transaction_id: str) -> str: |
| 82 | """The hosted checkout (card number + PIN) for a payment. Needs a ``callback_url`` on the payment.""" |
| 83 | return f"{self.base_url}/api/payment?tid={urllib.parse.quote(str(transaction_id), safe='')}" |
| 84 | |
| 85 | # ── Subscriptions ──────────────────────────────────────── |
| 86 | |
| 87 | def create_subscription(self, amount: Amount, currency: str, interval: str, interval_count: int = 1, |
| 88 | description: Optional[str] = None) -> Subscription: |
| 89 | """Offers a subscription (``interval``: day, week, month or year). Send the customer its ``url``.""" |
| 90 | return Subscription.from_json( |
| 91 | self._post("subscriptions", _offer(amount, currency, interval, interval_count, description))["subscription"]) |
| 92 | |
| 93 | def create_subscription_checkout(self, amount: Amount, currency: str, interval: str, interval_count: int = 1, |
| 94 | description: Optional[str] = None, |
| 95 | callback_url: Optional[str] = None) -> SubscriptionCheckout: |
| 96 | """Offers a subscription and creates its first payment, for the pay button / hosted checkout.""" |
| 97 | body = _offer(amount, currency, interval, interval_count, description) |
| 98 | _put(body, callback_url=callback_url) |
| 99 | return _checkout(self._post("subscriptions/checkout", body)) |
| 100 | |
| 101 | def create_subscriptions_checkout(self, subscriptions: List[Union[str, Dict[str, Any]]], |
| 102 | description: Optional[str] = None, |
| 103 | callback_url: Optional[str] = None) -> SubscriptionsCheckout: |
| 104 | """One first payment for several subscriptions (up to 20, one currency): each item is the id of a subscription |
| 105 | you offered (``"sub_…"``) or a new offer's fields as a dict (``amount``, ``currency``, ``interval``, optional |
| 106 | ``interval_count`` and ``description``). Paying it starts them all; after that each renews on its own. When one |
| 107 | is refused nothing is offered. |
| 108 | |
| 109 | >>> c = bank.create_subscriptions_checkout(["sub_Hk3…", {"amount": "2.50", "currency": "EUR", "interval": "week"}]) |
| 110 | """ |
| 111 | items: List[Any] = [] |
| 112 | for item in subscriptions: |
| 113 | if isinstance(item, str): |
| 114 | items.append(item) |
| 115 | else: |
| 116 | items.append(_offer(item["amount"], item["currency"], item["interval"], item.get("interval_count", 1), |
| 117 | item.get("description"))) |
| 118 | body: Dict[str, Any] = {"subscriptions": items} |
| 119 | _put(body, description=description, callback_url=callback_url) |
| 120 | d = self._post("subscriptions/checkout", body) |
| 121 | return SubscriptionsCheckout(transaction_id=d["transaction_id"], |
| 122 | subscriptions=[Subscription.from_json(s) for s in d["subscriptions"]]) |
| 123 | |
| 124 | def checkout_subscription(self, subscription_id: str, callback_url: Optional[str] = None) -> SubscriptionCheckout: |
| 125 | """A new first payment for a subscription already offered (``not_open`` once someone subscribed).""" |
| 126 | body: Dict[str, Any] = {} |
| 127 | _put(body, callback_url=callback_url) |
| 128 | return _checkout(self._post(f"subscriptions/{urllib.parse.quote(str(subscription_id), safe='')}/checkout", body)) |
| 129 | |
| 130 | def list_subscriptions(self) -> List[Subscription]: |
| 131 | """Your subscriptions, newest first (up to 100).""" |
| 132 | return [Subscription.from_json(s) for s in self._get("subscriptions")["subscriptions"]] |
| 133 | |
| 134 | def get_subscription(self, subscription_id: str) -> Subscription: |
| 135 | return Subscription.from_json(self._get(f"subscriptions/{urllib.parse.quote(str(subscription_id), safe='')}")["subscription"]) |
| 136 | |
| 137 | def cancel_subscription(self, subscription_id: str) -> Subscription: |
| 138 | """No more charges. It stays in its ``active_period`` until ``current_period_end``.""" |
| 139 | return Subscription.from_json(self._post(f"subscriptions/{urllib.parse.quote(str(subscription_id), safe='')}/cancel", {})["subscription"]) |
| 140 | |
| 141 | # ── Currencies ─────────────────────────────────────────── |
| 142 | |
| 143 | def convert(self, amount: Amount, currency_from: str, currency_to: str) -> Decimal: |
| 144 | d = self._get("currency/convert", {"amount": _amount(amount), "currency_from": currency_from, |
| 145 | "currency_to": currency_to}) |
| 146 | return _dec(d["amount"]) |
| 147 | |
| 148 | def rate(self, currency_from: str, currency_to: str) -> Rate: |
| 149 | d = self._get("currency/rate", {"currency_from": currency_from, "currency_to": currency_to}) |
| 150 | return Rate(to_rate=_dec(d["to_rate"]), from_rate=_dec(d["from_rate"])) |
| 151 | |
| 152 | # ── Transport ──────────────────────────────────────────── |
| 153 | |
| 154 | def _get(self, path: str, query: Optional[Dict[str, str]] = None) -> Dict[str, Any]: |
| 155 | suffix = "?" + urllib.parse.urlencode(query) if query else "" |
| 156 | return self._send("GET", path + suffix, None) |
| 157 | |
| 158 | def _post(self, path: str, body: Dict[str, Any]) -> Dict[str, Any]: |
| 159 | return self._send("POST", path, json.dumps(body).encode()) |
| 160 | |
| 161 | def _send(self, method: str, path: str, data: Optional[bytes]) -> Dict[str, Any]: |
| 162 | headers = {"Authorization": f"Bearer {self.api_key}", "Accept": "application/json", |
| 163 | "User-Agent": self.user_agent} |
| 164 | if data is not None: |
| 165 | headers["Content-Type"] = "application/json" |
| 166 | req = urllib.request.Request(f"{self.base_url}/api/v1/{path}", data=data, method=method, headers=headers) |
| 167 | try: |
| 168 | with urllib.request.urlopen(req, timeout=self.timeout) as res: |
| 169 | status, raw = res.status, res.read() |
| 170 | except urllib.error.HTTPError as e: |
| 171 | with e: |
| 172 | status, raw = e.code, e.read() |
| 173 | except (urllib.error.URLError, socket.timeout, TimeoutError, OSError) as e: |
| 174 | raise HBankConnectionError("connection_failed", None, str(getattr(e, "reason", e))) from e |
| 175 | |
| 176 | text = raw.decode("utf-8", "replace") |
| 177 | try: |
| 178 | body = json.loads(text, parse_float=Decimal) |
| 179 | except ValueError: |
| 180 | body = None |
| 181 | |
| 182 | if status == 401: |
| 183 | raise AuthenticationError("missing_api_key", status, text.strip() or None, text) |
| 184 | if status == 403: |
| 185 | raise AuthenticationError("invalid_api_key", status, text.strip() or None, text) |
| 186 | if not isinstance(body, dict): |
| 187 | raise HBankError("invalid_response", status, text[:200] or None, text) |
| 188 | if not (200 <= status < 300) or body.get("success") is False: |
| 189 | raise HBankError(str(body.get("error") or f"http_{status}"), status, body.get("message"), body) |
| 190 | return body |
| 191 | |
| 192 | |
| 193 | def _put(body: Dict[str, Any], **fields: Any) -> None: |
| 194 | for key, value in fields.items(): |
| 195 | if value is not None: |
| 196 | body[key] = value |
| 197 | |
| 198 | |
| 199 | def _offer(amount: Amount, currency: str, interval: str, interval_count: int, description: Optional[str]) -> Dict[str, Any]: |
| 200 | body: Dict[str, Any] = {"amount": _amount(amount), "currency": currency, "interval": interval, |
| 201 | "interval_count": interval_count} |
| 202 | _put(body, description=description) |
| 203 | return body |
| 204 | |
| 205 | |
| 206 | def _checkout(d: Dict[str, Any]) -> SubscriptionCheckout: |
| 207 | return SubscriptionCheckout(transaction_id=d["transaction_id"], subscription=Subscription.from_json(d["subscription"])) |