presto-pay-sdk 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.
Files changed (66) hide show
  1. presto_pay_sdk-0.1.0/.gitignore +18 -0
  2. presto_pay_sdk-0.1.0/CHANGELOG.md +31 -0
  3. presto_pay_sdk-0.1.0/LICENSE +202 -0
  4. presto_pay_sdk-0.1.0/PKG-INFO +301 -0
  5. presto_pay_sdk-0.1.0/README.md +272 -0
  6. presto_pay_sdk-0.1.0/docs/payments-and-errors.md +118 -0
  7. presto_pay_sdk-0.1.0/docs/production.md +37 -0
  8. presto_pay_sdk-0.1.0/docs/webhooks.md +177 -0
  9. presto_pay_sdk-0.1.0/pyproject.toml +90 -0
  10. presto_pay_sdk-0.1.0/spec/.gitattributes +6 -0
  11. presto_pay_sdk-0.1.0/spec/.gitignore +5 -0
  12. presto_pay_sdk-0.1.0/spec/.source-commit +1 -0
  13. presto_pay_sdk-0.1.0/spec/README.md +90 -0
  14. presto_pay_sdk-0.1.0/spec/keys/presto-staging.der +0 -0
  15. presto_pay_sdk-0.1.0/spec/keys/test-merchant-cert.der +0 -0
  16. presto_pay_sdk-0.1.0/spec/keys/test-merchant-cert.pem +20 -0
  17. presto_pay_sdk-0.1.0/spec/keys/test-merchant-key.pem +28 -0
  18. presto_pay_sdk-0.1.0/spec/keys/test-merchant-public.pem +9 -0
  19. presto_pay_sdk-0.1.0/spec/scripts/probe-canonicalization.mjs +78 -0
  20. presto_pay_sdk-0.1.0/spec/scripts/sign-vectors.mjs +78 -0
  21. presto_pay_sdk-0.1.0/spec/scripts/verify-vectors.mjs +168 -0
  22. presto_pay_sdk-0.1.0/spec/vectors/canonical.json +236 -0
  23. presto_pay_sdk-0.1.0/spec/vectors/refund-policy.json +9 -0
  24. presto_pay_sdk-0.1.0/spec/vectors/signatures.json +47 -0
  25. presto_pay_sdk-0.1.0/spec/vectors/timestamps.json +92 -0
  26. presto_pay_sdk-0.1.0/spec/wire-contract.md +401 -0
  27. presto_pay_sdk-0.1.0/src/presto_pay/__init__.py +96 -0
  28. presto_pay_sdk-0.1.0/src/presto_pay/_core/__init__.py +0 -0
  29. presto_pay_sdk-0.1.0/src/presto_pay/_core/canonical.py +76 -0
  30. presto_pay_sdk-0.1.0/src/presto_pay/_core/crypto.py +22 -0
  31. presto_pay_sdk-0.1.0/src/presto_pay/_core/keys.py +227 -0
  32. presto_pay_sdk-0.1.0/src/presto_pay/_core/mapping.py +101 -0
  33. presto_pay_sdk-0.1.0/src/presto_pay/_core/protocol.py +278 -0
  34. presto_pay_sdk-0.1.0/src/presto_pay/_core/redaction.py +71 -0
  35. presto_pay_sdk-0.1.0/src/presto_pay/_core/retry.py +136 -0
  36. presto_pay_sdk-0.1.0/src/presto_pay/_core/timestamp.py +53 -0
  37. presto_pay_sdk-0.1.0/src/presto_pay/_version.py +1 -0
  38. presto_pay_sdk-0.1.0/src/presto_pay/client.py +524 -0
  39. presto_pay_sdk-0.1.0/src/presto_pay/constants.py +187 -0
  40. presto_pay_sdk-0.1.0/src/presto_pay/errors.py +168 -0
  41. presto_pay_sdk-0.1.0/src/presto_pay/payments/__init__.py +0 -0
  42. presto_pay_sdk-0.1.0/src/presto_pay/payments/inputs.py +153 -0
  43. presto_pay_sdk-0.1.0/src/presto_pay/payments/results.py +197 -0
  44. presto_pay_sdk-0.1.0/src/presto_pay/payments/to_wire.py +183 -0
  45. presto_pay_sdk-0.1.0/src/presto_pay/py.typed +0 -0
  46. presto_pay_sdk-0.1.0/src/presto_pay/webhooks/__init__.py +0 -0
  47. presto_pay_sdk-0.1.0/src/presto_pay/webhooks/ack.py +20 -0
  48. presto_pay_sdk-0.1.0/src/presto_pay/webhooks/events.py +47 -0
  49. presto_pay_sdk-0.1.0/src/presto_pay/webhooks/verifier.py +159 -0
  50. presto_pay_sdk-0.1.0/tests/conftest.py +171 -0
  51. presto_pay_sdk-0.1.0/tests/fixtures/test-merchant-legacy.p12 +0 -0
  52. presto_pay_sdk-0.1.0/tests/test_config.py +143 -0
  53. presto_pay_sdk-0.1.0/tests/test_constants.py +73 -0
  54. presto_pay_sdk-0.1.0/tests/test_errors.py +65 -0
  55. presto_pay_sdk-0.1.0/tests/test_keys.py +181 -0
  56. presto_pay_sdk-0.1.0/tests/test_parity.py +69 -0
  57. presto_pay_sdk-0.1.0/tests/test_payments.py +459 -0
  58. presto_pay_sdk-0.1.0/tests/test_protocol.py +339 -0
  59. presto_pay_sdk-0.1.0/tests/test_release_fixes.py +189 -0
  60. presto_pay_sdk-0.1.0/tests/test_retry.py +283 -0
  61. presto_pay_sdk-0.1.0/tests/test_sockets.py +188 -0
  62. presto_pay_sdk-0.1.0/tests/test_staging.py +78 -0
  63. presto_pay_sdk-0.1.0/tests/test_vectors.py +103 -0
  64. presto_pay_sdk-0.1.0/tests/test_version.py +7 -0
  65. presto_pay_sdk-0.1.0/tests/test_webhooks.py +199 -0
  66. presto_pay_sdk-0.1.0/tests/test_wire.py +85 -0
