callbacks.py

Python SDK · 2.9 KB · 64 lines

1"""Answering HBank's callback: right before charging a customer, HBank POSTs the payment to its ``callback_url``
2and charges only if you answer 200 with ``{"resume": true}`` (as ``application/json``) within 10 seconds.
3
4It's signed: check the ``HBank-Signature`` header with your business's signing secret (business settings → Callback
5URLs) before you approve, with ``verify_signature``. Also check that ``id`` and ``amount`` match an order you created,
6and confirm with ``HBank.get_payment`` before handing out goods.
7"""
8
9import hashlib
10import hmac
11import json
12import time
13from dataclasses import dataclass
14from decimal import Decimal
15from typing import Any, Dict, Mapping, Optional, Union
16
17from .errors import HBankError
18
19
20@dataclass(frozen=True)
21class Callback:
22 id: str # the transaction id you got from create_payment ("tx_…")
23 amount: Decimal
24 currency: str
25 status: str
26 description: str
27
28
29def parse_callback(body: Union[bytes, str, Mapping[str, Any]]) -> Callback:
30 """Reads a callback request body. Raises HBankError("invalid_callback") if it doesn't look like one."""
31 try:
32 data = json.loads(body, parse_float=Decimal) if isinstance(body, (bytes, str)) else dict(body)
33 return Callback(id=str(data["id"]), amount=Decimal(str(data["amount"])), currency=str(data["currency"]),
34 status=str(data.get("status") or ""), description=str(data.get("description") or ""))
35 except (ValueError, KeyError, TypeError, ArithmeticError) as e:
36 raise HBankError("invalid_callback", None, str(e)) from e
37
38
39def verify_signature(secret: str, header: Optional[str], body: Union[bytes, str], tolerance: int = 300,
40 now: Optional[float] = None) -> bool:
41 """Whether ``header`` (the request's ``HBank-Signature``: ``t=<unix time>,v1=<hex>``) signs ``body`` (the raw request
42 body, exactly as received) with ``secret``, and was made within ``tolerance`` seconds."""
43 if not secret or not header:
44 return False
45 parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
46 try:
47 timestamp = int(parts.get("t", ""))
48 except ValueError:
49 return False
50 if abs((time.time() if now is None else now) - timestamp) > tolerance:
51 return False
52 raw = body if isinstance(body, bytes) else body.encode("utf-8")
53 expected = hmac.new(secret.encode("utf-8"), str(timestamp).encode("ascii") + b"." + raw, hashlib.sha256).hexdigest()
54 return hmac.compare_digest(expected, parts.get("v1", ""))
55
56
57def approve() -> Dict[str, Any]:
58 """The answer that lets HBank charge the customer. Send it as JSON with status 200."""
59 return {"resume": True}
60
61
62def refuse(error: Optional[str] = None) -> Dict[str, Any]:
63 """The answer that refuses the payment; the customer sees ``error``. Send it as JSON with status 200."""
64 return {"resume": False, "error": error} if error else {"resume": False}