sendclap 0.2.0__tar.gz
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-0.2.0/.gitignore +6 -0
- sendclap-0.2.0/PKG-INFO +94 -0
- sendclap-0.2.0/README.md +81 -0
- sendclap-0.2.0/pyproject.toml +21 -0
- sendclap-0.2.0/src/sendclap/__init__.py +419 -0
- sendclap-0.2.0/src/sendclap/py.typed +0 -0
- sendclap-0.2.0/tests/test_sendclap.py +221 -0
sendclap-0.2.0/PKG-INFO
ADDED
|
@@ -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
|
+
```
|
sendclap-0.2.0/README.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# sendclap (Python)
|
|
2
|
+
|
|
3
|
+
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
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install sendclap
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## License check (in your app, no API key)
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
import time
|
|
13
|
+
from sendclap import LicenseClient, NetworkError, instance_name
|
|
14
|
+
|
|
15
|
+
def licensed(key: str, cache: dict) -> bool:
|
|
16
|
+
try:
|
|
17
|
+
r = LicenseClient().validate(key, cache.get("instance") or instance_name())
|
|
18
|
+
except NetworkError: # offline: allow a 7-day grace period since the last good check
|
|
19
|
+
return time.time() - cache.get("validated_at", 0) < 7 * 86400
|
|
20
|
+
if r.valid:
|
|
21
|
+
cache["validated_at"] = time.time() # persist cache to disk yourself
|
|
22
|
+
return r.valid # status "invalid", "disabled" or "not_activated": lock the app
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
On first run, activate the device and remember the instance id:
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from sendclap import ActivationLimitError, DisabledLicenseError, InvalidLicenseError
|
|
29
|
+
try:
|
|
30
|
+
cache["instance"] = LicenseClient().activate(key, instance_name()).instance_id
|
|
31
|
+
except InvalidLicenseError: ... # unknown key
|
|
32
|
+
except DisabledLicenseError: ... # the payment was refunded or disputed
|
|
33
|
+
except ActivationLimitError as e: print(f"Used on {e.license.activations}/{e.license.max_activations} devices")
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`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"`.
|
|
37
|
+
|
|
38
|
+
**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.
|
|
39
|
+
|
|
40
|
+
## Creator API (server side only)
|
|
41
|
+
|
|
42
|
+
> **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.
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from sendclap import ApiClient
|
|
46
|
+
|
|
47
|
+
api = ApiClient("sc_your_key") # base_url="https://sendclap.com", timeout=15.0
|
|
48
|
+
checkout = api.create_checkout("product", product_id=1, email="buyer@example.com")
|
|
49
|
+
print(checkout["url"]) # send the buyer here
|
|
50
|
+
api.get_checkout(checkout["id"]) # poll until status == "paid"
|
|
51
|
+
page = api.list_payments(status="paid", limit=10) # page.data, page.has_more, page.next
|
|
52
|
+
if page.has_more:
|
|
53
|
+
page = api.list_payments(status="paid", limit=10, after=page.next)
|
|
54
|
+
for p in api.all_payments(status="paid"): # a generator that follows `next` across pages
|
|
55
|
+
print(p["amount"], p["email"])
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
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.
|
|
59
|
+
|
|
60
|
+
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`.
|
|
61
|
+
|
|
62
|
+
The client is synchronous. In async code, wrap calls with `await asyncio.to_thread(api.me)`.
|
|
63
|
+
|
|
64
|
+
## Errors
|
|
65
|
+
|
|
66
|
+
Every exception is a `SendclapError` with `.status`, `.code` (the server's machine-readable code) and `.message`. The typed ones are chosen by `code`:
|
|
67
|
+
|
|
68
|
+
| Exception | `code` | When |
|
|
69
|
+
|---|---|---|
|
|
70
|
+
| `InvalidLicenseError` | `license_not_found` | 404: the key doesn't exist |
|
|
71
|
+
| `DisabledLicenseError` | `license_disabled` | 403: disabled after a refund or dispute |
|
|
72
|
+
| `InstanceNotFoundError` | `instance_not_found` | 404: `deactivate` for an instance that isn't activated |
|
|
73
|
+
| `ActivationLimitError` | `activation_limit` | 409: every activation is used; `.license` and `.product` say how many |
|
|
74
|
+
| `NetworkError` | `network_error` | No response: offline, DNS, TLS, timeout (`.status == 0`) |
|
|
75
|
+
| `SendclapError` | anything else | e.g. `bad_request`, `invalid_api_key`, `not_found` |
|
|
76
|
+
|
|
77
|
+
## Tests
|
|
78
|
+
|
|
79
|
+
```sh
|
|
80
|
+
python3 -m unittest discover -s tests # or: python3 -m pytest
|
|
81
|
+
```
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sendclap"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Official Sendclap client: license key checks for your app and the creator REST API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = ["sendclap", "license", "license-key", "payments"]
|
|
14
|
+
classifiers = ["Programming Language :: Python :: 3", "Typing :: Typed"]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Homepage = "https://sendclap.com"
|
|
18
|
+
Documentation = "https://sendclap.com/docs"
|
|
19
|
+
|
|
20
|
+
[tool.hatch.build.targets.wheel]
|
|
21
|
+
packages = ["src/sendclap"]
|
|
@@ -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)}")
|
|
File without changes
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
import threading
|
|
5
|
+
import unittest
|
|
6
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
7
|
+
from urllib.parse import parse_qs, urlparse
|
|
8
|
+
|
|
9
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
|
10
|
+
|
|
11
|
+
import sendclap # noqa: E402
|
|
12
|
+
from sendclap import ( # noqa: E402
|
|
13
|
+
ActivationLimitError, ApiClient, DisabledLicenseError, InstanceNotFoundError, InvalidLicenseError,
|
|
14
|
+
LicenseClient, NetworkError, SendclapError,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
LICENSE = {"key": "GOOD", "activations": 1, "max_activations": 3}
|
|
18
|
+
PRODUCT = {"id": 1, "name": "Pro"}
|
|
19
|
+
CHECKOUT = {"id": "0xabc", "status": "pending", "type": "product", "amount": 29, "currency": "usd",
|
|
20
|
+
"method": "card", "email": "buyer@example.com", "url": "http://x/checkout/0xabc"}
|
|
21
|
+
PAYMENTS = [{"id": 3, "status": "paid"}, {"id": 2, "status": "paid"}, {"id": 1, "status": "paid"}]
|
|
22
|
+
SEEN = [] # (method, path, headers, body) of every request
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Mock(BaseHTTPRequestHandler):
|
|
26
|
+
def log_message(self, *args):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
def reply(self, status, body, ctype="application/json"):
|
|
30
|
+
raw = (json.dumps(body) if ctype == "application/json" else body).encode()
|
|
31
|
+
self.send_response(status)
|
|
32
|
+
self.send_header("Content-Type", ctype)
|
|
33
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
34
|
+
self.end_headers()
|
|
35
|
+
self.wfile.write(raw)
|
|
36
|
+
|
|
37
|
+
def handle_any(self, method):
|
|
38
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
39
|
+
body = json.loads(self.rfile.read(n)) if n else None
|
|
40
|
+
url = urlparse(self.path)
|
|
41
|
+
SEEN.append((method, self.path, dict(self.headers), body))
|
|
42
|
+
p = url.path
|
|
43
|
+
if p.startswith("/api/v1/licenses/"):
|
|
44
|
+
action, key, inst = p.rsplit("/", 1)[1], body.get("license_key"), body.get("instance_id")
|
|
45
|
+
if key == "REFUNDED":
|
|
46
|
+
return self.reply(403, {"valid": False, "error": "this license key is disabled", "code": "license_disabled"})
|
|
47
|
+
if key != "GOOD" and key != "FULL":
|
|
48
|
+
return self.reply(404, {"valid": False, "error": "license key not found", "code": "license_not_found"})
|
|
49
|
+
if action == "validate":
|
|
50
|
+
return self.reply(200, {"valid": inst in (None, "dev-1"), "license": LICENSE, "product": PRODUCT})
|
|
51
|
+
if not inst:
|
|
52
|
+
return self.reply(400, {"error": "instance_id is required", "code": "bad_request"})
|
|
53
|
+
if action == "activate" and key == "FULL":
|
|
54
|
+
return self.reply(409, {"activated": False, "error": "activation limit reached", "code": "activation_limit",
|
|
55
|
+
"license": {"key": "FULL", "activations": 3, "max_activations": 3}, "product": PRODUCT})
|
|
56
|
+
if action == "activate":
|
|
57
|
+
return self.reply(200, {"activated": True, "instance_id": inst, "license": LICENSE, "product": PRODUCT})
|
|
58
|
+
if inst != "dev-1":
|
|
59
|
+
return self.reply(404, {"deactivated": False, "error": "that instance is not activated",
|
|
60
|
+
"code": "instance_not_found", "license": LICENSE, "product": PRODUCT})
|
|
61
|
+
return self.reply(200, {"deactivated": True, "license": dict(LICENSE, activations=0), "product": PRODUCT})
|
|
62
|
+
if p == "/api/v1/creators/demo":
|
|
63
|
+
return self.reply(200, {"handle": "demo", "name": "Ada Builds"})
|
|
64
|
+
if p.startswith("/api/v1/") and self.headers.get("Authorization") != "Bearer sc_test":
|
|
65
|
+
return self.reply(401, {"error": "invalid API key", "code": "invalid_api_key"})
|
|
66
|
+
if p == "/api/v1/checkouts" and method == "POST":
|
|
67
|
+
return self.reply(201, CHECKOUT)
|
|
68
|
+
if p == "/api/v1/checkouts/0xabc":
|
|
69
|
+
return self.reply(200, CHECKOUT)
|
|
70
|
+
if p == "/api/v1/payments": # two per page, newest first, cursor = the last id on the page
|
|
71
|
+
after = int(parse_qs(url.query).get("after", ["1000"])[0])
|
|
72
|
+
rows = [r for r in PAYMENTS if r["id"] < after]
|
|
73
|
+
data, more = rows[:2], len(rows) > 2
|
|
74
|
+
return self.reply(200, {"data": data, "has_more": more, "next": data[-1]["id"] if more else None})
|
|
75
|
+
if p == "/api/v1/members":
|
|
76
|
+
return self.reply(200, {"data": [{"email": "a@b.co"}], "has_more": False, "next": None})
|
|
77
|
+
if p == "/api/v1/payments/42":
|
|
78
|
+
return self.reply(200, {"id": 42, "item": "Pro", "activity": []})
|
|
79
|
+
if p == "/api/v1/payments/7":
|
|
80
|
+
return self.reply(404, {"error": "payment not found", "code": "not_found"})
|
|
81
|
+
if p == "/api/v1/broken":
|
|
82
|
+
return self.reply(200, "not json", "text/plain")
|
|
83
|
+
return self.reply(404, "<html>Not found</html>", "text/html")
|
|
84
|
+
|
|
85
|
+
def do_GET(self):
|
|
86
|
+
self.handle_any("GET")
|
|
87
|
+
|
|
88
|
+
def do_POST(self):
|
|
89
|
+
self.handle_any("POST")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class SendclapTest(unittest.TestCase):
|
|
93
|
+
@classmethod
|
|
94
|
+
def setUpClass(cls):
|
|
95
|
+
cls.server = ThreadingHTTPServer(("127.0.0.1", 0), Mock)
|
|
96
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
97
|
+
cls.base = f"http://127.0.0.1:{cls.server.server_address[1]}"
|
|
98
|
+
cls.lic = LicenseClient(base_url=cls.base + "/")
|
|
99
|
+
cls.api = ApiClient("sc_test", base_url=cls.base)
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def tearDownClass(cls):
|
|
103
|
+
cls.server.shutdown()
|
|
104
|
+
cls.server.server_close()
|
|
105
|
+
|
|
106
|
+
def test_activate(self):
|
|
107
|
+
r = self.lic.activate("GOOD", "dev-1")
|
|
108
|
+
self.assertEqual(r.instance_id, "dev-1")
|
|
109
|
+
self.assertEqual(r.license.max_activations, 3)
|
|
110
|
+
self.assertEqual(r.product.name, "Pro")
|
|
111
|
+
method, path, headers, body = SEEN[-1]
|
|
112
|
+
self.assertEqual((method, path), ("POST", "/api/v1/licenses/activate"))
|
|
113
|
+
self.assertEqual(body, {"license_key": "GOOD", "instance_id": "dev-1"})
|
|
114
|
+
self.assertEqual(headers["User-Agent"], "sendclap-python/0.2.0")
|
|
115
|
+
self.assertEqual(headers["Content-Type"], "application/json")
|
|
116
|
+
self.assertNotIn("Authorization", headers)
|
|
117
|
+
|
|
118
|
+
def test_activate_limit(self):
|
|
119
|
+
with self.assertRaises(ActivationLimitError) as cm:
|
|
120
|
+
self.lic.activate("FULL", "dev-9")
|
|
121
|
+
self.assertEqual((cm.exception.status, cm.exception.code), (409, "activation_limit"))
|
|
122
|
+
self.assertEqual(cm.exception.license.activations, 3)
|
|
123
|
+
self.assertEqual(cm.exception.product.id, 1)
|
|
124
|
+
self.assertEqual(str(cm.exception), "activation limit reached")
|
|
125
|
+
|
|
126
|
+
def test_activate_invalid_key(self):
|
|
127
|
+
with self.assertRaises(InvalidLicenseError) as cm:
|
|
128
|
+
self.lic.activate("BAD", "dev-1")
|
|
129
|
+
self.assertEqual((cm.exception.status, cm.exception.code), (404, "license_not_found"))
|
|
130
|
+
self.assertEqual(cm.exception.message, "license key not found")
|
|
131
|
+
|
|
132
|
+
def test_activate_disabled_key(self):
|
|
133
|
+
with self.assertRaises(DisabledLicenseError) as cm:
|
|
134
|
+
self.lic.activate("REFUNDED", "dev-1")
|
|
135
|
+
self.assertNotIsInstance(cm.exception, InvalidLicenseError)
|
|
136
|
+
self.assertEqual((cm.exception.status, cm.exception.code), (403, "license_disabled"))
|
|
137
|
+
|
|
138
|
+
def test_activate_missing_instance(self):
|
|
139
|
+
with self.assertRaises(SendclapError) as cm:
|
|
140
|
+
self.lic.activate("GOOD", "")
|
|
141
|
+
self.assertEqual((cm.exception.status, cm.exception.code), (400, "bad_request"))
|
|
142
|
+
self.assertEqual(cm.exception.message, "instance_id is required")
|
|
143
|
+
|
|
144
|
+
def test_validate(self):
|
|
145
|
+
r = self.lic.validate("GOOD")
|
|
146
|
+
self.assertEqual((r.valid, r.status), (True, "active"))
|
|
147
|
+
self.assertEqual(SEEN[-1][3], {"license_key": "GOOD"})
|
|
148
|
+
self.assertEqual(self.lic.validate("GOOD", "dev-1").status, "active")
|
|
149
|
+
r = self.lic.validate("GOOD", "other")
|
|
150
|
+
self.assertEqual((r.valid, r.status, r.license.key), (False, "not_activated", "GOOD"))
|
|
151
|
+
r = self.lic.validate("BAD", "dev-1")
|
|
152
|
+
self.assertEqual((r.valid, r.status, r.license, r.product), (False, "invalid", None, None))
|
|
153
|
+
r = self.lic.validate("REFUNDED", "dev-1")
|
|
154
|
+
self.assertEqual((r.valid, r.status, r.license, r.product), (False, "disabled", None, None))
|
|
155
|
+
|
|
156
|
+
def test_deactivate(self):
|
|
157
|
+
r = self.lic.deactivate("GOOD", "dev-1")
|
|
158
|
+
self.assertEqual(r.license.activations, 0)
|
|
159
|
+
with self.assertRaises(InvalidLicenseError):
|
|
160
|
+
self.lic.deactivate("BAD", "dev-1")
|
|
161
|
+
with self.assertRaises(InstanceNotFoundError) as cm:
|
|
162
|
+
self.lic.deactivate("GOOD", "nope")
|
|
163
|
+
self.assertEqual((cm.exception.status, cm.exception.code), (404, "instance_not_found"))
|
|
164
|
+
|
|
165
|
+
def test_html_404_is_not_invalid_license(self):
|
|
166
|
+
wrong = LicenseClient(base_url=self.base + "/nope")
|
|
167
|
+
with self.assertRaises(SendclapError) as cm:
|
|
168
|
+
wrong.validate("GOOD")
|
|
169
|
+
self.assertNotIsInstance(cm.exception, InvalidLicenseError)
|
|
170
|
+
self.assertEqual((cm.exception.status, cm.exception.message, cm.exception.code), (404, "HTTP 404", ""))
|
|
171
|
+
|
|
172
|
+
def test_network_error(self):
|
|
173
|
+
with self.assertRaises(NetworkError) as cm:
|
|
174
|
+
LicenseClient(base_url="http://127.0.0.1:1", timeout=2).validate("GOOD")
|
|
175
|
+
self.assertEqual((cm.exception.status, cm.exception.code), (0, "network_error"))
|
|
176
|
+
|
|
177
|
+
def test_invalid_json(self):
|
|
178
|
+
with self.assertRaises(SendclapError) as cm:
|
|
179
|
+
self.api._http.request("GET", "/broken")
|
|
180
|
+
self.assertEqual((cm.exception.status, cm.exception.message), (200, "invalid JSON response"))
|
|
181
|
+
|
|
182
|
+
def test_checkouts(self):
|
|
183
|
+
c = self.api.create_checkout("product", product_id=1, email="buyer@example.com")
|
|
184
|
+
self.assertEqual(c["url"], "http://x/checkout/0xabc")
|
|
185
|
+
method, path, headers, body = SEEN[-1]
|
|
186
|
+
self.assertEqual(body, {"type": "product", "product_id": 1, "email": "buyer@example.com"})
|
|
187
|
+
self.assertEqual(headers["Authorization"], "Bearer sc_test")
|
|
188
|
+
g = self.api.get_checkout("0xabc")
|
|
189
|
+
self.assertEqual((g["status"], g["url"]), ("pending", "http://x/checkout/0xabc"))
|
|
190
|
+
|
|
191
|
+
def test_payments_page(self):
|
|
192
|
+
page = self.api.list_payments(status="paid", limit=2)
|
|
193
|
+
self.assertEqual((page.data, page.has_more, page.next), (PAYMENTS[:2], True, 2))
|
|
194
|
+
self.assertEqual(SEEN[-1][1], "/api/v1/payments?status=paid&limit=2")
|
|
195
|
+
last = self.api.list_payments(after=page.next)
|
|
196
|
+
self.assertEqual((last.data, last.has_more, last.next), (PAYMENTS[2:], False, None))
|
|
197
|
+
self.assertEqual(self.api.get_payment(42)["item"], "Pro")
|
|
198
|
+
with self.assertRaises(SendclapError) as cm:
|
|
199
|
+
self.api.get_payment(7)
|
|
200
|
+
self.assertEqual((cm.exception.status, cm.exception.code, cm.exception.message), (404, "not_found", "payment not found"))
|
|
201
|
+
|
|
202
|
+
def test_all_payments_follows_next(self):
|
|
203
|
+
self.assertEqual([p["id"] for p in self.api.all_payments(status="paid")], [3, 2, 1])
|
|
204
|
+
self.assertEqual(SEEN[-1][1], "/api/v1/payments?status=paid&after=2")
|
|
205
|
+
self.assertEqual(len(list(self.api.all_members())), 1)
|
|
206
|
+
|
|
207
|
+
def test_unauthorized(self):
|
|
208
|
+
with self.assertRaises(SendclapError) as cm:
|
|
209
|
+
ApiClient("sc_wrong", base_url=self.base).me()
|
|
210
|
+
self.assertEqual((cm.exception.status, cm.exception.code, cm.exception.message), (401, "invalid_api_key", "invalid API key"))
|
|
211
|
+
|
|
212
|
+
def test_creator_without_key(self):
|
|
213
|
+
self.assertEqual(ApiClient(base_url=self.base).get_creator("demo")["name"], "Ada Builds")
|
|
214
|
+
self.assertNotIn("Authorization", SEEN[-1][2])
|
|
215
|
+
|
|
216
|
+
def test_instance_name(self):
|
|
217
|
+
self.assertTrue(sendclap.instance_name())
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
if __name__ == "__main__":
|
|
221
|
+
unittest.main()
|