coinspay 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
coinspay/__init__.py ADDED
@@ -0,0 +1,63 @@
1
+ """Official Python library for the CoinsPay crypto payments API."""
2
+
3
+ from . import models, webhooks
4
+ from ._client import Client
5
+ from ._errors import (
6
+ APIConnectionError,
7
+ APIError,
8
+ APITimeoutError,
9
+ AuthenticationError,
10
+ CoinsPayError,
11
+ ConflictError,
12
+ InvalidRequestError,
13
+ InvalidResponseError,
14
+ NotFoundError,
15
+ PermissionDeniedError,
16
+ RateLimitError,
17
+ ServiceUnavailableError,
18
+ SignatureVerificationError,
19
+ UnprocessableError,
20
+ )
21
+ from ._http import HTTPResponse, ResponseInfo, Transport, TransportError, UrllibTransport, new_idempotency_key
22
+ from ._model import NOT_GIVEN, Model, NotGiven
23
+ from ._operations import ERROR_CODES, ErrorCode
24
+ from ._resource import Page
25
+ from ._version import __version__
26
+ from .webhooks import UnknownEvent, construct_event, signature_header, verify_signature
27
+
28
+ __all__ = [
29
+ "APIConnectionError",
30
+ "APIError",
31
+ "APITimeoutError",
32
+ "AuthenticationError",
33
+ "Client",
34
+ "CoinsPayError",
35
+ "ConflictError",
36
+ "ERROR_CODES",
37
+ "ErrorCode",
38
+ "HTTPResponse",
39
+ "InvalidRequestError",
40
+ "InvalidResponseError",
41
+ "Model",
42
+ "NOT_GIVEN",
43
+ "NotFoundError",
44
+ "NotGiven",
45
+ "Page",
46
+ "PermissionDeniedError",
47
+ "RateLimitError",
48
+ "ResponseInfo",
49
+ "ServiceUnavailableError",
50
+ "SignatureVerificationError",
51
+ "Transport",
52
+ "TransportError",
53
+ "UnknownEvent",
54
+ "UnprocessableError",
55
+ "UrllibTransport",
56
+ "__version__",
57
+ "construct_event",
58
+ "models",
59
+ "new_idempotency_key",
60
+ "signature_header",
61
+ "verify_signature",
62
+ "webhooks",
63
+ ]
coinspay/_client.py ADDED
@@ -0,0 +1,252 @@
1
+ import platform
2
+ import re
3
+ from decimal import Decimal
4
+ from typing import Any, Callable, Dict, List, Mapping, Optional
5
+
6
+ from . import models
7
+ from ._http import (
8
+ Requestor,
9
+ ResponseInfo,
10
+ Transport,
11
+ UrllibTransport,
12
+ check_idempotency_key,
13
+ default_sleep,
14
+ new_idempotency_key,
15
+ normalize_base_url,
16
+ )
17
+ from ._model import NotGiven
18
+ from ._operations import OPERATIONS
19
+ from ._resource import Page
20
+ from ._resources import Addresses, Balances, Chains, Currencies, Deposits, Invoices, Payouts, ShopResource
21
+ from ._version import __version__
22
+
23
+ UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", re.IGNORECASE)
24
+ PATH = re.compile(r"/[\w\-./]*")
25
+
26
+
27
+ class Client:
28
+ """
29
+ Client of the CoinsPay API::
30
+
31
+ coinspay = coinspay.Client(os.environ["COINSPAY_KEY"], "https://pay.example.com")
32
+ invoice = coinspay.invoices.create(currency="USD", amount="49.90", reference="order-1042")
33
+ redirect(invoice.pay_url)
34
+
35
+ :param api_key: API key of the shop: ``cpk_…``, or ``cpk_test_…`` for test mode. Keep it on your server.
36
+ :param base_url: The dashboard origin (``https://pay.example.com``) or the API address ending in ``/api/v1``.
37
+ :param timeout: Seconds for each socket operation of an attempt; 30 by default.
38
+ :param max_retries: Retries after failures that are safe to retry; 2 by default, 0 turns them off.
39
+ :param max_retry_delay: The longest pause before a retry in seconds; a longer ``Retry-After`` fails at once.
40
+ :param allow_insecure_http: Allows plain http to hosts other than localhost, for a test stand.
41
+ :param transport: Your own HTTP transport; ``UrllibTransport`` by default.
42
+ :param headers: Headers sent with every request.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ api_key: str,
48
+ base_url: str,
49
+ *,
50
+ timeout: float = 30.0,
51
+ max_retries: int = 2,
52
+ max_retry_delay: float = 5.0,
53
+ allow_insecure_http: bool = False,
54
+ transport: Optional[Transport] = None,
55
+ headers: Optional[Mapping[str, str]] = None,
56
+ _sleep: Optional[Callable[[float], None]] = None,
57
+ ) -> None:
58
+ if not isinstance(api_key, str) or api_key.strip() == "":
59
+ raise ValueError("api_key is required")
60
+ api_key = api_key.strip()
61
+ if re.search(r"[\s\x00-\x1f\x7f]", api_key):
62
+ raise ValueError("api_key contains spaces or control characters")
63
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or timeout <= 0:
64
+ raise ValueError("timeout must be a positive number")
65
+ if isinstance(max_retries, bool) or not isinstance(max_retries, int) or max_retries < 0:
66
+ raise ValueError("max_retries must be a non-negative integer")
67
+ if isinstance(max_retry_delay, bool) or not isinstance(max_retry_delay, (int, float)) or max_retry_delay < 0:
68
+ raise ValueError("max_retry_delay must not be negative")
69
+
70
+ self._base_url = normalize_base_url(base_url, allow_insecure_http)
71
+ self._test_mode = api_key.startswith("cpk_test_")
72
+ self._requestor = Requestor(
73
+ api_key,
74
+ self._base_url,
75
+ transport or UrllibTransport(),
76
+ timeout=float(timeout),
77
+ max_retries=max_retries,
78
+ max_retry_delay=float(max_retry_delay),
79
+ headers=headers or {},
80
+ sleep=_sleep or default_sleep,
81
+ user_agent=f"coinspay-python/{__version__} python/{platform.python_version()}",
82
+ )
83
+
84
+ self.invoices = Invoices(self)
85
+ self.addresses = Addresses(self)
86
+ self.deposits = Deposits(self)
87
+ self.balances = Balances(self)
88
+ self.payouts = Payouts(self)
89
+ self.shop = ShopResource(self)
90
+ self.chains = Chains(self)
91
+ self.currencies = Currencies(self)
92
+
93
+ @property
94
+ def base_url(self) -> str:
95
+ """The API address requests go to, ending in ``/api/v1``."""
96
+ return self._base_url
97
+
98
+ @property
99
+ def test_mode(self) -> bool:
100
+ """True for a test key (``cpk_test_…``): invoices only, paid without money."""
101
+ return self._test_mode
102
+
103
+ @property
104
+ def last_response(self) -> Optional[ResponseInfo]:
105
+ """Status, headers and ``replayed`` of the last answer."""
106
+ return self._requestor.last_response
107
+
108
+ def __repr__(self) -> str:
109
+ return f"coinspay.Client(base_url={self._base_url!r}, test_mode={self._test_mode})"
110
+
111
+ @staticmethod
112
+ def new_idempotency_key() -> str:
113
+ """A random idempotency key, for when there is no natural one such as an order or payout number."""
114
+ return new_idempotency_key()
115
+
116
+ def request(
117
+ self,
118
+ method: str,
119
+ path: str,
120
+ *,
121
+ query: Optional[Dict[str, Any]] = None,
122
+ body: Any = None,
123
+ idempotency_key: Optional[str] = None,
124
+ timeout: Optional[float] = None,
125
+ max_retries: Optional[int] = None,
126
+ headers: Optional[Dict[str, str]] = None,
127
+ ) -> Any:
128
+ """
129
+ Any API request, for methods this version of the library does not know yet.
130
+ ``path`` is relative to ``/api/v1``, for example ``/invoices``. Returns the parsed JSON.
131
+ """
132
+ if method not in ("GET", "POST"):
133
+ raise ValueError("method must be GET or POST")
134
+ if not isinstance(path, str) or not PATH.fullmatch(path) or any(part in (".", "..") for part in path.split("/")):
135
+ raise ValueError(f"Bad API path: {path!r}")
136
+ key = check_idempotency_key(idempotency_key) if idempotency_key is not None else None
137
+ return self._requestor.send(
138
+ method,
139
+ path,
140
+ query=query,
141
+ body=body,
142
+ retry="safe" if method == "GET" else ("idempotent" if key else "unsafe"),
143
+ idempotency_key=key,
144
+ timeout=timeout,
145
+ max_retries=max_retries,
146
+ headers=headers,
147
+ )
148
+
149
+ def _call(
150
+ self,
151
+ operation: str,
152
+ id: Optional[str],
153
+ params: Dict[str, Any],
154
+ extra: Optional[Dict[str, Any]],
155
+ idempotency_key: Optional[str],
156
+ *,
157
+ timeout: Optional[float],
158
+ max_retries: Optional[int],
159
+ headers: Optional[Dict[str, str]],
160
+ ) -> Any:
161
+ spec = OPERATIONS[operation]
162
+ path = spec["path"]
163
+ if "{id}" in path:
164
+ if not isinstance(id, str) or not UUID.fullmatch(id):
165
+ raise ValueError(f"id must be a UUID, got {id!r}")
166
+ path = path.replace("{id}", id.lower())
167
+
168
+ values = {key: value for key, value in params.items() if not isinstance(value, NotGiven)}
169
+ if spec["params"] is not None:
170
+ _check_keys(values, spec["params"], "")
171
+ for decimal_path in spec["decimals"]:
172
+ values = _decimals(values, decimal_path.split("."), "")
173
+ if extra:
174
+ # Fields this version of the library does not know yet: sent as given.
175
+ values.update(extra)
176
+
177
+ if spec["retry"] == "idempotent":
178
+ if idempotency_key is not None:
179
+ idempotency_key = check_idempotency_key(idempotency_key)
180
+ elif spec["idempotency"] == "required":
181
+ # A random key here would let a repeated call send the money twice.
182
+ raise ValueError(f"{operation} needs idempotency_key: take it from your own record, so that a repeat never sends twice")
183
+ else:
184
+ idempotency_key = new_idempotency_key()
185
+
186
+ data = self._requestor.send(
187
+ spec["method"],
188
+ path,
189
+ query=values if spec["method"] == "GET" else None,
190
+ body=values if spec["method"] == "POST" else None,
191
+ retry=spec["retry"],
192
+ idempotency_key=idempotency_key,
193
+ timeout=timeout,
194
+ max_retries=max_retries,
195
+ headers=headers,
196
+ )
197
+
198
+ cls = getattr(models, spec["returns"])
199
+ if spec["page"]:
200
+ items = data.get(spec["page"]) if isinstance(data, dict) else None
201
+ return Page([cls.from_dict(item) for item in items or [] if isinstance(item, dict)], data.get("next_cursor"))
202
+ if spec["unwrap"]:
203
+ data = data.get(spec["unwrap"]) if isinstance(data, dict) else None
204
+ if spec["many"]:
205
+ return [cls.from_dict(item) for item in data or [] if isinstance(item, dict)]
206
+ if not isinstance(data, dict):
207
+ raise TypeError(f"Unexpected answer of {operation}")
208
+ return cls.from_dict(data)
209
+
210
+
211
+ def _check_keys(values: Any, allowed: Dict[str, Any], where: str) -> None:
212
+ """Unknown keys are typos: the API would silently ignore them."""
213
+ if not isinstance(values, dict):
214
+ raise TypeError(f"{where.rstrip('.') or 'parameters'} must be a dict")
215
+ for key, value in values.items():
216
+ if key not in allowed:
217
+ raise TypeError(f"Unknown parameter {where}{key}; pass new API fields in extra_body or extra_query")
218
+ nested = allowed[key]
219
+ if isinstance(nested, dict) and value is not None:
220
+ if isinstance(value, list):
221
+ for index, item in enumerate(value):
222
+ _check_keys(item, nested, f"{where}{key}[{index}].")
223
+ else:
224
+ _check_keys(value, nested, f"{where}{key}.")
225
+
226
+
227
+ def _decimals(value: Any, segments: List[str], where: str) -> Any:
228
+ """Decimal → plain string; floats are refused: 0.1 + 0.2 is not what you meant."""
229
+ if value is None:
230
+ return None
231
+ if not segments:
232
+ if isinstance(value, Decimal):
233
+ if not value.is_finite():
234
+ raise ValueError(f"{where} must be a finite number")
235
+ return format(value, "f")
236
+ if isinstance(value, str):
237
+ return value
238
+ raise TypeError(f'{where} must be a decimal string such as "49.90" or a Decimal, not {type(value).__name__}')
239
+ if not isinstance(value, dict):
240
+ return value
241
+ segment, rest = segments[0], segments[1:]
242
+ many = segment.endswith("[]")
243
+ name = segment[:-2] if many else segment
244
+ if name not in value:
245
+ return value
246
+ prefix = f"{where}.{name}" if where else name
247
+ copy = dict(value)
248
+ if not many:
249
+ copy[name] = _decimals(value[name], rest, prefix)
250
+ elif isinstance(value[name], list):
251
+ copy[name] = [_decimals(item, rest, f"{prefix}[{index}]") for index, item in enumerate(value[name])]
252
+ return copy
coinspay/_errors.py ADDED
@@ -0,0 +1,146 @@
1
+ import re
2
+ from typing import Any, Dict, Mapping, Optional
3
+
4
+
5
+ class CoinsPayError(Exception):
6
+ """Base class of every error raised by this library."""
7
+
8
+
9
+ class APIError(CoinsPayError):
10
+ """
11
+ The API answered with an error: HTTP status 4xx or 5xx and a body
12
+ ``{"error": {"code", "message", "details"}}``. Branch on ``code``: ``message`` is an
13
+ English explanation and may change.
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ status: int,
19
+ code: str,
20
+ message: str,
21
+ details: Optional[Dict[str, Any]] = None,
22
+ headers: Optional[Mapping[str, str]] = None,
23
+ ) -> None:
24
+ super().__init__(message)
25
+ self.status = status
26
+ self.code = code
27
+ self.message = message
28
+ self.details = details
29
+ self.headers: Dict[str, str] = dict(headers or {})
30
+
31
+ def __repr__(self) -> str:
32
+ return f"{type(self).__name__}(status={self.status}, code={self.code!r}, message={self.message!r})"
33
+
34
+ @staticmethod
35
+ def create(
36
+ status: int,
37
+ code: str,
38
+ message: str,
39
+ details: Optional[Dict[str, Any]] = None,
40
+ headers: Optional[Mapping[str, str]] = None,
41
+ ) -> "APIError":
42
+ """The subclass that matches the HTTP status."""
43
+ cls = _BY_STATUS.get(status, APIError)
44
+ return cls(status, code, message, details, headers)
45
+
46
+
47
+ class InvalidRequestError(APIError):
48
+ """400: the request is invalid; for ``VALIDATION_ERROR`` ``details`` maps field paths to reasons."""
49
+
50
+
51
+ class AuthenticationError(APIError):
52
+ """401: the API key is missing, wrong or revoked."""
53
+
54
+
55
+ class PermissionDeniedError(APIError):
56
+ """
57
+ 403: the key may not do this: ``KEY_ACCESS_DENIED`` (an invoices-only key),
58
+ ``TEST_MODE_UNSUPPORTED`` (a test key), ``IP_NOT_ALLOWED`` (see ``details["ip"]``),
59
+ ``SHOP_DISABLED``.
60
+ """
61
+
62
+
63
+ class NotFoundError(APIError):
64
+ """404: no such object in this shop."""
65
+
66
+
67
+ class ConflictError(APIError):
68
+ """409: ``IDEMPOTENCY_CONFLICT``, or ``INVOICE_NOT_OPEN`` (see ``details["status"]``)."""
69
+
70
+
71
+ class UnprocessableError(APIError):
72
+ """422: the payout cannot be made: ``INSUFFICIENT_BALANCE``, ``FUNDS_NOT_MATURE``, ``BELOW_MINIMUM`` and others."""
73
+
74
+
75
+ class RateLimitError(APIError):
76
+ """429: too many requests."""
77
+
78
+ @property
79
+ def retry_after(self) -> Optional[int]:
80
+ """Seconds to wait before retrying, if the API said so."""
81
+ header = self.headers.get("retry-after", "")
82
+ if re.fullmatch(r"\s*\d+\s*", header):
83
+ return int(header)
84
+ value = (self.details or {}).get("retry_after")
85
+ if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
86
+ return value
87
+ return None
88
+
89
+
90
+ class ServiceUnavailableError(APIError):
91
+ """503: the service is temporarily unavailable; retry later."""
92
+
93
+
94
+ _BY_STATUS = {
95
+ 400: InvalidRequestError,
96
+ 401: AuthenticationError,
97
+ 403: PermissionDeniedError,
98
+ 404: NotFoundError,
99
+ 409: ConflictError,
100
+ 422: UnprocessableError,
101
+ 429: RateLimitError,
102
+ 503: ServiceUnavailableError,
103
+ }
104
+
105
+
106
+ class APIConnectionError(CoinsPayError):
107
+ """
108
+ The request did not get an answer. With ``sent`` false it never reached the API
109
+ (connection refused, DNS failure), so any request is safe to retry. With ``sent`` true it
110
+ may have been processed.
111
+ """
112
+
113
+ def __init__(self, message: str, sent: bool) -> None:
114
+ super().__init__(message)
115
+ self.sent = sent
116
+
117
+
118
+ class APITimeoutError(APIConnectionError):
119
+ """No answer within the timeout; the request may have been processed."""
120
+
121
+ def __init__(self, message: str) -> None:
122
+ super().__init__(message, sent=True)
123
+
124
+
125
+ class InvalidResponseError(CoinsPayError):
126
+ """The answer was not the JSON the API sends, for example an HTML error page of a proxy or a redirect."""
127
+
128
+ def __init__(self, message: str, status: int) -> None:
129
+ super().__init__(message)
130
+ self.status = status
131
+
132
+
133
+ class SignatureVerificationError(CoinsPayError):
134
+ """The webhook signature is missing, malformed, too old or does not match."""
135
+
136
+ MESSAGES = {
137
+ "missing": "No x-cpay-signature header",
138
+ "malformed": "The x-cpay-signature header is malformed",
139
+ "stale": "The webhook signature is too old or from the future",
140
+ "mismatch": "The webhook signature does not match the body and secret",
141
+ }
142
+
143
+ def __init__(self, reason: str) -> None:
144
+ super().__init__(self.MESSAGES[reason])
145
+ self.reason = reason
146
+ """``missing``, ``malformed``, ``stale`` or ``mismatch``."""