paysafe-tz 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.
- paysafe_tz-0.1.0/.gitignore +9 -0
- paysafe_tz-0.1.0/CHANGELOG.md +25 -0
- paysafe_tz-0.1.0/LICENSE +21 -0
- paysafe_tz-0.1.0/PKG-INFO +219 -0
- paysafe_tz-0.1.0/README.md +183 -0
- paysafe_tz-0.1.0/examples/async_payment.py +29 -0
- paysafe_tz-0.1.0/examples/auth.py +24 -0
- paysafe_tz-0.1.0/examples/control_number.py +34 -0
- paysafe_tz-0.1.0/examples/create_payment.py +51 -0
- paysafe_tz-0.1.0/examples/customers_and_balance.py +14 -0
- paysafe_tz-0.1.0/examples/events.py +18 -0
- paysafe_tz-0.1.0/examples/get_payment.py +23 -0
- paysafe_tz-0.1.0/examples/list_payments.py +15 -0
- paysafe_tz-0.1.0/examples/payment_link.py +27 -0
- paysafe_tz-0.1.0/examples/refund.py +27 -0
- paysafe_tz-0.1.0/examples/transfer.py +32 -0
- paysafe_tz-0.1.0/examples/verify_webhook.py +54 -0
- paysafe_tz-0.1.0/examples/webhook_endpoints.py +31 -0
- paysafe_tz-0.1.0/examples/webhooks/django_view.py +26 -0
- paysafe_tz-0.1.0/examples/webhooks/fastapi_app.py +24 -0
- paysafe_tz-0.1.0/examples/webhooks/flask_app.py +22 -0
- paysafe_tz-0.1.0/pyproject.toml +74 -0
- paysafe_tz-0.1.0/src/paysafe_tz/__init__.py +95 -0
- paysafe_tz-0.1.0/src/paysafe_tz/_response.py +105 -0
- paysafe_tz-0.1.0/src/paysafe_tz/_transport.py +332 -0
- paysafe_tz-0.1.0/src/paysafe_tz/_validate.py +162 -0
- paysafe_tz-0.1.0/src/paysafe_tz/_version.py +1 -0
- paysafe_tz-0.1.0/src/paysafe_tz/client.py +237 -0
- paysafe_tz-0.1.0/src/paysafe_tz/errors.py +202 -0
- paysafe_tz-0.1.0/src/paysafe_tz/models.py +260 -0
- paysafe_tz-0.1.0/src/paysafe_tz/page.py +110 -0
- paysafe_tz-0.1.0/src/paysafe_tz/py.typed +0 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/__init__.py +33 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/_base.py +118 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/balance.py +37 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/control_numbers.py +123 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/customers.py +42 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/events.py +51 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/payment_links.py +122 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/payments.py +136 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/refunds.py +90 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/topups.py +60 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/transfers.py +82 -0
- paysafe_tz-0.1.0/src/paysafe_tz/resources/webhook_endpoints.py +90 -0
- paysafe_tz-0.1.0/src/paysafe_tz/webhooks.py +115 -0
- paysafe_tz-0.1.0/tests/__init__.py +0 -0
- paysafe_tz-0.1.0/tests/conftest.py +118 -0
- paysafe_tz-0.1.0/tests/fixtures/cancelControlNumber.json +205 -0
- paysafe_tz-0.1.0/tests/fixtures/cancelPayment.json +191 -0
- paysafe_tz-0.1.0/tests/fixtures/createControlNumber.json +227 -0
- paysafe_tz-0.1.0/tests/fixtures/createPayment.json +209 -0
- paysafe_tz-0.1.0/tests/fixtures/createPaymentLink.json +202 -0
- paysafe_tz-0.1.0/tests/fixtures/createRefund.json +183 -0
- paysafe_tz-0.1.0/tests/fixtures/createTransfer.json +191 -0
- paysafe_tz-0.1.0/tests/fixtures/createWebhookEndpoint.json +182 -0
- paysafe_tz-0.1.0/tests/fixtures/deleteWebhookEndpoint.json +160 -0
- paysafe_tz-0.1.0/tests/fixtures/getBalance.json +173 -0
- paysafe_tz-0.1.0/tests/fixtures/getControlNumber.json +226 -0
- paysafe_tz-0.1.0/tests/fixtures/getCustomer.json +170 -0
- paysafe_tz-0.1.0/tests/fixtures/getEvent.json +191 -0
- paysafe_tz-0.1.0/tests/fixtures/getPayment.json +187 -0
- paysafe_tz-0.1.0/tests/fixtures/getPaymentLink.json +187 -0
- paysafe_tz-0.1.0/tests/fixtures/getRefund.json +174 -0
- paysafe_tz-0.1.0/tests/fixtures/getTransfer.json +183 -0
- paysafe_tz-0.1.0/tests/fixtures/getWebhookEndpoint.json +175 -0
- paysafe_tz-0.1.0/tests/fixtures/index.json +179 -0
- paysafe_tz-0.1.0/tests/fixtures/listControlNumbers.json +214 -0
- paysafe_tz-0.1.0/tests/fixtures/listCustomers.json +179 -0
- paysafe_tz-0.1.0/tests/fixtures/listEvents.json +203 -0
- paysafe_tz-0.1.0/tests/fixtures/listPaymentLinks.json +196 -0
- paysafe_tz-0.1.0/tests/fixtures/listPayments.json +200 -0
- paysafe_tz-0.1.0/tests/fixtures/listRefunds.json +184 -0
- paysafe_tz-0.1.0/tests/fixtures/listTransactions.json +183 -0
- paysafe_tz-0.1.0/tests/fixtures/listTransfers.json +191 -0
- paysafe_tz-0.1.0/tests/fixtures/listWebhookEndpoints.json +180 -0
- paysafe_tz-0.1.0/tests/fixtures/retry-scenarios.json +264 -0
- paysafe_tz-0.1.0/tests/fixtures/updatePaymentLink.json +199 -0
- paysafe_tz-0.1.0/tests/fixtures/updateWebhookEndpoint.json +182 -0
- paysafe_tz-0.1.0/tests/fixtures/webhook-vector.json +32 -0
- paysafe_tz-0.1.0/tests/test_async.py +56 -0
- paysafe_tz-0.1.0/tests/test_client.py +97 -0
- paysafe_tz-0.1.0/tests/test_contract.py +115 -0
- paysafe_tz-0.1.0/tests/test_errors.py +127 -0
- paysafe_tz-0.1.0/tests/test_integration.py +77 -0
- paysafe_tz-0.1.0/tests/test_page_polling.py +78 -0
- paysafe_tz-0.1.0/tests/test_retry.py +122 -0
- paysafe_tz-0.1.0/tests/test_security.py +144 -0
- paysafe_tz-0.1.0/tests/test_topups.py +115 -0
- paysafe_tz-0.1.0/tests/test_webhooks.py +69 -0
|
@@ -0,0 +1,25 @@
|
|
|
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
|
+
## [Unreleased]
|
|
6
|
+
|
|
7
|
+
## [0.1.0] - 2026-12-05
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Client with sandbox/production selection from the key prefix, configurable base URL, timeout, retries, logger and HTTP client.
|
|
12
|
+
- Payments: create, list, get, cancel, wait for terminal state.
|
|
13
|
+
- Payment links: create, list, get, update.
|
|
14
|
+
- Control numbers: create, list, get, cancel.
|
|
15
|
+
- Refunds: create, list, get, wait for terminal state.
|
|
16
|
+
- Balance and transactions.
|
|
17
|
+
- Top-ups: create, list, get (sync and async).
|
|
18
|
+
- Customers: list, get.
|
|
19
|
+
- Transfers: create, list, get, wait for terminal state.
|
|
20
|
+
- Webhook endpoints: list, create, get, update, delete.
|
|
21
|
+
- Events: list, get.
|
|
22
|
+
- Webhook signature verification and event construction.
|
|
23
|
+
- Typed models for every API schema, structured errors per documented code, cursor pagination helpers.
|
|
24
|
+
|
|
25
|
+
API version: 2026-09-07.
|
paysafe_tz-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PaySafe
|
|
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,219 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: paysafe-tz
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for the PaySafe payments API (Tanzania mobile money, refunds, control numbers, payment links, transfers, webhooks)
|
|
5
|
+
Project-URL: Homepage, https://paysafe.co.tz/docs
|
|
6
|
+
Project-URL: Documentation, https://paysafe.co.tz/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/AmDev255/paysafe-python
|
|
8
|
+
Project-URL: Issues, https://github.com/AmDev255/paysafe-python/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/AmDev255/paysafe-python/blob/main/CHANGELOG.md
|
|
10
|
+
Author: PaySafe
|
|
11
|
+
License: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: airtel-money,api,mobile-money,mpesa,payments,paysafe,sdk,tanzania,tigopesa
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.9
|
|
27
|
+
Requires-Dist: httpx<1,>=0.24
|
|
28
|
+
Requires-Dist: typing-extensions>=4.5; python_version < '3.11'
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: mypy>=1.11; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
33
|
+
Requires-Dist: respx>=0.21; extra == 'dev'
|
|
34
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# PaySafe Python SDK
|
|
38
|
+
|
|
39
|
+
Official Python library for the [PaySafe](https://paysafe.co.tz) payments API. Accept mobile-money payments in Tanzania, issue refunds, control numbers and payment links, move money between projects, and receive signed webhooks.
|
|
40
|
+
|
|
41
|
+
Part of the [PaySafe SDK directory](https://github.com/AmDev255/paysafe-sdks). API reference: https://paysafe.co.tz/docs.
|
|
42
|
+
|
|
43
|
+
## Features
|
|
44
|
+
|
|
45
|
+
- Every served PaySafe API operation (29 operations, 10 resources) with typed request and response models
|
|
46
|
+
- Sandbox and production selected automatically from the key prefix
|
|
47
|
+
- Safe retries that honour `Retry-After`, idempotency keys that survive retries, cursor pagination helpers
|
|
48
|
+
- Polling helpers that wait for a payment, refund or transfer to reach a terminal state
|
|
49
|
+
- Webhook signature verification with secret rotation support and constant-time comparison
|
|
50
|
+
- One structured exception per documented error code, every error carries the request id
|
|
51
|
+
- Configurable timeouts, base URL, logger and HTTP client
|
|
52
|
+
|
|
53
|
+
## Installation
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pip install paysafe-tz
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Requirements
|
|
60
|
+
|
|
61
|
+
Python 3.9 or newer. Depends on `httpx`; the async client uses `asyncio`.
|
|
62
|
+
|
|
63
|
+
## Authentication
|
|
64
|
+
|
|
65
|
+
Create a secret key in the dashboard under API keys. Test keys start with `paysafe_test_`, live keys with `paysafe_live_`. Keep keys on the server; never ship them in browsers or mobile apps. The SDK reads `PAYSAFE_SECRET_KEY` when no key is passed.
|
|
66
|
+
|
|
67
|
+
## Sandbox setup
|
|
68
|
+
|
|
69
|
+
Use a `paysafe_test_` key. The sandbox is the same API with a simulated provider; the last four digits of the customer phone choose the outcome (`0000` succeeds, `1111` is declined, `4444` expires, see the [Sandbox guide](https://paysafe.co.tz/docs/sandbox)).
|
|
70
|
+
|
|
71
|
+
## Production setup
|
|
72
|
+
|
|
73
|
+
Switch to a `paysafe_live_` key once your organisation is verified. Register a live webhook endpoint and add your server's address to the project's IP allowlist. Nothing else changes.
|
|
74
|
+
|
|
75
|
+
## Quickstart
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
import os
|
|
79
|
+
from paysafe_tz import PaySafe, RequestOptions, is_payment_successful
|
|
80
|
+
|
|
81
|
+
client = PaySafe(os.environ["PAYSAFE_SECRET_KEY"]) # paysafe_test_… selects the sandbox
|
|
82
|
+
|
|
83
|
+
payment = client.payments.create(
|
|
84
|
+
{
|
|
85
|
+
"amount": 10000, # TZS, integer
|
|
86
|
+
"customer": {"phone": "+255712340000", "name": "Amina Juma"},
|
|
87
|
+
"reference": "order-8812",
|
|
88
|
+
},
|
|
89
|
+
RequestOptions(idempotency_key="order-8812-attempt-1"), # persist the key before calling
|
|
90
|
+
)
|
|
91
|
+
print(payment.id, payment.status) # 202 Accepted: still pending
|
|
92
|
+
|
|
93
|
+
final = client.payments.wait_for_terminal(payment.id) # or wait for the webhook
|
|
94
|
+
if is_payment_successful(final):
|
|
95
|
+
print("Paid, net TZS", final.net)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Supported API resources
|
|
99
|
+
|
|
100
|
+
| Resource | Operations |
|
|
101
|
+
|---|---|
|
|
102
|
+
| Payments | create, list, get, cancel, waitForTerminal |
|
|
103
|
+
| Payment links | create, list, get, update |
|
|
104
|
+
| Control numbers | create, list, get, cancel |
|
|
105
|
+
| Refunds | create, list, get, waitForTerminal |
|
|
106
|
+
| Top-ups | create, list, get |
|
|
107
|
+
| Balance | get, transactions |
|
|
108
|
+
| Customers | list, get |
|
|
109
|
+
| Transfers | create, list, get, waitForTerminal |
|
|
110
|
+
| Webhook endpoints | list, create, get, update, delete |
|
|
111
|
+
| Events | list, get |
|
|
112
|
+
| Webhooks | verifySignature, constructEvent |
|
|
113
|
+
|
|
114
|
+
Planned by PaySafe and not yet served (not included): `ping`, payouts (`createPayout`, `getPayout`), `rotateWebhookEndpointSecret`.
|
|
115
|
+
|
|
116
|
+
## Usage examples
|
|
117
|
+
|
|
118
|
+
Runnable programs live in [`examples/`](examples/): authentication, creating and polling a payment, listing with pagination, refunds, payment links, control numbers, transfers, webhook endpoints, events and webhook verification, plus framework handlers under `examples/webhooks/`.
|
|
119
|
+
|
|
120
|
+
Every resource follows the same shape: `create`, `list`, `get`, plus resource-specific actions. Objects come back as `ApiObject`, a `dict` with the API's snake_case keys that also allows attribute access (`payment.status` or `payment["status"]`) and carries `last_response`. Lists return a `Page`; iterate it for its items or call `auto_paging_iter()` to walk every page.
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
# Pagination
|
|
124
|
+
for payment in client.payments.list({"status": "succeeded", "limit": 100}).auto_paging_iter():
|
|
125
|
+
...
|
|
126
|
+
|
|
127
|
+
# Top-ups: add money to your own balance (prompt=False opens the order for token, QR or hosted-page payment)
|
|
128
|
+
topup = client.topups.create({"amount": 500000, "phone": "+255712345000", "prompt": False, "reference": "FLOAT-DEC-03"})
|
|
129
|
+
topup = client.topups.get(topup.id) # topup.checkout holds pay_token, qr and url once the order is open
|
|
130
|
+
|
|
131
|
+
# Refunds
|
|
132
|
+
refund = client.refunds.create({"payment": payment.id, "amount": 5000, "reason": "requested_by_customer"})
|
|
133
|
+
|
|
134
|
+
# Payment links and control numbers
|
|
135
|
+
link = client.payment_links.create({"title": "Workshop ticket", "amount": 25000})
|
|
136
|
+
number = client.control_numbers.create({"payer_name": "Amina Juma", "title": "Term 2 fees", "amount": 450000})
|
|
137
|
+
|
|
138
|
+
# Transfers, balance, customers, events
|
|
139
|
+
transfer = client.transfers.create({"to": "merchant_shop", "amount": 5000})
|
|
140
|
+
balance = client.balance.get()
|
|
141
|
+
customer = client.customers.get("cus_…")
|
|
142
|
+
event = client.events.get("evt_…")
|
|
143
|
+
|
|
144
|
+
# Webhook endpoints (the secret is returned once)
|
|
145
|
+
endpoint = client.webhook_endpoints.create({"url": "https://example.com/paysafe", "events": ["payment.succeeded"]})
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Async: `AsyncPaySafe` has the same surface with awaitable methods and `AsyncPage` (`async for item in page`). Both clients are context managers; pass your own `httpx.Client`/`httpx.AsyncClient` to reuse connection pools. `date`/`datetime` values are accepted wherever the API takes RFC 3339 timestamps.
|
|
149
|
+
|
|
150
|
+
Per-request options: `RequestOptions(idempotency_key=…, request_id=…, timeout=…, max_retries=…, headers={…})`. Retries: 429 and 503 wait for `Retry-After`; `idempotency_in_progress` waits one second; 5xx and network errors are retried only when the request is idempotent (GET, PATCH, DELETE, or a POST with an idempotency key). The SDK generates a UUID key for `payments.create`, `refunds.create`, `transfers.create` and `payments.cancel` when you do not pass one and exposes it on `obj.last_response.idempotency_key`; pass your own key derived from the order to survive process restarts.
|
|
151
|
+
|
|
152
|
+
Security: ids, filters, headers and amounts are validated before any request; path and query values are percent-encoded; the base URL must be https (plain http only for localhost); redirects are never followed; TLS verification stays on; response bodies are capped at 16 MB; the key never appears in exceptions or logs.
|
|
153
|
+
|
|
154
|
+
## Error handling
|
|
155
|
+
|
|
156
|
+
Every non-2xx response raises a subclass of `ApiError` chosen by the error code, with `status`, `code`, `request_id`, `param`, `details`, `doc_url`, `retry_after` and `rate_limit`:
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from paysafe_tz import (
|
|
160
|
+
ApiConnectionError,
|
|
161
|
+
ApiError,
|
|
162
|
+
InvalidRequestError,
|
|
163
|
+
InvalidStateError,
|
|
164
|
+
RateLimitError,
|
|
165
|
+
ValidationError,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
try:
|
|
169
|
+
client.payments.cancel(payment_id)
|
|
170
|
+
except ValidationError as e: # 400: fix the request (e.param names the field)
|
|
171
|
+
...
|
|
172
|
+
except InvalidStateError as e: # 409: read the object and decide again
|
|
173
|
+
...
|
|
174
|
+
except RateLimitError as e: # 429 after retries: back off e.retry_after seconds
|
|
175
|
+
...
|
|
176
|
+
except ApiError as e: # anything else from the API
|
|
177
|
+
print(e) # code (status) message [request_id]
|
|
178
|
+
except ApiConnectionError as e: # no response at all (DNS, TLS, timeout)
|
|
179
|
+
...
|
|
180
|
+
except InvalidRequestError as e: # rejected locally before any request was sent
|
|
181
|
+
...
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Classes: ValidationError, AuthenticationError, PermissionDeniedError (`is_ip_not_allowed`, `observed_ip`), FeatureDisabledError, NotFoundError, InsufficientFundsError, ConflictError, IdempotencyConflictError, IdempotencyInProgressError, InvalidStateError, RateLimitError, ProviderError, ProviderUnavailableError, ServiceUnavailableError, InternalError, ApiConnectionError, ApiTimeoutError, ResponseTooLargeError, SignatureVerificationError, PollingTimeoutError, ConfigurationError, InvalidRequestError. Unknown codes map by HTTP status.
|
|
185
|
+
|
|
186
|
+
## Webhook integration
|
|
187
|
+
|
|
188
|
+
Verify the raw body before parsing it. `construct_event` checks the `PaySafe-Signature` header (HMAC-SHA256 over `t.body`, 300 s tolerance, constant-time comparison, several `v1=` values during rotation) and returns the event:
|
|
189
|
+
|
|
190
|
+
```python
|
|
191
|
+
from paysafe_tz import SignatureVerificationError, construct_event
|
|
192
|
+
|
|
193
|
+
try:
|
|
194
|
+
event = construct_event(os.environ["PAYSAFE_WEBHOOK_SECRET"], raw_body, request.headers.get("PaySafe-Signature"))
|
|
195
|
+
except SignatureVerificationError:
|
|
196
|
+
return Response(status=400)
|
|
197
|
+
if event["type"] == "payment.succeeded":
|
|
198
|
+
mark_paid(event["data"]["object"]["reference"]) # deduplicate on event["id"] first
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`verify_signature(...)` returns a boolean instead of raising; both accept a list of secrets. Handlers for FastAPI, Django and Flask are in `examples/webhooks/`, and `examples/verify_webhook.py` is a complete receiver on the standard library server.
|
|
202
|
+
|
|
203
|
+
## Testing
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
python -m venv .venv && . .venv/bin/activate
|
|
207
|
+
pip install -e '.[dev]'
|
|
208
|
+
ruff check . && ruff format --check . && mypy && pytest
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Unit, contract, network, security, webhook and async suites run offline against the fixtures in `tests/fixtures/` that are shared by every PaySafe SDK (HTTP is mocked with `httpx.MockTransport`). The integration suite runs only when `PAYSAFE_SECRET_KEY` holds a `paysafe_test_` key (and optionally `PAYSAFE_BASE_URL`); it refuses live keys and uses the sandbox phone suffixes documented at https://paysafe.co.tz/docs/sandbox.
|
|
212
|
+
|
|
213
|
+
## Contributing
|
|
214
|
+
|
|
215
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). Report security issues as described in [SECURITY.md](SECURITY.md).
|
|
216
|
+
|
|
217
|
+
## License
|
|
218
|
+
|
|
219
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
# PaySafe Python SDK
|
|
2
|
+
|
|
3
|
+
Official Python library for the [PaySafe](https://paysafe.co.tz) payments API. Accept mobile-money payments in Tanzania, issue refunds, control numbers and payment links, move money between projects, and receive signed webhooks.
|
|
4
|
+
|
|
5
|
+
Part of the [PaySafe SDK directory](https://github.com/AmDev255/paysafe-sdks). API reference: https://paysafe.co.tz/docs.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- Every served PaySafe API operation (29 operations, 10 resources) with typed request and response models
|
|
10
|
+
- Sandbox and production selected automatically from the key prefix
|
|
11
|
+
- Safe retries that honour `Retry-After`, idempotency keys that survive retries, cursor pagination helpers
|
|
12
|
+
- Polling helpers that wait for a payment, refund or transfer to reach a terminal state
|
|
13
|
+
- Webhook signature verification with secret rotation support and constant-time comparison
|
|
14
|
+
- One structured exception per documented error code, every error carries the request id
|
|
15
|
+
- Configurable timeouts, base URL, logger and HTTP client
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install paysafe-tz
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Requirements
|
|
24
|
+
|
|
25
|
+
Python 3.9 or newer. Depends on `httpx`; the async client uses `asyncio`.
|
|
26
|
+
|
|
27
|
+
## Authentication
|
|
28
|
+
|
|
29
|
+
Create a secret key in the dashboard under API keys. Test keys start with `paysafe_test_`, live keys with `paysafe_live_`. Keep keys on the server; never ship them in browsers or mobile apps. The SDK reads `PAYSAFE_SECRET_KEY` when no key is passed.
|
|
30
|
+
|
|
31
|
+
## Sandbox setup
|
|
32
|
+
|
|
33
|
+
Use a `paysafe_test_` key. The sandbox is the same API with a simulated provider; the last four digits of the customer phone choose the outcome (`0000` succeeds, `1111` is declined, `4444` expires, see the [Sandbox guide](https://paysafe.co.tz/docs/sandbox)).
|
|
34
|
+
|
|
35
|
+
## Production setup
|
|
36
|
+
|
|
37
|
+
Switch to a `paysafe_live_` key once your organisation is verified. Register a live webhook endpoint and add your server's address to the project's IP allowlist. Nothing else changes.
|
|
38
|
+
|
|
39
|
+
## Quickstart
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import os
|
|
43
|
+
from paysafe_tz import PaySafe, RequestOptions, is_payment_successful
|
|
44
|
+
|
|
45
|
+
client = PaySafe(os.environ["PAYSAFE_SECRET_KEY"]) # paysafe_test_… selects the sandbox
|
|
46
|
+
|
|
47
|
+
payment = client.payments.create(
|
|
48
|
+
{
|
|
49
|
+
"amount": 10000, # TZS, integer
|
|
50
|
+
"customer": {"phone": "+255712340000", "name": "Amina Juma"},
|
|
51
|
+
"reference": "order-8812",
|
|
52
|
+
},
|
|
53
|
+
RequestOptions(idempotency_key="order-8812-attempt-1"), # persist the key before calling
|
|
54
|
+
)
|
|
55
|
+
print(payment.id, payment.status) # 202 Accepted: still pending
|
|
56
|
+
|
|
57
|
+
final = client.payments.wait_for_terminal(payment.id) # or wait for the webhook
|
|
58
|
+
if is_payment_successful(final):
|
|
59
|
+
print("Paid, net TZS", final.net)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Supported API resources
|
|
63
|
+
|
|
64
|
+
| Resource | Operations |
|
|
65
|
+
|---|---|
|
|
66
|
+
| Payments | create, list, get, cancel, waitForTerminal |
|
|
67
|
+
| Payment links | create, list, get, update |
|
|
68
|
+
| Control numbers | create, list, get, cancel |
|
|
69
|
+
| Refunds | create, list, get, waitForTerminal |
|
|
70
|
+
| Top-ups | create, list, get |
|
|
71
|
+
| Balance | get, transactions |
|
|
72
|
+
| Customers | list, get |
|
|
73
|
+
| Transfers | create, list, get, waitForTerminal |
|
|
74
|
+
| Webhook endpoints | list, create, get, update, delete |
|
|
75
|
+
| Events | list, get |
|
|
76
|
+
| Webhooks | verifySignature, constructEvent |
|
|
77
|
+
|
|
78
|
+
Planned by PaySafe and not yet served (not included): `ping`, payouts (`createPayout`, `getPayout`), `rotateWebhookEndpointSecret`.
|
|
79
|
+
|
|
80
|
+
## Usage examples
|
|
81
|
+
|
|
82
|
+
Runnable programs live in [`examples/`](examples/): authentication, creating and polling a payment, listing with pagination, refunds, payment links, control numbers, transfers, webhook endpoints, events and webhook verification, plus framework handlers under `examples/webhooks/`.
|
|
83
|
+
|
|
84
|
+
Every resource follows the same shape: `create`, `list`, `get`, plus resource-specific actions. Objects come back as `ApiObject`, a `dict` with the API's snake_case keys that also allows attribute access (`payment.status` or `payment["status"]`) and carries `last_response`. Lists return a `Page`; iterate it for its items or call `auto_paging_iter()` to walk every page.
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
# Pagination
|
|
88
|
+
for payment in client.payments.list({"status": "succeeded", "limit": 100}).auto_paging_iter():
|
|
89
|
+
...
|
|
90
|
+
|
|
91
|
+
# Top-ups: add money to your own balance (prompt=False opens the order for token, QR or hosted-page payment)
|
|
92
|
+
topup = client.topups.create({"amount": 500000, "phone": "+255712345000", "prompt": False, "reference": "FLOAT-DEC-03"})
|
|
93
|
+
topup = client.topups.get(topup.id) # topup.checkout holds pay_token, qr and url once the order is open
|
|
94
|
+
|
|
95
|
+
# Refunds
|
|
96
|
+
refund = client.refunds.create({"payment": payment.id, "amount": 5000, "reason": "requested_by_customer"})
|
|
97
|
+
|
|
98
|
+
# Payment links and control numbers
|
|
99
|
+
link = client.payment_links.create({"title": "Workshop ticket", "amount": 25000})
|
|
100
|
+
number = client.control_numbers.create({"payer_name": "Amina Juma", "title": "Term 2 fees", "amount": 450000})
|
|
101
|
+
|
|
102
|
+
# Transfers, balance, customers, events
|
|
103
|
+
transfer = client.transfers.create({"to": "merchant_shop", "amount": 5000})
|
|
104
|
+
balance = client.balance.get()
|
|
105
|
+
customer = client.customers.get("cus_…")
|
|
106
|
+
event = client.events.get("evt_…")
|
|
107
|
+
|
|
108
|
+
# Webhook endpoints (the secret is returned once)
|
|
109
|
+
endpoint = client.webhook_endpoints.create({"url": "https://example.com/paysafe", "events": ["payment.succeeded"]})
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Async: `AsyncPaySafe` has the same surface with awaitable methods and `AsyncPage` (`async for item in page`). Both clients are context managers; pass your own `httpx.Client`/`httpx.AsyncClient` to reuse connection pools. `date`/`datetime` values are accepted wherever the API takes RFC 3339 timestamps.
|
|
113
|
+
|
|
114
|
+
Per-request options: `RequestOptions(idempotency_key=…, request_id=…, timeout=…, max_retries=…, headers={…})`. Retries: 429 and 503 wait for `Retry-After`; `idempotency_in_progress` waits one second; 5xx and network errors are retried only when the request is idempotent (GET, PATCH, DELETE, or a POST with an idempotency key). The SDK generates a UUID key for `payments.create`, `refunds.create`, `transfers.create` and `payments.cancel` when you do not pass one and exposes it on `obj.last_response.idempotency_key`; pass your own key derived from the order to survive process restarts.
|
|
115
|
+
|
|
116
|
+
Security: ids, filters, headers and amounts are validated before any request; path and query values are percent-encoded; the base URL must be https (plain http only for localhost); redirects are never followed; TLS verification stays on; response bodies are capped at 16 MB; the key never appears in exceptions or logs.
|
|
117
|
+
|
|
118
|
+
## Error handling
|
|
119
|
+
|
|
120
|
+
Every non-2xx response raises a subclass of `ApiError` chosen by the error code, with `status`, `code`, `request_id`, `param`, `details`, `doc_url`, `retry_after` and `rate_limit`:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from paysafe_tz import (
|
|
124
|
+
ApiConnectionError,
|
|
125
|
+
ApiError,
|
|
126
|
+
InvalidRequestError,
|
|
127
|
+
InvalidStateError,
|
|
128
|
+
RateLimitError,
|
|
129
|
+
ValidationError,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
client.payments.cancel(payment_id)
|
|
134
|
+
except ValidationError as e: # 400: fix the request (e.param names the field)
|
|
135
|
+
...
|
|
136
|
+
except InvalidStateError as e: # 409: read the object and decide again
|
|
137
|
+
...
|
|
138
|
+
except RateLimitError as e: # 429 after retries: back off e.retry_after seconds
|
|
139
|
+
...
|
|
140
|
+
except ApiError as e: # anything else from the API
|
|
141
|
+
print(e) # code (status) message [request_id]
|
|
142
|
+
except ApiConnectionError as e: # no response at all (DNS, TLS, timeout)
|
|
143
|
+
...
|
|
144
|
+
except InvalidRequestError as e: # rejected locally before any request was sent
|
|
145
|
+
...
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Classes: ValidationError, AuthenticationError, PermissionDeniedError (`is_ip_not_allowed`, `observed_ip`), FeatureDisabledError, NotFoundError, InsufficientFundsError, ConflictError, IdempotencyConflictError, IdempotencyInProgressError, InvalidStateError, RateLimitError, ProviderError, ProviderUnavailableError, ServiceUnavailableError, InternalError, ApiConnectionError, ApiTimeoutError, ResponseTooLargeError, SignatureVerificationError, PollingTimeoutError, ConfigurationError, InvalidRequestError. Unknown codes map by HTTP status.
|
|
149
|
+
|
|
150
|
+
## Webhook integration
|
|
151
|
+
|
|
152
|
+
Verify the raw body before parsing it. `construct_event` checks the `PaySafe-Signature` header (HMAC-SHA256 over `t.body`, 300 s tolerance, constant-time comparison, several `v1=` values during rotation) and returns the event:
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
from paysafe_tz import SignatureVerificationError, construct_event
|
|
156
|
+
|
|
157
|
+
try:
|
|
158
|
+
event = construct_event(os.environ["PAYSAFE_WEBHOOK_SECRET"], raw_body, request.headers.get("PaySafe-Signature"))
|
|
159
|
+
except SignatureVerificationError:
|
|
160
|
+
return Response(status=400)
|
|
161
|
+
if event["type"] == "payment.succeeded":
|
|
162
|
+
mark_paid(event["data"]["object"]["reference"]) # deduplicate on event["id"] first
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
`verify_signature(...)` returns a boolean instead of raising; both accept a list of secrets. Handlers for FastAPI, Django and Flask are in `examples/webhooks/`, and `examples/verify_webhook.py` is a complete receiver on the standard library server.
|
|
166
|
+
|
|
167
|
+
## Testing
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
python -m venv .venv && . .venv/bin/activate
|
|
171
|
+
pip install -e '.[dev]'
|
|
172
|
+
ruff check . && ruff format --check . && mypy && pytest
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Unit, contract, network, security, webhook and async suites run offline against the fixtures in `tests/fixtures/` that are shared by every PaySafe SDK (HTTP is mocked with `httpx.MockTransport`). The integration suite runs only when `PAYSAFE_SECRET_KEY` holds a `paysafe_test_` key (and optionally `PAYSAFE_BASE_URL`); it refuses live keys and uses the sandbox phone suffixes documented at https://paysafe.co.tz/docs/sandbox.
|
|
176
|
+
|
|
177
|
+
## Contributing
|
|
178
|
+
|
|
179
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). Report security issues as described in [SECURITY.md](SECURITY.md).
|
|
180
|
+
|
|
181
|
+
## License
|
|
182
|
+
|
|
183
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""The same payment flow with the asyncio client.
|
|
2
|
+
|
|
3
|
+
Usage: python examples/async_payment.py [+255712340000]
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
import secrets
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from paysafe_tz import AsyncPaySafe, RequestOptions, is_payment_successful
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
async def main() -> None:
|
|
14
|
+
phone = sys.argv[1] if len(sys.argv) > 1 else "+255712340000"
|
|
15
|
+
order_id = f"order-{secrets.token_hex(4)}"
|
|
16
|
+
async with AsyncPaySafe() as client:
|
|
17
|
+
payment = await client.payments.create(
|
|
18
|
+
{"amount": 10000, "customer": {"phone": phone}, "reference": order_id},
|
|
19
|
+
RequestOptions(idempotency_key=f"{order_id}-attempt-1"),
|
|
20
|
+
)
|
|
21
|
+
print(f"Created {payment.id} {payment.status}")
|
|
22
|
+
final = await client.payments.wait_for_terminal(payment.id, on_update=lambda p: print(f" {p.status}"))
|
|
23
|
+
print("Paid" if is_payment_successful(final) else f"Not paid: {final.status}")
|
|
24
|
+
|
|
25
|
+
async for p in await client.payments.list({"limit": 3}):
|
|
26
|
+
print(f"{p.id} {p.status}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Proves the key works with a read-only call and prints the rate-limit budget.
|
|
2
|
+
|
|
3
|
+
Usage: PAYSAFE_SECRET_KEY=paysafe_test_... python examples/auth.py
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from paysafe_tz import ApiError, PaySafe, PaySafeError, balance_amount
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
with PaySafe() as client:
|
|
12
|
+
balance = client.balance.get()
|
|
13
|
+
rate = balance.last_response.rate_limit if balance.last_response else None
|
|
14
|
+
print(f"Environment : {client.environment}")
|
|
15
|
+
print(f"Available : TZS {balance_amount(balance['available']):,}")
|
|
16
|
+
print(f"Pending : TZS {balance_amount(balance['pending']):,}")
|
|
17
|
+
print(f"Rate limit : {rate.remaining if rate else '?'} remaining of {rate.limit if rate else '?'}")
|
|
18
|
+
print(f"Request id : {balance.request_id}")
|
|
19
|
+
except ApiError as e:
|
|
20
|
+
print(f"API error {e.code} ({e.status}): {e.message} [{e.request_id}]", file=sys.stderr)
|
|
21
|
+
sys.exit(1)
|
|
22
|
+
except PaySafeError as e:
|
|
23
|
+
print(f"Error: {e}", file=sys.stderr)
|
|
24
|
+
sys.exit(1)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Issues a control number for an invoice, reads it back with its payment entries, then cancels it."""
|
|
2
|
+
|
|
3
|
+
from paysafe_tz import PaySafe
|
|
4
|
+
|
|
5
|
+
with PaySafe() as client:
|
|
6
|
+
number = client.control_numbers.create(
|
|
7
|
+
{
|
|
8
|
+
"payer_name": "Amina Juma",
|
|
9
|
+
"payer_phone": "+255712340000",
|
|
10
|
+
"payer_reference": "STU-2024-0091",
|
|
11
|
+
"title": "Term 2 school fees",
|
|
12
|
+
"reference": "INV-2026-0042",
|
|
13
|
+
"payment_type": "fees",
|
|
14
|
+
"mode": "instalment",
|
|
15
|
+
"amount": 450000,
|
|
16
|
+
"expires_at": "2026-12-31",
|
|
17
|
+
"instalments": [
|
|
18
|
+
{"amount": 225000, "due_at": "2026-11-30T00:00:00Z"},
|
|
19
|
+
{"amount": 225000, "due_at": "2026-12-31T00:00:00Z"},
|
|
20
|
+
],
|
|
21
|
+
}
|
|
22
|
+
)
|
|
23
|
+
print(f"Control number {number.formatted} ({number.id}) pay at {number['pay_url']}")
|
|
24
|
+
|
|
25
|
+
detail = client.control_numbers.get(number.id)
|
|
26
|
+
print(f"Balance TZS {detail.balance}, {len(detail['entries'])} entries, {detail['payment_status']}")
|
|
27
|
+
for entry in detail["entries"]:
|
|
28
|
+
print(f" {entry['paid_at']} {entry['status']} {entry['amount']} via {entry['method']}")
|
|
29
|
+
|
|
30
|
+
for item in client.control_numbers.list({"state": "unpaid", "limit": 5}):
|
|
31
|
+
print(f"{item.formatted} {item['payer']['name']} owes {item.balance}")
|
|
32
|
+
|
|
33
|
+
cancelled = client.control_numbers.cancel(number.id, "Issued in error during SDK example")
|
|
34
|
+
print(f"Cancelled: {cancelled.status}")
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Creates a TZS 10,000 payment with a persisted idempotency key, then polls until it is terminal.
|
|
2
|
+
|
|
3
|
+
Usage: python examples/create_payment.py [+255712340000]
|
|
4
|
+
Sandbox suffixes: 0000 succeeds, 1111 is declined, 4444 expires.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import secrets
|
|
8
|
+
import sys
|
|
9
|
+
import tempfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from paysafe_tz import ApiError, PaySafe, PollingTimeoutError, RequestOptions, is_payment_successful
|
|
13
|
+
|
|
14
|
+
phone = sys.argv[1] if len(sys.argv) > 1 else "+255712340000"
|
|
15
|
+
order_id = f"order-{secrets.token_hex(4)}"
|
|
16
|
+
|
|
17
|
+
# Store the key with the order before sending, so a crash and restart reuses it instead of charging twice.
|
|
18
|
+
key_file = Path(tempfile.gettempdir()) / f"paysafe-{order_id}.key"
|
|
19
|
+
idempotency_key = key_file.read_text() if key_file.exists() else f"{order_id}-attempt-1"
|
|
20
|
+
key_file.write_text(idempotency_key)
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
with PaySafe() as client:
|
|
24
|
+
payment = client.payments.create(
|
|
25
|
+
{
|
|
26
|
+
"amount": 10000,
|
|
27
|
+
"currency": "TZS",
|
|
28
|
+
"customer": {"phone": phone, "name": "Amina Juma"},
|
|
29
|
+
"reference": order_id,
|
|
30
|
+
"description": f"Order {order_id}",
|
|
31
|
+
"metadata": {"order_id": order_id},
|
|
32
|
+
},
|
|
33
|
+
RequestOptions(idempotency_key=idempotency_key),
|
|
34
|
+
)
|
|
35
|
+
response = payment.last_response
|
|
36
|
+
replayed = ", replayed" if response and response.idempotent_replayed else ""
|
|
37
|
+
print(f"Created {payment.id} status={payment.status} (HTTP {response.status if response else '?'}{replayed})")
|
|
38
|
+
|
|
39
|
+
final = client.payments.wait_for_terminal(payment.id, on_update=lambda p: print(f" {p.status}"))
|
|
40
|
+
if is_payment_successful(final):
|
|
41
|
+
print(f"Paid: amount {final.amount} fee {final.fee} net {final.net}")
|
|
42
|
+
else:
|
|
43
|
+
failure = final.get("failure") or {}
|
|
44
|
+
print(f"Not paid: {final.status} {failure.get('code') or ''}")
|
|
45
|
+
except PollingTimeoutError as e:
|
|
46
|
+
print(f"Still {e.last_seen.get('status') if e.last_seen else 'unknown'} after the timeout; rely on the webhook")
|
|
47
|
+
except ApiError as e:
|
|
48
|
+
print(f"API error {e.code} ({e.status}): {e.message} [{e.request_id}]", file=sys.stderr)
|
|
49
|
+
sys.exit(1)
|
|
50
|
+
finally:
|
|
51
|
+
key_file.unlink(missing_ok=True)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Reads the balance, the latest ledger entries and recent customers."""
|
|
2
|
+
|
|
3
|
+
from paysafe_tz import PaySafe, balance_amount
|
|
4
|
+
|
|
5
|
+
with PaySafe() as client:
|
|
6
|
+
balance = client.balance.get()
|
|
7
|
+
print(f"Available TZS {balance_amount(balance['available']):,}, pending TZS {balance_amount(balance['pending']):,}")
|
|
8
|
+
|
|
9
|
+
for tx in client.balance.transactions({"limit": 5}):
|
|
10
|
+
print(f"{tx['created_at']} {tx.direction:<6} {tx.bucket:<9} {tx.amount:>8} → {tx['balance_after']}")
|
|
11
|
+
|
|
12
|
+
for customer in client.customers.list({"limit": 5}):
|
|
13
|
+
paid = customer.get("payment_count", 0)
|
|
14
|
+
print(f"{customer.id} {customer.phone} paid {paid} times, TZS {customer.get('total_paid', 0)}")
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Lists recent payment events and shows the delivery attempts for the newest one."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timedelta, timezone
|
|
4
|
+
|
|
5
|
+
from paysafe_tz import PaySafe
|
|
6
|
+
|
|
7
|
+
with PaySafe() as client:
|
|
8
|
+
events = client.events.list(
|
|
9
|
+
{"type": "payment.succeeded", "from_": datetime.now(timezone.utc) - timedelta(days=1), "limit": 10}
|
|
10
|
+
)
|
|
11
|
+
for event in events:
|
|
12
|
+
print(f"{event['created_at']} {event.id} {event['data']['object'].get('id', '')}")
|
|
13
|
+
|
|
14
|
+
if events.data:
|
|
15
|
+
detail = client.events.get(events.data[0].id)
|
|
16
|
+
for d in detail["deliveries"]:
|
|
17
|
+
status = d.get("response_status") or "-"
|
|
18
|
+
print(f" attempt {d['attempt']} {d['status']} HTTP {status} {d.get('latency_ms') or '-'}ms")
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Retrieves a payment by id and waits for a terminal state.
|
|
2
|
+
|
|
3
|
+
Usage: python examples/get_payment.py pay_01J7A9Q0K3M4N5P6R7S8T9V0W1
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from paysafe_tz import NotFoundError, PaySafe, is_payment_terminal
|
|
9
|
+
|
|
10
|
+
if len(sys.argv) < 2:
|
|
11
|
+
print("usage: python examples/get_payment.py <payment id>", file=sys.stderr)
|
|
12
|
+
sys.exit(2)
|
|
13
|
+
|
|
14
|
+
with PaySafe() as client:
|
|
15
|
+
try:
|
|
16
|
+
payment = client.payments.get(sys.argv[1])
|
|
17
|
+
print(f"{payment.id} {payment.status} TZS {payment.amount} for {payment['customer']['phone']}")
|
|
18
|
+
if not is_payment_terminal(payment):
|
|
19
|
+
payment = client.payments.wait_for_terminal(payment.id)
|
|
20
|
+
print(f"Final status: {payment.status}")
|
|
21
|
+
except NotFoundError:
|
|
22
|
+
print("No such payment in this project and environment", file=sys.stderr)
|
|
23
|
+
sys.exit(1)
|