loyaltte 0.1.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.
@@ -0,0 +1,2 @@
1
+ .venv/
2
+ dist/
loyaltte-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Loyaltte
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,203 @@
1
+ Metadata-Version: 2.5
2
+ Name: loyaltte
3
+ Version: 0.1.0
4
+ Summary: Loyaltte server SDK: record bills and returns, look up customers, sign customers in, verify webhooks.
5
+ Project-URL: Homepage, https://loyaltte.com
6
+ Project-URL: Documentation, https://developers.loyaltte.com
7
+ Project-URL: Source, https://github.com/loyaltte/sdks/tree/main/packages/sdk-python
8
+ Project-URL: Issues, https://github.com/loyaltte/sdks/issues
9
+ Author: Loyaltte
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: crm,loyaltte,loyalty,sdk,webhooks
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.9
24
+ Provides-Extra: dev
25
+ Requires-Dist: build>=1.2; extra == 'dev'
26
+ Requires-Dist: mypy>=1.10; extra == 'dev'
27
+ Requires-Dist: pytest>=8; extra == 'dev'
28
+ Requires-Dist: ruff>=0.6; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # loyaltte 0.1.0 (Python)
32
+
33
+ The Loyaltte server SDK for Python: record bills and returns, look up customers and their points, send events, sign customers in to your app, and verify webhooks.
34
+
35
+ **Zero dependencies** (standard library only), fully typed (`py.typed`), Python 3.9+.
36
+
37
+ | | |
38
+ | --------------- | ---------------------------------------------------------------------------------------------------------------- |
39
+ | Needs | Python **3.9+**, nothing else |
40
+ | Source of truth | the contract in [`packages/sdk-spec`](https://github.com/loyaltte/sdks/tree/main/packages/sdk-spec) (Server API) |
41
+ | Use it on | **your server only**: it holds a secret key. Apps and web pages use the publishable SDKs |
42
+
43
+ ## Install
44
+
45
+ ```sh
46
+ pip install loyaltte
47
+ ```
48
+
49
+ ## Keys
50
+
51
+ | Key | Looks like | Where it goes |
52
+ | --------------- | --------------------------- | --------------------------------------------- |
53
+ | **Secret key** | `lyt_live_…` / `lyt_test_…` | `Loyaltte(...)`: server only, from an env var |
54
+ | Identify secret | `lps_…` | `loyaltte.sign_identity(...)`: server only |
55
+ | Webhook secret | `whsec_…` | `loyaltte.webhooks.verify(...)`: server only |
56
+ | Publishable key | `lak_…` | apps and web pages: **never** here |
57
+
58
+ `Loyaltte("lak_…")` and `Loyaltte("lps_…")` are refused with an error that says which key you need. The key is never in an error message, `repr` or log line.
59
+
60
+ ## Quick start
61
+
62
+ ```python
63
+ import os
64
+ from decimal import Decimal
65
+ from loyaltte import Loyaltte
66
+
67
+ client = Loyaltte(os.environ["LOYALTTE_SECRET_KEY"])
68
+
69
+ print(client.key.retrieve()) # which account and mode, permissions, stores
70
+
71
+ found = client.customers.lookup(phone="9876543210") # or email=..., or external_id=...
72
+ if found["found"]:
73
+ print(client.customers.points(found["customer"]["id"]))
74
+
75
+ receipt = client.bills.create({
76
+ "store_id": "8a2d4e6f-1b3c-4d5e-8f70-9a1b2c3d4e5f",
77
+ "bill_number": "BLR-IND-000482",
78
+ "amount": Decimal("4200.00"), # or "4200.00": never a float
79
+ "customer": {"phone": "9876543210"},
80
+ })
81
+ print(receipt["points_earned"], receipt["replayed"])
82
+ ```
83
+
84
+ Options: `Loyaltte(secret_key, base_url="https://api.loyaltte.com", timeout=30, max_retries=7)`.
85
+
86
+ | Call | API |
87
+ | --------------------------------------------------------------------------- | ------------------------------------- |
88
+ | `client.key.retrieve()` | `GET /v1/key` |
89
+ | `client.events.send(events)` | `POST /v1/events` |
90
+ | `client.visitors.identify(anonymous_id, phone=… / email=… / external_id=…)` | `POST /v1/identify` |
91
+ | `client.customers.lookup(phone=… / email=… / external_id=…)` | `GET /v1/customers/lookup` |
92
+ | `client.customers.retrieve(id)` / `.points(id)` | `GET /v1/customers/{id}` / `…/points` |
93
+ | `client.bills.preview(body)` | `POST /v1/bills/preview` |
94
+ | `client.bills.create(body, idempotency_key=None)` | `POST /v1/bills` |
95
+ | `client.returns.create(body, idempotency_key=None)` | `POST /v1/returns` |
96
+
97
+ Answers are plain dicts (with `TypedDict` shapes in `loyaltte.types` for your editor).
98
+
99
+ **Events** are sent in batches of at most 100 events and 64 KiB, in order, and the counts are summed (`batches` says how many requests were made). Give every event an `id` so a resend is counted once. If a later batch fails, the earlier ones were already accepted and the error is raised.
100
+
101
+ **Money is a decimal string.** Pass a `str` or a `Decimal`; a `float` in a bill, preview or return raises `TypeError` before anything is sent.
102
+
103
+ ## Sign a customer in (your sign-in endpoint)
104
+
105
+ The app never tells Loyaltte who the customer is: your server signs the sign-in with your identify secret, and hands the app the values. The install id comes from the app (`SDK.installId`).
106
+
107
+ ```python
108
+ import os
109
+ from flask import Flask, jsonify, request
110
+ from loyaltte import sign_identity
111
+
112
+ app = Flask(__name__)
113
+
114
+ @app.post("/loyaltte/sign-in")
115
+ def loyaltte_sign_in():
116
+ customer = current_customer() # your own session check; 401 if nobody is signed in
117
+ signed = sign_identity(
118
+ os.environ["LOYALTTE_IDENTIFY_SECRET"],
119
+ customer.id, # your customer id (or the customer's mobile number)
120
+ request.json["installId"],
121
+ )
122
+ return jsonify(signed) # {"customer_id", "timestamp", "signature", "bind": "install"}
123
+ ```
124
+
125
+ FastAPI is the same: `return sign_identity(secret, user.id, body.install_id)`. Without an `install_id` you get the older plain form (`bind` is `None`). The server accepts a timestamp within 15 minutes.
126
+
127
+ ## Webhooks
128
+
129
+ Check the signature on the **raw body**, exactly as received. Parsing the JSON first and re-serialising it changes the bytes and breaks the check.
130
+
131
+ ```python
132
+ import os
133
+ from flask import Flask, request
134
+ from loyaltte import WebhookSignatureError, webhooks
135
+
136
+ app = Flask(__name__)
137
+
138
+ @app.post("/loyaltte/webhook")
139
+ def loyaltte_webhook():
140
+ try:
141
+ event = webhooks.construct_event(
142
+ os.environ["LOYALTTE_WEBHOOK_SECRET"],
143
+ request.headers.get("Loyaltte-Signature"),
144
+ request.get_data(), # bytes, NOT request.json
145
+ )
146
+ except WebhookSignatureError:
147
+ return "", 400
148
+ if already_handled(event["id"]): # ids are unique; a retry has the same id
149
+ return "", 200
150
+ handle(event["type"], event["data"])
151
+ return "", 200
152
+ ```
153
+
154
+ `webhooks.verify(secret_or_secrets, header, raw_body, tolerance=300, now=None) -> bool` is the same check without raising. It compares in constant time, refuses a timestamp more than `tolerance` seconds away (older or newer), treats a malformed header as `False`, and accepts any matching `v1` (during a secret rotation Loyaltte sends two). Pass a list of secrets to accept both old and new on your side.
155
+
156
+ ## Bills and idempotency
157
+
158
+ `bills.create` and `returns.create` are safe to retry. If you pass no `idempotency_key`, the SDK makes a UUID and sends the **same one on every retry** of that call. To make a retry safe across your own process restarts or queues, pass your own stable key (a bill or order reference):
159
+
160
+ ```python
161
+ client.bills.create(body, idempotency_key=f"order-{order.id}")
162
+ client.returns.create({"bill_number": "BLR-IND-000482", "return_number": "RET-000091", "amount": "2100.00"})
163
+ ```
164
+
165
+ The same `bill_number` again returns the first receipt with `replayed: true`; the same key with a different body is a `ConflictError` (409).
166
+
167
+ ## Errors
168
+
169
+ All errors derive from `LoyaltteError` (`status`, `code`, `message`, `fields`, `request_id`, `retry_after`):
170
+
171
+ | Class | When |
172
+ | ----------------------- | --------------------------------------------------------------------------------- |
173
+ | `AuthenticationError` | 401: the key is missing, revoked or mistyped |
174
+ | `PermissionDeniedError` | 403: the key lacks a permission (`fields["scope"]`) or the plan lacks the feature |
175
+ | `NotFoundError` | 404 |
176
+ | `ConflictError` | 409 |
177
+ | `ValidationError` | 400, 422 (`fields` names each input) |
178
+ | `RateLimitError` | 429 (`retry_after` seconds) |
179
+ | `ApiError` | 5xx |
180
+ | `APIConnectionError` | no answer: DNS, connect, TLS, reset, timeout |
181
+ | `WebhookSignatureError` | from `webhooks.construct_event` |
182
+
183
+ Quote `request_id` to support.
184
+
185
+ ## Retries
186
+
187
+ Built in, per the contract: full-jitter exponential backoff (1 s base, 60 s cap, doubling), at most 8 attempts, on network errors and statuses 408, 425, 429, 500, 502, 503 and 504, honouring `Retry-After` (a call never sleeps more than 5 minutes in total). Other 4xx are never retried.
188
+
189
+ - `GET`s and `bills` / `returns` (idempotent) are retried freely.
190
+ - Other `POST`s (`events`, `identify`, `bills.preview`) are retried only when the request certainly never reached Loyaltte (the connection could not be made) or on a 429/503 that carries `Retry-After`. A 500 or a lost answer is raised, never repeated blindly.
191
+ - `max_retries=0` turns retries off.
192
+
193
+ TLS certificates are always verified, redirects are never followed (so the key cannot be sent to another host), and plain `http://` is accepted only for `localhost`.
194
+
195
+ ## Develop
196
+
197
+ ```sh
198
+ python -m venv .venv && .venv/bin/pip install -e '.[dev]'
199
+ .venv/bin/pytest && .venv/bin/ruff check . && .venv/bin/mypy
200
+ .venv/bin/python -m build # sdist + wheel
201
+ ```
202
+
203
+ MIT licence.
@@ -0,0 +1,173 @@
1
+ # loyaltte 0.1.0 (Python)
2
+
3
+ The Loyaltte server SDK for Python: record bills and returns, look up customers and their points, send events, sign customers in to your app, and verify webhooks.
4
+
5
+ **Zero dependencies** (standard library only), fully typed (`py.typed`), Python 3.9+.
6
+
7
+ | | |
8
+ | --------------- | ---------------------------------------------------------------------------------------------------------------- |
9
+ | Needs | Python **3.9+**, nothing else |
10
+ | Source of truth | the contract in [`packages/sdk-spec`](https://github.com/loyaltte/sdks/tree/main/packages/sdk-spec) (Server API) |
11
+ | Use it on | **your server only**: it holds a secret key. Apps and web pages use the publishable SDKs |
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ pip install loyaltte
17
+ ```
18
+
19
+ ## Keys
20
+
21
+ | Key | Looks like | Where it goes |
22
+ | --------------- | --------------------------- | --------------------------------------------- |
23
+ | **Secret key** | `lyt_live_…` / `lyt_test_…` | `Loyaltte(...)`: server only, from an env var |
24
+ | Identify secret | `lps_…` | `loyaltte.sign_identity(...)`: server only |
25
+ | Webhook secret | `whsec_…` | `loyaltte.webhooks.verify(...)`: server only |
26
+ | Publishable key | `lak_…` | apps and web pages: **never** here |
27
+
28
+ `Loyaltte("lak_…")` and `Loyaltte("lps_…")` are refused with an error that says which key you need. The key is never in an error message, `repr` or log line.
29
+
30
+ ## Quick start
31
+
32
+ ```python
33
+ import os
34
+ from decimal import Decimal
35
+ from loyaltte import Loyaltte
36
+
37
+ client = Loyaltte(os.environ["LOYALTTE_SECRET_KEY"])
38
+
39
+ print(client.key.retrieve()) # which account and mode, permissions, stores
40
+
41
+ found = client.customers.lookup(phone="9876543210") # or email=..., or external_id=...
42
+ if found["found"]:
43
+ print(client.customers.points(found["customer"]["id"]))
44
+
45
+ receipt = client.bills.create({
46
+ "store_id": "8a2d4e6f-1b3c-4d5e-8f70-9a1b2c3d4e5f",
47
+ "bill_number": "BLR-IND-000482",
48
+ "amount": Decimal("4200.00"), # or "4200.00": never a float
49
+ "customer": {"phone": "9876543210"},
50
+ })
51
+ print(receipt["points_earned"], receipt["replayed"])
52
+ ```
53
+
54
+ Options: `Loyaltte(secret_key, base_url="https://api.loyaltte.com", timeout=30, max_retries=7)`.
55
+
56
+ | Call | API |
57
+ | --------------------------------------------------------------------------- | ------------------------------------- |
58
+ | `client.key.retrieve()` | `GET /v1/key` |
59
+ | `client.events.send(events)` | `POST /v1/events` |
60
+ | `client.visitors.identify(anonymous_id, phone=… / email=… / external_id=…)` | `POST /v1/identify` |
61
+ | `client.customers.lookup(phone=… / email=… / external_id=…)` | `GET /v1/customers/lookup` |
62
+ | `client.customers.retrieve(id)` / `.points(id)` | `GET /v1/customers/{id}` / `…/points` |
63
+ | `client.bills.preview(body)` | `POST /v1/bills/preview` |
64
+ | `client.bills.create(body, idempotency_key=None)` | `POST /v1/bills` |
65
+ | `client.returns.create(body, idempotency_key=None)` | `POST /v1/returns` |
66
+
67
+ Answers are plain dicts (with `TypedDict` shapes in `loyaltte.types` for your editor).
68
+
69
+ **Events** are sent in batches of at most 100 events and 64 KiB, in order, and the counts are summed (`batches` says how many requests were made). Give every event an `id` so a resend is counted once. If a later batch fails, the earlier ones were already accepted and the error is raised.
70
+
71
+ **Money is a decimal string.** Pass a `str` or a `Decimal`; a `float` in a bill, preview or return raises `TypeError` before anything is sent.
72
+
73
+ ## Sign a customer in (your sign-in endpoint)
74
+
75
+ The app never tells Loyaltte who the customer is: your server signs the sign-in with your identify secret, and hands the app the values. The install id comes from the app (`SDK.installId`).
76
+
77
+ ```python
78
+ import os
79
+ from flask import Flask, jsonify, request
80
+ from loyaltte import sign_identity
81
+
82
+ app = Flask(__name__)
83
+
84
+ @app.post("/loyaltte/sign-in")
85
+ def loyaltte_sign_in():
86
+ customer = current_customer() # your own session check; 401 if nobody is signed in
87
+ signed = sign_identity(
88
+ os.environ["LOYALTTE_IDENTIFY_SECRET"],
89
+ customer.id, # your customer id (or the customer's mobile number)
90
+ request.json["installId"],
91
+ )
92
+ return jsonify(signed) # {"customer_id", "timestamp", "signature", "bind": "install"}
93
+ ```
94
+
95
+ FastAPI is the same: `return sign_identity(secret, user.id, body.install_id)`. Without an `install_id` you get the older plain form (`bind` is `None`). The server accepts a timestamp within 15 minutes.
96
+
97
+ ## Webhooks
98
+
99
+ Check the signature on the **raw body**, exactly as received. Parsing the JSON first and re-serialising it changes the bytes and breaks the check.
100
+
101
+ ```python
102
+ import os
103
+ from flask import Flask, request
104
+ from loyaltte import WebhookSignatureError, webhooks
105
+
106
+ app = Flask(__name__)
107
+
108
+ @app.post("/loyaltte/webhook")
109
+ def loyaltte_webhook():
110
+ try:
111
+ event = webhooks.construct_event(
112
+ os.environ["LOYALTTE_WEBHOOK_SECRET"],
113
+ request.headers.get("Loyaltte-Signature"),
114
+ request.get_data(), # bytes, NOT request.json
115
+ )
116
+ except WebhookSignatureError:
117
+ return "", 400
118
+ if already_handled(event["id"]): # ids are unique; a retry has the same id
119
+ return "", 200
120
+ handle(event["type"], event["data"])
121
+ return "", 200
122
+ ```
123
+
124
+ `webhooks.verify(secret_or_secrets, header, raw_body, tolerance=300, now=None) -> bool` is the same check without raising. It compares in constant time, refuses a timestamp more than `tolerance` seconds away (older or newer), treats a malformed header as `False`, and accepts any matching `v1` (during a secret rotation Loyaltte sends two). Pass a list of secrets to accept both old and new on your side.
125
+
126
+ ## Bills and idempotency
127
+
128
+ `bills.create` and `returns.create` are safe to retry. If you pass no `idempotency_key`, the SDK makes a UUID and sends the **same one on every retry** of that call. To make a retry safe across your own process restarts or queues, pass your own stable key (a bill or order reference):
129
+
130
+ ```python
131
+ client.bills.create(body, idempotency_key=f"order-{order.id}")
132
+ client.returns.create({"bill_number": "BLR-IND-000482", "return_number": "RET-000091", "amount": "2100.00"})
133
+ ```
134
+
135
+ The same `bill_number` again returns the first receipt with `replayed: true`; the same key with a different body is a `ConflictError` (409).
136
+
137
+ ## Errors
138
+
139
+ All errors derive from `LoyaltteError` (`status`, `code`, `message`, `fields`, `request_id`, `retry_after`):
140
+
141
+ | Class | When |
142
+ | ----------------------- | --------------------------------------------------------------------------------- |
143
+ | `AuthenticationError` | 401: the key is missing, revoked or mistyped |
144
+ | `PermissionDeniedError` | 403: the key lacks a permission (`fields["scope"]`) or the plan lacks the feature |
145
+ | `NotFoundError` | 404 |
146
+ | `ConflictError` | 409 |
147
+ | `ValidationError` | 400, 422 (`fields` names each input) |
148
+ | `RateLimitError` | 429 (`retry_after` seconds) |
149
+ | `ApiError` | 5xx |
150
+ | `APIConnectionError` | no answer: DNS, connect, TLS, reset, timeout |
151
+ | `WebhookSignatureError` | from `webhooks.construct_event` |
152
+
153
+ Quote `request_id` to support.
154
+
155
+ ## Retries
156
+
157
+ Built in, per the contract: full-jitter exponential backoff (1 s base, 60 s cap, doubling), at most 8 attempts, on network errors and statuses 408, 425, 429, 500, 502, 503 and 504, honouring `Retry-After` (a call never sleeps more than 5 minutes in total). Other 4xx are never retried.
158
+
159
+ - `GET`s and `bills` / `returns` (idempotent) are retried freely.
160
+ - Other `POST`s (`events`, `identify`, `bills.preview`) are retried only when the request certainly never reached Loyaltte (the connection could not be made) or on a 429/503 that carries `Retry-After`. A 500 or a lost answer is raised, never repeated blindly.
161
+ - `max_retries=0` turns retries off.
162
+
163
+ TLS certificates are always verified, redirects are never followed (so the key cannot be sent to another host), and plain `http://` is accepted only for `localhost`.
164
+
165
+ ## Develop
166
+
167
+ ```sh
168
+ python -m venv .venv && .venv/bin/pip install -e '.[dev]'
169
+ .venv/bin/pytest && .venv/bin/ruff check . && .venv/bin/mypy
170
+ .venv/bin/python -m build # sdist + wheel
171
+ ```
172
+
173
+ MIT licence.
@@ -0,0 +1,66 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.21"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "loyaltte"
7
+ dynamic = ["version"]
8
+ description = "Loyaltte server SDK: record bills and returns, look up customers, sign customers in, verify webhooks."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ dependencies = []
14
+ authors = [{ name = "Loyaltte" }]
15
+ keywords = ["loyaltte", "loyalty", "crm", "sdk", "webhooks"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Typing :: Typed",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://loyaltte.com"
31
+ Documentation = "https://developers.loyaltte.com"
32
+ Source = "https://github.com/loyaltte/sdks/tree/main/packages/sdk-python"
33
+ Issues = "https://github.com/loyaltte/sdks/issues"
34
+
35
+ [project.optional-dependencies]
36
+ dev = ["pytest>=8", "ruff>=0.6", "mypy>=1.10", "build>=1.2"]
37
+
38
+ [tool.hatch.version]
39
+ path = "src/loyaltte/_version.py"
40
+
41
+ [tool.hatch.build.targets.wheel]
42
+ packages = ["src/loyaltte"]
43
+
44
+ [tool.hatch.build.targets.sdist]
45
+ include = ["src/loyaltte", "README.md", "LICENSE", "pyproject.toml"]
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
49
+ pythonpath = ["src"]
50
+
51
+ [tool.ruff]
52
+ line-length = 110
53
+ target-version = "py39"
54
+ src = ["src", "tests"]
55
+
56
+ [tool.ruff.lint]
57
+ select = ["E", "F", "I", "UP", "B", "S", "SIM"]
58
+ ignore = ["S101", "UP006", "UP007", "UP035", "UP045", "E501"]
59
+
60
+ [tool.ruff.lint.per-file-ignores]
61
+ "tests/*" = ["S"]
62
+ "_harness.py" = ["S"]
63
+
64
+ [tool.mypy]
65
+ strict = true
66
+ files = ["src", "tests", "_harness.py"]
@@ -0,0 +1,36 @@
1
+ """Loyaltte server SDK."""
2
+
3
+ from . import webhooks
4
+ from ._version import __version__
5
+ from .client import Loyaltte
6
+ from .errors import (
7
+ APIConnectionError,
8
+ ApiError,
9
+ AuthenticationError,
10
+ ConflictError,
11
+ LoyaltteError,
12
+ NotFoundError,
13
+ PermissionDeniedError,
14
+ RateLimitError,
15
+ ValidationError,
16
+ WebhookSignatureError,
17
+ )
18
+ from .identity import SignedIdentity, sign_identity
19
+
20
+ __all__ = [
21
+ "APIConnectionError",
22
+ "ApiError",
23
+ "AuthenticationError",
24
+ "ConflictError",
25
+ "Loyaltte",
26
+ "LoyaltteError",
27
+ "NotFoundError",
28
+ "PermissionDeniedError",
29
+ "RateLimitError",
30
+ "SignedIdentity",
31
+ "ValidationError",
32
+ "WebhookSignatureError",
33
+ "__version__",
34
+ "sign_identity",
35
+ "webhooks",
36
+ ]
@@ -0,0 +1,302 @@
1
+ """The HTTP core: one request, retried per the contract (packages/sdk-spec x-retry). Standard library only.
2
+
3
+ http.client is used rather than urllib so that redirects are never followed (a redirect must not carry the
4
+ Authorization header to another host) and TLS uses the default, verifying context.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import http.client
10
+ import json
11
+ import random
12
+ import ssl
13
+ import time
14
+ import uuid
15
+ from decimal import Decimal
16
+ from typing import Any, Callable, Dict, Mapping, Optional, Tuple
17
+ from urllib.parse import urlencode, urlsplit
18
+
19
+ from ._version import __version__
20
+ from .errors import (
21
+ APIConnectionError,
22
+ ApiError,
23
+ AuthenticationError,
24
+ ConflictError,
25
+ LoyaltteError,
26
+ NotFoundError,
27
+ PermissionDeniedError,
28
+ RateLimitError,
29
+ ValidationError,
30
+ )
31
+
32
+ # x-retry in packages/sdk-spec/openapi.yaml
33
+ RETRY_STATUSES = frozenset({408, 425, 429, 500, 502, 503, 504})
34
+ BASE_MS = 1000
35
+ MAX_MS = 60000
36
+ MULTIPLIER = 2
37
+ MAX_ATTEMPTS = 8
38
+ MAX_RETRY_AFTER_S = 3600
39
+ MAX_TOTAL_SLEEP_S = 300 # across one call's retries: a bad Retry-After must not park a worker for hours
40
+ MAX_RESPONSE_BYTES = 16 * 1024 * 1024
41
+ LOOPBACK = {"localhost", "127.0.0.1", "::1"}
42
+
43
+
44
+ class _CertificateError(Exception):
45
+ """TLS certificate verification failed: never retried."""
46
+
47
+
48
+ class _NeverReached(Exception):
49
+ """The connection could not be made, so the request certainly did not reach the server."""
50
+
51
+
52
+ def normalise(value: Any, *, strict_money: bool, path: str = "body") -> Any:
53
+ """Make a body JSON-safe: Decimal -> str. With strict_money a float anywhere is refused."""
54
+ if isinstance(value, Decimal):
55
+ if not value.is_finite():
56
+ raise ValueError(f"{path}: amounts must be finite")
57
+ return format(value, "f")
58
+ if isinstance(value, float):
59
+ if strict_money:
60
+ raise TypeError(f"{path}: floats are not accepted for money; pass a decimal string or Decimal (e.g. \"4200.00\")")
61
+ return value
62
+ if isinstance(value, Mapping):
63
+ return {str(k): normalise(v, strict_money=strict_money, path=f"{path}.{k}") for k, v in value.items()}
64
+ if isinstance(value, (list, tuple)):
65
+ return [normalise(v, strict_money=strict_money, path=f"{path}[{i}]") for i, v in enumerate(value)]
66
+ return value
67
+
68
+
69
+ def check_secret_key(secret_key: Any) -> str:
70
+ if not isinstance(secret_key, str) or not secret_key.strip():
71
+ raise ValueError("Loyaltte needs your secret key (lyt_live_... or lyt_test_...), from Settings > API keys.")
72
+ if secret_key.startswith("lak_"):
73
+ raise ValueError(
74
+ "That is a publishable key (lak_...), which belongs in apps and web pages. "
75
+ "Server code needs a secret key (lyt_live_... or lyt_test_...)."
76
+ )
77
+ if secret_key.startswith("lps_"):
78
+ raise ValueError(
79
+ "That is an identify secret (lps_...). Use it with loyaltte.sign_identity(); "
80
+ "the API client needs a secret key (lyt_live_... or lyt_test_...)."
81
+ )
82
+ if not (secret_key.isascii() and secret_key.isprintable()) or " " in secret_key:
83
+ raise ValueError("The secret key has stray whitespace or odd characters; check how you read it from your settings.")
84
+ return secret_key
85
+
86
+
87
+ class HttpClient:
88
+ def __init__(
89
+ self,
90
+ secret_key: str,
91
+ base_url: str = "https://api.loyaltte.com",
92
+ timeout: float = 30,
93
+ max_retries: int = MAX_ATTEMPTS - 1,
94
+ sleep: Callable[[float], None] = time.sleep,
95
+ rand: Callable[[], float] = random.random,
96
+ ) -> None:
97
+ self._secret = check_secret_key(secret_key)
98
+ parts = urlsplit(base_url)
99
+ if parts.scheme not in ("https", "http") or not parts.hostname:
100
+ raise ValueError("base_url must be an http(s) URL")
101
+ if parts.scheme == "http" and parts.hostname not in LOOPBACK:
102
+ raise ValueError("base_url must be https (plain http is only allowed for localhost, in tests)")
103
+ if max_retries < 0:
104
+ raise ValueError("max_retries must be 0 or more")
105
+ if timeout <= 0:
106
+ raise ValueError("timeout must be positive")
107
+ self._scheme = parts.scheme
108
+ self._host = parts.hostname
109
+ self._port = parts.port
110
+ self._prefix = parts.path.rstrip("/")
111
+ self._timeout = timeout
112
+ self._max_retries = max_retries
113
+ self._sleep = sleep
114
+ self._rand = rand
115
+ self.base_url = base_url
116
+ self._ssl = ssl.create_default_context()
117
+
118
+ def __repr__(self) -> str:
119
+ return f"Loyaltte(base_url={self.base_url!r}, secret_key='[redacted]')"
120
+
121
+ # -- one attempt -------------------------------------------------------------------------------------
122
+ def _send_once(self, method: str, target: str, payload: Optional[bytes], headers: Dict[str, str]) -> Tuple[int, Mapping[str, str], bytes]:
123
+ conn: http.client.HTTPConnection
124
+ if self._scheme == "https":
125
+ conn = http.client.HTTPSConnection(self._host, self._port, timeout=self._timeout, context=self._ssl)
126
+ else:
127
+ conn = http.client.HTTPConnection(self._host, self._port, timeout=self._timeout)
128
+ try:
129
+ try:
130
+ conn.connect()
131
+ except ssl.SSLCertVerificationError:
132
+ raise _CertificateError from None
133
+ except (OSError, ssl.SSLError) as exc: # includes timeouts, DNS and TLS failures: nothing was sent
134
+ raise _NeverReached(type(exc).__name__) from None
135
+ conn.request(method, target, body=payload, headers=headers)
136
+ resp = conn.getresponse()
137
+ data = resp.read(MAX_RESPONSE_BYTES + 1)
138
+ if len(data) > MAX_RESPONSE_BYTES:
139
+ raise OSError("response too large")
140
+ return resp.status, {k.lower(): v for k, v in resp.getheaders()}, data
141
+ finally:
142
+ conn.close()
143
+
144
+ # -- retry policy ------------------------------------------------------------------------------------
145
+ def _delay(self, attempt: int, retry_after: Optional[float]) -> float:
146
+ """Full jitter: random(0, min(max, base * multiplier^(attempt-1))), seconds; Retry-After raises the floor."""
147
+ ceiling = min(MAX_MS, BASE_MS * MULTIPLIER ** (attempt - 1))
148
+ delay = float(self._rand()) * ceiling / 1000
149
+ if retry_after is not None:
150
+ delay = max(delay, min(retry_after, MAX_RETRY_AFTER_S))
151
+ return float(delay)
152
+
153
+ def _pause(self, attempt: int, retry_after: Optional[float], slept: float) -> float:
154
+ delay = min(self._delay(attempt, retry_after), max(MAX_TOTAL_SLEEP_S - slept, 0.0))
155
+ self._sleep(delay)
156
+ return delay
157
+
158
+ @staticmethod
159
+ def _retry_after(headers: Mapping[str, str]) -> Optional[float]:
160
+ raw = headers.get("retry-after")
161
+ if raw is None:
162
+ return None
163
+ raw = raw.strip()
164
+ if raw.isascii() and raw.isdigit() and len(raw) <= 9:
165
+ return float(raw)
166
+ return None
167
+
168
+ def request(
169
+ self,
170
+ method: str,
171
+ path: str,
172
+ *,
173
+ query: Optional[Mapping[str, str]] = None,
174
+ body: Optional[Any] = None,
175
+ idempotent: bool = False,
176
+ idempotency_key: Optional[str] = None,
177
+ strict_money: bool = False,
178
+ ) -> Any:
179
+ """Send a request. ``idempotent`` is the operation's x-idempotent (GET is always safe to repeat)."""
180
+ target = f"{self._prefix}{path}"
181
+ if query:
182
+ target += "?" + urlencode(query)
183
+ payload: Optional[bytes] = None
184
+ headers = {
185
+ "Authorization": f"Bearer {self._secret}",
186
+ "Accept": "application/json",
187
+ "User-Agent": f"loyaltte-python/{__version__}",
188
+ "X-Loyaltte-SDK": f"python/{__version__}",
189
+ }
190
+ if body is not None:
191
+ payload = json.dumps(normalise(body, strict_money=strict_money), separators=(",", ":"), allow_nan=False).encode("utf-8")
192
+ headers["Content-Type"] = "application/json"
193
+ if idempotency_key is not None:
194
+ headers["Idempotency-Key"] = idempotency_key # the same value on every attempt
195
+ repeatable = method == "GET" or idempotent
196
+ try:
197
+ return self._attempts(method, target, payload, headers, repeatable)
198
+ except LoyaltteError as exc:
199
+ if idempotency_key is not None:
200
+ exc.idempotency_key = idempotency_key # resend with this key to stay safe after a raised error
201
+ raise
202
+
203
+ def _attempts(self, method: str, target: str, payload: Optional[bytes], headers: Dict[str, str], repeatable: bool) -> Any:
204
+
205
+ attempt = 0
206
+ slept = 0.0
207
+ while True:
208
+ attempt += 1
209
+ can_retry = attempt <= self._max_retries and slept < MAX_TOTAL_SLEEP_S
210
+ try:
211
+ status, rheaders, data = self._send_once(method, target, payload, headers)
212
+ except _CertificateError:
213
+ raise APIConnectionError(
214
+ "TLS certificate verification failed; refusing to send the request.", code="TLS_VERIFICATION_FAILED"
215
+ ) from None
216
+ except _NeverReached as exc:
217
+ if can_retry:
218
+ slept += self._pause(attempt, None, slept)
219
+ continue
220
+ raise APIConnectionError(f"Could not connect to Loyaltte ({exc}).", code="CONNECTION_ERROR") from None
221
+ except (OSError, http.client.HTTPException) as exc:
222
+ # The request may have been processed: only repeat it when that is safe.
223
+ if can_retry and repeatable:
224
+ slept += self._pause(attempt, None, slept)
225
+ continue
226
+ raise APIConnectionError(
227
+ f"No answer from Loyaltte ({type(exc).__name__}); the request may have been processed.",
228
+ code="CONNECTION_ERROR",
229
+ ) from None
230
+ if 200 <= status < 300:
231
+ return self._decode_ok(status, data)
232
+ retry_after = self._retry_after(rheaders)
233
+ safe_to_repeat = repeatable or (status in (429, 503) and retry_after is not None)
234
+ if can_retry and status in RETRY_STATUSES and safe_to_repeat:
235
+ slept += self._pause(attempt, retry_after, slept)
236
+ continue
237
+ raise self._error(status, rheaders, data, retry_after)
238
+
239
+ # -- responses ---------------------------------------------------------------------------------------
240
+ def _decode_ok(self, status: int, data: bytes) -> Any:
241
+ if not data.strip():
242
+ return {}
243
+ try:
244
+ return json.loads(data)
245
+ except ValueError:
246
+ raise ApiError("Loyaltte answered with something that is not JSON.", status=status, code="INVALID_RESPONSE") from None
247
+
248
+ def _redact(self, text: str) -> str:
249
+ return text.replace(self._secret, "[redacted]") if self._secret in text else text
250
+
251
+ def _error(self, status: int, headers: Mapping[str, str], data: bytes, retry_after: Optional[float]) -> LoyaltteError:
252
+ code: Optional[str] = None
253
+ message = f"Loyaltte answered HTTP {status}."
254
+ fields: Dict[str, Any] = {}
255
+ request_id: Optional[str] = headers.get("x-request-id")
256
+ try:
257
+ parsed = json.loads(data)
258
+ err = parsed.get("error") if isinstance(parsed, dict) else None
259
+ if isinstance(err, dict):
260
+ code = err.get("code") if isinstance(err.get("code"), str) else None
261
+ if isinstance(err.get("message"), str) and err["message"]:
262
+ message = err["message"]
263
+ if isinstance(err.get("fields"), dict):
264
+ fields = err["fields"]
265
+ if isinstance(err.get("requestId"), str):
266
+ request_id = err["requestId"]
267
+ except (ValueError, AttributeError):
268
+ pass
269
+ message = self._redact(message)
270
+ fields = json.loads(self._redact(json.dumps(fields)))
271
+ kwargs: Dict[str, Any] = dict(status=status, code=code, fields=fields, request_id=request_id, retry_after=retry_after)
272
+ cls: type[LoyaltteError]
273
+ if status == 401:
274
+ cls = AuthenticationError
275
+ elif status == 403:
276
+ cls = PermissionDeniedError
277
+ elif status == 404:
278
+ cls = NotFoundError
279
+ elif status == 409:
280
+ cls = ConflictError
281
+ elif status in (400, 422):
282
+ cls = ValidationError
283
+ elif status == 429:
284
+ cls = RateLimitError
285
+ elif status >= 500:
286
+ cls = ApiError
287
+ else:
288
+ cls = LoyaltteError
289
+ return cls(message, **kwargs)
290
+
291
+
292
+ def new_idempotency_key() -> str:
293
+ return str(uuid.uuid4())
294
+
295
+
296
+ def check_idempotency_key(key: Optional[str]) -> str:
297
+ if key is None:
298
+ return new_idempotency_key()
299
+ if not isinstance(key, str) or not key or len(key) > 255 or not (key.isascii() and key.isprintable()):
300
+ raise ValueError("idempotency_key must be 1-255 printable ASCII characters")
301
+ return key
302
+
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ import time
5
+ from typing import Callable
6
+
7
+ from ._http import MAX_ATTEMPTS, HttpClient
8
+ from .resources import Bills, Customers, Events, Key, Returns, Visitors
9
+
10
+
11
+ class Loyaltte:
12
+ """The Loyaltte server client. Keep the secret key on your server, in an environment variable.
13
+
14
+ ``max_retries`` is how many times a failed call is repeated (default 7: the contract's 8 attempts).
15
+ ``sleep`` and ``rand`` exist so tests can run without waiting.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ secret_key: str,
21
+ base_url: str = "https://api.loyaltte.com",
22
+ timeout: float = 30,
23
+ max_retries: int = MAX_ATTEMPTS - 1,
24
+ *,
25
+ sleep: Callable[[float], None] = time.sleep,
26
+ rand: Callable[[], float] = random.random,
27
+ ) -> None:
28
+ http = HttpClient(secret_key, base_url, timeout, max_retries, sleep, rand)
29
+ self._http = http
30
+ self.key = Key(http)
31
+ self.events = Events(http)
32
+ self.visitors = Visitors(http)
33
+ self.customers = Customers(http)
34
+ self.bills = Bills(http)
35
+ self.returns = Returns(http)
36
+
37
+ def __repr__(self) -> str:
38
+ return repr(self._http)
@@ -0,0 +1,77 @@
1
+ """Exceptions. None of them ever carries the secret key."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional
6
+
7
+
8
+ class LoyaltteError(Exception):
9
+ """Base class of every error this SDK raises about a call."""
10
+
11
+ def __init__(
12
+ self,
13
+ message: str,
14
+ *,
15
+ status: Optional[int] = None,
16
+ code: Optional[str] = None,
17
+ fields: Optional[Dict[str, Any]] = None,
18
+ request_id: Optional[str] = None,
19
+ retry_after: Optional[float] = None,
20
+ ) -> None:
21
+ super().__init__(message)
22
+ self.message = message
23
+ self.status = status
24
+ self.code = code
25
+ self.fields = fields or {}
26
+ self.request_id = request_id
27
+ self.retry_after = retry_after
28
+ self.idempotency_key: Optional[str] = None # set on bills/returns errors: reuse it to retry safely
29
+
30
+ def __str__(self) -> str:
31
+ parts = [self.message]
32
+ if self.status is not None:
33
+ parts.append(f"(HTTP {self.status}" + (f", {self.code}" if self.code else "") + ")")
34
+ elif self.code:
35
+ parts.append(f"({self.code})")
36
+ if self.request_id:
37
+ parts.append(f"[request {self.request_id}]")
38
+ return " ".join(parts)
39
+
40
+ def __repr__(self) -> str:
41
+ return f"{type(self).__name__}(status={self.status!r}, code={self.code!r}, message={self.message!r})"
42
+
43
+
44
+ class AuthenticationError(LoyaltteError):
45
+ """401: no key, or the key is revoked, expired or mistyped."""
46
+
47
+
48
+ class PermissionDeniedError(LoyaltteError):
49
+ """403: the key lacks the permission (``fields["scope"]`` names it), or the plan lacks the feature."""
50
+
51
+
52
+ class NotFoundError(LoyaltteError):
53
+ """404: not found, or not in this key's account."""
54
+
55
+
56
+ class ConflictError(LoyaltteError):
57
+ """409: e.g. a bill number already used for a different bill, or an Idempotency-Key reused with another body."""
58
+
59
+
60
+ class ValidationError(LoyaltteError):
61
+ """400 or 422: ``fields`` names each invalid input."""
62
+
63
+
64
+ class RateLimitError(LoyaltteError):
65
+ """429: wait ``retry_after`` seconds."""
66
+
67
+
68
+ class ApiError(LoyaltteError):
69
+ """5xx: Loyaltte failed to answer."""
70
+
71
+
72
+ class APIConnectionError(LoyaltteError):
73
+ """No answer: DNS, connect, TLS, reset or timeout. The request may or may not have been processed."""
74
+
75
+
76
+ class WebhookSignatureError(LoyaltteError):
77
+ """The webhook's signature is missing, malformed, wrong or outside the tolerance window."""
@@ -0,0 +1,47 @@
1
+ """Signing a customer in: the brand's server signs, the app/page only passes the values on."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import time
8
+ from typing import Optional, TypedDict
9
+
10
+
11
+ class SignedIdentity(TypedDict):
12
+ customer_id: str
13
+ timestamp: int
14
+ signature: str
15
+ bind: Optional[str] # "install" when bound to an install id, else None (the older plain form)
16
+
17
+
18
+ def sign_identity(
19
+ secret: str,
20
+ customer_id: str,
21
+ install_id: Optional[str] = None,
22
+ timestamp: Optional[int] = None,
23
+ ) -> SignedIdentity:
24
+ """Sign a customer in with your identify secret (``lps_...``, Settings > App push).
25
+
26
+ Install-bound (use this): hex HMAC-SHA256 of ``"<customer_id>:<timestamp>:<install_id>"``, ``bind="install"``.
27
+ Plain (older SDKs, when ``install_id`` is None): ``"<customer_id>:<timestamp>"``, ``bind=None``.
28
+ The server accepts a timestamp within 900 seconds. UTF-8 bytes.
29
+ """
30
+ if not isinstance(secret, str) or not secret:
31
+ raise ValueError("secret must be your identify secret (lps_...)")
32
+ if not isinstance(customer_id, str) or not customer_id:
33
+ raise ValueError("customer_id must be a non-empty string")
34
+ if timestamp is None:
35
+ timestamp = int(time.time())
36
+ elif isinstance(timestamp, bool) or not isinstance(timestamp, int):
37
+ raise ValueError("timestamp must be an int (unix seconds)")
38
+ if install_id is not None and (not isinstance(install_id, str) or not install_id):
39
+ raise ValueError("install_id must be a non-empty string, or None for the older plain form")
40
+ if install_id is not None:
41
+ text = f"{customer_id}:{timestamp}:{install_id}"
42
+ bind: Optional[str] = "install"
43
+ else:
44
+ text = f"{customer_id}:{timestamp}"
45
+ bind = None
46
+ signature = hmac.new(secret.encode("utf-8"), text.encode("utf-8"), hashlib.sha256).hexdigest()
47
+ return {"customer_id": customer_id, "timestamp": timestamp, "signature": signature, "bind": bind}
File without changes
@@ -0,0 +1,155 @@
1
+ """The API's resources. Each returns the decoded JSON (plain dicts)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from decimal import Decimal
7
+ from typing import Any, Dict, Iterable, List, Mapping, Optional, Union
8
+ from urllib.parse import quote
9
+
10
+ from ._http import HttpClient, check_idempotency_key, normalise
11
+ from .types import BillReceipt, EventsResult, IdentifyResult, KeyInfo, LookupResult, PointsBalance
12
+
13
+ MAX_EVENTS_PER_BATCH = 100 # x-limits.maxEventsPerBatch
14
+ MAX_BODY_BYTES = 65536 # x-limits.maxBodyBytes
15
+
16
+ Money = Union[str, Decimal]
17
+
18
+
19
+ def _id(value: str, what: str) -> str:
20
+ if not isinstance(value, str) or not value.strip():
21
+ raise ValueError(f"{what} must be a non-empty string")
22
+ if value.strip(".") == "":
23
+ raise ValueError(f"{what} is not valid")
24
+ return quote(value, safe="")
25
+
26
+
27
+ class Key:
28
+ def __init__(self, http: HttpClient) -> None:
29
+ self._http = http
30
+
31
+ def retrieve(self) -> KeyInfo:
32
+ """GET /v1/key: which account and mode the key is for, its permissions and stores. A good first call."""
33
+ return self._http.request("GET", "/v1/key") # type: ignore[no-any-return]
34
+
35
+
36
+ class Events:
37
+ def __init__(self, http: HttpClient) -> None:
38
+ self._http = http
39
+
40
+ def send(self, events: Iterable[Mapping[str, Any]]) -> EventsResult:
41
+ """POST /v1/events. Sent in batches of at most 100 events and 64 KiB, in order; the counts are summed.
42
+
43
+ Give each event an ``id`` so a resend is counted once: this call is not retried after a lost answer.
44
+ If a batch fails, the earlier batches were already accepted and the error is raised.
45
+ """
46
+ items = [normalise(e, strict_money=False, path="event") for e in events]
47
+ if not items:
48
+ raise ValueError("events must not be empty")
49
+ batches: List[List[Any]] = []
50
+ current: List[Any] = []
51
+ size = len('{"events":[]}')
52
+ for item in items:
53
+ n = len(json.dumps(item, separators=(",", ":"), allow_nan=False).encode("utf-8")) + 1
54
+ if n + len('{"events":[]}') > MAX_BODY_BYTES:
55
+ raise ValueError(f"one event is larger than {MAX_BODY_BYTES} bytes")
56
+ if current and (len(current) >= MAX_EVENTS_PER_BATCH or size + n > MAX_BODY_BYTES):
57
+ batches.append(current)
58
+ current, size = [], len('{"events":[]}')
59
+ current.append(item)
60
+ size += n
61
+ batches.append(current)
62
+ total: Dict[str, Any] = {"accepted": 0, "duplicates": 0, "rejected": [], "dropped_properties": [], "batches": 0}
63
+ for batch in batches:
64
+ res = self._http.request("POST", "/v1/events", body={"events": batch})
65
+ total["accepted"] += int(res.get("accepted", 0))
66
+ total["duplicates"] += int(res.get("duplicates", 0))
67
+ total["rejected"].extend(res.get("rejected", []))
68
+ total["dropped_properties"].extend(res.get("dropped_properties", []))
69
+ total["batches"] += 1
70
+ return total # type: ignore[return-value]
71
+
72
+
73
+ class Visitors:
74
+ def __init__(self, http: HttpClient) -> None:
75
+ self._http = http
76
+
77
+ def identify(
78
+ self,
79
+ anonymous_id: str,
80
+ *,
81
+ phone: Optional[str] = None,
82
+ email: Optional[str] = None,
83
+ external_id: Optional[str] = None,
84
+ ) -> IdentifyResult:
85
+ """POST /v1/identify: link a visitor's earlier events to the customer (phone, email or your external_id)."""
86
+ if not anonymous_id:
87
+ raise ValueError("anonymous_id is required")
88
+ body: Dict[str, Any] = {"anonymous_id": anonymous_id}
89
+ for k, v in (("phone", phone), ("email", email), ("external_id", external_id)):
90
+ if v is not None:
91
+ body[k] = v
92
+ return self._http.request("POST", "/v1/identify", body=body) # type: ignore[no-any-return]
93
+
94
+
95
+ class Customers:
96
+ def __init__(self, http: HttpClient) -> None:
97
+ self._http = http
98
+
99
+ def lookup(
100
+ self,
101
+ *,
102
+ phone: Optional[str] = None,
103
+ email: Optional[str] = None,
104
+ external_id: Optional[str] = None,
105
+ ) -> LookupResult:
106
+ """GET /v1/customers/lookup by exactly one of phone, email or external_id."""
107
+ given = {k: v for k, v in (("phone", phone), ("email", email), ("external_id", external_id)) if v is not None}
108
+ if len(given) != 1:
109
+ raise ValueError("give exactly one of phone, email or external_id")
110
+ return self._http.request("GET", "/v1/customers/lookup", query=given) # type: ignore[no-any-return]
111
+
112
+ def retrieve(self, customer_id: str) -> Dict[str, Any]:
113
+ """GET /v1/customers/{id}."""
114
+ return self._http.request("GET", f"/v1/customers/{_id(customer_id, 'customer_id')}") # type: ignore[no-any-return]
115
+
116
+ def points(self, customer_id: str) -> PointsBalance:
117
+ """GET /v1/customers/{id}/points."""
118
+ return self._http.request("GET", f"/v1/customers/{_id(customer_id, 'customer_id')}/points") # type: ignore[no-any-return]
119
+
120
+
121
+ class Bills:
122
+ def __init__(self, http: HttpClient) -> None:
123
+ self._http = http
124
+
125
+ def preview(self, body: Mapping[str, Any]) -> Dict[str, Any]:
126
+ """POST /v1/bills/preview: what a bill would earn and cost, without recording it. Amounts: str or Decimal."""
127
+ return self._http.request("POST", "/v1/bills/preview", body=body, strict_money=True) # type: ignore[no-any-return]
128
+
129
+ def create(self, body: Mapping[str, Any], idempotency_key: Optional[str] = None) -> BillReceipt:
130
+ """POST /v1/bills. A UUID Idempotency-Key is made when you give none, and reused on every retry.
131
+
132
+ If it raises, the error's ``idempotency_key`` is the key used: pass it to a later attempt.
133
+ Amounts are decimal strings (or Decimal), never floats. The same ``bill_number`` again returns the first
134
+ receipt with ``replayed: true``.
135
+ """
136
+ key = check_idempotency_key(idempotency_key)
137
+ return self._http.request( # type: ignore[no-any-return]
138
+ "POST", "/v1/bills", body=body, idempotent=True, idempotency_key=key, strict_money=True
139
+ )
140
+
141
+
142
+ class Returns:
143
+ def __init__(self, http: HttpClient) -> None:
144
+ self._http = http
145
+
146
+ def create(self, body: Mapping[str, Any], idempotency_key: Optional[str] = None) -> Dict[str, Any]:
147
+ """POST /v1/returns. Same idempotency rules as ``bills.create``.
148
+
149
+ A return has no natural unique key, so after a raised error (connection, 5xx) retry with the SAME
150
+ ``idempotency_key`` (``error.idempotency_key``, or one derived from your return number), or it may record twice.
151
+ """
152
+ key = check_idempotency_key(idempotency_key)
153
+ return self._http.request( # type: ignore[no-any-return]
154
+ "POST", "/v1/returns", body=body, idempotent=True, idempotency_key=key, strict_money=True
155
+ )
@@ -0,0 +1,57 @@
1
+ """Typed shapes of the answers (for your editor; at run time everything is a plain dict)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List, TypedDict
6
+
7
+
8
+ class Account(TypedDict):
9
+ id: str
10
+ name: str
11
+
12
+
13
+ class KeyInfo(TypedDict, total=False):
14
+ key_id: str
15
+ mode: str # "live" or "test"
16
+ scopes: List[str]
17
+ account: Account
18
+ stores: List[str]
19
+
20
+
21
+ class EventsResult(TypedDict):
22
+ accepted: int
23
+ duplicates: int
24
+ rejected: List[Any]
25
+ dropped_properties: List[Any]
26
+ batches: int # how many requests the SDK made (events are sent 100 at a time)
27
+
28
+
29
+ class IdentifyResult(TypedDict, total=False):
30
+ status: str
31
+ earlier_events: int
32
+
33
+
34
+ class LookupResult(TypedDict, total=False):
35
+ found: bool
36
+ customer: Dict[str, Any]
37
+
38
+
39
+ class PointsBalance(TypedDict, total=False):
40
+ customer_id: str
41
+ balance: int
42
+ lifetime_earned: int
43
+ lifetime_redeemed: int
44
+ expiring_soon: int
45
+
46
+
47
+ class BillReceipt(TypedDict, total=False):
48
+ bill_id: str
49
+ bill_number: str
50
+ customer_id: str
51
+ replayed: bool
52
+ subtotal: str # money is always a decimal string
53
+ discount: str
54
+ payable: str
55
+ points_earned: int
56
+ points_spent: int
57
+ points_balance: int
@@ -0,0 +1,89 @@
1
+ """Verifying webhooks: ``Loyaltte-Signature: t=<unix time>,v1=<hex>[,v1=<hex>]``.
2
+
3
+ The signature is hex HMAC-SHA256, keyed with the signing secret (``whsec_...``), of ``"<t>."`` + the RAW body
4
+ exactly as received (bytes, before any JSON parsing).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import hmac
11
+ import json
12
+ import time
13
+ from typing import Any, Dict, Iterable, Optional, Tuple, Union
14
+
15
+ from .errors import WebhookSignatureError
16
+
17
+ Secrets = Union[str, Iterable[str]]
18
+ DEFAULT_TOLERANCE = 300
19
+
20
+
21
+ def _parse(header: str) -> Optional[Tuple[int, list[str]]]:
22
+ t: Optional[int] = None
23
+ sigs: list[str] = []
24
+ for piece in header.split(","):
25
+ key, sep, value = piece.strip().partition("=")
26
+ if not sep:
27
+ return None
28
+ if key == "t":
29
+ if t is not None or not (value.isascii() and value.isdigit()) or len(value) > 15:
30
+ return None # duplicate, non-numeric, signed, or absurd
31
+ t = int(value)
32
+ elif key == "v1":
33
+ sigs.append(value)
34
+ if t is None or not sigs:
35
+ return None
36
+ return t, sigs
37
+
38
+
39
+ def verify(
40
+ secret_or_secrets: Secrets,
41
+ header: Optional[str],
42
+ raw_body: Union[bytes, bytearray, str],
43
+ tolerance: int = DEFAULT_TOLERANCE,
44
+ now: Optional[int] = None,
45
+ ) -> bool:
46
+ """True only when a ``v1`` matches (constant time) and ``t`` is within ``tolerance`` seconds of now, both ways.
47
+
48
+ Pass several secrets (or, in the header, several ``v1``) during a rotation: any match is enough.
49
+ A malformed header is False, never an exception.
50
+ """
51
+ if not isinstance(header, str):
52
+ return False
53
+ secrets = [secret_or_secrets] if isinstance(secret_or_secrets, str) else list(secret_or_secrets)
54
+ secrets = [s for s in secrets if isinstance(s, str) and s]
55
+ if not secrets:
56
+ return False
57
+ parsed = _parse(header)
58
+ if parsed is None:
59
+ return False
60
+ t, sigs = parsed
61
+ current = int(time.time()) if now is None else now
62
+ if abs(current - t) > tolerance:
63
+ return False
64
+ body = raw_body.encode("utf-8") if isinstance(raw_body, str) else bytes(raw_body)
65
+ signed = f"{t}.".encode() + body
66
+ candidates = [s.encode("utf-8", "replace") for s in sigs]
67
+ matched = False
68
+ for secret in secrets: # no early exit: the work does not depend on which one matches
69
+ expected = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest().encode()
70
+ for candidate in candidates:
71
+ if hmac.compare_digest(expected, candidate):
72
+ matched = True
73
+ return matched
74
+
75
+
76
+ def construct_event(
77
+ secret_or_secrets: Secrets,
78
+ header: Optional[str],
79
+ raw_body: Union[bytes, bytearray, str],
80
+ tolerance: int = DEFAULT_TOLERANCE,
81
+ now: Optional[int] = None,
82
+ ) -> Dict[str, Any]:
83
+ """Verify, then return the decoded event. Raises :class:`WebhookSignatureError` when verification fails."""
84
+ if not verify(secret_or_secrets, header, raw_body, tolerance, now):
85
+ raise WebhookSignatureError("Webhook signature verification failed.", code="INVALID_SIGNATURE")
86
+ event = json.loads(raw_body)
87
+ if not isinstance(event, dict):
88
+ raise WebhookSignatureError("Webhook body is not a JSON object.", code="INVALID_PAYLOAD")
89
+ return event