"""Small standard-library client for RL Sell Partner API v2. No request is retried automatically. Save a PreparedRequest in private server storage BEFORE execute() for purchase/quote operations. A timeout is not a rejection: reconcile or explicitly resend the exact saved request and key. Never put keys, recipient fields, or issued codes in logs. """ from __future__ import annotations import json from http.client import IncompleteRead import re import socket from dataclasses import dataclass, field from decimal import Decimal from typing import Any, Callable from urllib.error import HTTPError, URLError from urllib.parse import quote, urlencode, urlsplit from urllib.request import HTTPRedirectHandler, Request, build_opener _KEY = re.compile(r"[A-Za-z0-9._:-]{1,128}\Z") _USD = re.compile(r"(?:0|[1-9][0-9]*)(?:\.[0-9]{1,2})?\Z") class _NoRedirect(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): # X-API-Key must never follow a redirect to another host or URL. return None _open_once = build_opener(_NoRedirect()).open def usd(value: str) -> Decimal: """Read a positive API amount without passing through binary float.""" if not isinstance(value, str) or not _USD.fullmatch(value): raise ValueError("Amount must be a positive decimal string with at most two places") result = Decimal(value) if result <= 0 or result > Decimal("999999999999.99"): raise ValueError("Amount is outside the supported range") return result @dataclass(frozen=True) class PreparedRequest: """Immutable intent; repr hides the payload and idempotency key.""" method: str path: str body: bytes | None = field(default=None, repr=False) idempotency_key: str | None = field(default=None, repr=False) def to_json(self) -> str: """Persist privately; this contains recipient data, never the API key.""" return json.dumps({"method": self.method, "path": self.path, "body": self.body.decode("utf-8") if self.body is not None else None, "idempotency_key": self.idempotency_key}, ensure_ascii=False) @classmethod def from_json(cls, value: str) -> PreparedRequest: record = json.loads(value) if not isinstance(record, dict) or set(record) != {"method", "path", "body", "idempotency_key"}: raise ValueError("Invalid saved request") if record["body"] is not None and not isinstance(record["body"], str): raise ValueError("Invalid saved body") intent = cls(record["method"], record["path"], record["body"].encode("utf-8") if record["body"] is not None else None, record["idempotency_key"]) _validate_intent(intent) return intent class ApiError(Exception): """HTTP error; public repr omits server messages, fields, and credentials.""" def __init__(self, status: int, code: str, request_id: str | None, retryable: bool, details: dict[str, Any] | None = None, retry_after: int | None = None): super().__init__(f"Partner API returned HTTP {status} ({code})") self.status = status self.code = code self.request_id = request_id self.retryable = retryable self.details = details or {} self.retry_after = retry_after # seconds, from Retry-After on 429/503 class TransportError(Exception): """No usable API answer. A POST/PUT may already have been accepted. Also raised when a write gets a 5xx that is not an API error body (for example a proxy page): the request may have reached the API first. """ def __init__(self, prepared: PreparedRequest): super().__init__("No complete API response; reconcile the saved request before a new operation") self.prepared = prepared self.outcome_unknown = prepared.method != "GET" def _validate_intent(intent: PreparedRequest) -> None: if intent.method not in {"GET", "POST", "PUT"}: raise ValueError("Unsupported method") if (not isinstance(intent.path, str) or not intent.path.startswith("/") or intent.path.startswith("//") or urlsplit(intent.path).netloc or "#" in intent.path or any(ord(c) < 32 for c in intent.path)): raise ValueError("Request path must be relative to the API base") if intent.idempotency_key is not None and ( not isinstance(intent.idempotency_key, str) or not _KEY.fullmatch(intent.idempotency_key) ): raise ValueError("Invalid Idempotency-Key") if intent.body is not None: if not isinstance(intent.body, bytes): raise ValueError("Body must be saved UTF-8 JSON bytes") json.loads(intent.body) class PartnerClient: def __init__(self, base_url: str, api_key: str, *, timeout: float = 15, opener: Callable[..., Any] = _open_once): parsed = urlsplit(base_url) if (parsed.scheme != "https" or not parsed.netloc or parsed.username or parsed.password or parsed.query or parsed.fragment or not parsed.path.rstrip("/").endswith("/b2b/v2")): raise ValueError("Use the approved HTTPS base URL ending in /b2b/v2") if not isinstance(api_key, str) or not api_key or "\r" in api_key or "\n" in api_key: raise ValueError("A server-side v2 API key is required") if timeout <= 0: raise ValueError("Timeout must be positive") self.base_url = base_url.rstrip("/") self._api_key = api_key self.timeout = timeout self._opener = opener # Latest X-RateLimit-Limit/Remaining/Reset seen, as integers. self.rate_limit: dict[str, int] = {} def _remember_rate_limit(self, headers: Any) -> None: if not headers: return for name in ("Limit", "Remaining", "Reset"): value = headers.get(f"X-RateLimit-{name}") if value is not None and str(value).isdigit(): self.rate_limit[name.lower()] = int(value) def __repr__(self) -> str: return "PartnerClient(api_key=)" def execute(self, prepared: PreparedRequest) -> Any: """Send once. No new key, retry, or independent purchase is generated.""" _validate_intent(prepared) headers = {"X-API-Key": self._api_key, "Accept": "application/json"} if prepared.body is not None: headers["Content-Type"] = "application/json" if prepared.idempotency_key is not None: headers["Idempotency-Key"] = prepared.idempotency_key request = Request(self.base_url + prepared.path, data=prepared.body, headers=headers, method=prepared.method) try: with self._opener(request, timeout=self.timeout) as response: self._remember_rate_limit(response.headers) raw = response.read() try: return json.loads(raw) except (ValueError, UnicodeDecodeError): if prepared.method != "GET": # A 2xx we cannot read: the write may have been applied. raise TransportError(prepared) from None raise ApiError(response.status, "INVALID_RESPONSE", response.headers.get("X-Request-ID"), False) from None except HTTPError as exc: self._remember_rate_limit(exc.headers) request_id = exc.headers.get("X-Request-ID") if exc.headers else None api_error = False try: payload = json.loads(exc.read()) error = payload.get("error", {}) if isinstance(payload, dict) else {} if not isinstance(error, dict): error = {} api_error = bool(error.get("code")) if isinstance(payload, dict): request_id = payload.get("request_id") or request_id except (ValueError, UnicodeDecodeError): error = {} if exc.code >= 500 and not api_error and prepared.method != "GET": # Not an answer from the API itself (e.g. a gateway page): the # write may have been accepted. Reconcile before anything new. raise TransportError(prepared) from None retry_after = exc.headers.get("Retry-After") if exc.headers else None raise ApiError(exc.code, str(error.get("code", "HTTP_ERROR")), request_id, error.get("retryable") is True, error, int(retry_after) if retry_after and str(retry_after).isdigit() else None) from None except (URLError, TimeoutError, socket.timeout, ConnectionError, OSError, IncompleteRead): raise TransportError(prepared) from None def _read(self, path: str) -> Any: return self.execute(PreparedRequest("GET", path)) @staticmethod def _prepare(path: str, body: dict[str, Any], key: str) -> PreparedRequest: if not isinstance(key, str) or not _KEY.fullmatch(key): raise ValueError("Supply and save a valid Idempotency-Key for this operation") encoded = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8") return PreparedRequest("POST", path, encoded, key) def me(self) -> Any: return self._read("/me") def balance(self) -> Any: return self._read("/balance") def products(self, **filters: Any) -> Any: allowed = {"search", "category", "region", "platform", "limit", "cursor"} if set(filters) - allowed: raise ValueError("Unknown catalog filter") values = {key: value for key, value in filters.items() if value is not None} return self._read("/catalog/products" + ("?" + urlencode(values) if values else "")) def product(self, product_id: str) -> Any: return self._read("/catalog/products/" + quote(product_id, safe="")) def offers(self, product_id: str, *, cursor: str | None = None, limit: int | None = None, include_retired: bool = False) -> Any: values = {key: value for key, value in (("cursor", cursor), ("limit", limit)) if value is not None} if include_retired: values["include_retired"] = "true" return self._read("/catalog/products/" + quote(product_id, safe="") + "/offers" + ("?" + urlencode(values) if values else "")) def changes(self, *, since: int = 0, cursor: str | None = None, limit: int | None = None) -> Any: """One page of catalog changes. Follow next_cursor; then store next_since.""" values: dict[str, Any] = {"since": since} if cursor is not None: values["cursor"] = cursor if limit is not None: values["limit"] = limit return self._read("/catalog/changes?" + urlencode(values)) def facets(self) -> Any: return self._read("/catalog/facets") def offer(self, offer_id: str) -> Any: return self._read("/catalog/offers/" + quote(offer_id, safe="")) def prepare_order(self, *, offer_id: str, price_version: str, max_total: str, fields: dict[str, Any], idempotency_key: str) -> PreparedRequest: usd(max_total) if not isinstance(fields, dict): raise ValueError("fields must match the chosen offer's input_schema") return self._prepare("/orders", {"offer_id": offer_id, "price_version": price_version, "max_total": max_total, "fields": fields, "quantity": 1}, idempotency_key) def order(self, order_id: str) -> Any: return self._read("/orders/" + quote(order_id, safe="")) def find_order(self, idempotency_key: str) -> Any: return self._read("/orders?" + urlencode({"reference_id": idempotency_key})) def codes(self, order_id: str) -> Any: return self._read("/orders/" + quote(order_id, safe="") + "/codes") def prepare_quote(self, *, offer_id: str, fields: dict[str, Any], idempotency_key: str) -> PreparedRequest: if not isinstance(fields, dict): raise ValueError("fields must match the chosen offer's input_schema") return self._prepare("/quotes", {"offer_id": offer_id, "fields": fields}, idempotency_key) def quote(self, quote_id: str) -> Any: return self._read("/quotes/" + quote(quote_id, safe="")) def prepare_confirmation(self, *, quote_id: str, max_total: str, idempotency_key: str) -> PreparedRequest: usd(max_total) return self._prepare("/quotes/" + quote(quote_id, safe="") + "/confirm", {"max_total": max_total}, idempotency_key) # Steam gifts: catalogue and prices, then a quote and its confirmation. def gift_games(self, *, scope: str = "showcase", search: str | None = None, cursor: int = 0, limit: int = 30) -> Any: """One page of games: the showcase, every game on sale (scope="all") or a name search.""" values: dict[str, Any] = {"scope": scope, "cursor": cursor, "limit": limit} if search: values["search"] = search return self._read("/steam-gifts/games?" + urlencode(values)) def gift_game(self, app_id: int) -> Any: return self._read(f"/steam-gifts/games/{int(app_id)}") def gift_prices(self, app_ids: list[int]) -> Any: """Editions, regions and prices of up to 50 games in one request.""" return self._read("/steam-gifts/prices?" + urlencode({"app_ids": ",".join(str(int(app_id)) for app_id in app_ids)})) def gift_regions(self) -> Any: return self._read("/steam-gifts/regions") def prepare_gift_quote(self, *, app_id: int, edition_id: str, recipient_url: str, idempotency_key: str, region: str | None = None, country: str | None = None) -> PreparedRequest: """Give the Steam price zone (region) or the recipient's ISO country (country).""" if (region is None) == (country is None): raise ValueError("Give region or country") body: dict[str, Any] = {"app_id": int(app_id), "edition_id": edition_id, "recipient_url": recipient_url} body.update({"region": region} if region is not None else {"country": country}) return self._prepare("/steam-gifts/quotes", body, idempotency_key) def gift_quote(self, quote_id: str) -> Any: return self._read("/steam-gifts/quotes/" + quote(quote_id, safe="")) def prepare_gift_confirmation(self, *, quote_id: str, max_total: str, idempotency_key: str) -> PreparedRequest: usd(max_total) return self._prepare("/steam-gifts/quotes/" + quote(quote_id, safe="") + "/confirm", {"max_total": max_total}, idempotency_key) def prepare_gift_order(self, *, app_id: int, edition_id: str, recipient_url: str, max_total: str, idempotency_key: str, region: str | None = None, country: str | None = None) -> PreparedRequest: """Buy one gift in one request (orders:write); the order's steam_gift.delivery tracks it.""" usd(max_total) if (region is None) == (country is None): raise ValueError("Give region or country") body: dict[str, Any] = {"app_id": int(app_id), "edition_id": edition_id, "recipient_url": recipient_url, "max_total": max_total} body.update({"region": region} if region is not None else {"country": country}) return self._prepare("/steam-gifts/orders", body, idempotency_key) # Delivery page for a marketplace order. Idempotent by marketplace and # external_order_id: the same body answers the same session, so a retry # after a lost answer is safe and needs no Idempotency-Key. @staticmethod def _post(path: str, body: dict[str, Any]) -> PreparedRequest: encoded = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8") return PreparedRequest("POST", path, encoded) def check_delivery(self, *, offer_id: str, buyer_fields: dict[str, Any] | None = None) -> Any: return self.execute(self._post("/delivery-sessions/check", { "offer_id": offer_id, "quantity": 1, "buyer_fields": buyer_fields or {}})) def prepare_delivery_session(self, *, marketplace: str, external_order_id: str, offer_id: str, max_unit_price: str, buyer_fields: dict[str, Any] | None = None, support_url: str | None = None) -> PreparedRequest: usd(max_unit_price) body = {"marketplace": marketplace, "external_order_id": external_order_id, "offer_id": offer_id, "quantity": 1, "max_unit_price": max_unit_price, "buyer_fields": buyer_fields or {}} if support_url: body["support_url"] = support_url return self._post("/delivery-sessions", body) def delivery_session(self, session_id: str) -> Any: return self._read("/delivery-sessions/" + quote(session_id, safe="")) def find_delivery_session(self, *, marketplace: str, external_order_id: str) -> Any: return self._read("/delivery-sessions?" + urlencode({"marketplace": marketplace, "external_order_id": external_order_id})) def cancel_delivery_session(self, session_id: str) -> Any: return self.execute(PreparedRequest("POST", "/delivery-sessions/" + quote(session_id, safe="") + "/cancel"))