qwikipay 1.0.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.
- qwikipay-1.0.0/LICENSE +21 -0
- qwikipay-1.0.0/PKG-INFO +25 -0
- qwikipay-1.0.0/README.md +13 -0
- qwikipay-1.0.0/pyproject.toml +15 -0
- qwikipay-1.0.0/qwikipay/__init__.py +108 -0
- qwikipay-1.0.0/qwikipay.egg-info/PKG-INFO +25 -0
- qwikipay-1.0.0/qwikipay.egg-info/SOURCES.txt +9 -0
- qwikipay-1.0.0/qwikipay.egg-info/dependency_links.txt +1 -0
- qwikipay-1.0.0/qwikipay.egg-info/top_level.txt +1 -0
- qwikipay-1.0.0/setup.cfg +4 -0
- qwikipay-1.0.0/tests/test_qwikipay.py +70 -0
qwikipay-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Deepcode Innovations
|
|
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.
|
qwikipay-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: qwikipay
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: QwikiPay payments for Python servers
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://docs.qwikipay.com
|
|
7
|
+
Project-URL: Source, https://github.com/Deepcodeinnovations/qwikipay-sdks
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# qwikipay (Python)
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from qwikipay import Client, QwikiPayError, verify_webhook
|
|
17
|
+
|
|
18
|
+
qp = Client("qp_sk_test_...", business="qp_biz_test_...")
|
|
19
|
+
charge = qp.charges.create(reference=order_id, amount="50000", currency="UGX",
|
|
20
|
+
customer={"email": "joan@example.com", "name": "Joan"},
|
|
21
|
+
method={"type": "card", "card_token": token_from_the_browser})
|
|
22
|
+
paid = qp.charges.retrieve(charge["id"])["status"] == "successful" # only this decides
|
|
23
|
+
|
|
24
|
+
event = verify_webhook(request.body, request.headers["QwikiPay-Signature"], webhook_secret)
|
|
25
|
+
```
|
qwikipay-1.0.0/README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# qwikipay (Python)
|
|
2
|
+
|
|
3
|
+
```python
|
|
4
|
+
from qwikipay import Client, QwikiPayError, verify_webhook
|
|
5
|
+
|
|
6
|
+
qp = Client("qp_sk_test_...", business="qp_biz_test_...")
|
|
7
|
+
charge = qp.charges.create(reference=order_id, amount="50000", currency="UGX",
|
|
8
|
+
customer={"email": "joan@example.com", "name": "Joan"},
|
|
9
|
+
method={"type": "card", "card_token": token_from_the_browser})
|
|
10
|
+
paid = qp.charges.retrieve(charge["id"])["status"] == "successful" # only this decides
|
|
11
|
+
|
|
12
|
+
event = verify_webhook(request.body, request.headers["QwikiPay-Signature"], webhook_secret)
|
|
13
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "qwikipay"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "QwikiPay payments for Python servers"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
|
|
9
|
+
[project.urls]
|
|
10
|
+
Homepage = "https://docs.qwikipay.com"
|
|
11
|
+
Source = "https://github.com/Deepcodeinnovations/qwikipay-sdks"
|
|
12
|
+
|
|
13
|
+
[build-system]
|
|
14
|
+
requires = ["setuptools>=68"]
|
|
15
|
+
build-backend = "setuptools.build_meta"
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""QwikiPay for Python servers. Standard library only.
|
|
2
|
+
|
|
3
|
+
qp = Client(secret_key, business="qp_biz_test_...")
|
|
4
|
+
charge = qp.charges.create(reference=order.id, amount="50000", currency="UGX",
|
|
5
|
+
customer={"email": ..., "name": ...}, method={"type": "card", "card_token": token})
|
|
6
|
+
|
|
7
|
+
Only a GET decides that something is paid: charges.retrieve(id) or payments.retrieve(reference), never a redirect.
|
|
8
|
+
"""
|
|
9
|
+
import hashlib
|
|
10
|
+
import hmac
|
|
11
|
+
import json
|
|
12
|
+
import time
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.parse
|
|
15
|
+
import urllib.request
|
|
16
|
+
|
|
17
|
+
__all__ = ["Client", "QwikiPayError", "verify_webhook"]
|
|
18
|
+
API = "https://api.qwikipay.com"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class QwikiPayError(Exception):
|
|
22
|
+
"""An answer with an error. charge_created says whether a charge exists anyway: check it before trying again."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, status: int, error: dict):
|
|
25
|
+
super().__init__(error.get("message") or f"HTTP {status}")
|
|
26
|
+
self.status, self.code, self.message = status, error.get("code", "error"), error.get("message", "")
|
|
27
|
+
self.request_id = error.get("request_id")
|
|
28
|
+
self.charge_created, self.charge_id = error.get("charge_created"), error.get("charge_id")
|
|
29
|
+
self.error = error
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Client:
|
|
33
|
+
def __init__(self, secret_key: str, business: str | None = None, api: str = API, timeout: float = 30):
|
|
34
|
+
if not secret_key.startswith("qp_sk_"):
|
|
35
|
+
raise ValueError("Use your secret key (qp_sk_...) on your server.")
|
|
36
|
+
self.secret_key, self.business, self.api, self.timeout = secret_key, business, api.rstrip("/"), timeout
|
|
37
|
+
self.charges, self.payments = _Charges(self), _Payments(self)
|
|
38
|
+
|
|
39
|
+
def request(self, method: str, path: str, body: dict | None = None, query: dict | None = None, headers: dict | None = None) -> dict:
|
|
40
|
+
url = f"{self.api}/v1{path}" + (f"?{urllib.parse.urlencode(query)}" if query else "")
|
|
41
|
+
sent = {"Authorization": f"Bearer {self.secret_key}", "Accept": "application/json", **(headers or {})}
|
|
42
|
+
if self.business:
|
|
43
|
+
sent["QwikiPay-Business"] = self.business
|
|
44
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
45
|
+
if data is not None:
|
|
46
|
+
sent["Content-Type"] = "application/json"
|
|
47
|
+
try:
|
|
48
|
+
with urllib.request.urlopen(urllib.request.Request(url, data=data, headers=sent, method=method), timeout=self.timeout) as r:
|
|
49
|
+
return json.loads(r.read() or b"{}")
|
|
50
|
+
except urllib.error.HTTPError as e:
|
|
51
|
+
try:
|
|
52
|
+
error = json.loads(e.read()).get("error") or {}
|
|
53
|
+
except ValueError:
|
|
54
|
+
error = {}
|
|
55
|
+
error.setdefault("request_id", e.headers.get("QwikiPay-Request-Id"))
|
|
56
|
+
raise QwikiPayError(e.code, error) from None
|
|
57
|
+
|
|
58
|
+
def account(self) -> dict:
|
|
59
|
+
return self.request("GET", "/account")
|
|
60
|
+
|
|
61
|
+
def balance(self) -> dict:
|
|
62
|
+
return self.request("GET", "/balance")
|
|
63
|
+
|
|
64
|
+
def rates(self) -> dict:
|
|
65
|
+
return self.request("GET", "/rates")
|
|
66
|
+
|
|
67
|
+
def convert(self, amount: str, currency: str) -> dict:
|
|
68
|
+
return self.request("GET", "/convert", query={"amount": str(amount), "currency": currency})
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class _Charges:
|
|
72
|
+
def __init__(self, client: Client):
|
|
73
|
+
self._c = client
|
|
74
|
+
|
|
75
|
+
def create(self, **charge) -> dict:
|
|
76
|
+
# the reference is the idempotency key: sending the same order again returns the same charge
|
|
77
|
+
return self._c.request("POST", "/charges", charge)
|
|
78
|
+
|
|
79
|
+
def authorize(self, charge_id: str, pin: str | None = None, otp: str | None = None) -> dict:
|
|
80
|
+
return self._c.request("POST", f"/charges/{charge_id}/authorize", {k: v for k, v in {"pin": pin, "otp": otp}.items() if v})
|
|
81
|
+
|
|
82
|
+
def retrieve(self, charge_id: str) -> dict:
|
|
83
|
+
return self._c.request("GET", f"/charges/{charge_id}")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class _Payments:
|
|
87
|
+
def __init__(self, client: Client):
|
|
88
|
+
self._c = client
|
|
89
|
+
|
|
90
|
+
def create(self, idempotency_key: str, **payment) -> dict:
|
|
91
|
+
return self._c.request("POST", "/payments", payment, headers={"Idempotency-Key": idempotency_key})
|
|
92
|
+
|
|
93
|
+
def retrieve(self, reference: str) -> dict:
|
|
94
|
+
return self._c.request("GET", f"/payments/{urllib.parse.quote(reference, safe='')}")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def verify_webhook(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> dict:
|
|
98
|
+
"""The event, if QwikiPay signed this exact body in the last `tolerance` seconds. Pass the raw bytes, before any
|
|
99
|
+
JSON parsing: re-serialising changes them and the signature no longer matches."""
|
|
100
|
+
parts = dict(p.split("=", 1) for p in (header or "").split(",") if "=" in p)
|
|
101
|
+
if "t" not in parts or "v1" not in parts or not parts["t"].isdigit():
|
|
102
|
+
raise ValueError("Missing or malformed QwikiPay-Signature header.")
|
|
103
|
+
if abs(time.time() - int(parts["t"])) > tolerance:
|
|
104
|
+
raise ValueError("Webhook timestamp is too old.")
|
|
105
|
+
expected = hmac.new(secret.encode(), parts["t"].encode() + b"." + raw_body, hashlib.sha256).hexdigest()
|
|
106
|
+
if not hmac.compare_digest(expected, parts["v1"]):
|
|
107
|
+
raise ValueError("Webhook signature doesn't match.")
|
|
108
|
+
return json.loads(raw_body)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: qwikipay
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: QwikiPay payments for Python servers
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://docs.qwikipay.com
|
|
7
|
+
Project-URL: Source, https://github.com/Deepcodeinnovations/qwikipay-sdks
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# qwikipay (Python)
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from qwikipay import Client, QwikiPayError, verify_webhook
|
|
17
|
+
|
|
18
|
+
qp = Client("qp_sk_test_...", business="qp_biz_test_...")
|
|
19
|
+
charge = qp.charges.create(reference=order_id, amount="50000", currency="UGX",
|
|
20
|
+
customer={"email": "joan@example.com", "name": "Joan"},
|
|
21
|
+
method={"type": "card", "card_token": token_from_the_browser})
|
|
22
|
+
paid = qp.charges.retrieve(charge["id"])["status"] == "successful" # only this decides
|
|
23
|
+
|
|
24
|
+
event = verify_webhook(request.body, request.headers["QwikiPay-Signature"], webhook_secret)
|
|
25
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
qwikipay
|
qwikipay-1.0.0/setup.cfg
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import json
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
7
|
+
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
from qwikipay import Client, QwikiPayError, verify_webhook
|
|
11
|
+
|
|
12
|
+
SECRET = "whsec_test"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def signed(body: bytes, t: int | None = None) -> str:
|
|
16
|
+
t = t or int(time.time())
|
|
17
|
+
return f"t={t},v1=" + hmac.new(SECRET.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_webhooks_verify_only_the_exact_body():
|
|
21
|
+
body = b'{"type":"charge.succeeded","data":{"id":"ch_1"}}'
|
|
22
|
+
assert verify_webhook(body, signed(body), SECRET)["type"] == "charge.succeeded"
|
|
23
|
+
with pytest.raises(ValueError):
|
|
24
|
+
verify_webhook(body.replace(b"ch_1", b"ch_2"), signed(body), SECRET)
|
|
25
|
+
with pytest.raises(ValueError):
|
|
26
|
+
verify_webhook(body, signed(body, int(time.time()) - 600), SECRET)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@pytest.fixture
|
|
30
|
+
def api():
|
|
31
|
+
seen = []
|
|
32
|
+
|
|
33
|
+
class Fake(BaseHTTPRequestHandler):
|
|
34
|
+
def do_POST(self):
|
|
35
|
+
seen.append((self.path, {k.lower(): v for k, v in self.headers.items()}, json.loads(self.rfile.read(int(self.headers["Content-Length"])))))
|
|
36
|
+
self.answer(502, {"error": {"code": "payments_unavailable", "message": "Slow", "charge_created": True, "charge_id": "ch_9"}})
|
|
37
|
+
|
|
38
|
+
def do_GET(self):
|
|
39
|
+
seen.append((self.path, {k.lower(): v for k, v in self.headers.items()}, None))
|
|
40
|
+
self.answer(200, {"id": "ch_9", "status": "successful"})
|
|
41
|
+
|
|
42
|
+
def answer(self, status, payload):
|
|
43
|
+
self.send_response(status)
|
|
44
|
+
self.send_header("QwikiPay-Request-Id", "req_abc")
|
|
45
|
+
self.end_headers()
|
|
46
|
+
self.wfile.write(json.dumps(payload).encode())
|
|
47
|
+
|
|
48
|
+
def log_message(self, *_):
|
|
49
|
+
pass
|
|
50
|
+
server = HTTPServer(("127.0.0.1", 0), Fake)
|
|
51
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
52
|
+
yield f"http://127.0.0.1:{server.server_port}", seen
|
|
53
|
+
server.shutdown()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_errors_say_whether_a_charge_exists(api):
|
|
57
|
+
url, seen = api
|
|
58
|
+
qp = Client("qp_sk_test_x", business="qp_biz_test_1", api=url)
|
|
59
|
+
with pytest.raises(QwikiPayError) as e:
|
|
60
|
+
qp.charges.create(reference="ORDER-1", amount="1000", currency="KES", customer={}, method={"type": "card", "card_token": "ct_1"})
|
|
61
|
+
assert (e.value.code, e.value.charge_created, e.value.charge_id, e.value.request_id) == ("payments_unavailable", True, "ch_9", "req_abc")
|
|
62
|
+
assert qp.charges.retrieve("ch_9")["status"] == "successful"
|
|
63
|
+
path, headers, body = seen[0]
|
|
64
|
+
assert path == "/v1/charges" and headers["authorization"] == "Bearer qp_sk_test_x" and headers["qwikipay-business"] == "qp_biz_test_1"
|
|
65
|
+
assert body["method"]["card_token"] == "ct_1"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_a_public_key_is_refused():
|
|
69
|
+
with pytest.raises(ValueError):
|
|
70
|
+
Client("qp_pk_test_x")
|