@@ -0,0 +1,18 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ /.venv/
4
+ /dist/
5
+ /build/
6
+ *.egg-info/
7
+ /.pytest_cache/
8
+ /.mypy_cache/
9
+ /.ruff_cache/
10
+ /.coverage
11
+ /htmlcov/
12
+ .env
13
+ *.p12
14
+ *.pfx
15
+ *.key
16
+ *.pem
17
+ !/spec/keys/*.pem
18
+ !/tests/fixtures/*.p12
@@ -0,0 +1,31 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.1.0 - 2026-10-01
6
+
7
+ First published release.
8
+
9
+ - Initial Python 3.11+ SDK: `init`, `query`, `reverse` and `refund`, sync (`PrestoPay`) and async
10
+ (`AsyncPrestoPay`) over one sans-IO core, with a CI test that both send byte-identical requests.
11
+ - Request signing and response verification (RSASSA-PKCS1-v1_5 / SHA-256). Every vector in the vendored
12
+ `presto-pay-spec` passes, including two staging captures verified against Presto's staging certificate.
13
+ - Keys from PKCS#8 PEM or DER, encrypted PEM, and PKCS#12 keystores, including the RC2-40 legacy encryption of
14
+ the onboarding keystore. Presto keys from X.509 certificates (PEM or DER) or SPKI PEM, with several keys
15
+ accepted at once for rotation.
16
+ - `may_have_taken_effect` and `reconcile_by` on every error, decided per operation where the error is raised.
17
+ - A whole-call `deadline` and a `retry_reads` policy (exponential backoff, full jitter, `Retry-After`). The async
18
+ client enforces the deadline exactly, and the sync client checks it after each chunk of the response. `init`,
19
+ `reverse` and `refund` are retried only when `httpx` proves the request was never sent. A loopback socket suite
20
+ proves that classification.
21
+ - Webhook verification with multi-`mid` and multi-key support and a 15-minute freshness window.
22
+ `NotifyAck.for_error` answers `resend:false` only when verifying the webhook itself failed. Errors from calls
23
+ made inside the handler get `resend:true`, so the event is redelivered. `WebhookEvent` carries `event_code` and
24
+ `success` as sent and derives no payment status; handlers call `query` for the latest status.
25
+ - `sample/flask-store/` and `sample/fastapi-store/`: a MyStore checkout sample, on Flask with `PrestoPay` and on
26
+ FastAPI with `AsyncPrestoPay`.
27
+ - `from_env`, `strict` mode, and the `raw.post` escape hatch.
28
+ - Error bodies and canonical strings are redacted of card, receipt and customer details (`qrValue`,
29
+ `payerRefNum`, `bindData`, device and transactional data).
30
+ - Constructors reject a mismatched `http_client` (sync versus async), and non-finite `deadline`, backoff and
31
+ webhook-window values.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,301 @@
1
+ Metadata-Version: 2.5
2
+ Name: presto-pay-sdk
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the Presto Pay payment gateway
5
+ Project-URL: Homepage, https://github.com/prestoconnect/presto-pay-sdk-python
6
+ Project-URL: Source, https://github.com/prestoconnect/presto-pay-sdk-python
7
+ Project-URL: Issues, https://github.com/prestoconnect/presto-pay-sdk-python/issues
8
+ Project-URL: Changelog, https://github.com/prestoconnect/presto-pay-sdk-python/blob/main/CHANGELOG.md
9
+ Author-email: Presto Connect Developer <developer@prestoconnect.io>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: payment gateway,payments,presto,presto pay,sdk
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Office/Business :: Financial
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.11
26
+ Requires-Dist: cryptography>=42
27
+ Requires-Dist: httpx<1,>=0.27
28
+ Description-Content-Type: text/markdown
29
+
30
+ # Presto Pay SDK for Python
31
+
32
+ [![PyPI](https://img.shields.io/pypi/v/presto-pay-sdk.svg)](https://pypi.org/project/presto-pay-sdk/)
33
+ [![CI](https://github.com/prestoconnect/presto-pay-sdk-python/actions/workflows/ci.yml/badge.svg)](https://github.com/prestoconnect/presto-pay-sdk-python/actions/workflows/ci.yml)
34
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/prestoconnect/presto-pay-sdk-python/blob/main/LICENSE)
35
+
36
+ A Python 3.11+ library for the **Presto Connect** payment gateway. It takes care of the parts of a signed
37
+ payment API that are easy to get slightly wrong by hand: RSA request signing, verifying response and webhook
38
+ signatures, gateway timestamps, loading keys (including the onboarding `.p12` keystore), and errors that tell
39
+ you when a payment might have gone through anyway.
40
+
41
+ - **Sync and async** with the same API: `PrestoPay` for Django, Flask and Celery, and `AsyncPrestoPay` for
42
+ FastAPI and other asyncio apps. Both run on the same core, and CI checks that they send identical bytes.
43
+ - Two dependencies: `cryptography` and `httpx`. No pydantic.
44
+ - Fully typed (`py.typed`, `mypy --strict`). Results are frozen dataclasses with snake_case fields.
45
+
46
+ ## Contents
47
+
48
+ - [Install](#install)
49
+ - [Quick start](#quick-start)
50
+ - [Merchant identity](#merchant-identity)
51
+ - [Configuration from environment](#configuration-from-environment)
52
+ - [Retries and idempotency](#retries-and-idempotency)
53
+ - [Webhooks](#webhooks)
54
+ - [Errors](#errors)
55
+ - [Custom HTTP client](#custom-http-client)
56
+ - [Debugging signatures](#debugging-signatures)
57
+ - [Samples](#samples)
58
+ - [Contributing](#contributing)
59
+ - [License](#license)
60
+
61
+ ## Install
62
+
63
+ ```bash
64
+ pip install presto-pay-sdk
65
+ ```
66
+
67
+ The package imports as `presto_pay`. CI runs it on CPython 3.11, 3.12, 3.13 and 3.14.
68
+
69
+ ## Quick start
70
+
71
+ ```python
72
+ from pathlib import Path
73
+
74
+ from presto_pay import PaymentMethod, PrestoPay, TxnType
75
+
76
+ presto = PrestoPay(
77
+ environment="staging", # "staging", "production", or Environment(base_url=...)
78
+ merchant_id="YOUR_MID", # mid, sent on every request
79
+ private_key=Path("partner.p12"), # onboarding keystore, PKCS#8 PEM, or DER
80
+ private_key_password="keystore-password",
81
+ presto_public_key=Path("presto.der"), # Presto's certificate (PEM or DER), or a list during rotation
82
+ )
83
+
84
+ payment = presto.payments.init(
85
+ presto_mrn="YOUR_PRESTO_MRN", # required on every request
86
+ txn_type=TxnType.WEB_PAY,
87
+ txn_ref_num="order-123",
88
+ display_desc="Order 123",
89
+ amount=10_000, # minor currency units: MYR 100.00
90
+ currency_code="MYR",
91
+ notify_url="https://your-app.example/presto/notify",
92
+ redirect_url="https://your-app.example/presto/return/order-123",
93
+ allowed_payment_methods=[PaymentMethod.WALLET],
94
+ )
95
+ redirect(payment.payment_url)
96
+ ```
97
+
98
+ The async client has the same API, but you `await` each call:
99
+
100
+ ```python
101
+ from presto_pay import AsyncPrestoPay
102
+
103
+ async with AsyncPrestoPay(environment="staging", ...) as presto:
104
+ payment = await presto.payments.init(...)
105
+ ```
106
+
107
+ Key material is parsed when the client is constructed, so a bad key or password fails at startup rather than
108
+ on the first payment. Give each order its own `txn_ref_num`. See [payments and errors](https://github.com/prestoconnect/presto-pay-sdk-python/blob/main/docs/payments-and-errors.md)
109
+ for `query`, `reverse` and `refund`.
110
+
111
+ ## Merchant identity
112
+
113
+ Each client belongs to one merchant. `merchant_id` (`mid`) goes on the constructor and is sent with every
114
+ request. The client's webhook verifier rejects events addressed to any other `mid`. `presto_mrn` is passed on
115
+ each call, because one `mid` can have several.
116
+
117
+ To serve several merchants, create one client per `mid`. They can share keys and an `httpx` client. To receive
118
+ webhooks for several merchants on one endpoint, use `create_webhook_verifier(merchant_id={...})`.
119
+
120
+ ## Configuration from environment
121
+
122
+ ```python
123
+ import os
124
+
125
+ from presto_pay import PrestoPay
126
+
127
+ presto = PrestoPay.from_env(os.environ)
128
+ ```
129
+
130
+ `from_env` accepts any mapping: `os.environ`, a dict from a secrets manager, or flattened Django settings. It
131
+ also takes the constructor's other options as keyword arguments, such as `http_client`, `deadline` and
132
+ `strict`. `AsyncPrestoPay.from_env` works the same way.
133
+
134
+ | Variable | Description |
135
+ |----------|-------------|
136
+ | `PRESTOPAY_ENV` or `PRESTOPAY_BASE_URL` | `staging` / `production`, or an explicit HTTPS base URL (set one, not both) |
137
+ | `PRESTOPAY_MID` | Merchant ID |
138
+ | `PRESTOPAY_PRIVATE_KEY` or `PRESTOPAY_PRIVATE_KEY_FILE` | PEM text, or a path to a PEM, DER or `.p12` file |
139
+ | `PRESTOPAY_PRIVATE_KEY_PASSWORD` | Keystore or encrypted-PEM password, if any |
140
+ | `PRESTOPAY_PUBLIC_KEY` or `PRESTOPAY_PUBLIC_KEY_FILE` | Presto's certificate (PEM or DER) or SPKI public key |
141
+
142
+ If a PEM is stored on one line with literal `\n` sequences (common in `.env` files and secrets managers), it is
143
+ unescaped automatically.
144
+
145
+ ### The onboarding `.p12`
146
+
147
+ `cryptography` reads Presto's PKCS#12 keystore directly, including its RC2-40 certificate bag, which the OpenSSL 3
148
+ command line rejects unless the legacy provider is loaded. You don't need to convert it; pass the file and its
149
+ password.
150
+
151
+ ## Retries and idempotency
152
+
153
+ The SDK **never** automatically resends `init`, `reverse` or `refund` once any byte of the request may have
154
+ reached the gateway. It retries them only when `httpx` shows the request was never sent (DNS failure, refused or
155
+ timed-out connect, TLS failure, pool timeout). `query` is read-only, so it is also retried on other transport
156
+ errors and on HTTP 5xx.
157
+
158
+ Retries use exponential backoff with full jitter and honour `Retry-After`. All attempts, backoff included,
159
+ share one whole-call `deadline` (30 s by default). Configure them with `retry_reads=RetryReads(max_retries=2,
160
+ initial_backoff=0.2, max_backoff=5.0)`.
161
+
162
+ `AsyncPrestoPay` enforces the deadline exactly. `PrestoPay` limits each connect, write and read to the time
163
+ remaining, and checks the deadline after each chunk of the response. A single network operation that stalls
164
+ can still run up to its own limit before the deadline is noticed.
165
+
166
+ When the outcome is unknown, the error says so, and it carries the lookup key you need to find out:
167
+
168
+ ```python
169
+ from presto_pay import PrestoPayError
170
+
171
+ try:
172
+ payment = presto.payments.init(...)
173
+ except PrestoPayError as exc:
174
+ if not exc.may_have_taken_effect or exc.reconcile_by is None:
175
+ raise
176
+ payment = presto.payments.query(**exc.reconcile_by)
177
+ ```
178
+
179
+ `may_have_taken_effect` is set where the error is raised, because the answer depends on the operation. For
180
+ example, an HTTP 502 on `init` is ambiguous, but an HTTP 502 on `query` means nothing happened. `reconcile_by`
181
+ holds `presto_mrn` plus `txn_ref_num` after `init`, or `payment_ref_num` after `reverse` and `refund`. It is
182
+ `None` after `presto.raw.post`, which can't know the lookup key for an endpoint the SDK doesn't model.
183
+
184
+ `init` is idempotent by `txn_ref_num` on the gateway side. Resending an existing `txn_ref_num` returns that
185
+ payment's current status instead of creating a second one. Business error `1203` proves a record exists but not
186
+ what state it is in, so it is also flagged `may_have_taken_effect`.
187
+
188
+ ## Webhooks
189
+
190
+ Presto POSTs a signed JSON body to your `notify_url`, which must be publicly reachable. Always verify the
191
+ **raw** request body. The verifier checks four things: the signature, the required fields, that the `mid`
192
+ belongs to you, and that `ts` is within 15 minutes of your clock. Then deduplicate on `event_ref_num` before
193
+ fulfilling:
194
+
195
+ ```python
196
+ from presto_pay import NotifyAck
197
+
198
+
199
+ @app.post("/presto/notify") # Flask
200
+ def presto_notify():
201
+ try:
202
+ event = presto.webhooks.verify(request.get_data())
203
+ record_once(event.event_ref_num, event) # unique constraint on event_ref_num
204
+ body = NotifyAck.OK
205
+ except Exception as exc:
206
+ body = NotifyAck.for_error(exc)
207
+ return body, 200, {"Content-Type": NotifyAck.CONTENT_TYPE}
208
+ ```
209
+
210
+ `NotifyAck.for_error` replies `{"resend":false}` only when verifying the webhook itself failed: a bad
211
+ signature, a foreign `mid`, a stale `ts`, or a malformed body. Presto retries at 1, 2, 5 and 10 minutes, and each
212
+ of those redeliveries would fail the same way. Anything else gets `{"resend":true}`. That includes your own
213
+ transient failures, and SDK errors from calls your handler makes, such as a `query` that fails.
214
+
215
+ A process that only receives webhooks doesn't need the private key:
216
+
217
+ ```python
218
+ from presto_pay import create_webhook_verifier
219
+
220
+ verifier = create_webhook_verifier(merchant_id=os.environ["PRESTOPAY_MID"], presto_public_key=Path("presto.der"))
221
+ ```
222
+
223
+ A webhook tells you something happened, not the payment's resulting status. The event carries `event_code` and
224
+ `success` as Presto sent them. Call `presto.payments.query(...)` in the handler to get the latest status.
225
+
226
+ For Django, FastAPI and Flask handlers, deduplication and the raw-body accessor for each framework, see
227
+ [webhook handling](https://github.com/prestoconnect/presto-pay-sdk-python/blob/main/docs/webhooks.md).
228
+
229
+ ## Errors
230
+
231
+ Every error is a `PrestoPayError` and carries `operation`, `may_have_taken_effect` and `reconcile_by`.
232
+
233
+ | Class | When | Extra attributes |
234
+ |-------|------|------------------|
235
+ | `PrestoPayConfigError` | Invalid options or request input, including bad keys and unencodable strings | `field` |
236
+ | `PrestoPayTransportError` | Network failure or timeout | `request_not_sent` |
237
+ | `PrestoPayApiError` | Non-200 status (`kind="http"`) or `success: false` (`kind="business"`) | `http_status`, `error_code`, `error_message`, `raw_body`; `canonical` on `1006`/`1007`; `clock_offset` on `1005` |
238
+ | `PrestoPaySignatureError` | Missing or invalid signature, wrong webhook `mid`, stale webhook `ts` | `source`, `canonical` |
239
+ | `PrestoPayResponseError` | Malformed body, missing required field, bad `ts`, echo mismatch | `source`, `raw_body` |
240
+
241
+ Compare error codes against `ErrorCode`, for example `ErrorCode.CLOCK_SKEW == "1005"`. The original `httpx`
242
+ exception is chained as `__cause__`. No `httpx` type is part of the public API.
243
+
244
+ **Redaction.** `raw_body` and `canonical` can contain card, receipt and customer details. By default the
245
+ values of `cardBin`, `cardSummary`, `receiptEmail`, `receiptName`, `qrValue`, `payerRefNum`, `bindData`,
246
+ `deviceIp`, `deviceRefNum` and `transactionalData` are replaced with `[redacted]`, including inside the
247
+ stringified `paymentDetails`. An unparseable body is replaced entirely. `str()` and `repr()` of an error never
248
+ include a body. To keep full bodies for debugging, pass `redact_error_bodies=False`.
249
+
250
+ **Strict mode.** `strict=True` rejects contract drift that is tolerated by default: a number where the gateway
251
+ documents a string, or a field longer than its documented maximum. Use it in staging.
252
+
253
+ ## Custom HTTP client
254
+
255
+ Pass your own `httpx.Client` (or `httpx.AsyncClient`) to set up proxies, TLS, connection limits or tracing, or to
256
+ share a pool:
257
+
258
+ ```python
259
+ import httpx
260
+
261
+ presto = PrestoPay(..., http_client=httpx.Client(proxy="http://proxy.internal:3128"))
262
+ ```
263
+
264
+ The SDK sets the timeout on each request and turns redirects off. It never closes a client you pass in. It
265
+ closes only the one it creates, when you use `with` / `async with`, `close()` or `aclose()`. Don't configure the
266
+ client to retry requests. `httpx.HTTPTransport(retries=n)` is safe because it retries only failed connections,
267
+ which never send any bytes.
268
+
269
+ ## Debugging signatures
270
+
271
+ `canonicalize(body)` builds the canonical string for a raw JSON body, which is the exact text that gets signed.
272
+ When the gateway rejects a request signature (`1006`/`1007`), `exc.canonical` holds the string the SDK signed.
273
+ For endpoints the SDK doesn't wrap yet, `presto.raw.post(path, body)` signs, sends, verifies and returns the
274
+ parsed dict. `presto.raw.sign(canonical)` and `presto.raw.verify_body(body)` expose the two halves.
275
+
276
+ `parse_gateway_timestamp` reads the gateway's `yyyyMMddHHmmss.SSS` date fields into aware `datetime`s at
277
+ UTC+08:00. Result date fields are left as strings.
278
+
279
+ ## Samples
280
+
281
+ [`sample/`](https://github.com/prestoconnect/presto-pay-sdk-python/tree/main/sample) is a runnable **MyStore** checkout against Presto staging. It includes the hosted and
282
+ self-hosted payment-method flows, a return page that queries the payment's status, and a webhook handler with a
283
+ "recent webhooks" list. It comes as two self-contained projects:
284
+
285
+ - [`sample/flask-store/`](https://github.com/prestoconnect/presto-pay-sdk-python/tree/main/sample/flask-store): Flask on the sync `PrestoPay` client.
286
+ - [`sample/fastapi-store/`](https://github.com/prestoconnect/presto-pay-sdk-python/tree/main/sample/fastapi-store): FastAPI on the async `AsyncPrestoPay` client.
287
+
288
+ See [sample/README.md](https://github.com/prestoconnect/presto-pay-sdk-python/blob/main/sample/README.md).
289
+
290
+ ## Contributing
291
+
292
+ [CONTRIBUTING.md](https://github.com/prestoconnect/presto-pay-sdk-python/blob/main/CONTRIBUTING.md) covers building, testing, code style and releasing. Report security issues
293
+ as described in [SECURITY.md](https://github.com/prestoconnect/presto-pay-sdk-python/blob/main/SECURITY.md), not in a public issue.
294
+
295
+ `spec/` is a checked-in copy of the shared wire contract and test vectors. The commit it was copied from is
296
+ recorded in [`spec/.source-commit`](https://github.com/prestoconnect/presto-pay-sdk-python/blob/main/spec/.source-commit). Real merchant or staging credentials must never be
297
+ committed to this repository.
298
+
299
+ ## License
300
+
301
+ Apache License 2.0. See [LICENSE](https://github.com/prestoconnect/presto-pay-sdk-python/blob/main/LICENSE).