karni-payments 0.3.1__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.
- karni_payments-0.3.1/.gitignore +38 -0
- karni_payments-0.3.1/LICENSE +201 -0
- karni_payments-0.3.1/PKG-INFO +126 -0
- karni_payments-0.3.1/README.md +92 -0
- karni_payments-0.3.1/karni_payments/AGENTS.fragment.md +14 -0
- karni_payments-0.3.1/karni_payments/__init__.py +14 -0
- karni_payments-0.3.1/karni_payments/api.py +77 -0
- karni_payments-0.3.1/karni_payments/apps.py +20 -0
- karni_payments-0.3.1/karni_payments/conf.py +71 -0
- karni_payments-0.3.1/karni_payments/errorcodes.py +105 -0
- karni_payments-0.3.1/karni_payments/migrations/0001_initial.py +82 -0
- karni_payments-0.3.1/karni_payments/migrations/__init__.py +0 -0
- karni_payments-0.3.1/karni_payments/models.py +149 -0
- karni_payments-0.3.1/karni_payments/providers/__init__.py +40 -0
- karni_payments-0.3.1/karni_payments/providers/base.py +311 -0
- karni_payments-0.3.1/karni_payments/providers/razorpay.py +168 -0
- karni_payments-0.3.1/karni_payments/providers/stripe.py +161 -0
- karni_payments-0.3.1/karni_payments/providers/test.py +110 -0
- karni_payments-0.3.1/karni_payments/services.py +384 -0
- karni_payments-0.3.1/karni_payments/tasks.py +65 -0
- karni_payments-0.3.1/karni_payments/urls.py +23 -0
- karni_payments-0.3.1/karni_payments/viewsets.py +138 -0
- karni_payments-0.3.1/karni_payments/webhooks.py +85 -0
- karni_payments-0.3.1/pyproject.toml +91 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
.learning/
|
|
2
|
+
|
|
3
|
+
# Python
|
|
4
|
+
__pycache__/
|
|
5
|
+
*.py[cod]
|
|
6
|
+
*.egg-info/
|
|
7
|
+
.venv/
|
|
8
|
+
venv/
|
|
9
|
+
.pytest_cache/
|
|
10
|
+
.mypy_cache/
|
|
11
|
+
.ruff_cache/
|
|
12
|
+
.coverage
|
|
13
|
+
htmlcov/
|
|
14
|
+
|
|
15
|
+
# Build artifacts
|
|
16
|
+
dist/
|
|
17
|
+
build/
|
|
18
|
+
packages/karni-cli/karni_cli/_templates/
|
|
19
|
+
packages/karni-cli/karni_cli/_agent/
|
|
20
|
+
packages/karni-cli/karni_cli/_changelog/
|
|
21
|
+
packages/karni-cli/karni_cli/_errorcodes/
|
|
22
|
+
|
|
23
|
+
# Node
|
|
24
|
+
node_modules/
|
|
25
|
+
storybook-static/
|
|
26
|
+
*.tsbuildinfo
|
|
27
|
+
|
|
28
|
+
# Local env / editor / tooling
|
|
29
|
+
.env
|
|
30
|
+
.env.*
|
|
31
|
+
!.env.example
|
|
32
|
+
.DS_Store
|
|
33
|
+
.idea/
|
|
34
|
+
.claude/scheduled_tasks.lock
|
|
35
|
+
.claude/settings.local.json
|
|
36
|
+
|
|
37
|
+
# MkDocs build output
|
|
38
|
+
site/
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: karni-payments
|
|
3
|
+
Version: 0.3.1
|
|
4
|
+
Summary: Payments module for the Karni Django + React framework: hosted checkout, refunds and signature-verified webhooks for Stripe and Razorpay, with a test provider for CI.
|
|
5
|
+
Project-URL: Homepage, https://github.com/cbsshekhawat18-lab/karni
|
|
6
|
+
Project-URL: Documentation, https://cbsshekhawat18-lab.github.io/karni/
|
|
7
|
+
Project-URL: Repository, https://github.com/cbsshekhawat18-lab/karni
|
|
8
|
+
Project-URL: Issues, https://github.com/cbsshekhawat18-lab/karni/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/cbsshekhawat18-lab/karni/tree/main/docs/migrations
|
|
10
|
+
Author-email: Chandrabhan Shekhawat <cbsshekhawat18@gmail.com>
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: checkout,django,karni,payments,razorpay,react,stripe,webhooks
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Environment :: Web Environment
|
|
16
|
+
Classifier: Framework :: Django
|
|
17
|
+
Classifier: Framework :: Django :: 5.2
|
|
18
|
+
Classifier: Intended Audience :: Developers
|
|
19
|
+
Classifier: Operating System :: OS Independent
|
|
20
|
+
Classifier: Programming Language :: Python :: 3
|
|
21
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
26
|
+
Classifier: Typing :: Typed
|
|
27
|
+
Requires-Python: >=3.12
|
|
28
|
+
Requires-Dist: karni<0.4,>=0.3
|
|
29
|
+
Provides-Extra: razorpay
|
|
30
|
+
Requires-Dist: razorpay>=1.4; extra == 'razorpay'
|
|
31
|
+
Provides-Extra: stripe
|
|
32
|
+
Requires-Dist: stripe>=10; extra == 'stripe'
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# karni-payments
|
|
36
|
+
|
|
37
|
+
Payments module for [Karni](https://github.com/cbsshekhawat18-lab/karni): hosted checkout, refunds and
|
|
38
|
+
webhook-driven payment state for **Stripe** (Checkout Sessions) and
|
|
39
|
+
**Razorpay** (Payment Links), plus an in-memory **test provider**.
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
karni add payments # wires dependency + INSTALLED_APPS + agent guidance
|
|
43
|
+
pip install "karni-payments[stripe]" # or [razorpay]
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
One line of project wiring (the viewsets ride Karni's auto-router):
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
# config/urls.py
|
|
50
|
+
(path("payments/", include("karni_payments.urls")),) # the webhook endpoint
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
then `make migrate`. Register `https://<host>/payments/webhook/stripe/` (or
|
|
54
|
+
`.../razorpay/`) at the provider.
|
|
55
|
+
|
|
56
|
+
## What you get
|
|
57
|
+
|
|
58
|
+
- **Models** (all on `karni.models.BaseModel`): `Payment`, `Refund`,
|
|
59
|
+
`WebhookEvent` (the `(provider, event_id)` dedupe record). Derived admin
|
|
60
|
+
via `AdminMeta` — no `admin.py`.
|
|
61
|
+
- **API** (auto-routed, authenticated only):
|
|
62
|
+
- `GET /api/payments/` — owner-scoped; the `payments-admin` role sees all.
|
|
63
|
+
- `POST /api/payments/checkout/` — create a pending payment + provider
|
|
64
|
+
session; redirect the customer to the returned `url`.
|
|
65
|
+
- `POST /api/payments/{id}/refund/` — requires the `payments-admin` role;
|
|
66
|
+
omit `amount` to refund the full unrefunded remainder.
|
|
67
|
+
- `GET /api/refunds/` — `payments-admin` only.
|
|
68
|
+
- Writes to the resources themselves answer 405: state belongs to webhooks.
|
|
69
|
+
- **Webhooks**: `POST /payments/webhook/<provider>/` verifies the signature
|
|
70
|
+
(400 + warning log on failure, nothing persisted), dedupes on
|
|
71
|
+
`(provider, event_id)` and hands processing to a Celery task
|
|
72
|
+
(`process_webhook_event`: row lock + monotonic state machine +
|
|
73
|
+
`processed_at` stamp in one transaction; 3 retries with backoff). Nothing
|
|
74
|
+
state-changing runs in the request cycle.
|
|
75
|
+
- **Services** (`karni_payments.services`) — the only module project code
|
|
76
|
+
should call: `create_checkout`, `create_refund` (lock-validated against
|
|
77
|
+
the unrefunded remainder — over-refunds are impossible), `apply_event`.
|
|
78
|
+
|
|
79
|
+
## Settings (via the `karni.settings` fragment — all overridable)
|
|
80
|
+
|
|
81
|
+
| Setting (env var of the same name) | Default | Meaning |
|
|
82
|
+
| --- | --- | --- |
|
|
83
|
+
| `KARNI_PAYMENTS_PROVIDER` | `"stripe"` | `"stripe"`, `"razorpay"`, `"test"` or a dotted path to your own `PaymentProvider` subclass |
|
|
84
|
+
| `KARNI_PAYMENTS_CURRENCY` | `"usd"` | default checkout currency |
|
|
85
|
+
| `KARNI_PAYMENTS_CHECKOUT_VALIDATOR` | pass-through | dotted path called with `(user=, amount=, currency=, metadata=)` **before** a Payment exists — set it; never trust client amounts |
|
|
86
|
+
| `KARNI_PAYMENTS_EVENT_HANDLER` | `karni_payments.services.apply_event` | dotted path the webhook task calls — the state-machine escape hatch |
|
|
87
|
+
| `KARNI_PAYMENTS_ALLOWED_REDIRECTS` | `[]` | extra origins allowed for checkout redirect URLs (on top of `KARNI_FRONTEND_URL`) |
|
|
88
|
+
| `STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET` | `""` | validated lazily at provider use |
|
|
89
|
+
| `RAZORPAY_KEY_ID` / `RAZORPAY_KEY_SECRET` / `RAZORPAY_WEBHOOK_SECRET` | `""` | validated lazily at provider use |
|
|
90
|
+
|
|
91
|
+
## Semantics worth knowing
|
|
92
|
+
|
|
93
|
+
- **Monotonic state**: `pending → processing → succeeded →
|
|
94
|
+
partially_refunded → refunded`; `failed`/`canceled` are terminal. Events
|
|
95
|
+
that would regress a status are recorded as a `no-op:` note on the
|
|
96
|
+
`WebhookEvent` and count as processed. Expired checkout sessions map to
|
|
97
|
+
`canceled`.
|
|
98
|
+
- **Zero-decimal currencies** (JPY, KRW, …) are handled by
|
|
99
|
+
`providers.base.to_minor_units` / `from_minor_units`; 3-decimal currencies
|
|
100
|
+
(BHD, KWD, …) are unsupported in v0.1 and raise.
|
|
101
|
+
- A provider failure during checkout marks the Payment `failed` before
|
|
102
|
+
re-raising. Abandoned pending payments are not reaped in v0.1 — expire
|
|
103
|
+
them yourself if you need to (sessions that expire at the provider arrive
|
|
104
|
+
as webhook events and cancel the payment).
|
|
105
|
+
- Razorpay webhooks take their event id from the `X-Razorpay-Event-Id`
|
|
106
|
+
header; Payment Links have a single `callback_url`, so `cancel_url` is
|
|
107
|
+
unused there.
|
|
108
|
+
|
|
109
|
+
## Testing your project
|
|
110
|
+
|
|
111
|
+
Set `KARNI_PAYMENTS_PROVIDER = "test"` in test settings:
|
|
112
|
+
`TestProvider` is in-memory and deterministic (`test_cs_1`, `test_re_1`, …),
|
|
113
|
+
and `TestProvider.build_webhook({...})` returns a correctly signed
|
|
114
|
+
`(body, headers)` pair for driving the full webhook pipeline. Call
|
|
115
|
+
`TestProvider.reset()` between tests.
|
|
116
|
+
|
|
117
|
+
## Development
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
pip install -e . --group dev
|
|
121
|
+
python -m pytest # standalone suite (sqlite + eager Celery + TestProvider)
|
|
122
|
+
ruff check . && ruff format --check .
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
This module is also the reference implementation of the Karni module
|
|
126
|
+
contract — see `docs/modules.md` in the Karni repo.
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# karni-payments
|
|
2
|
+
|
|
3
|
+
Payments module for [Karni](https://github.com/cbsshekhawat18-lab/karni): hosted checkout, refunds and
|
|
4
|
+
webhook-driven payment state for **Stripe** (Checkout Sessions) and
|
|
5
|
+
**Razorpay** (Payment Links), plus an in-memory **test provider**.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
karni add payments # wires dependency + INSTALLED_APPS + agent guidance
|
|
9
|
+
pip install "karni-payments[stripe]" # or [razorpay]
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
One line of project wiring (the viewsets ride Karni's auto-router):
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
# config/urls.py
|
|
16
|
+
(path("payments/", include("karni_payments.urls")),) # the webhook endpoint
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
then `make migrate`. Register `https://<host>/payments/webhook/stripe/` (or
|
|
20
|
+
`.../razorpay/`) at the provider.
|
|
21
|
+
|
|
22
|
+
## What you get
|
|
23
|
+
|
|
24
|
+
- **Models** (all on `karni.models.BaseModel`): `Payment`, `Refund`,
|
|
25
|
+
`WebhookEvent` (the `(provider, event_id)` dedupe record). Derived admin
|
|
26
|
+
via `AdminMeta` — no `admin.py`.
|
|
27
|
+
- **API** (auto-routed, authenticated only):
|
|
28
|
+
- `GET /api/payments/` — owner-scoped; the `payments-admin` role sees all.
|
|
29
|
+
- `POST /api/payments/checkout/` — create a pending payment + provider
|
|
30
|
+
session; redirect the customer to the returned `url`.
|
|
31
|
+
- `POST /api/payments/{id}/refund/` — requires the `payments-admin` role;
|
|
32
|
+
omit `amount` to refund the full unrefunded remainder.
|
|
33
|
+
- `GET /api/refunds/` — `payments-admin` only.
|
|
34
|
+
- Writes to the resources themselves answer 405: state belongs to webhooks.
|
|
35
|
+
- **Webhooks**: `POST /payments/webhook/<provider>/` verifies the signature
|
|
36
|
+
(400 + warning log on failure, nothing persisted), dedupes on
|
|
37
|
+
`(provider, event_id)` and hands processing to a Celery task
|
|
38
|
+
(`process_webhook_event`: row lock + monotonic state machine +
|
|
39
|
+
`processed_at` stamp in one transaction; 3 retries with backoff). Nothing
|
|
40
|
+
state-changing runs in the request cycle.
|
|
41
|
+
- **Services** (`karni_payments.services`) — the only module project code
|
|
42
|
+
should call: `create_checkout`, `create_refund` (lock-validated against
|
|
43
|
+
the unrefunded remainder — over-refunds are impossible), `apply_event`.
|
|
44
|
+
|
|
45
|
+
## Settings (via the `karni.settings` fragment — all overridable)
|
|
46
|
+
|
|
47
|
+
| Setting (env var of the same name) | Default | Meaning |
|
|
48
|
+
| --- | --- | --- |
|
|
49
|
+
| `KARNI_PAYMENTS_PROVIDER` | `"stripe"` | `"stripe"`, `"razorpay"`, `"test"` or a dotted path to your own `PaymentProvider` subclass |
|
|
50
|
+
| `KARNI_PAYMENTS_CURRENCY` | `"usd"` | default checkout currency |
|
|
51
|
+
| `KARNI_PAYMENTS_CHECKOUT_VALIDATOR` | pass-through | dotted path called with `(user=, amount=, currency=, metadata=)` **before** a Payment exists — set it; never trust client amounts |
|
|
52
|
+
| `KARNI_PAYMENTS_EVENT_HANDLER` | `karni_payments.services.apply_event` | dotted path the webhook task calls — the state-machine escape hatch |
|
|
53
|
+
| `KARNI_PAYMENTS_ALLOWED_REDIRECTS` | `[]` | extra origins allowed for checkout redirect URLs (on top of `KARNI_FRONTEND_URL`) |
|
|
54
|
+
| `STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET` | `""` | validated lazily at provider use |
|
|
55
|
+
| `RAZORPAY_KEY_ID` / `RAZORPAY_KEY_SECRET` / `RAZORPAY_WEBHOOK_SECRET` | `""` | validated lazily at provider use |
|
|
56
|
+
|
|
57
|
+
## Semantics worth knowing
|
|
58
|
+
|
|
59
|
+
- **Monotonic state**: `pending → processing → succeeded →
|
|
60
|
+
partially_refunded → refunded`; `failed`/`canceled` are terminal. Events
|
|
61
|
+
that would regress a status are recorded as a `no-op:` note on the
|
|
62
|
+
`WebhookEvent` and count as processed. Expired checkout sessions map to
|
|
63
|
+
`canceled`.
|
|
64
|
+
- **Zero-decimal currencies** (JPY, KRW, …) are handled by
|
|
65
|
+
`providers.base.to_minor_units` / `from_minor_units`; 3-decimal currencies
|
|
66
|
+
(BHD, KWD, …) are unsupported in v0.1 and raise.
|
|
67
|
+
- A provider failure during checkout marks the Payment `failed` before
|
|
68
|
+
re-raising. Abandoned pending payments are not reaped in v0.1 — expire
|
|
69
|
+
them yourself if you need to (sessions that expire at the provider arrive
|
|
70
|
+
as webhook events and cancel the payment).
|
|
71
|
+
- Razorpay webhooks take their event id from the `X-Razorpay-Event-Id`
|
|
72
|
+
header; Payment Links have a single `callback_url`, so `cancel_url` is
|
|
73
|
+
unused there.
|
|
74
|
+
|
|
75
|
+
## Testing your project
|
|
76
|
+
|
|
77
|
+
Set `KARNI_PAYMENTS_PROVIDER = "test"` in test settings:
|
|
78
|
+
`TestProvider` is in-memory and deterministic (`test_cs_1`, `test_re_1`, …),
|
|
79
|
+
and `TestProvider.build_webhook({...})` returns a correctly signed
|
|
80
|
+
`(body, headers)` pair for driving the full webhook pipeline. Call
|
|
81
|
+
`TestProvider.reset()` between tests.
|
|
82
|
+
|
|
83
|
+
## Development
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
pip install -e . --group dev
|
|
87
|
+
python -m pytest # standalone suite (sqlite + eager Celery + TestProvider)
|
|
88
|
+
ruff check . && ruff format --check .
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
This module is also the reference implementation of the Karni module
|
|
92
|
+
contract — see `docs/modules.md` in the Karni repo.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
## Payments (karni-payments)
|
|
2
|
+
- Checkout, refunds and webhook-driven state ship ready-made. Never call
|
|
3
|
+
provider SDKs (stripe/razorpay) directly — go through `karni_payments.services`.
|
|
4
|
+
- NEVER trust client amounts: set `KARNI_PAYMENTS_CHECKOUT_VALIDATOR` (dotted
|
|
5
|
+
path) to enforce server-side pricing, or override the checkout action.
|
|
6
|
+
- Wire URLs once in config/urls.py:
|
|
7
|
+
`path("payments/", include("karni_payments.urls"))`
|
|
8
|
+
- API rides the auto-router: `/api/payments/` + `checkout/` (POST) +
|
|
9
|
+
`{id}/refund/` (POST, role `payments-admin`), `/api/refunds/` (same role).
|
|
10
|
+
- Settings arrive via the module's settings fragment; env vars:
|
|
11
|
+
KARNI_PAYMENTS_PROVIDER (stripe|razorpay|test|dotted path),
|
|
12
|
+
KARNI_PAYMENTS_CURRENCY, STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET,
|
|
13
|
+
RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET, RAZORPAY_WEBHOOK_SECRET.
|
|
14
|
+
- Webhook state changes run in Celery — keep the worker service running.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""karni-payments — the Karni payments module (Stripe, Razorpay, test provider).
|
|
2
|
+
|
|
3
|
+
Checkout sessions, refunds and webhook-driven payment state, built on Karni's
|
|
4
|
+
bases: models on :class:`karni.models.BaseModel`, viewsets on
|
|
5
|
+
:class:`karni.api.BaseViewSet`, settings via the ``karni.settings`` fragment,
|
|
6
|
+
admin derived via ``AdminMeta``.
|
|
7
|
+
|
|
8
|
+
Project code talks to :mod:`karni_payments.services` — never to a provider
|
|
9
|
+
SDK directly.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Hand-written serializers for the payments API actions.
|
|
2
|
+
|
|
3
|
+
Only the ``checkout`` / ``refund`` action payloads live here — the resource
|
|
4
|
+
serializers for ``Payment`` and ``Refund`` are generated by
|
|
5
|
+
:func:`karni.api.serializers.build_serializer` from the models' ``APIMeta``
|
|
6
|
+
(see :mod:`karni_payments.viewsets`). These explicit input/output
|
|
7
|
+
serializers feed ``@extend_schema`` so the OpenAPI schema (and with it
|
|
8
|
+
@karni/ui's typed client) knows the action shapes.
|
|
9
|
+
|
|
10
|
+
Override / escape hatch: subclass the viewset and swap the serializer in an
|
|
11
|
+
overridden action; these classes are plain DRF serializers.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from decimal import Decimal
|
|
17
|
+
|
|
18
|
+
from rest_framework import serializers
|
|
19
|
+
|
|
20
|
+
from karni_payments.models import Refund
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"CheckoutInputSerializer",
|
|
24
|
+
"CheckoutOutputSerializer",
|
|
25
|
+
"RefundInputSerializer",
|
|
26
|
+
"RefundSerializer",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class CheckoutInputSerializer(serializers.Serializer):
|
|
31
|
+
"""Input of ``POST /api/payments/checkout/``.
|
|
32
|
+
|
|
33
|
+
The amount is transport, not authority: the server-side
|
|
34
|
+
``KARNI_PAYMENTS_CHECKOUT_VALIDATOR`` decides whether it is acceptable
|
|
35
|
+
(amendment G2 — never trust client amounts).
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
amount = serializers.DecimalField(max_digits=12, decimal_places=2, min_value=Decimal("0.01"))
|
|
39
|
+
currency = serializers.CharField(max_length=3, required=False)
|
|
40
|
+
metadata = serializers.JSONField(required=False)
|
|
41
|
+
success_url = serializers.URLField(max_length=2000)
|
|
42
|
+
cancel_url = serializers.URLField(max_length=2000)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CheckoutOutputSerializer(serializers.Serializer):
|
|
46
|
+
"""Output of the checkout action: redirect the customer to ``url``."""
|
|
47
|
+
|
|
48
|
+
payment_id = serializers.UUIDField(read_only=True)
|
|
49
|
+
session_id = serializers.CharField(read_only=True)
|
|
50
|
+
url = serializers.URLField(read_only=True)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class RefundInputSerializer(serializers.Serializer):
|
|
54
|
+
"""Input of ``POST /api/payments/{id}/refund/`` (empty body → full remainder)."""
|
|
55
|
+
|
|
56
|
+
amount = serializers.DecimalField(
|
|
57
|
+
max_digits=12, decimal_places=2, min_value=Decimal("0.01"), required=False
|
|
58
|
+
)
|
|
59
|
+
reason = serializers.CharField(max_length=255, required=False, allow_blank=True, default="")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class RefundSerializer(serializers.ModelSerializer):
|
|
63
|
+
"""Read-only representation of a refund (the refund action's response)."""
|
|
64
|
+
|
|
65
|
+
class Meta:
|
|
66
|
+
model = Refund
|
|
67
|
+
fields = [
|
|
68
|
+
"id",
|
|
69
|
+
"payment",
|
|
70
|
+
"amount",
|
|
71
|
+
"status",
|
|
72
|
+
"provider_refund_id",
|
|
73
|
+
"reason",
|
|
74
|
+
"created_at",
|
|
75
|
+
"updated_at",
|
|
76
|
+
]
|
|
77
|
+
read_only_fields = fields
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Django app configuration for ``karni_payments``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from django.apps import AppConfig
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class KarniPaymentsConfig(AppConfig):
|
|
9
|
+
"""App config for the Karni payments module (label ``karni_payments``).
|
|
10
|
+
|
|
11
|
+
Override / escape hatch: subclass this config in your project and point
|
|
12
|
+
``INSTALLED_APPS`` at the subclass's dotted path to change startup
|
|
13
|
+
behaviour; the app label must stay ``karni_payments`` so the shipped
|
|
14
|
+
migrations keep applying.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
name = "karni_payments"
|
|
18
|
+
label = "karni_payments"
|
|
19
|
+
verbose_name = "Karni payments"
|
|
20
|
+
default_auto_field = "django.db.models.BigAutoField"
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Settings vocabulary for karni-payments.
|
|
2
|
+
|
|
3
|
+
:data:`DEFAULTS` is the module's **settings fragment**: it is exposed through
|
|
4
|
+
the ``karni.settings`` entry point (see this module's ``pyproject.toml``), so
|
|
5
|
+
:func:`karni.conf.karni_settings` merges it into every project's settings
|
|
6
|
+
automatically — after Karni's BASE/profile defaults and before project
|
|
7
|
+
overrides, new top-level names only.
|
|
8
|
+
|
|
9
|
+
The fragment is import-light on purpose: plain data plus django-environ
|
|
10
|
+
reads, and it never touches ``django.conf.settings`` at import time.
|
|
11
|
+
Per-profile values would read ``os.environ["DJANGO_ENV"]`` here directly —
|
|
12
|
+
the documented hatch, since fragments merge before profiles are observable.
|
|
13
|
+
|
|
14
|
+
:func:`get` is the accessor every ``karni_payments`` module reads settings
|
|
15
|
+
through — ``getattr(settings, name, DEFAULTS[name])`` — so the module also
|
|
16
|
+
works in projects that configure Django without ``karni_settings()`` (the
|
|
17
|
+
fragment merge is convenience, not correctness).
|
|
18
|
+
|
|
19
|
+
Override / escape hatch: define any of these names in your ``settings.py``
|
|
20
|
+
(before or after ``karni_settings()``) or set the matching environment
|
|
21
|
+
variable; provider credentials default to ``""`` and are validated lazily at
|
|
22
|
+
provider use, never at boot.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
import environ
|
|
30
|
+
from django.conf import settings
|
|
31
|
+
|
|
32
|
+
env = environ.Env()
|
|
33
|
+
|
|
34
|
+
DEFAULTS: dict[str, Any] = {
|
|
35
|
+
# Active provider: "stripe", "razorpay", "test" or any dotted path to a
|
|
36
|
+
# karni_payments.providers.base.PaymentProvider subclass (the escape
|
|
37
|
+
# hatch for custom gateways).
|
|
38
|
+
"KARNI_PAYMENTS_PROVIDER": env("KARNI_PAYMENTS_PROVIDER", default="stripe"),
|
|
39
|
+
# Default ISO currency code used when create_checkout gets none.
|
|
40
|
+
"KARNI_PAYMENTS_CURRENCY": env("KARNI_PAYMENTS_CURRENCY", default="usd"),
|
|
41
|
+
# Dotted path called with (user=, amount=, currency=, metadata=) BEFORE a
|
|
42
|
+
# Payment is created — the server-side pricing authority. The default is
|
|
43
|
+
# a pass-through; production projects should replace it (never trust
|
|
44
|
+
# client amounts).
|
|
45
|
+
"KARNI_PAYMENTS_CHECKOUT_VALIDATOR": ("karni_payments.services.default_checkout_validator"),
|
|
46
|
+
# Dotted path of the webhook state machine applied by the Celery task.
|
|
47
|
+
"KARNI_PAYMENTS_EVENT_HANDLER": "karni_payments.services.apply_event",
|
|
48
|
+
# Extra URLs whose origins are allowed as checkout success/cancel
|
|
49
|
+
# redirects, on top of KARNI_FRONTEND_URL's origin.
|
|
50
|
+
"KARNI_PAYMENTS_ALLOWED_REDIRECTS": env.list("KARNI_PAYMENTS_ALLOWED_REDIRECTS", default=[]),
|
|
51
|
+
# Provider credentials — blank by default, validated lazily at use.
|
|
52
|
+
"STRIPE_SECRET_KEY": env("STRIPE_SECRET_KEY", default=""),
|
|
53
|
+
"STRIPE_WEBHOOK_SECRET": env("STRIPE_WEBHOOK_SECRET", default=""),
|
|
54
|
+
"RAZORPAY_KEY_ID": env("RAZORPAY_KEY_ID", default=""),
|
|
55
|
+
"RAZORPAY_KEY_SECRET": env("RAZORPAY_KEY_SECRET", default=""),
|
|
56
|
+
"RAZORPAY_WEBHOOK_SECRET": env("RAZORPAY_WEBHOOK_SECRET", default=""),
|
|
57
|
+
}
|
|
58
|
+
"""The karni-payments settings fragment (``karni.settings`` entry point)."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def get(name: str) -> Any:
|
|
62
|
+
"""Return the effective value of a karni-payments setting.
|
|
63
|
+
|
|
64
|
+
Project settings win; :data:`DEFAULTS` is the fallback, so the accessor
|
|
65
|
+
works whether or not the project assembled its settings through
|
|
66
|
+
``karni_settings()``.
|
|
67
|
+
|
|
68
|
+
:raises KeyError: when ``name`` is not a karni-payments setting and the
|
|
69
|
+
project has not defined it either.
|
|
70
|
+
"""
|
|
71
|
+
return getattr(settings, name, DEFAULTS[name])
|