blupay-sdk 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
blupay/__init__.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Server-side client for BluPay v1."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import http.client
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
import time
|
|
9
|
+
from urllib.parse import urlsplit
|
|
10
|
+
|
|
11
|
+
__all__ = ["BluPay", "BluPayError", "verify_webhook"]
|
|
12
|
+
|
|
13
|
+
_MAX_RESPONSE = 4 * 1024 * 1024
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class BluPayError(Exception):
|
|
17
|
+
def __init__(self, message, status=None, request_id=None):
|
|
18
|
+
super().__init__(message)
|
|
19
|
+
self.status = status
|
|
20
|
+
self.request_id = request_id
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _header(value):
|
|
24
|
+
if not isinstance(value, str) or not re.fullmatch(r"[\x21-\x7e]{1,255}", value):
|
|
25
|
+
raise ValueError("Expected a non-empty ASCII header value")
|
|
26
|
+
return value
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _invoice(link):
|
|
30
|
+
if not isinstance(link, str) or not re.fullmatch(r"[A-Za-z0-9_-]{12}", link):
|
|
31
|
+
raise ValueError("Invalid invoice link")
|
|
32
|
+
return f"/v1/invoices/{link}/"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class BluPay:
|
|
36
|
+
def __init__(self, api_key, base_url="https://blupay.me/api", timeout=10.0):
|
|
37
|
+
self._key = _header(api_key)
|
|
38
|
+
self._url = urlsplit(base_url)
|
|
39
|
+
loopback = self._url.hostname in ("127.0.0.1", "::1", "localhost")
|
|
40
|
+
if (not self._url.hostname or self._url.username is not None or self._url.password is not None
|
|
41
|
+
or self._url.query or self._url.fragment
|
|
42
|
+
or (self._url.scheme != "https" and not (loopback and self._url.scheme == "http"))):
|
|
43
|
+
raise ValueError("API base URL must use HTTPS (HTTP is allowed on loopback)")
|
|
44
|
+
if not math.isfinite(timeout) or not 0 < timeout <= 120:
|
|
45
|
+
raise ValueError("Timeout must be between 0 and 120 seconds")
|
|
46
|
+
self._timeout = timeout
|
|
47
|
+
|
|
48
|
+
def create_invoice(self, invoice, idempotency_key):
|
|
49
|
+
if not isinstance(invoice.get("currencyAmount"), str):
|
|
50
|
+
raise ValueError("currencyAmount must be a decimal string")
|
|
51
|
+
return self._request("POST", "/v1/invoices/", invoice, _header(idempotency_key))
|
|
52
|
+
|
|
53
|
+
def get_invoice(self, link):
|
|
54
|
+
return self._request("GET", _invoice(link))
|
|
55
|
+
|
|
56
|
+
def get_receipt(self, link):
|
|
57
|
+
return self._request("GET", _invoice(link) + "received/")
|
|
58
|
+
|
|
59
|
+
def get_checkout(self, link):
|
|
60
|
+
return self._request("GET", _invoice(link) + "checkout/")
|
|
61
|
+
|
|
62
|
+
def select_currency(self, link, currency_network_id):
|
|
63
|
+
if type(currency_network_id) is not int or not 1 <= currency_network_id <= 2_147_483_647:
|
|
64
|
+
raise ValueError("Invalid currencyNetworkId")
|
|
65
|
+
return self._request("POST", _invoice(link) + "checkout/select-currency/",
|
|
66
|
+
{"currencyNetworkId": currency_network_id})
|
|
67
|
+
|
|
68
|
+
def _request(self, method, path, body=None, key=None):
|
|
69
|
+
headers = {"X-API-Key": self._key, "Accept": "application/json"}
|
|
70
|
+
payload = None
|
|
71
|
+
if body is not None:
|
|
72
|
+
headers["Content-Type"] = "application/json"
|
|
73
|
+
payload = json.dumps(body, allow_nan=False, separators=(",", ":")).encode()
|
|
74
|
+
if key is not None:
|
|
75
|
+
headers["Idempotency-Key"] = key
|
|
76
|
+
transport = http.client.HTTPSConnection if self._url.scheme == "https" else http.client.HTTPConnection
|
|
77
|
+
connection = transport(self._url.hostname, self._url.port, timeout=self._timeout)
|
|
78
|
+
try:
|
|
79
|
+
connection.request(method, self._url.path.rstrip("/") + path, body=payload, headers=headers)
|
|
80
|
+
response = connection.getresponse()
|
|
81
|
+
status = response.status
|
|
82
|
+
request_id = response.getheader("X-Request-Id")
|
|
83
|
+
if not 200 <= status < 300:
|
|
84
|
+
raise BluPayError(f"BluPay returned HTTP {status}", status, request_id)
|
|
85
|
+
raw = response.read(_MAX_RESPONSE + 1)
|
|
86
|
+
except (OSError, http.client.HTTPException) as cause:
|
|
87
|
+
raise BluPayError("BluPay request failed or timed out") from cause
|
|
88
|
+
finally:
|
|
89
|
+
connection.close()
|
|
90
|
+
if len(raw) > _MAX_RESPONSE:
|
|
91
|
+
raise BluPayError("BluPay response exceeds the size limit", status, request_id)
|
|
92
|
+
try:
|
|
93
|
+
result = json.loads(raw)
|
|
94
|
+
except (ValueError, UnicodeError) as cause:
|
|
95
|
+
raise BluPayError("Invalid BluPay JSON response", status, request_id) from cause
|
|
96
|
+
if (not isinstance(result, dict) or result.get("error") is not False
|
|
97
|
+
or type(result.get("number")) is not int or result["number"] != 0 or "message" not in result):
|
|
98
|
+
raise BluPayError("Invalid BluPay response envelope", status, request_id)
|
|
99
|
+
return result["message"]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def verify_webhook(raw_body, *, timestamp, signature, event_id, secret, now_ms=None):
|
|
103
|
+
"""Authenticate the exact body and return the event for durable deduplication."""
|
|
104
|
+
now_ms = time.time_ns() // 1_000_000 if now_ms is None else now_ms
|
|
105
|
+
if (not isinstance(raw_body, bytes) or not isinstance(secret, str) or not secret
|
|
106
|
+
or not isinstance(timestamp, str) or not re.fullmatch(r"[0-9]{10,16}", timestamp)
|
|
107
|
+
or type(now_ms) is not int or abs(now_ms - int(timestamp)) > 300_000
|
|
108
|
+
or not isinstance(signature, str) or not re.fullmatch(r"[a-f0-9]{64}", signature)
|
|
109
|
+
or not isinstance(event_id, str) or not 1 <= len(event_id) <= 255):
|
|
110
|
+
raise BluPayError("Invalid or stale BluPay webhook")
|
|
111
|
+
expected = hmac.new(secret.encode(), timestamp.encode() + raw_body, hashlib.sha256).hexdigest()
|
|
112
|
+
if not hmac.compare_digest(expected, signature):
|
|
113
|
+
raise BluPayError("Invalid BluPay webhook signature")
|
|
114
|
+
try:
|
|
115
|
+
event = json.loads(raw_body.decode("utf-8"))
|
|
116
|
+
except (ValueError, UnicodeError) as cause:
|
|
117
|
+
raise BluPayError("Invalid BluPay webhook JSON") from cause
|
|
118
|
+
if not isinstance(event, dict) or event.get("event_id") != event_id or not isinstance(event.get("event_type"), str):
|
|
119
|
+
raise BluPayError("Invalid BluPay webhook event")
|
|
120
|
+
return event
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: blupay-sdk
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Server-side BluPay REST API client
|
|
5
|
+
License: MIT License
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2026 BluPay
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
|
|
27
|
+
Project-URL: Repository, https://github.com/blupay-dev/blupay-python
|
|
28
|
+
Requires-Python: >=3.9
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
License-File: LICENSE
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# BluPay SDK for Python
|
|
34
|
+
|
|
35
|
+
Version **0.1.1**. Requires Python 3.9+. Uses BluPay's public v1 API at `https://blupay.me/api`.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
Install the tagged release from GitHub:
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
python -m pip install 'blupay-sdk @ git+https://github.com/blupay-dev/blupay-python.git@v0.1.1'
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
With the 0.1.1 source directory unpacked alongside your project:
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
python -m pip install ./blupay-python
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Distribution and registry status are listed in the [BluPay integration docs](https://blupay.me/docs#sdks).
|
|
52
|
+
|
|
53
|
+
## Create a test invoice
|
|
54
|
+
|
|
55
|
+
Configure `BLUPAY_API_KEY` in the server environment using a key for a Sandbox shop with `invoices:write` and `invoices:read`. Persist a distinct `SAVED_ATTEMPT_KEY` with the order and request body before the first call. Use an enabled quote currency.
|
|
56
|
+
|
|
57
|
+
From the SDK checkout with its dependencies installed:
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
python examples/invoice.py 49.00 USD order-1024 "$SAVED_ATTEMPT_KEY"
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
The command prints the invoice link and hosted payment URL. Save the link with the order. A merchant-hosted page reads the checkout from its own authenticated backend, posts a returned currency-network ID, and renders the exact instructions returned by BluPay.
|
|
64
|
+
|
|
65
|
+
## Methods
|
|
66
|
+
|
|
67
|
+
`create_invoice`, `get_invoice`, `get_checkout`, `select_currency`, `get_receipt`, `verify_webhook`
|
|
68
|
+
|
|
69
|
+
| Operation | API path | Permission |
|
|
70
|
+
| --- | --- | --- |
|
|
71
|
+
| Create invoice | `POST /v1/invoices/` | `invoices:write` |
|
|
72
|
+
| Read invoice | `GET /v1/invoices/{link}/` | `invoices:read` |
|
|
73
|
+
| Read checkout | `GET /v1/invoices/{link}/checkout/` | `invoices:read` |
|
|
74
|
+
| Select asset and network | `POST /v1/invoices/{link}/checkout/select-currency/` | `invoices:write` |
|
|
75
|
+
| Read receipt | `GET /v1/invoices/{link}/received/` | `invoices:read` |
|
|
76
|
+
|
|
77
|
+
All amounts are handled as decimal strings. The SDK unwraps the success envelope and exposes the HTTP status and request ID on API errors. Defaults to 10 seconds per socket operation (`timeout`). Supply API keys from server configuration and keep them out of client bundles and logs.
|
|
78
|
+
|
|
79
|
+
## Reconcile and confirm
|
|
80
|
+
|
|
81
|
+
- On a timed-out invoice creation, use the same saved attempt key and identical body. A 409 can mean the first request is still in progress or the key was reused with a different body.
|
|
82
|
+
- On selection timeout or 409, read the checkout again to reconcile its current quote before retrying. Use `paymentInstructions.amount` and handle a missing instruction by checking checkout state.
|
|
83
|
+
- The browser return is a status view. Look up the invoice on your server and compare stored link, order ID, decimal amount, currency and environment. Fulfill a production order once after authoritative `Paid`.
|
|
84
|
+
- For webhooks pass the exact raw request body, `X-BluPay-Timestamp`, `X-BluPay-Signature` and `X-BluPay-Event-Id` to the verifier. It authenticates HMAC-SHA256 and a five-minute timestamp window. Persist events in a durable inbox keyed by event ID and make order fulfillment idempotent. A verification result is an authentication check.
|
|
85
|
+
- Use the receipt to reconcile the confirmed received amount and any overpayment separately.
|
|
86
|
+
|
|
87
|
+
## Tests
|
|
88
|
+
|
|
89
|
+
```sh
|
|
90
|
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Run the tests against the included isolated fixture. The contract suite uses loopback endpoints and fixture credentials. For version changes compare routes, scopes, envelopes and signatures with the [API reference](https://blupay.me/docs), then exercise a Sandbox shop and record its outcomes before a release.
|
|
94
|
+
|
|
95
|
+
See [CHANGELOG.md](CHANGELOG.md) for compatibility changes.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
blupay/__init__.py,sha256=CQtrpxTQn_T77h4Q9z-Mxf8-TVeezD6uINWQq90MJ0A,5733
|
|
2
|
+
blupay_sdk-0.1.1.dist-info/licenses/LICENSE,sha256=QUsJYljHWHXW_uPHAm1_--eZXg7S0gH_jh16vHFLFtM,1063
|
|
3
|
+
blupay_sdk-0.1.1.dist-info/METADATA,sha256=97WqeFNsYJ6zAW69nbZi4hAWYLCof-ywS17XbBn0eNo,5030
|
|
4
|
+
blupay_sdk-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
blupay_sdk-0.1.1.dist-info/top_level.txt,sha256=I--HWhWvBrQvx5dd6l3QpDwIEwqH2d_zxHR0aR45iTA,7
|
|
6
|
+
blupay_sdk-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BluPay
|
|
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 @@
|
|
|
1
|
+
blupay
|