leverprice 0.3.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.
- leverprice-0.3.0/.gitignore +11 -0
- leverprice-0.3.0/CHANGELOG.md +19 -0
- leverprice-0.3.0/LICENSE +21 -0
- leverprice-0.3.0/PKG-INFO +282 -0
- leverprice-0.3.0/README.md +244 -0
- leverprice-0.3.0/conformance/README.md +12 -0
- leverprice-0.3.0/pyproject.toml +90 -0
- leverprice-0.3.0/src/leverprice/__init__.py +32 -0
- leverprice-0.3.0/src/leverprice/_bots.py +113 -0
- leverprice-0.3.0/src/leverprice/_client.py +1280 -0
- leverprice-0.3.0/src/leverprice/_cookie.py +93 -0
- leverprice-0.3.0/src/leverprice/_crypto.py +62 -0
- leverprice-0.3.0/src/leverprice/_ed25519.py +114 -0
- leverprice-0.3.0/src/leverprice/_request.py +171 -0
- leverprice-0.3.0/src/leverprice/_responses.py +36 -0
- leverprice-0.3.0/src/leverprice/_transport.py +63 -0
- leverprice-0.3.0/src/leverprice/_trust.py +158 -0
- leverprice-0.3.0/src/leverprice/_util.py +161 -0
- leverprice-0.3.0/src/leverprice/_version.py +2 -0
- leverprice-0.3.0/src/leverprice/_wire.py +239 -0
- leverprice-0.3.0/src/leverprice/py.typed +0 -0
- leverprice-0.3.0/tests/_support.py +289 -0
- leverprice-0.3.0/tests/conftest.py +47 -0
- leverprice-0.3.0/tests/test_async.py +88 -0
- leverprice-0.3.0/tests/test_client.py +786 -0
- leverprice-0.3.0/tests/test_conformance.py +179 -0
- leverprice-0.3.0/tests/test_ed25519.py +96 -0
- leverprice-0.3.0/tests/test_fork.py +72 -0
- leverprice-0.3.0/tests/test_requests.py +208 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
|
|
4
|
+
|
|
5
|
+
## [0.3.0] - 2026-11-17
|
|
6
|
+
|
|
7
|
+
First release of the Python SDK, implementing protocol v2 of the Leverprice server SDK specification.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `Leverprice` client with `get_price`, `log_exposure`, `track_purchase`, `track_refund`, `flush`, `refresh`, `preload` and `close`, plus `_async` variants for asyncio.
|
|
12
|
+
- Signed config trust chain (root → keyset → config) with key revocation, rollback protection and expiry.
|
|
13
|
+
- Ed25519 verification through `cryptography` when installed, with a bundled pure-Python RFC 8032 verifier as fallback.
|
|
14
|
+
- Request adapters for Django, Flask/Werkzeug, Starlette/FastAPI, aiohttp, WSGI environ, ASGI scope and plain header maps.
|
|
15
|
+
- `apply_cookies` helper for Django, Flask/Werkzeug, Starlette/FastAPI and aiohttp responses.
|
|
16
|
+
- Kill switch through `disabled=True` or `LEVERPRICE_DISABLED`.
|
|
17
|
+
- Fork safety for pre-forking servers.
|
|
18
|
+
|
|
19
|
+
[0.3.0]: https://github.com/leverprice/leverprice-python/releases/tag/v0.3.0
|
leverprice-0.3.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Leverprice
|
|
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,282 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: leverprice
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Server-side SDK for Leverprice price experiments
|
|
5
|
+
Project-URL: Homepage, https://leverprice.com
|
|
6
|
+
Project-URL: Documentation, https://leverprice.com/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/leverprice/leverprice-python
|
|
8
|
+
Project-URL: Issues, https://github.com/leverprice/leverprice-python/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/leverprice/leverprice-python/blob/main/CHANGELOG.md
|
|
10
|
+
Author-email: Leverprice <support@leverprice.com>
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: ab-testing,checkout,django,fastapi,flask,leverprice,price-experiments,pricing,saas,stripe
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Framework :: AsyncIO
|
|
16
|
+
Classifier: Framework :: Django
|
|
17
|
+
Classifier: Framework :: FastAPI
|
|
18
|
+
Classifier: Framework :: Flask
|
|
19
|
+
Classifier: Intended Audience :: Developers
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Classifier: Programming Language :: Python
|
|
22
|
+
Classifier: Programming Language :: Python :: 3
|
|
23
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
27
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
28
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
29
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
30
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
|
31
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
32
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
33
|
+
Classifier: Typing :: Typed
|
|
34
|
+
Requires-Python: >=3.9
|
|
35
|
+
Provides-Extra: crypto
|
|
36
|
+
Requires-Dist: cryptography>=3.4; extra == 'crypto'
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
# Leverprice Python SDK
|
|
40
|
+
|
|
41
|
+
[](https://pypi.org/project/leverprice/)
|
|
42
|
+
[](https://github.com/leverprice/leverprice-python/actions/workflows/ci.yml)
|
|
43
|
+
[](https://pypi.org/project/leverprice/)
|
|
44
|
+
|
|
45
|
+
Server-side SDK for [Leverprice](https://leverprice.com) price experiments. No required dependencies, Python 3.9+, works with Django, Flask, FastAPI, Starlette, aiohttp and plain WSGI/ASGI.
|
|
46
|
+
|
|
47
|
+
**Your payments stay yours.** The SDK gives your server a number. Your own code creates the checkout with your own provider keys. Leverprice never sees card data or provider API keys.
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
pip install leverprice
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Signature checks use [`cryptography`](https://pypi.org/project/cryptography/) when it is installed and a bundled pure-Python verifier otherwise. To install it alongside: `pip install "leverprice[crypto]"`.
|
|
56
|
+
|
|
57
|
+
## Quick start
|
|
58
|
+
|
|
59
|
+
Create one client per process (for example in `settings.py` or `app.py`) and share it:
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
import os
|
|
63
|
+
from leverprice import Leverprice
|
|
64
|
+
|
|
65
|
+
leverprice = Leverprice(
|
|
66
|
+
secret_key=os.environ.get("LEVERPRICE_SECRET_KEY"), # server-only
|
|
67
|
+
products={
|
|
68
|
+
# Local guardrails: prices outside these bounds are never returned.
|
|
69
|
+
"pro": {"currency": "usd", "fallback_price": 1900, "min_price": 1500, "max_price": 3900},
|
|
70
|
+
},
|
|
71
|
+
)
|
|
72
|
+
leverprice.preload() # optional: fetch the config at startup instead of on the first request
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### 1. Show the price
|
|
76
|
+
|
|
77
|
+
`get_price` reads the visitor's cookie and user agent from the request. Append `quote.set_cookie` to your response; `apply_cookies` does it for the common frameworks.
|
|
78
|
+
|
|
79
|
+
**Django**
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from django.shortcuts import render
|
|
83
|
+
from leverprice import apply_cookies
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def pricing(request):
|
|
87
|
+
user_id = request.user.pk if request.user.is_authenticated else None
|
|
88
|
+
quote = leverprice.get_price("pro", request, user_id=user_id)
|
|
89
|
+
return apply_cookies(render(request, "pricing.html", {"quote": quote}), quote)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
**Flask**
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from flask import make_response, render_template, request
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@app.get("/pricing")
|
|
99
|
+
def pricing():
|
|
100
|
+
quote = leverprice.get_price("pro", request)
|
|
101
|
+
response = make_response(render_template("pricing.html", quote=quote))
|
|
102
|
+
for cookie in quote.set_cookie:
|
|
103
|
+
response.headers.add("Set-Cookie", cookie)
|
|
104
|
+
return response
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
**FastAPI**
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
from fastapi import FastAPI, Request, Response
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@app.get("/pricing")
|
|
114
|
+
async def pricing(request: Request, response: Response):
|
|
115
|
+
quote = await leverprice.get_price_async("pro", request)
|
|
116
|
+
for cookie in quote.set_cookie:
|
|
117
|
+
response.headers.append("set-cookie", cookie)
|
|
118
|
+
return {"price": quote.price, "currency": quote.currency}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### 2. Create the checkout
|
|
122
|
+
|
|
123
|
+
Price the checkout on the server again. Never trust a price sent by the browser.
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
import stripe
|
|
127
|
+
|
|
128
|
+
quote = leverprice.get_price("pro", request)
|
|
129
|
+
session = stripe.checkout.Session.create(
|
|
130
|
+
mode="payment",
|
|
131
|
+
line_items=[
|
|
132
|
+
{
|
|
133
|
+
"quantity": 1,
|
|
134
|
+
"price_data": {"currency": quote.currency, "unit_amount": quote.price, "product_data": {"name": "Pro"}},
|
|
135
|
+
}
|
|
136
|
+
],
|
|
137
|
+
metadata=quote.metadata, # signed attribution: pass it whole
|
|
138
|
+
payment_intent_data={"metadata": quote.metadata},
|
|
139
|
+
success_url=success_url,
|
|
140
|
+
cancel_url=cancel_url,
|
|
141
|
+
)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### 3. Report the purchase
|
|
145
|
+
|
|
146
|
+
In your webhook handler (or connect your provider's webhooks to Leverprice directly):
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
event = stripe.Webhook.construct_event(payload, signature_header, endpoint_secret)
|
|
150
|
+
if event["type"] == "checkout.session.completed":
|
|
151
|
+
session = event["data"]["object"]
|
|
152
|
+
leverprice.track_purchase(
|
|
153
|
+
provider="stripe",
|
|
154
|
+
order_id=session["payment_intent"],
|
|
155
|
+
amount=session["amount_total"] - (session["total_details"] or {}).get("amount_tax", 0),
|
|
156
|
+
currency=session["currency"],
|
|
157
|
+
metadata=session["metadata"],
|
|
158
|
+
timestamp=event["created"], # Unix seconds are detected
|
|
159
|
+
)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Refunds: `track_refund(provider=..., order_id=..., currency=..., refund_id=..., amount=...)`, or `refunded_total=...` for the order's cumulative refunded amount.
|
|
163
|
+
|
|
164
|
+
## Guarantees
|
|
165
|
+
|
|
166
|
+
- **Fails safe.** If Leverprice is off, slow (no config within 500 ms), down, misconfigured or returns anything unexpected, `get_price` returns your `fallback_price`. It never raises for those reasons.
|
|
167
|
+
- **Verified config.** Root key → keyset → config signature chain, version-monotonic (no rollback, no revoked keys), time-limited.
|
|
168
|
+
- **Bounded.** Every price is checked against your local `min_price`, `max_price` and `currency`.
|
|
169
|
+
- **Sticky and tamper-proof.** Visitors keep their price. The assignment cookie is HMAC-signed with your project's assignment key, so rotating your API key does not reshuffle visitors.
|
|
170
|
+
- **Private.** Visitor and user ids are HMAC-hashed on your server; Leverprice only sees the hash.
|
|
171
|
+
- **No price flips.** A visitor who got the fallback during an outage keeps it for the rest of their session.
|
|
172
|
+
- **Search engines see the standard price.** Crawlers and link previews are never put into experiments.
|
|
173
|
+
- **Never blocks your process.** Background work runs on daemon threads; the async API never blocks the event loop.
|
|
174
|
+
|
|
175
|
+
## Requests and cookies
|
|
176
|
+
|
|
177
|
+
Pass the framework's request object: Django `HttpRequest`, Flask/Werkzeug `request`, Starlette/FastAPI `Request`, aiohttp `Request`, a WSGI `environ`, an ASGI scope, any object with a `headers` mapping, or a plain dict of headers. Header names are case-insensitive. `cookie=` and `user_agent=` override what is read from the request.
|
|
178
|
+
|
|
179
|
+
`quote.set_cookie` is a **list** of `Set-Cookie` header values: usually empty, one value when the assignment cookie (`__pp`) changes, or the outage pin (`__pp_f`). Append every value. `apply_cookies(response, quote)` supports Django, Flask/Werkzeug, Starlette/FastAPI and aiohttp responses and WSGI header lists. Django has no API for raw `Set-Cookie` values, so there it loads them into `response.cookies`.
|
|
180
|
+
|
|
181
|
+
Pricing several products for one page? Pass the **same request object** to each `get_price` call: the quotes share one visitor, and the last quote's cookie carries every assignment. Plain header dicts are not shared; pass the request itself.
|
|
182
|
+
|
|
183
|
+
## Exposures
|
|
184
|
+
|
|
185
|
+
An exposure is one person seeing an experiment price. With `exposure="auto"` (default) the SDK logs it the first time a visitor gets a price from an experiment, once per visitor and experiment. Prefetch and prerender requests (`Sec-Purpose`, `Purpose`, `X-Purpose`, `X-Moz`, `Next-Router-Prefetch`) are priced but not counted.
|
|
186
|
+
|
|
187
|
+
If you compute the price before it is visible, use manual mode:
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
quote = leverprice.get_price("pro", request, exposure="manual")
|
|
191
|
+
# later, when the price is on screen:
|
|
192
|
+
leverprice.log_exposure(quote)
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Exposures are sent in the background within `flush_interval_ms` (2 s). Call `flush()` before a short-lived process exits; long-lived servers need nothing.
|
|
196
|
+
|
|
197
|
+
## Bots
|
|
198
|
+
|
|
199
|
+
Crawlers, link previewers, headless browsers, uptime monitors and command-line clients get the product's standard price (or your fallback if no config is available) with reason `"bot"`: no assignment, no cookie, no exposure. An empty user agent counts as a person. Pass `bot=True` or `bot=False` to use your own detection; the built-in check is `leverprice.is_bot(user_agent)`.
|
|
200
|
+
|
|
201
|
+
## Kill switch
|
|
202
|
+
|
|
203
|
+
Set `LEVERPRICE_DISABLED=1` (or `true`) in the environment, or pass `disabled=True`. It is read on every call: `get_price` returns your fallback price with reason `"disabled"`, sets no cookies, makes no network calls and logs nothing; tracking calls do nothing. A missing or malformed `secret_key` behaves the same way (a malformed key is reported once through `on_error`).
|
|
204
|
+
|
|
205
|
+
## Outages
|
|
206
|
+
|
|
207
|
+
When no usable config is available (reason `"no_config"`), the quote also sets `__pp_f=1` for 30 minutes. While a browser sends it, it gets the fallback price with reason `"pinned_fallback"` and is not enrolled; each pinned request extends it, so the price changes only after 30 minutes of inactivity. Purchases and refunds that cannot be delivered are kept and retried on the next flush.
|
|
208
|
+
|
|
209
|
+
## Trust chain and updates
|
|
210
|
+
|
|
211
|
+
The SDK embeds only Leverprice's offline root public keys (`ROOT_PUBLIC_KEYS`). Each config carries a keyset of online signing keys signed by a root key, and must be signed by one of those keys. Keyset versions only move forward within a process, so a revoked key cannot come back; `MIN_KEYSET_VERSION` sets the floor for fresh processes. Config versions only move forward, and configs expire. For local development pass `trusted_root_keys={"r1": "<dev root public key>"}`.
|
|
212
|
+
|
|
213
|
+
The config is revalidated every 30 s with an ETag. When any Leverprice response announces a newer version in `Leverprice-Config-Version`, the SDK fetches it right away.
|
|
214
|
+
|
|
215
|
+
## Threads, asyncio and forking servers
|
|
216
|
+
|
|
217
|
+
The client is thread-safe. Every method has an `_async` variant for asyncio apps (`get_price_async`, `track_purchase_async`, `track_refund_async`, `flush_async`, `refresh_async`, `preload_async`, `close_async`). The client works under pre-forking servers (gunicorn, uWSGI): a child process starts with fresh threads, locks and an empty event queue. It also works as a context manager (`with` / `async with`), which flushes on exit.
|
|
218
|
+
|
|
219
|
+
## Reference
|
|
220
|
+
|
|
221
|
+
`get_price(product_key, request=None, *, cookie=None, user_agent=None, user_id=None, exposure="auto", bot=None) -> Quote`. Raises `UnknownProductError` only if `product_key` is missing from `products`.
|
|
222
|
+
|
|
223
|
+
| Quote field | |
|
|
224
|
+
|---|---|
|
|
225
|
+
| `product_key` | The key you asked for |
|
|
226
|
+
| `price` | Minor units; use it for display and as the checkout amount |
|
|
227
|
+
| `currency` | Lowercase ISO 4217, from your product guard |
|
|
228
|
+
| `is_fallback` | `True` when `price` is your `fallback_price` |
|
|
229
|
+
| `reason` | See below |
|
|
230
|
+
| `experiment_id`, `variant_id` | Set when `reason` is `"experiment"`, else `None` |
|
|
231
|
+
| `visitor_id` | Hashed visitor id Leverprice sees; `None` unless `reason` is `"experiment"` |
|
|
232
|
+
| `metadata` | `{pp_exp, pp_var, pp_vid, pp_sig}` for the checkout (signed); `{}` otherwise |
|
|
233
|
+
| `set_cookie` | `Set-Cookie` values to append (zero or more) |
|
|
234
|
+
| `checkout_url` | Hosted checkout link for this price, or `None` |
|
|
235
|
+
| `exposure_logged` | An exposure for this visitor and experiment has been logged |
|
|
236
|
+
|
|
237
|
+
| `reason` | Price |
|
|
238
|
+
|---|---|
|
|
239
|
+
| `experiment` | The visitor's sticky variant |
|
|
240
|
+
| `base_price` | Standard price (no experiment running) |
|
|
241
|
+
| `bot` | Standard price, or fallback if unavailable; never enrolled |
|
|
242
|
+
| `disabled` | Fallback: kill switch, or no valid secret key |
|
|
243
|
+
| `no_config` | Fallback: no usable signed config (timeout, outage, rejected or expired); sets the pin |
|
|
244
|
+
| `pinned_fallback` | Fallback: this browser got a fallback during an outage in this session |
|
|
245
|
+
| `unknown_product` | Fallback: the config has no such product |
|
|
246
|
+
| `currency_mismatch` | Fallback: the config's currency differs from your guard |
|
|
247
|
+
| `out_of_bounds` | Fallback: a price is outside your (or Leverprice's) min/max |
|
|
248
|
+
|
|
249
|
+
| Method | |
|
|
250
|
+
|---|---|
|
|
251
|
+
| `log_exposure(quote)` | Logs a manual-mode exposure; returns `True` if one was queued |
|
|
252
|
+
| `track_purchase(*, provider, order_id, amount, currency, metadata=None, timestamp=None)` | Reads `pp_exp`, `pp_var`, `pp_vid`, `pp_sig` from `metadata`; sends right away |
|
|
253
|
+
| `track_refund(*, provider, order_id, currency, refund_id=None, amount=None, refunded_total=None, timestamp=None)` | Sends right away |
|
|
254
|
+
| `flush()` | Sends queued events and waits (at most 500 per request; purchases and refunds are kept on failure) |
|
|
255
|
+
| `refresh()` / `preload()` | Fetch the config now / only if none is usable |
|
|
256
|
+
| `close()` | Flushes and stops the flush timer |
|
|
257
|
+
|
|
258
|
+
Providers: `stripe`, `polar`, `lemonsqueezy`, `dodo`, `other`. Timestamps are milliseconds, Unix seconds or a `datetime`. None of these methods raise.
|
|
259
|
+
|
|
260
|
+
| Option | Default | |
|
|
261
|
+
|---|---|---|
|
|
262
|
+
| `secret_key` | required | `pp_sk_live_…` or `pp_sk_test_…` |
|
|
263
|
+
| `products` | required | Product key → `{currency, fallback_price, min_price?, max_price?}` or `ProductGuard` |
|
|
264
|
+
| `disabled` | `False` | Kill switch |
|
|
265
|
+
| `api_url` | `https://api.leverprice.com` | |
|
|
266
|
+
| `timeout_ms` | `500` | Longest wait for a config when none is usable |
|
|
267
|
+
| `refresh_interval_ms` | `30000` | Config revalidation period |
|
|
268
|
+
| `max_stale_ms` | `86400000` | Stop using a config this long after the server last confirmed it |
|
|
269
|
+
| `cookie_name` | `"__pp"` | The outage pin is `<cookie_name>_f` |
|
|
270
|
+
| `cookie_max_age_seconds` | `15552000` | 180 days |
|
|
271
|
+
| `cookie_secure` | `True` | Set `False` only for plain-HTTP development |
|
|
272
|
+
| `cookie_domain` | `None` | |
|
|
273
|
+
| `flush_interval_ms` | `2000` | Longest time exposures wait before being sent |
|
|
274
|
+
| `trusted_root_keys` | `ROOT_PUBLIC_KEYS` | For staging and local development |
|
|
275
|
+
| `transport` | `UrllibTransport()` | Any object with `request(method, url, headers, body, timeout)` |
|
|
276
|
+
| `on_error` | log a warning | Receives every SDK error; exceptions it raises are ignored |
|
|
277
|
+
|
|
278
|
+
Errors are logged on the `leverprice` logger when no `on_error` is given.
|
|
279
|
+
|
|
280
|
+
## License
|
|
281
|
+
|
|
282
|
+
MIT
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
# Leverprice Python SDK
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/leverprice/)
|
|
4
|
+
[](https://github.com/leverprice/leverprice-python/actions/workflows/ci.yml)
|
|
5
|
+
[](https://pypi.org/project/leverprice/)
|
|
6
|
+
|
|
7
|
+
Server-side SDK for [Leverprice](https://leverprice.com) price experiments. No required dependencies, Python 3.9+, works with Django, Flask, FastAPI, Starlette, aiohttp and plain WSGI/ASGI.
|
|
8
|
+
|
|
9
|
+
**Your payments stay yours.** The SDK gives your server a number. Your own code creates the checkout with your own provider keys. Leverprice never sees card data or provider API keys.
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
pip install leverprice
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Signature checks use [`cryptography`](https://pypi.org/project/cryptography/) when it is installed and a bundled pure-Python verifier otherwise. To install it alongside: `pip install "leverprice[crypto]"`.
|
|
18
|
+
|
|
19
|
+
## Quick start
|
|
20
|
+
|
|
21
|
+
Create one client per process (for example in `settings.py` or `app.py`) and share it:
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import os
|
|
25
|
+
from leverprice import Leverprice
|
|
26
|
+
|
|
27
|
+
leverprice = Leverprice(
|
|
28
|
+
secret_key=os.environ.get("LEVERPRICE_SECRET_KEY"), # server-only
|
|
29
|
+
products={
|
|
30
|
+
# Local guardrails: prices outside these bounds are never returned.
|
|
31
|
+
"pro": {"currency": "usd", "fallback_price": 1900, "min_price": 1500, "max_price": 3900},
|
|
32
|
+
},
|
|
33
|
+
)
|
|
34
|
+
leverprice.preload() # optional: fetch the config at startup instead of on the first request
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### 1. Show the price
|
|
38
|
+
|
|
39
|
+
`get_price` reads the visitor's cookie and user agent from the request. Append `quote.set_cookie` to your response; `apply_cookies` does it for the common frameworks.
|
|
40
|
+
|
|
41
|
+
**Django**
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from django.shortcuts import render
|
|
45
|
+
from leverprice import apply_cookies
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def pricing(request):
|
|
49
|
+
user_id = request.user.pk if request.user.is_authenticated else None
|
|
50
|
+
quote = leverprice.get_price("pro", request, user_id=user_id)
|
|
51
|
+
return apply_cookies(render(request, "pricing.html", {"quote": quote}), quote)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
**Flask**
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from flask import make_response, render_template, request
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@app.get("/pricing")
|
|
61
|
+
def pricing():
|
|
62
|
+
quote = leverprice.get_price("pro", request)
|
|
63
|
+
response = make_response(render_template("pricing.html", quote=quote))
|
|
64
|
+
for cookie in quote.set_cookie:
|
|
65
|
+
response.headers.add("Set-Cookie", cookie)
|
|
66
|
+
return response
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
**FastAPI**
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from fastapi import FastAPI, Request, Response
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@app.get("/pricing")
|
|
76
|
+
async def pricing(request: Request, response: Response):
|
|
77
|
+
quote = await leverprice.get_price_async("pro", request)
|
|
78
|
+
for cookie in quote.set_cookie:
|
|
79
|
+
response.headers.append("set-cookie", cookie)
|
|
80
|
+
return {"price": quote.price, "currency": quote.currency}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### 2. Create the checkout
|
|
84
|
+
|
|
85
|
+
Price the checkout on the server again. Never trust a price sent by the browser.
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
import stripe
|
|
89
|
+
|
|
90
|
+
quote = leverprice.get_price("pro", request)
|
|
91
|
+
session = stripe.checkout.Session.create(
|
|
92
|
+
mode="payment",
|
|
93
|
+
line_items=[
|
|
94
|
+
{
|
|
95
|
+
"quantity": 1,
|
|
96
|
+
"price_data": {"currency": quote.currency, "unit_amount": quote.price, "product_data": {"name": "Pro"}},
|
|
97
|
+
}
|
|
98
|
+
],
|
|
99
|
+
metadata=quote.metadata, # signed attribution: pass it whole
|
|
100
|
+
payment_intent_data={"metadata": quote.metadata},
|
|
101
|
+
success_url=success_url,
|
|
102
|
+
cancel_url=cancel_url,
|
|
103
|
+
)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### 3. Report the purchase
|
|
107
|
+
|
|
108
|
+
In your webhook handler (or connect your provider's webhooks to Leverprice directly):
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
event = stripe.Webhook.construct_event(payload, signature_header, endpoint_secret)
|
|
112
|
+
if event["type"] == "checkout.session.completed":
|
|
113
|
+
session = event["data"]["object"]
|
|
114
|
+
leverprice.track_purchase(
|
|
115
|
+
provider="stripe",
|
|
116
|
+
order_id=session["payment_intent"],
|
|
117
|
+
amount=session["amount_total"] - (session["total_details"] or {}).get("amount_tax", 0),
|
|
118
|
+
currency=session["currency"],
|
|
119
|
+
metadata=session["metadata"],
|
|
120
|
+
timestamp=event["created"], # Unix seconds are detected
|
|
121
|
+
)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Refunds: `track_refund(provider=..., order_id=..., currency=..., refund_id=..., amount=...)`, or `refunded_total=...` for the order's cumulative refunded amount.
|
|
125
|
+
|
|
126
|
+
## Guarantees
|
|
127
|
+
|
|
128
|
+
- **Fails safe.** If Leverprice is off, slow (no config within 500 ms), down, misconfigured or returns anything unexpected, `get_price` returns your `fallback_price`. It never raises for those reasons.
|
|
129
|
+
- **Verified config.** Root key → keyset → config signature chain, version-monotonic (no rollback, no revoked keys), time-limited.
|
|
130
|
+
- **Bounded.** Every price is checked against your local `min_price`, `max_price` and `currency`.
|
|
131
|
+
- **Sticky and tamper-proof.** Visitors keep their price. The assignment cookie is HMAC-signed with your project's assignment key, so rotating your API key does not reshuffle visitors.
|
|
132
|
+
- **Private.** Visitor and user ids are HMAC-hashed on your server; Leverprice only sees the hash.
|
|
133
|
+
- **No price flips.** A visitor who got the fallback during an outage keeps it for the rest of their session.
|
|
134
|
+
- **Search engines see the standard price.** Crawlers and link previews are never put into experiments.
|
|
135
|
+
- **Never blocks your process.** Background work runs on daemon threads; the async API never blocks the event loop.
|
|
136
|
+
|
|
137
|
+
## Requests and cookies
|
|
138
|
+
|
|
139
|
+
Pass the framework's request object: Django `HttpRequest`, Flask/Werkzeug `request`, Starlette/FastAPI `Request`, aiohttp `Request`, a WSGI `environ`, an ASGI scope, any object with a `headers` mapping, or a plain dict of headers. Header names are case-insensitive. `cookie=` and `user_agent=` override what is read from the request.
|
|
140
|
+
|
|
141
|
+
`quote.set_cookie` is a **list** of `Set-Cookie` header values: usually empty, one value when the assignment cookie (`__pp`) changes, or the outage pin (`__pp_f`). Append every value. `apply_cookies(response, quote)` supports Django, Flask/Werkzeug, Starlette/FastAPI and aiohttp responses and WSGI header lists. Django has no API for raw `Set-Cookie` values, so there it loads them into `response.cookies`.
|
|
142
|
+
|
|
143
|
+
Pricing several products for one page? Pass the **same request object** to each `get_price` call: the quotes share one visitor, and the last quote's cookie carries every assignment. Plain header dicts are not shared; pass the request itself.
|
|
144
|
+
|
|
145
|
+
## Exposures
|
|
146
|
+
|
|
147
|
+
An exposure is one person seeing an experiment price. With `exposure="auto"` (default) the SDK logs it the first time a visitor gets a price from an experiment, once per visitor and experiment. Prefetch and prerender requests (`Sec-Purpose`, `Purpose`, `X-Purpose`, `X-Moz`, `Next-Router-Prefetch`) are priced but not counted.
|
|
148
|
+
|
|
149
|
+
If you compute the price before it is visible, use manual mode:
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
quote = leverprice.get_price("pro", request, exposure="manual")
|
|
153
|
+
# later, when the price is on screen:
|
|
154
|
+
leverprice.log_exposure(quote)
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Exposures are sent in the background within `flush_interval_ms` (2 s). Call `flush()` before a short-lived process exits; long-lived servers need nothing.
|
|
158
|
+
|
|
159
|
+
## Bots
|
|
160
|
+
|
|
161
|
+
Crawlers, link previewers, headless browsers, uptime monitors and command-line clients get the product's standard price (or your fallback if no config is available) with reason `"bot"`: no assignment, no cookie, no exposure. An empty user agent counts as a person. Pass `bot=True` or `bot=False` to use your own detection; the built-in check is `leverprice.is_bot(user_agent)`.
|
|
162
|
+
|
|
163
|
+
## Kill switch
|
|
164
|
+
|
|
165
|
+
Set `LEVERPRICE_DISABLED=1` (or `true`) in the environment, or pass `disabled=True`. It is read on every call: `get_price` returns your fallback price with reason `"disabled"`, sets no cookies, makes no network calls and logs nothing; tracking calls do nothing. A missing or malformed `secret_key` behaves the same way (a malformed key is reported once through `on_error`).
|
|
166
|
+
|
|
167
|
+
## Outages
|
|
168
|
+
|
|
169
|
+
When no usable config is available (reason `"no_config"`), the quote also sets `__pp_f=1` for 30 minutes. While a browser sends it, it gets the fallback price with reason `"pinned_fallback"` and is not enrolled; each pinned request extends it, so the price changes only after 30 minutes of inactivity. Purchases and refunds that cannot be delivered are kept and retried on the next flush.
|
|
170
|
+
|
|
171
|
+
## Trust chain and updates
|
|
172
|
+
|
|
173
|
+
The SDK embeds only Leverprice's offline root public keys (`ROOT_PUBLIC_KEYS`). Each config carries a keyset of online signing keys signed by a root key, and must be signed by one of those keys. Keyset versions only move forward within a process, so a revoked key cannot come back; `MIN_KEYSET_VERSION` sets the floor for fresh processes. Config versions only move forward, and configs expire. For local development pass `trusted_root_keys={"r1": "<dev root public key>"}`.
|
|
174
|
+
|
|
175
|
+
The config is revalidated every 30 s with an ETag. When any Leverprice response announces a newer version in `Leverprice-Config-Version`, the SDK fetches it right away.
|
|
176
|
+
|
|
177
|
+
## Threads, asyncio and forking servers
|
|
178
|
+
|
|
179
|
+
The client is thread-safe. Every method has an `_async` variant for asyncio apps (`get_price_async`, `track_purchase_async`, `track_refund_async`, `flush_async`, `refresh_async`, `preload_async`, `close_async`). The client works under pre-forking servers (gunicorn, uWSGI): a child process starts with fresh threads, locks and an empty event queue. It also works as a context manager (`with` / `async with`), which flushes on exit.
|
|
180
|
+
|
|
181
|
+
## Reference
|
|
182
|
+
|
|
183
|
+
`get_price(product_key, request=None, *, cookie=None, user_agent=None, user_id=None, exposure="auto", bot=None) -> Quote`. Raises `UnknownProductError` only if `product_key` is missing from `products`.
|
|
184
|
+
|
|
185
|
+
| Quote field | |
|
|
186
|
+
|---|---|
|
|
187
|
+
| `product_key` | The key you asked for |
|
|
188
|
+
| `price` | Minor units; use it for display and as the checkout amount |
|
|
189
|
+
| `currency` | Lowercase ISO 4217, from your product guard |
|
|
190
|
+
| `is_fallback` | `True` when `price` is your `fallback_price` |
|
|
191
|
+
| `reason` | See below |
|
|
192
|
+
| `experiment_id`, `variant_id` | Set when `reason` is `"experiment"`, else `None` |
|
|
193
|
+
| `visitor_id` | Hashed visitor id Leverprice sees; `None` unless `reason` is `"experiment"` |
|
|
194
|
+
| `metadata` | `{pp_exp, pp_var, pp_vid, pp_sig}` for the checkout (signed); `{}` otherwise |
|
|
195
|
+
| `set_cookie` | `Set-Cookie` values to append (zero or more) |
|
|
196
|
+
| `checkout_url` | Hosted checkout link for this price, or `None` |
|
|
197
|
+
| `exposure_logged` | An exposure for this visitor and experiment has been logged |
|
|
198
|
+
|
|
199
|
+
| `reason` | Price |
|
|
200
|
+
|---|---|
|
|
201
|
+
| `experiment` | The visitor's sticky variant |
|
|
202
|
+
| `base_price` | Standard price (no experiment running) |
|
|
203
|
+
| `bot` | Standard price, or fallback if unavailable; never enrolled |
|
|
204
|
+
| `disabled` | Fallback: kill switch, or no valid secret key |
|
|
205
|
+
| `no_config` | Fallback: no usable signed config (timeout, outage, rejected or expired); sets the pin |
|
|
206
|
+
| `pinned_fallback` | Fallback: this browser got a fallback during an outage in this session |
|
|
207
|
+
| `unknown_product` | Fallback: the config has no such product |
|
|
208
|
+
| `currency_mismatch` | Fallback: the config's currency differs from your guard |
|
|
209
|
+
| `out_of_bounds` | Fallback: a price is outside your (or Leverprice's) min/max |
|
|
210
|
+
|
|
211
|
+
| Method | |
|
|
212
|
+
|---|---|
|
|
213
|
+
| `log_exposure(quote)` | Logs a manual-mode exposure; returns `True` if one was queued |
|
|
214
|
+
| `track_purchase(*, provider, order_id, amount, currency, metadata=None, timestamp=None)` | Reads `pp_exp`, `pp_var`, `pp_vid`, `pp_sig` from `metadata`; sends right away |
|
|
215
|
+
| `track_refund(*, provider, order_id, currency, refund_id=None, amount=None, refunded_total=None, timestamp=None)` | Sends right away |
|
|
216
|
+
| `flush()` | Sends queued events and waits (at most 500 per request; purchases and refunds are kept on failure) |
|
|
217
|
+
| `refresh()` / `preload()` | Fetch the config now / only if none is usable |
|
|
218
|
+
| `close()` | Flushes and stops the flush timer |
|
|
219
|
+
|
|
220
|
+
Providers: `stripe`, `polar`, `lemonsqueezy`, `dodo`, `other`. Timestamps are milliseconds, Unix seconds or a `datetime`. None of these methods raise.
|
|
221
|
+
|
|
222
|
+
| Option | Default | |
|
|
223
|
+
|---|---|---|
|
|
224
|
+
| `secret_key` | required | `pp_sk_live_…` or `pp_sk_test_…` |
|
|
225
|
+
| `products` | required | Product key → `{currency, fallback_price, min_price?, max_price?}` or `ProductGuard` |
|
|
226
|
+
| `disabled` | `False` | Kill switch |
|
|
227
|
+
| `api_url` | `https://api.leverprice.com` | |
|
|
228
|
+
| `timeout_ms` | `500` | Longest wait for a config when none is usable |
|
|
229
|
+
| `refresh_interval_ms` | `30000` | Config revalidation period |
|
|
230
|
+
| `max_stale_ms` | `86400000` | Stop using a config this long after the server last confirmed it |
|
|
231
|
+
| `cookie_name` | `"__pp"` | The outage pin is `<cookie_name>_f` |
|
|
232
|
+
| `cookie_max_age_seconds` | `15552000` | 180 days |
|
|
233
|
+
| `cookie_secure` | `True` | Set `False` only for plain-HTTP development |
|
|
234
|
+
| `cookie_domain` | `None` | |
|
|
235
|
+
| `flush_interval_ms` | `2000` | Longest time exposures wait before being sent |
|
|
236
|
+
| `trusted_root_keys` | `ROOT_PUBLIC_KEYS` | For staging and local development |
|
|
237
|
+
| `transport` | `UrllibTransport()` | Any object with `request(method, url, headers, body, timeout)` |
|
|
238
|
+
| `on_error` | log a warning | Receives every SDK error; exceptions it raises are ignored |
|
|
239
|
+
|
|
240
|
+
Errors are logged on the `leverprice` logger when no `on_error` is given.
|
|
241
|
+
|
|
242
|
+
## License
|
|
243
|
+
|
|
244
|
+
MIT
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Leverprice SDK conformance vectors
|
|
2
|
+
|
|
3
|
+
`vectors.json` is generated from the Leverprice server's own signing and HMAC code and the
|
|
4
|
+
reference JavaScript SDK, with fixed test keys. Every Leverprice SDK (JavaScript, Python, PHP,
|
|
5
|
+
Ruby, Go) runs its test suite against this exact file, so they all verify configs, sign cookies,
|
|
6
|
+
hash visitors, bucket them, detect bots and validate events identically.
|
|
7
|
+
|
|
8
|
+
`SPEC.md` describes the protocol and the behaviour every SDK implements, and section 12 explains
|
|
9
|
+
each part of the vectors file. Want an SDK for another language? Implement the spec and pass the
|
|
10
|
+
vectors.
|
|
11
|
+
|
|
12
|
+
The keys in this file are test keys. Nothing here is secret.
|