sendclap 0.2.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.
sendclap/__init__.py ADDED
@@ -0,0 +1,419 @@
1
+ """Official Sendclap client: license checks for shipped apps and the creator REST API."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import socket
6
+ import urllib.error
7
+ import urllib.parse
8
+ import urllib.request
9
+ from dataclasses import dataclass
10
+ from typing import Any, Callable, Dict, Generic, Iterator, List, Optional, TypedDict, TypeVar
11
+
12
+ __version__ = "0.2.0"
13
+ DEFAULT_BASE_URL = "https://sendclap.com"
14
+ USER_AGENT = f"sendclap-python/{__version__}"
15
+
16
+ __all__ = [
17
+ "LicenseClient", "ApiClient", "instance_name",
18
+ "SendclapError", "InvalidLicenseError", "DisabledLicenseError", "InstanceNotFoundError",
19
+ "ActivationLimitError", "NetworkError",
20
+ "ActivateResult", "ValidateResult", "DeactivateResult", "LicenseInfo", "ProductRef",
21
+ "Page", "Checkout", "Totals", "Stats", "Payment", "PaymentDetail", "Member", "IssuedLicense",
22
+ "Dispute", "Product", "Membership", "Creator",
23
+ ]
24
+
25
+
26
+ # ---- errors ----
27
+
28
+ class SendclapError(Exception):
29
+ """Any failed request.
30
+
31
+ `status` is the HTTP status (0 when no response arrived) and `code` the server's machine-readable
32
+ code, such as "invalid_api_key" or "not_found" ("" when the reply wasn't a Sendclap error,
33
+ "network_error" with no reply).
34
+ """
35
+
36
+ def __init__(self, status: int, message: str, code: str = "") -> None:
37
+ super().__init__(message)
38
+ self.status = status
39
+ self.message = message
40
+ self.code = code
41
+
42
+
43
+ class InvalidLicenseError(SendclapError):
44
+ """The license key does not exist (license_not_found)."""
45
+
46
+
47
+ class DisabledLicenseError(SendclapError):
48
+ """The key exists but was disabled after a refund or dispute (license_disabled)."""
49
+
50
+
51
+ class InstanceNotFoundError(SendclapError):
52
+ """Deactivate was called for an instance that isn't activated (instance_not_found)."""
53
+
54
+
55
+ class ActivationLimitError(SendclapError):
56
+ """The key is already activated on its maximum number of instances (activation_limit)."""
57
+
58
+ def __init__(self, status: int, message: str, license: LicenseInfo, product: ProductRef) -> None:
59
+ super().__init__(status, message, "activation_limit")
60
+ self.license = license
61
+ self.product = product
62
+
63
+
64
+ class NetworkError(SendclapError):
65
+ """No HTTP response: DNS, refused connection, TLS or timeout."""
66
+
67
+ def __init__(self, message: str) -> None:
68
+ super().__init__(0, message, "network_error")
69
+
70
+
71
+ # ---- license results ----
72
+
73
+ @dataclass(frozen=True)
74
+ class LicenseInfo:
75
+ key: str
76
+ activations: int
77
+ max_activations: int
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class ProductRef:
82
+ id: Optional[int] = None
83
+ name: Optional[str] = None
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class ActivateResult:
88
+ instance_id: str
89
+ license: LicenseInfo
90
+ product: ProductRef
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class ValidateResult:
95
+ valid: bool
96
+ status: str # "active", "not_activated", "invalid" (unknown key) or "disabled" (refunded or disputed)
97
+ license: Optional[LicenseInfo] = None
98
+ product: Optional[ProductRef] = None
99
+
100
+
101
+ @dataclass(frozen=True)
102
+ class DeactivateResult:
103
+ license: LicenseInfo
104
+ product: ProductRef
105
+
106
+
107
+ # ---- API response shapes (plain dicts at runtime) ----
108
+
109
+ class Checkout(TypedDict):
110
+ id: str
111
+ status: str
112
+ type: str
113
+ amount: float
114
+ currency: str
115
+ method: str
116
+ email: Optional[str]
117
+ url: str # where to send the customer to pay
118
+
119
+
120
+ T = TypeVar("T")
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class Page(Generic[T]):
125
+ data: List[T]
126
+ has_more: bool
127
+ next: Optional[int] # pass as `after` to get the following page
128
+
129
+
130
+ class Totals(TypedDict):
131
+ payments: int
132
+ gross: float
133
+ fees: float
134
+ net: float
135
+
136
+
137
+ class Stats(TypedDict):
138
+ handle: str
139
+ name: str
140
+ url: str
141
+ currency: str
142
+ last_30_days: Totals
143
+ all_time: Totals
144
+ members: Dict[str, float] # {"active": int, "monthly_recurring": float}
145
+ open_disputes: int
146
+
147
+
148
+ class Payment(TypedDict):
149
+ id: int
150
+ type: str
151
+ method: str
152
+ status: str
153
+ amount: float
154
+ fee: float
155
+ currency: str
156
+ email: Optional[str]
157
+ message: Optional[str]
158
+ reference: Optional[str]
159
+ test: bool
160
+ created_at: str
161
+
162
+
163
+ class PaymentDetail(Payment):
164
+ item: str
165
+ purchase_ip: Optional[str]
166
+ purchase_device: Optional[str]
167
+ dispute: Optional[Dict[str, Any]] # {id, status, reason, respond_by}
168
+ activity: List[Dict[str, Any]] # [{at, event, detail, ip}]
169
+ evidence_pdf: str
170
+
171
+
172
+ class Member(TypedDict):
173
+ email: str
174
+ tier: str
175
+ method: str
176
+ status: str
177
+ price: float
178
+ interval: str
179
+ current_period_ends: str
180
+ joined_at: str
181
+
182
+
183
+ class IssuedLicense(TypedDict):
184
+ key: str
185
+ product: str
186
+ email: str
187
+ activations: int
188
+ max_activations: int
189
+ disabled: bool
190
+ issued_at: str
191
+
192
+
193
+ class Dispute(TypedDict):
194
+ id: str
195
+ payment_id: int
196
+ email: Optional[str]
197
+ amount: float
198
+ reason: Optional[str]
199
+ status: str
200
+ respond_by: Optional[str]
201
+ opened_at: str
202
+
203
+
204
+ class Product(TypedDict):
205
+ id: int
206
+ name: str
207
+ description: str
208
+ price: float
209
+ currency: str
210
+ delivers_file: bool
211
+ issues_license_key: bool
212
+ page: str
213
+ x402: Optional[str]
214
+
215
+
216
+ class Membership(TypedDict):
217
+ id: int
218
+ name: str
219
+ description: str
220
+ price: float
221
+ currency: str
222
+ interval: str
223
+ x402: Optional[str]
224
+
225
+
226
+ class Creator(TypedDict):
227
+ handle: str
228
+ name: str
229
+ bio: str
230
+ url: str
231
+ avatar: Optional[str]
232
+ links: List[Dict[str, str]]
233
+ payment_methods: Dict[str, bool]
234
+ tip: Dict[str, Any]
235
+ memberships: List[Membership]
236
+ products: List[Product]
237
+
238
+
239
+ # ---- transport ----
240
+
241
+ class _Http:
242
+ def __init__(self, base_url: str, timeout: float, api_key: Optional[str] = None) -> None:
243
+ self.base = base_url.rstrip("/") + "/api/v1"
244
+ self.timeout = timeout
245
+ self.api_key = api_key
246
+
247
+ def request(self, method: str, path: str, body: Optional[Dict[str, Any]] = None,
248
+ query: Optional[Dict[str, Any]] = None) -> Any:
249
+ url = self.base + path
250
+ q = {k: v for k, v in (query or {}).items() if v is not None}
251
+ if q:
252
+ url += "?" + urllib.parse.urlencode(q)
253
+ headers = {"Accept": "application/json", "User-Agent": USER_AGENT}
254
+ data = None
255
+ if body is not None:
256
+ data = json.dumps({k: v for k, v in body.items() if v is not None}).encode()
257
+ headers["Content-Type"] = "application/json"
258
+ if self.api_key:
259
+ headers["Authorization"] = f"Bearer {self.api_key}"
260
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
261
+ try:
262
+ with urllib.request.urlopen(req, timeout=self.timeout) as res:
263
+ status, text = res.status, res.read().decode("utf-8", "replace")
264
+ except urllib.error.HTTPError as e:
265
+ with e:
266
+ status, text = e.code, e.read().decode("utf-8", "replace")
267
+ except (urllib.error.URLError, OSError) as e: # covers socket.timeout and ConnectionError
268
+ raise NetworkError(str(getattr(e, "reason", e))) from e
269
+ try:
270
+ parsed = json.loads(text)
271
+ except ValueError:
272
+ if 200 <= status < 300:
273
+ raise SendclapError(status, "invalid JSON response") from None
274
+ parsed = None
275
+ if 200 <= status < 300:
276
+ return parsed
277
+ d = parsed if isinstance(parsed, dict) else {}
278
+ msg = d["error"] if isinstance(d.get("error"), str) else f"HTTP {status}"
279
+ code = d["code"] if isinstance(d.get("code"), str) else ""
280
+ if code == "license_not_found":
281
+ raise InvalidLicenseError(status, msg, code)
282
+ if code == "license_disabled":
283
+ raise DisabledLicenseError(status, msg, code)
284
+ if code == "instance_not_found":
285
+ raise InstanceNotFoundError(status, msg, code)
286
+ if code == "activation_limit":
287
+ raise ActivationLimitError(status, msg, _license(d), _product(d))
288
+ raise SendclapError(status, msg, code)
289
+
290
+
291
+ def _license(d: Dict[str, Any]) -> LicenseInfo:
292
+ lic = d.get("license") or {}
293
+ return LicenseInfo(key=lic.get("key", ""), activations=lic.get("activations", 0),
294
+ max_activations=lic.get("max_activations", 0))
295
+
296
+
297
+ def _product(d: Dict[str, Any]) -> ProductRef:
298
+ p = d.get("product") or {}
299
+ return ProductRef(id=p.get("id"), name=p.get("name"))
300
+
301
+
302
+ # ---- clients ----
303
+
304
+ def instance_name() -> str:
305
+ """This machine's hostname, a stable default instance name.
306
+
307
+ It is sent to Sendclap and shown to the creator, and two machines with the same
308
+ hostname share one activation. Pass your own id (a UUID saved on first run) if that matters.
309
+ """
310
+ return socket.gethostname()
311
+
312
+
313
+ class LicenseClient:
314
+ """Keyless license checks, safe to call from the app you ship."""
315
+
316
+ def __init__(self, base_url: str = DEFAULT_BASE_URL, timeout: float = 15.0) -> None:
317
+ self._http = _Http(base_url, timeout)
318
+
319
+ def _post(self, action: str, license_key: str, instance_id: Optional[str]) -> Dict[str, Any]:
320
+ return self._http.request("POST", f"/licenses/{action}",
321
+ {"license_key": license_key, "instance_id": instance_id})
322
+
323
+ def activate(self, license_key: str, instance_name: str) -> ActivateResult:
324
+ d = self._post("activate", license_key, instance_name)
325
+ return ActivateResult(instance_id=d["instance_id"], license=_license(d), product=_product(d))
326
+
327
+ def validate(self, license_key: str, instance_id: Optional[str] = None) -> ValidateResult:
328
+ """Never raises for a bad key: returns status "invalid" or "disabled". Raises NetworkError when offline."""
329
+ try:
330
+ d = self._post("validate", license_key, instance_id)
331
+ except InvalidLicenseError:
332
+ return ValidateResult(valid=False, status="invalid")
333
+ except DisabledLicenseError:
334
+ return ValidateResult(valid=False, status="disabled")
335
+ valid = d.get("valid") is True
336
+ return ValidateResult(valid=valid, status="active" if valid else "not_activated",
337
+ license=_license(d), product=_product(d))
338
+
339
+ def deactivate(self, license_key: str, instance_id: str) -> DeactivateResult:
340
+ d = self._post("deactivate", license_key, instance_id)
341
+ return DeactivateResult(license=_license(d), product=_product(d))
342
+
343
+
344
+ def _paginate(fetch: Callable[..., Page[T]], filters: Dict[str, Any]) -> Iterator[T]:
345
+ after = None
346
+ while True:
347
+ page = fetch(**filters, after=after)
348
+ yield from page.data
349
+ if not page.has_more or page.next is None:
350
+ return
351
+ after = page.next
352
+
353
+
354
+ def _seg(s: Any) -> str:
355
+ return urllib.parse.quote(str(s), safe="")
356
+
357
+
358
+ class ApiClient:
359
+ """Creator REST API. Server side only: never ship the sc_ key inside an app."""
360
+
361
+ def __init__(self, api_key: Optional[str] = None, base_url: str = DEFAULT_BASE_URL, timeout: float = 15.0) -> None:
362
+ self._http = _Http(base_url, timeout, api_key)
363
+
364
+ def create_checkout(self, type: str, amount: Optional[float] = None, product_id: Optional[int] = None,
365
+ tier_id: Optional[int] = None, email: Optional[str] = None,
366
+ method: Optional[str] = None, message: Optional[str] = None) -> Checkout:
367
+ return self._http.request("POST", "/checkouts", {
368
+ "type": type, "amount": amount, "product_id": product_id, "tier_id": tier_id,
369
+ "email": email, "method": method, "message": message})
370
+
371
+ def get_checkout(self, id: str) -> Checkout:
372
+ return self._http.request("GET", f"/checkouts/{_seg(id)}")
373
+
374
+ def me(self) -> Stats:
375
+ return self._http.request("GET", "/me")
376
+
377
+ def _page(self, path: str, query: Dict[str, Any]) -> Page:
378
+ d = self._http.request("GET", path, query=query)
379
+ return Page(data=d["data"], has_more=d["has_more"], next=d["next"])
380
+
381
+ # Lists are pages: `limit` is at most 500, `after` is the previous page's `next`. The all_* generators follow `next`.
382
+ def list_payments(self, status: Optional[str] = None, type: Optional[str] = None, email: Optional[str] = None,
383
+ limit: Optional[int] = None, after: Optional[int] = None) -> Page[Payment]:
384
+ return self._page("/payments", {"status": status, "type": type, "email": email, "limit": limit, "after": after})
385
+
386
+ def get_payment(self, id: int) -> PaymentDetail:
387
+ return self._http.request("GET", f"/payments/{_seg(id)}")
388
+
389
+ def list_members(self, limit: Optional[int] = None, after: Optional[int] = None) -> Page[Member]:
390
+ return self._page("/members", {"limit": limit, "after": after})
391
+
392
+ def list_licenses(self, email: Optional[str] = None, limit: Optional[int] = None,
393
+ after: Optional[int] = None) -> Page[IssuedLicense]:
394
+ return self._page("/licenses", {"email": email, "limit": limit, "after": after})
395
+
396
+ def list_disputes(self, limit: Optional[int] = None, after: Optional[int] = None) -> Page[Dispute]:
397
+ return self._page("/disputes", {"limit": limit, "after": after})
398
+
399
+ def all_payments(self, **filters: Any) -> Iterator[Payment]:
400
+ return _paginate(self.list_payments, filters)
401
+
402
+ def all_members(self, **filters: Any) -> Iterator[Member]:
403
+ return _paginate(self.list_members, filters)
404
+
405
+ def all_licenses(self, **filters: Any) -> Iterator[IssuedLicense]:
406
+ return _paginate(self.list_licenses, filters)
407
+
408
+ def all_disputes(self, **filters: Any) -> Iterator[Dispute]:
409
+ return _paginate(self.list_disputes, filters)
410
+
411
+ def list_products(self) -> List[Product]:
412
+ return self._http.request("GET", "/products")
413
+
414
+ def list_memberships(self) -> List[Membership]:
415
+ return self._http.request("GET", "/memberships")
416
+
417
+ def get_creator(self, handle: str) -> Creator:
418
+ """Public: works without an API key."""
419
+ return self._http.request("GET", f"/creators/{_seg(handle)}")
sendclap/py.typed ADDED
File without changes
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.5
2
+ Name: sendclap
3
+ Version: 0.2.0
4
+ Summary: Official Sendclap client: license key checks for your app and the creator REST API
5
+ Project-URL: Homepage, https://sendclap.com
6
+ Project-URL: Documentation, https://sendclap.com/docs
7
+ License-Expression: MIT
8
+ Keywords: license,license-key,payments,sendclap
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+
14
+ # sendclap (Python)
15
+
16
+ Official Python client for [Sendclap](https://sendclap.com): check license keys from the app you ship, and call the creator REST API from your server. Standard library only, Python 3.9+, fully typed. API reference: https://sendclap.com/docs
17
+
18
+ ```sh
19
+ pip install sendclap
20
+ ```
21
+
22
+ ## License check (in your app, no API key)
23
+
24
+ ```python
25
+ import time
26
+ from sendclap import LicenseClient, NetworkError, instance_name
27
+
28
+ def licensed(key: str, cache: dict) -> bool:
29
+ try:
30
+ r = LicenseClient().validate(key, cache.get("instance") or instance_name())
31
+ except NetworkError: # offline: allow a 7-day grace period since the last good check
32
+ return time.time() - cache.get("validated_at", 0) < 7 * 86400
33
+ if r.valid:
34
+ cache["validated_at"] = time.time() # persist cache to disk yourself
35
+ return r.valid # status "invalid", "disabled" or "not_activated": lock the app
36
+ ```
37
+
38
+ On first run, activate the device and remember the instance id:
39
+
40
+ ```python
41
+ from sendclap import ActivationLimitError, DisabledLicenseError, InvalidLicenseError
42
+ try:
43
+ cache["instance"] = LicenseClient().activate(key, instance_name()).instance_id
44
+ except InvalidLicenseError: ... # unknown key
45
+ except DisabledLicenseError: ... # the payment was refunded or disputed
46
+ except ActivationLimitError as e: print(f"Used on {e.license.activations}/{e.license.max_activations} devices")
47
+ ```
48
+
49
+ `deactivate(key, instance_id)` frees the device again, and raises `InstanceNotFoundError` if it wasn't activated. `validate` never raises for a bad key; it returns `status` `"active"`, `"not_activated"`, `"invalid"` (unknown key) or `"disabled"` (refunded or disputed), and raises `NetworkError` only when it could not reach Sendclap, so you can tell "offline" from "invalid" and show "this license was refunded" for `"disabled"`.
50
+
51
+ **Instance name:** `instance_name()` is the machine's hostname. It is sent to Sendclap and shown to the creator, and two machines with the same hostname share one activation. If that matters, pass your own stable id instead (for example a `uuid4()` saved on first run). The instance id Sendclap returns is the name you send.
52
+
53
+ ## Creator API (server side only)
54
+
55
+ > **Never ship your `sc_` API key inside an app, website or anything a customer can download.** Anyone holding it can read your payments and customers. Use it only on your own server.
56
+
57
+ ```python
58
+ from sendclap import ApiClient
59
+
60
+ api = ApiClient("sc_your_key") # base_url="https://sendclap.com", timeout=15.0
61
+ checkout = api.create_checkout("product", product_id=1, email="buyer@example.com")
62
+ print(checkout["url"]) # send the buyer here
63
+ api.get_checkout(checkout["id"]) # poll until status == "paid"
64
+ page = api.list_payments(status="paid", limit=10) # page.data, page.has_more, page.next
65
+ if page.has_more:
66
+ page = api.list_payments(status="paid", limit=10, after=page.next)
67
+ for p in api.all_payments(status="paid"): # a generator that follows `next` across pages
68
+ print(p["amount"], p["email"])
69
+ ```
70
+
71
+ Lists (`list_payments`, `list_members`, `list_licenses`, `list_disputes`) return a `Page` with `data`, `has_more` and `next`, newest first; `limit` is at most 500 and `after` is the previous page's `next`. `all_payments`, `all_members`, `all_licenses` and `all_disputes` take the same filters and yield every item.
72
+
73
+ Methods: `create_checkout` and `get_checkout` (both return the checkout `url`), `me`, `get_payment`, `list_products`, `list_memberships`, the list and `all_*` methods above, and `get_creator` (public, works with `ApiClient()` and no key). Items are plain dicts with the API's JSON fields, typed with `TypedDict`.
74
+
75
+ The client is synchronous. In async code, wrap calls with `await asyncio.to_thread(api.me)`.
76
+
77
+ ## Errors
78
+
79
+ Every exception is a `SendclapError` with `.status`, `.code` (the server's machine-readable code) and `.message`. The typed ones are chosen by `code`:
80
+
81
+ | Exception | `code` | When |
82
+ |---|---|---|
83
+ | `InvalidLicenseError` | `license_not_found` | 404: the key doesn't exist |
84
+ | `DisabledLicenseError` | `license_disabled` | 403: disabled after a refund or dispute |
85
+ | `InstanceNotFoundError` | `instance_not_found` | 404: `deactivate` for an instance that isn't activated |
86
+ | `ActivationLimitError` | `activation_limit` | 409: every activation is used; `.license` and `.product` say how many |
87
+ | `NetworkError` | `network_error` | No response: offline, DNS, TLS, timeout (`.status == 0`) |
88
+ | `SendclapError` | anything else | e.g. `bad_request`, `invalid_api_key`, `not_found` |
89
+
90
+ ## Tests
91
+
92
+ ```sh
93
+ python3 -m unittest discover -s tests # or: python3 -m pytest
94
+ ```
@@ -0,0 +1,5 @@
1
+ sendclap/__init__.py,sha256=9YZaIYAtPxjt0kBBY37lVonXoENzw7oBmYg1ESWxrgA,13865
2
+ sendclap/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ sendclap-0.2.0.dist-info/METADATA,sha256=zLkDxPhi4w2xjkiWKUB38Tt3a8zah7du4yyTRDIxO3g,5054
4
+ sendclap-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ sendclap-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any