| 1 | """A stand-in for the HBank merchant API (/api/v1), for testing the SDKs without a database. |
| 2 | |
| 3 | python sdks/testing/mock_server.py [--port 8765] |
| 4 | |
| 5 | Accepts the API key "test_key". State lives in memory and is lost on exit. It mirrors the real API's request |
| 6 | validation, status codes, error codes and response shapes (see MerchantApiController.cs), including 7-digit |
| 7 | fractional seconds in timestamps, as System.Text.Json writes them. It does not charge anyone: POST |
| 8 | /_mock/pay/{transaction_id} marks a payment completed so refunds can be tested. |
| 9 | """ |
| 10 | |
| 11 | import argparse |
| 12 | import json |
| 13 | import re |
| 14 | import secrets |
| 15 | import string |
| 16 | import threading |
| 17 | from datetime import datetime, timedelta, timezone |
| 18 | from decimal import Decimal, InvalidOperation |
| 19 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 20 | from urllib.parse import parse_qs, urlparse |
| 21 | |
| 22 | API_KEY = "test_key" |
| 23 | BASE = "http://127.0.0.1" |
| 24 | DECIMALS = {"EUR": 2, "USD": 2, "CHF": 2, "GBP": 2, "SEK": 2, "DKK": 2, "JPY": 0} |
| 25 | RATES = {"EUR": Decimal("1"), "USD": Decimal("1.0837"), "CHF": Decimal("0.9312"), "GBP": Decimal("0.8421"), |
| 26 | "SEK": Decimal("11.42"), "DKK": Decimal("7.46"), "JPY": Decimal("162.3")} |
| 27 | INTERVALS = ("day", "week", "month", "year") |
| 28 | |
| 29 | lock = threading.Lock() |
| 30 | transactions: dict[str, dict] = {} |
| 31 | subscriptions: dict[str, dict] = {} |
| 32 | next_id = [7300] |
| 33 | |
| 34 | |
| 35 | def new_id() -> int: |
| 36 | next_id[0] += 1 |
| 37 | return next_id[0] |
| 38 | |
| 39 | |
| 40 | def new_subscription_id() -> str: |
| 41 | """"sub_" and 24 random letters and digits, like the real ones.""" |
| 42 | return "sub_" + "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(24)) |
| 43 | |
| 44 | |
| 45 | def new_transaction_id() -> str: |
| 46 | """Like the real ones: "tx_" and 24 random letters and digits, never a number that counts up.""" |
| 47 | return "tx_" + "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(24)) |
| 48 | |
| 49 | |
| 50 | def stamp(dt: datetime | None) -> str | None: |
| 51 | return None if dt is None else dt.strftime("%Y-%m-%dT%H:%M:%S.%f") + "1Z" |
| 52 | |
| 53 | |
| 54 | def number(value) -> Decimal | None: |
| 55 | if isinstance(value, bool) or value is None: |
| 56 | return None |
| 57 | try: |
| 58 | return Decimal(str(value).strip()) if isinstance(value, (int, float, str, Decimal)) else None |
| 59 | except InvalidOperation: |
| 60 | return None |
| 61 | |
| 62 | |
| 63 | def round_to(amount: Decimal, currency: str) -> Decimal: |
| 64 | return amount.quantize(Decimal(1).scaleb(-DECIMALS[currency])) |
| 65 | |
| 66 | |
| 67 | def details(t: dict) -> dict: |
| 68 | refundable = t["amount"] - t["refunded"] if t["type"] == "payment" and t["status"] == "completed" else Decimal(0) |
| 69 | return {"id": t["id"], "type": t["type"], "amount": t["amount"], "currency": t["currency"], "status": t["status"], |
| 70 | "description": t["description"], "reference": t["reference"], "payment_code": t["payment_code"], |
| 71 | "refunded": t["refunded"], "refundable": refundable, "refund_of": t["refund_of"], |
| 72 | "subscription_id": t["subscription_id"], "subscription_ids": t.get("subscription_ids") or |
| 73 | ([t["subscription_id"]] if t["subscription_id"] else [])} |
| 74 | |
| 75 | |
| 76 | def subscription_json(s: dict) -> dict: |
| 77 | url = f"{BASE}/s/{s['code']}" |
| 78 | return {"id": s["id"], "status": s["status"], "active_period": s["status"] == "active", |
| 79 | "amount": s["amount"], "currency": s["currency"], "interval": s["interval"], |
| 80 | "interval_count": s["interval_count"], "description": s["description"], "url": url, "qr_svg": url + "/qr.svg", |
| 81 | "subscribed_at": stamp(s["started_at"]), "subscribed_for_days": 0 if s["started_at"] else None, |
| 82 | "subscribed_for_seconds": 5 if s["started_at"] else None, "canceled": s["canceled_at"] is not None, |
| 83 | "canceled_at": stamp(s["canceled_at"]), "canceled_by": s["canceled_by"], |
| 84 | "current_period_start": None, "current_period_end": None, "next_charge_at": None, "ends_at": None, |
| 85 | "last_day": None, "charges": 0, "last_error": None, "customer": None} |
| 86 | |
| 87 | |
| 88 | def create_transaction(amount, currency, description, callback_url, subscription_id=None) -> dict: |
| 89 | t = {"id": new_transaction_id(), "type": "payment", "amount": amount, "currency": currency, "status": "pending", |
| 90 | "description": description or "", "reference": None, "payment_code": None, "refunded": Decimal(0), |
| 91 | "refund_of": None, "subscription_id": subscription_id, "callback_url": callback_url} |
| 92 | transactions[t["id"]] = t |
| 93 | return t |
| 94 | |
| 95 | |
| 96 | def text(v): |
| 97 | return None if v is None else (v if isinstance(v, str) else json.dumps(v)) |
| 98 | |
| 99 | |
| 100 | class Handler(BaseHTTPRequestHandler): |
| 101 | def log_message(self, *args): |
| 102 | pass |
| 103 | |
| 104 | def send(self, status: int, body, content_type="application/json"): |
| 105 | data = (to_json(body) if content_type == "application/json" else body).encode() |
| 106 | self.send_response(status) |
| 107 | self.send_header("Content-Type", content_type + "; charset=utf-8") |
| 108 | self.send_header("Content-Length", str(len(data))) |
| 109 | self.end_headers() |
| 110 | self.wfile.write(data) |
| 111 | |
| 112 | def fail(self, status: int, error: str, message: str | None = None): |
| 113 | body = {"success": False, "error": error} |
| 114 | if message: |
| 115 | body["message"] = message |
| 116 | self.send(status, body) |
| 117 | |
| 118 | def body(self): |
| 119 | length = int(self.headers.get("Content-Length") or 0) |
| 120 | raw = self.rfile.read(length) if length else b"" |
| 121 | if not raw: |
| 122 | return None |
| 123 | try: |
| 124 | return json.loads(raw) |
| 125 | except ValueError: |
| 126 | return None |
| 127 | |
| 128 | def do_GET(self): |
| 129 | self.route("GET") |
| 130 | |
| 131 | def do_POST(self): |
| 132 | self.route("POST") |
| 133 | |
| 134 | def route(self, method: str): |
| 135 | url = urlparse(self.path) |
| 136 | path = url.path |
| 137 | if method == "POST" and (m := re.fullmatch(r"/_mock/pay/(tx_[A-Za-z0-9]+)", path)): |
| 138 | with lock: |
| 139 | t = transactions.get(m[1]) |
| 140 | if t: |
| 141 | t["status"], t["reference"] = "completed", f"HB20261103MOCK{new_id()}" |
| 142 | for sid in t.get("subscription_ids") or ([t["subscription_id"]] if t["subscription_id"] else []): |
| 143 | s = subscriptions[sid] |
| 144 | s["status"], s["started_at"] = "active", datetime.now(timezone.utc) - timedelta(seconds=5) |
| 145 | return self.send(200 if t else 404, {"success": bool(t)}) |
| 146 | if not path.startswith("/api/v1/"): |
| 147 | return self.send(404, "Not found", "text/plain") |
| 148 | |
| 149 | auth = self.headers.get("Authorization", "") |
| 150 | token = auth[7:].strip() if auth.lower().startswith("bearer ") else "" |
| 151 | if not token: |
| 152 | return self.send(401, "API key is missing", "text/plain") |
| 153 | if token != API_KEY: |
| 154 | return self.send(403, "Invalid API key", "text/plain") |
| 155 | |
| 156 | route = path[len("/api/v1/"):] |
| 157 | with lock: |
| 158 | if method == "GET" and route in ("currency/convert", "currency/rate"): |
| 159 | return self.currency(route, {k: v[0] for k, v in parse_qs(url.query).items()}) |
| 160 | if method == "GET" and route == "subscriptions": |
| 161 | items = sorted(subscriptions.values(), key=lambda s: -s["seq"])[:100] |
| 162 | return self.send(200, {"success": True, "subscriptions": [subscription_json(s) for s in items]}) |
| 163 | if method == "GET" and (m := re.fullmatch(r"subscriptions/(sub_[A-Za-z0-9]+)", route)): |
| 164 | s = subscriptions.get(m[1]) |
| 165 | return self.send(200, {"success": True, "subscription": subscription_json(s)}) if s \ |
| 166 | else self.fail(404, "subscription_not_found") |
| 167 | if method != "POST": |
| 168 | return self.send(405, "", "text/plain") |
| 169 | |
| 170 | body = self.body() |
| 171 | if m := re.fullmatch(r"subscriptions/([A-Za-z0-9_]+)/(checkout|cancel)", route): |
| 172 | return self.subscription_action(m[1], m[2], body if isinstance(body, dict) else {}) |
| 173 | if not isinstance(body, dict): |
| 174 | return self.fail(400, "invalid_request") |
| 175 | handler = {"payment/request": self.payment_request, "payment/code": self.payment_code, |
| 176 | "payment/details": self.payment_details, "payment/refund": self.refund, |
| 177 | "subscriptions": self.offer, "subscriptions/checkout": self.offer}.get(route) |
| 178 | if handler is None: |
| 179 | return self.send(404, "Not found", "text/plain") |
| 180 | return handler(body) if handler != self.offer else self.offer(body, checkout=route.endswith("checkout")) |
| 181 | |
| 182 | def payment_request(self, body): |
| 183 | if "amount" not in body or "currency" not in body: |
| 184 | return self.fail(400, "missing_parameters") |
| 185 | amount = number(body["amount"]) |
| 186 | if amount is None or amount <= 0: |
| 187 | return self.fail(400, "invalid_amount") |
| 188 | currency = body["currency"] if isinstance(body["currency"], str) else None |
| 189 | if currency not in DECIMALS: |
| 190 | return self.fail(400, "unknown_currency") |
| 191 | amount = round_to(amount, currency) |
| 192 | if amount <= 0: |
| 193 | return self.fail(400, "invalid_amount") |
| 194 | t = create_transaction(amount, currency, text(body.get("description")), text(body.get("callback_url"))) |
| 195 | self.send(200, {"success": True, "transaction_id": t["id"]}) |
| 196 | |
| 197 | def transaction_id(self, body): |
| 198 | raw = body.get("transaction_id") |
| 199 | if raw is None: |
| 200 | return None |
| 201 | # Ids are strings; anything else (a number from before, say) names no payment here. |
| 202 | return raw if isinstance(raw, str) else "" |
| 203 | |
| 204 | def payment_code(self, body): |
| 205 | tid = self.transaction_id(body) |
| 206 | if tid is None: |
| 207 | return self.fail(400, "missing_parameters") |
| 208 | t = transactions.get(tid) |
| 209 | if not t or t["status"] != "pending": |
| 210 | return self.fail(404, "transaction_not_payable") |
| 211 | t["payment_code"] = t["payment_code"] or ("mockcode" + t["id"][-8:]) |
| 212 | url = f"{BASE}/p/{t['payment_code']}" |
| 213 | self.send(200, {"success": True, "code": t["payment_code"], "url": url, "qr_svg": url + "/qr.svg"}) |
| 214 | |
| 215 | def payment_details(self, body): |
| 216 | tid = self.transaction_id(body) |
| 217 | if tid is None: |
| 218 | return self.fail(400, "missing_parameters") |
| 219 | t = transactions.get(tid) |
| 220 | if not t: |
| 221 | return self.fail(404, "transaction_not_found") |
| 222 | self.send(200, {"success": True, "transaction": details(t)}) |
| 223 | |
| 224 | def refund(self, body): |
| 225 | tid = self.transaction_id(body) |
| 226 | if tid is None: |
| 227 | return self.fail(400, "missing_parameters") |
| 228 | amount = None |
| 229 | if body.get("amount") is not None: |
| 230 | amount = number(body["amount"]) |
| 231 | if amount is None: |
| 232 | return self.fail(400, "invalid_amount") |
| 233 | t = transactions.get(tid) |
| 234 | if not t: |
| 235 | return self.fail(404, "transaction_not_found", "Payment not found.") |
| 236 | left = t["amount"] - t["refunded"] |
| 237 | if t["status"] != "completed" or t["type"] != "payment" or left <= 0: |
| 238 | return self.fail(409, "not_refundable", "This payment can't be refunded.") |
| 239 | amount = left if amount is None else amount |
| 240 | if amount <= 0 or amount != round_to(amount, t["currency"]): |
| 241 | return self.fail(400, "invalid_amount", "Enter an amount above 0.") |
| 242 | if amount > left: |
| 243 | return self.fail(400, "amount_too_high", "That's more than what can still be refunded.") |
| 244 | reason = text(body.get("reason")) |
| 245 | if reason and len(reason) > 200: |
| 246 | return self.fail(400, "invalid_reason", "The reason can be at most 200 characters.") |
| 247 | t["refunded"] += amount |
| 248 | r = {"id": new_transaction_id(), "type": "refund", "amount": amount, "currency": t["currency"], "status": "completed", |
| 249 | "description": reason or "", "reference": f"HB20261103RF{new_id()}", "payment_code": None, |
| 250 | "refunded": Decimal(0), "refund_of": t["id"], "subscription_id": None} |
| 251 | transactions[r["id"]] = r |
| 252 | self.send(200, {"success": True, "refund": {"id": r["id"], "amount": amount, "currency": r["currency"], |
| 253 | "reference": r["reference"], "reason": reason}, |
| 254 | "transaction": details(t)}) |
| 255 | |
| 256 | def offer(self, body, checkout: bool): |
| 257 | if checkout and body.get("subscriptions") is not None: |
| 258 | return self.checkout_many(body) |
| 259 | problem = self.offer_problem(body) |
| 260 | if problem: |
| 261 | return self.fail(400, *problem) |
| 262 | s = self.new_offer(body) |
| 263 | if checkout: |
| 264 | return self.subscription_action(s["id"], "checkout", body) |
| 265 | self.send(200, {"success": True, "subscription": subscription_json(s)}) |
| 266 | |
| 267 | def checkout_many(self, body): |
| 268 | """Several subscriptions in one checkout: offer ids or new offers, one currency, all or nothing.""" |
| 269 | items = body["subscriptions"] |
| 270 | if not isinstance(items, list): |
| 271 | return self.fail(400, "invalid_subscriptions", "subscriptions has to be a list.") |
| 272 | if not 1 <= len(items) <= 20: |
| 273 | return self.fail(400, "invalid_subscriptions", "List 1 to 20 subscriptions.") |
| 274 | ids = [i if isinstance(i, str) else text(i.get("id")) for i in items if isinstance(i, str) or (isinstance(i, dict) and "id" in i)] |
| 275 | if len(ids) != len(set(ids)): |
| 276 | return self.fail(400, "duplicate_subscription", "Each subscription can be listed only once.") |
| 277 | chosen = [] |
| 278 | for n, item in enumerate(items, 1): |
| 279 | sid = item if isinstance(item, str) else (text(item.get("id")) if isinstance(item, dict) and "id" in item else None) |
| 280 | if sid is not None: |
| 281 | s = subscriptions.get(sid) |
| 282 | if not s: |
| 283 | return self.fail(404, "subscription_not_found", f"Subscription {n}: not found.") |
| 284 | if s["status"] != "offered": |
| 285 | return self.fail(409, "not_open", f"Subscription {n}: it can't be started (anymore).") |
| 286 | chosen.append(s) |
| 287 | continue |
| 288 | problem = self.offer_problem(item if isinstance(item, dict) else None) |
| 289 | if problem: |
| 290 | return self.fail(400, problem[0], f"Subscription {n}: {problem[1] if len(problem) > 1 else problem[0]}") |
| 291 | chosen.append(item) |
| 292 | if len({(c["currency"] if "seq" in c else text(c["currency"])) for c in chosen}) > 1: |
| 293 | return self.fail(400, "mixed_currencies", "All subscriptions in one checkout have to be in the same currency.") |
| 294 | # Validated: only now are the new offers made. |
| 295 | started = [c if "seq" in c else self.new_offer(c) for c in chosen] |
| 296 | description = text(body.get("description")) or ", ".join(s["description"] or "Subscription" for s in started) |
| 297 | t = create_transaction(sum(s["amount"] for s in started), started[0]["currency"], description[:200], |
| 298 | text(body.get("callback_url"))) |
| 299 | t["subscription_ids"] = [s["id"] for s in started] |
| 300 | self.send(200, {"success": True, "transaction_id": t["id"], "subscriptions": [subscription_json(s) for s in started]}) |
| 301 | |
| 302 | def offer_problem(self, body): |
| 303 | """(error, message) for a new offer's fields, or None when they're fine.""" |
| 304 | if not isinstance(body, dict): |
| 305 | return ("invalid_request",) |
| 306 | if "amount" not in body or "currency" not in body or "interval" not in body: |
| 307 | return ("missing_parameters",) |
| 308 | amount = number(body["amount"]) |
| 309 | if amount is None: |
| 310 | return ("invalid_amount",) |
| 311 | count = body.get("interval_count") |
| 312 | count = Decimal(1) if count is None else number(count) |
| 313 | if count is None or count != count.to_integral() or not 1 <= count <= 120: |
| 314 | return ("invalid_interval", "Charge every 1 to 120 days, weeks, months or years.") |
| 315 | currency = text(body["currency"]) |
| 316 | if currency not in DECIMALS: |
| 317 | return ("unknown_currency", "Unknown currency.") |
| 318 | if amount <= 0 or amount != round_to(amount, currency): |
| 319 | return ("invalid_amount", "Enter an amount above 0.") |
| 320 | if text(body["interval"]) not in INTERVALS: |
| 321 | return ("invalid_interval", "Charge every 1 to 120 days, weeks, months or years.") |
| 322 | description = text(body.get("description")) |
| 323 | if description and len(description) > 200: |
| 324 | return ("invalid_description", "The description can be at most 200 characters.") |
| 325 | return None |
| 326 | |
| 327 | def new_offer(self, body) -> dict: |
| 328 | currency = text(body["currency"]) |
| 329 | count = body.get("interval_count") |
| 330 | sid = new_subscription_id() |
| 331 | s = {"id": sid, "seq": new_id(), "code": "mocksub" + sid[-9:], "status": "offered", |
| 332 | "amount": round_to(number(body["amount"]), currency), "currency": currency, |
| 333 | "interval": body["interval"], "interval_count": 1 if count is None else int(number(count)), |
| 334 | "description": text(body.get("description")), "started_at": None, "canceled_at": None, "canceled_by": None} |
| 335 | subscriptions[sid] = s |
| 336 | return s |
| 337 | |
| 338 | def subscription_action(self, sid: str, action: str, body: dict): |
| 339 | s = subscriptions.get(sid) |
| 340 | if not s: |
| 341 | return self.fail(404, "subscription_not_found") |
| 342 | if action == "cancel": |
| 343 | if s["canceled_at"]: |
| 344 | return self.fail(409, "already_canceled") |
| 345 | s["canceled_at"], s["canceled_by"] = datetime.now(timezone.utc), "merchant" |
| 346 | s["status"] = "canceled" |
| 347 | return self.send(200, {"success": True, "subscription": subscription_json(s)}) |
| 348 | if s["status"] != "offered": |
| 349 | return self.fail(409, "not_open", "This subscription can't be started (anymore). Ask for a new link.") |
| 350 | t = create_transaction(s["amount"], s["currency"], s["description"], text(body.get("callback_url")), sid) |
| 351 | self.send(200, {"success": True, "transaction_id": t["id"], "subscription": subscription_json(s)}) |
| 352 | |
| 353 | def currency(self, route: str, p: dict): |
| 354 | body = self.body() |
| 355 | if body is not None: |
| 356 | if not isinstance(body, dict): |
| 357 | return self.fail(400, "invalid_request") |
| 358 | p = body |
| 359 | needed = ("currency_from", "currency_to") + (("amount",) if route.endswith("convert") else ()) |
| 360 | if any(k not in p for k in needed): |
| 361 | return self.fail(400, "missing_parameters") |
| 362 | if route.endswith("convert") and number(p["amount"]) is None: |
| 363 | return self.fail(400, "invalid_amount") |
| 364 | f, t = text(p["currency_from"]), text(p["currency_to"]) |
| 365 | if f not in RATES or t not in RATES: |
| 366 | return self.fail(400, "unknown_currency") |
| 367 | rate = RATES[t] / RATES[f] |
| 368 | if route.endswith("convert"): |
| 369 | return self.send(200, {"success": True, "amount": round_to(number(p["amount"]) * rate, t)}) |
| 370 | self.send(200, {"success": True, "from_rate": RATES[f] / RATES[t], "to_rate": rate}) |
| 371 | |
| 372 | |
| 373 | def to_json(body) -> str: |
| 374 | """JSON with Decimals written as exact numbers (24.90 stays 24.90), as .NET writes decimals.""" |
| 375 | marked = json.dumps(body, default=lambda d: f"@@DEC:{d}@@") |
| 376 | return re.sub(r'"@@DEC:([^@]+)@@"', lambda m: m[1], marked) |
| 377 | |
| 378 | |
| 379 | def main(): |
| 380 | global BASE |
| 381 | parser = argparse.ArgumentParser() |
| 382 | parser.add_argument("--port", type=int, default=8765) |
| 383 | args = parser.parse_args() |
| 384 | BASE = f"http://127.0.0.1:{args.port}" |
| 385 | server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler) |
| 386 | print(f"Mock HBank API on {BASE}/api/v1 (API key: {API_KEY})", flush=True) |
| 387 | server.serve_forever() |
| 388 | |
| 389 | |
| 390 | if __name__ == "__main__": |
| 391 | main() |