import os
import json
import urllib.error
import urllib.request
API_URL = os.environ.get("ZAHLO_API_URL", "https://merchant-demo.zahlo.eu")
API_KEY = os.environ["ZAHLO_API_KEY"]
idempotency_key = "checkout-order-1001"
request = urllib.request.Request(
f"{API_URL}/api/v1/checkout-sessions",
data=json.dumps({
"mode": "hosted",
"amountMinor": 4990,
"currency": "EUR",
"method": "card",
"orderId": "order-1001",
"successUrl": "https://store.example/checkout/success",
"cancelUrl": "https://store.example/checkout/cancelled",
}).encode(),
headers={"Content-Type": "application/json", "x-api-key": API_KEY,
"Idempotency-Key": idempotency_key},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=10) as response:
checkout = json.load(response)
except (TimeoutError, urllib.error.URLError) as error:
# Reuse idempotency_key to retrieve/reconcile; do not create a new payment.
raise RuntimeError("retryable checkout error") from error
except urllib.error.HTTPError as error:
body = json.loads(error.read().decode() or "{}")
retryable = error.code == 429 or error.code >= 500
raise RuntimeError(body.get("error", "merchant API error")) from error