karni-payments
Payments for Karni: hosted checkout, refunds and signature-verified webhooks for Stripe and Razorpay, with a test provider for CI.
Stripe works through Checkout Sessions and Razorpay through Payment Links. An in-memory test provider runs in CI with no account.
karni add payments # wires dependency + INSTALLED_APPS + agent guidance
pip install "karni-payments[stripe]" # or [razorpay]
One line of project wiring (the viewsets ride Karni's auto-router):
# config/urls.py
(path("payments/", include("karni_payments.urls")),) # the webhook endpoint
then make migrate. Register https://<host>/payments/webhook/stripe/ (or
.../razorpay/) at the provider.
What you get
- Models (all on
karni.models.BaseModel):Payment,Refund,WebhookEvent(the(provider, event_id)dedupe record). The admin is derived throughAdminMeta, with noadmin.py. - Role:
payments-adminis declared by the module (thekarni.rolesentry point), sokarni migratecreates it and a project writes nothing inKARNI_ROLES. Give a person the role to let them refund. - API (auto-routed, authenticated only):
GET /api/payments/: owner-scoped. Thepayments-adminrole sees all.POST /api/payments/checkout/: create a pending payment + provider session, then redirect the customer to the returnedurl.POST /api/payments/{id}/refund/: requires thepayments-adminrole. Omitamountto refund the full unrefunded remainder.GET /api/refunds/:payments-adminonly.- Writes to the resources themselves answer 405: state belongs to webhooks.
- Webhooks:
POST /payments/webhook/<provider>/verifies the signature (400 + warning log on failure, nothing persisted), dedupes on(provider, event_id)and hands processing to a Celery task (process_webhook_event: row lock + monotonic state machine +processed_atstamp in one transaction, and 3 retries with backoff). Nothing state-changing runs in the request cycle. - Services (
karni_payments.services): the only module project code should call. It holdscreate_checkout,create_refund(lock-validated against the unrefunded remainder, so over-refunds are impossible) andapply_event.
Settings (via the karni.settings fragment, all overridable)
| Setting (env var of the same name) | Default | Meaning |
|---|---|---|
KARNI_PAYMENTS_PROVIDER |
"stripe" |
"stripe", "razorpay", "test" or a dotted path to your own PaymentProvider subclass. The environment variable wins over a value in settings.py or karni.yaml (FROM_ENVIRONMENT), so .env switches a local try to test |
KARNI_PAYMENTS_CURRENCY |
"usd" |
default checkout currency |
KARNI_PAYMENTS_CHECKOUT_VALIDATOR |
pass-through | dotted path called with (user=, amount=, currency=, metadata=) before a Payment exists. Set it, and never trust client amounts |
KARNI_PAYMENTS_EVENT_HANDLER |
karni_payments.services.apply_event |
dotted path the webhook task calls (the state-machine escape hatch) |
KARNI_PAYMENTS_ALLOWED_REDIRECTS |
[] |
extra origins allowed for checkout redirect URLs (on top of KARNI_FRONTEND_URL) |
KARNI_PAYMENTS_TEST_CHECKOUT_PAGE |
None |
experimental: the test provider's checkout page. None serves it while DEBUG is on, True always, False never |
STRIPE_SECRET_KEY / STRIPE_WEBHOOK_SECRET |
"" |
validated lazily at provider use |
RAZORPAY_KEY_ID / RAZORPAY_KEY_SECRET / RAZORPAY_WEBHOOK_SECRET |
"" |
validated lazily at provider use |
Semantics worth knowing
- Monotonic state:
pending → processing → succeeded → partially_refunded → refunded.failed/canceledare terminal. Events that would regress a status are recorded as ano-op:note on theWebhookEventand count as processed. Expired checkout sessions map tocanceled. - Zero-decimal currencies (JPY, KRW, …) are handled by
providers.base.to_minor_units/from_minor_units. Currencies with 3 decimals (BHD, KWD, …) are unsupported in v0.1 and raise. - A provider failure during checkout marks the Payment
failedbefore re-raising. Abandoned pending payments are not reaped in v0.1, so expire them yourself if you need to (sessions that expire at the provider arrive as webhook events and cancel the payment). - Razorpay webhooks take their event id from the
X-Razorpay-Event-Idheader. Payment Links have a singlecallback_url, socancel_urlis unused there.
Signals (experimental)
karni_payments.events sends Django signals any app can receive in its
listeners.py, so an order, a booking or an enrolment reacts to its payment
without reading the webhook:
payment_status_changed(payment,source,target): a payment moved, for example frompendingtosucceeded,failedorrefunded.refund_created(refund,payment):create_refundasked the provider.refund_status_changed(refund,payment,source,target): a refund went through or failed.
They are sent by the webhook state machine inside its transaction: a
receiver that raises undoes the change, and the webhook task retries. A
project that replaces the state machine sends them with
karni_payments.events.announce(row, source).
Trying a checkout in the browser (experimental)
With KARNI_PAYMENTS_PROVIDER = "test" and DEBUG on, a checkout started in
a request points at /payments/test-checkout/<session>/ on that host
instead of a provider: a page with the amount, Pay and Decline. A
choice is applied the way the provider's webhook would be (a signed test
event through KARNI_PAYMENTS_EVENT_HANDLER, at once), then the page sends
the person to the checkout's success_url or cancel_url. No money moves.
Session ids never repeat one a stored payment has, so a development server
that restarts keeps working. Replace the template
karni_payments/test_checkout.html to change the page.
Testing your project
Set KARNI_PAYMENTS_PROVIDER = "test" in test settings:
TestProvider is in-memory and deterministic (test_cs_1, test_re_1, …),
and TestProvider.build_webhook({...}) returns a correctly signed
(body, headers) pair for driving the full webhook pipeline. Call
TestProvider.reset() between tests.
Development
pip install -e . --group dev
python -m pytest # standalone suite (sqlite + eager Celery + TestProvider)
ruff check . && ruff format --check .
This module is also the reference implementation of the Karni module
contract. See docs/modules.md in the Karni repo.
Links
- The module in the docs: https://cbsshekhawat18-lab.github.io/karni/modules/#modules-in-this-repository
- The module contract it is the reference for: https://cbsshekhawat18-lab.github.io/karni/modules/
- React components: https://www.npmjs.com/package/@karni/payments-ui
- Karni, the framework this package is part of: https://github.com/cbsshekhawat18-lab/karni
- Changelog: https://github.com/cbsshekhawat18-lab/karni/blob/main/CHANGELOG.md
- Issues: https://github.com/cbsshekhawat18-lab/karni/issues
- License: Apache-2.0. karni-payments is released with every other Karni package, at one version.
Metadata
Release files for karni-payments 0.7.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| karni_payments-0.7.0.tar.gz | 38.9 kB | Without provenance | Details for karni_payments-0.7.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| karni_payments-0.7.0-py3-none-any.whl | Python 3 | none | any | Details for karni_payments-0.7.0-py3-none-any.whl |
Total release size: 91.1 kB
Release files / karni_payments-0.7.0.tar.gz
| Download URL | karni_payments-0.7.0.tar.gz |
|---|---|
| Size | 38.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
6a87c16932181c86be8f28c1251d3bd9b1e3b5b4e8fbbb5f38eefbe7f6509c7d
|
|
BLAKE2b-256 checksum How to use checksums |
a69b97120099988ce42baec50c16f852eb52fab33c414a68dba45228f73a6822
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / karni_payments-0.7.0-py3-none-any.whl
| Download URL | karni_payments-0.7.0-py3-none-any.whl |
|---|---|
| Size | 52.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f8be251ed1d6d0700a8d5cd346807362f65a4d0abebcf24b73d1ac394f5d87ee
|
|
BLAKE2b-256 checksum How to use checksums |
1ba02a8ce3262a5b4a8544344f8457b1e7c14fbbd7318a810c6175f988a89422
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for karni-payments 0.7.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.