The Kirak Payments Module provides an enterprise-grade, provider-neutral abstraction layer for payment processing. Kirak currently launches with an initial set of 13 leading payment gateways and merchant platforms, with new gateways and payment methods continuously being added by both the core engineering team and the open-source community.
Every payment operation runs through the central Kirak dispatch pipeline, firing lifecycle hooks (before_<operation> and after_<operation>), while incoming webhooks are cryptographically verified, deduplicated in two layers, and translated into standardized event payloads delivered to your after_webhook handlers.
Kirak organizes payment gateways into two tiers: SDK-driven gateways (which require official client libraries installed as optional extras) and REST-driven gateways (which call official REST endpoints via the built-in, async-native httpx HTTP client without external dependencies).
[!TIP]
An Expanding Gateway Ecosystem:
The 13 gateways below represent Kirak’s currently supported foundational providers. Additional gateways are actively being added by the core team and community contributors. If you need a gateway not listed here, you can easily plug in a custom integration using Kirak’s modular architecture — see Adding a Custom Provider.
Terminal window
# SDK-driven providers (install specific extras as needed):
pipinstall"kirak[payments-razorpay]"# Razorpay
pipinstall"kirak[payments-square]"# Square
# Or install all payment extras at once:
pipinstall"kirak[all-payments]"
[!NOTE]
No Extra Dependencies Needed for REST Providers:
Stripe, Stripe Connect, PayPal, Paddle Billing, Paystack, Flutterwave, Mercado Pago, Xendit, Airwallex, Omise, and Telr communicate directly with provider REST APIs using standard async HTTP. No third-party SDKs or extra pip packages are required.
A return URL given as a path (success_url, cancel_url, and Stripe Connect’s refresh_url and return_url) is prefixed with the app’s top-level base_url, so /payment/success reaches the gateway as https://api.example.com/payment/success. An absolute URL is used as it is. Without base_url a path stays a path, and gateways that redirect the buyer from their own site (Stripe among them) refuse it.
kirak.json defines named instances of payment gateways. Each instance has a unique configuration key (its instance name) and a type specifying the gateway implementation. Multiple instances of the same gateway type can be active simultaneously (e.g. stripe_us and stripe_eu).
All Payments Settings, Provider Settings & Environment Variables
payments key
Type
Description
default_provider
string
Instance name used when a call names no provider. Must be one of the instances under providers.
providers
object
Payment provider instances (types stripe, stripe_connect, razorpay, square, or a custom type), by instance name.
success_url
string or null
Redirect after a successful payment; a path is prefixed with base_url. Each provider instance can override it.
cancel_url
string or null
Redirect after a cancelled payment; a path is prefixed with base_url. Each provider instance can override it.
require_auth
boolean
Require a signed-in caller on the payment routes. false lets guests check out (initiate_payment, connect_checkout, verify_payment, list_providers); owner and admin operations stay protected either way. Default true.
plan_catalog
boolean
Allow ensure_plan to create subscription plans on the provider account. Default false.
<INSTANCE> is the provider instance’s name in kirak.json, upper-cased: an instance
named main reads ..._MAIN_....
stripe (no extra install) – Stripe Checkout, subscriptions, saved payment methods, off-session charges and disputes.
Credential check (check()): GET /v1/balance.
Name
Where
Required / default
Description
success_url
kirak.json
default /payment/success
URL Stripe returns the buyer to after a successful payment; a path is prefixed with base_url. Stripe refuses a relative URL, so a path without base_url cannot create a checkout. Overrides payments.success_url.
cancel_url
kirak.json
default /payment/cancel
URL Stripe returns the buyer to after a cancelled payment; a path is prefixed with base_url. Stripe refuses a relative URL, so a path without base_url cannot create a checkout. Overrides payments.cancel_url.
timeout
kirak.json
default 15
Seconds one gateway call may take before it fails with 502.
KIRAK_PAYMENT_<INSTANCE>_SECRET_KEY
environment
required
Stripe secret API key (sk_live_… or sk_test_…).
KIRAK_PAYMENT_<INSTANCE>_WEBHOOK_SECRET
environment
Webhook signing secret (whsec_…); without it every webhook is refused.
stripe_connect (no extra install) – Stripe Connect marketplace: merchant onboarding, checkout on behalf of merchants, platform fees.
Credential check (check()): GET /v1/account (the platform account).
Name
Where
Required / default
Description
timeout
kirak.json
default 15
Seconds one gateway call may take before it fails with 502.
success_url
kirak.json
default /payment/success
URL Stripe returns the buyer to after a successful payment; a path is prefixed with base_url. Stripe refuses a relative URL, so a path without base_url cannot create a checkout. Overrides payments.success_url.
cancel_url
kirak.json
default /payment/cancel
URL Stripe returns the buyer to after a cancelled payment; a path is prefixed with base_url. Stripe refuses a relative URL, so a path without base_url cannot create a checkout. Overrides payments.cancel_url.
refresh_url
kirak.json
default /connect/onboard/refresh
Onboarding URL Stripe sends a merchant back to when a link expired; a path is prefixed with base_url.
return_url
kirak.json
default /connect/onboard/return
URL Stripe sends a merchant to after onboarding; a path is prefixed with base_url.
platform_fee_percent
kirak.json
default 10.0
Platform fee, in percent (0 to 100), of a merchant onboarded without one. update_merchant_fee sets a merchant’s own.
KIRAK_PAYMENT_<INSTANCE>_SECRET_KEY
environment
required
Stripe secret API key of the platform account.
KIRAK_PAYMENT_<INSTANCE>_WEBHOOK_SECRET
environment
Signing secret of the connected-accounts webhook endpoint.
KIRAK_PAYMENT_<INSTANCE>_PLATFORM_WEBHOOK_SECRET
environment
Signing secret of the platform-account webhook endpoint (checkout, refunds, saved methods).
Default Instance: Calls omitting the "provider" parameter automatically use default_provider.
Explicit Routing: Pass "provider": "<instance_name>" in operation parameters to route to a specific gateway instance.
Allow-List Isolation: Only instances declared in kirak.json can be invoked. Unknown names fail immediately with PROVIDER_NOT_CONFIGURED (400).
Secret Storage Convention: Secrets are never stored in kirak.json. They are read from environment variables following the convention:
$$\text{KIRAK_PAYMENT_}\langle\text{INSTANCE}\rangle\text{_}\langle\text{FIELD}\rangle$$
(e.g., KIRAK_PAYMENT_STRIPE_SECRET_KEY, KIRAK_PAYMENT_RAZORPAY_KEY_SECRET).
Gateway Call Timeouts: Gateway calls enforce a default 15-second timeout. Set "timeout": 20 inside an instance entry to override.
[!WARNING]
CRITICAL: Renaming a Provider Instance Requires Updating 4 Database Tables
The payment_service column in payments_transactions, payments_subscriptions, payments_payment_methods, and payments_customers records the exact instance name string declared in kirak.json (e.g. "stripe" or "stripe_primary").
Because Kirak strictly filters queries, webhook reconciliations, subscription cancellations, and off-session card charges by payment_service = self.instance_name, renaming an instance without updating the database will cause historical records to immediately stop working:
Past transactions will not be returned by lookup or receipt queries.
Subscriptions cannot be updated, paused, resumed, or canceled via the API.
Webhook events matching the old instance name will fail to reconcile.
Saved customer profiles and off-session payment methods will be unreachable.
If you change an instance name in kirak.json, you MUST execute the following SQL migration across all four tables within an atomic transaction:
START TRANSACTION; -- or BEGIN TRANSACTION; in SQLite / PostgreSQL
UPDATE payments_transactions SET payment_service ='new_instance_name'WHERE payment_service ='old_instance_name';
UPDATE payments_subscriptions SET payment_service ='new_instance_name'WHERE payment_service ='old_instance_name';
UPDATE payments_payment_methods SET payment_service ='new_instance_name'WHERE payment_service ='old_instance_name';
UPDATE payments_customers SET payment_service ='new_instance_name'WHERE payment_service ='old_instance_name';
Different gateways support different feature sets. For example, some gateways support customer billing portals, while others support only one-time checkout links.
Clients and user interfaces can query GET /payments/providers to inspect the live capabilities of all configured instances:
"require_auth": false only lets guests check out: initiate_payment, connect_checkout, verify_payment and list_providers. Every other operation is checked as below whatever the setting.
For all operations except handle_webhook and the checkout operations above, the caller’s authenticated user ID (from JWT or API Key) must match user_id in the request parameters, unless the caller holds admin or system roles. A guest is refused.
For verification (verify_payment) and subscription lifecycle management (cancel_subscription), ownership is resolved directly from the database record rather than trusted from client parameters.
Privileged Operations:
refund_payment, charge_off_session, get_dispute, submit_dispute_evidence, ensure_plan, and PUT /payments/connect/merchant-fee require admin or system credentials.
Cost Rate Limiting:
Public checkout creation (POST /payments/initiate and POST /payments/connect/checkout) is rate-limited to 20 requests per minute per IP address.
This control prevents malicious abuse, automated scraping of checkout URLs, and card-testing attacks.
All monetary amounts in Kirak are strictly stored and manipulated as integers in ISO 4217 minor units (e.g. cents, pence, paise). For example, $29.99 is represented as 2999.
Decimal Precision & ISO 4217 Single Source of Truth
Kirak maintains an internal ISO 4217 currency specification (kirak/payments/utils/currency.py). Every provider class declares its internal conversion attributes:
MAJOR_UNITS (boolean): Flag indicating whether the external gateway expects major-unit decimals (e.g. PayPal, Flutterwave, Mercado Pago) or integer subunits (e.g. Stripe, Razorpay, Paddle).
Floating point numbers (e.g. 29.99) and numeric strings ("2999") are rejected with VALIDATION_ERROR (400).
Amounts that cannot be represented in a currency’s legal decimals are rejected with AMOUNT_NOT_REPRESENTABLE (400) before any gateway call is dispatched.
Amounts below the gateway minimum are rejected with INVALID_PARAMS (400).
Initiates a hosted checkout session or subscription. Returns a hosted URL (url) to which the buyer should be redirected, alongside a local transaction_id and reference, a unique id for the payment that Kirak records on the transaction. It is Kirak’s random reference (kirak-...) on Paddle, PayPal, Razorpay, Stripe, Stripe Connect and Square, and the provider’s own random reference on Airwallex, Flutterwave, Mercado Pago, Paystack, Telr and Xendit. On Omise it is the payment link’s id. Each provider also returns its own ids (session_id, order_id, paddle_transaction_id…) as extra keys.
result =await kirak.payments.initiate_payment({
"user_id": "usr_9921",
"amount": 2999, # 29.99 USD in minor units
"currency": "USD",
"name": "Annual Pro License",
"type": "one_time", # "one_time" | "subscription"
"provider": "stripe", # Optional: defaults to default_provider
Because POST /payments/initiate accepts the payload from the client browser, an attacker could attempt to tamper with the amount or currency. Kirak triggers a warning if no before_initiate_payment hook is configured:
For subscriptions, the price and billing interval are dictated by the gateway’s recurring plan. Pass "type": "subscription" and the provider’s recurring plan identifier (subscription_plan_id):
result =await kirak.payments.initiate_payment({
"user_id": "usr_9921",
"amount": 0, # Recorded as plan price upon gateway synchronization
"currency": "USD",
"name": "Pro Monthly Plan",
"type": "subscription",
"subscription_plan_id": "price_1NXXXXXXXXXXXXXX", # Stripe Price ID or Razorpay Plan ID
"provider": "stripe",
})
The charge uses the price the provider holds for subscription_plan_id. The amount and currency in the request are not used for a subscription. Kirak does not check which plan a caller may choose: an app limits that with a before_initiate_payment hook that rejects plan ids the caller may not buy.
The same keys on every provider: transaction_id, amount, currency, and status, the transaction’s payment_status (below; null when Kirak has no row for the payment). When the gateway’s own status differs, it is in gateway_status (for example Stripe’s succeeded, Razorpay’s captured), next to the provider’s own object (payment_intent, payment, session…).
Paid or authorized, the gateway has not confirmed it yet
requires_action
The bank asks the buyer to authenticate (3DS / SCA)
completed
Paid
failed
Declined, canceled or expired
partially_refunded, refunded
Refunded in part or in full
amount_mismatch
Paid, but the gateway reported another amount or currency than the row expected
A dispute does not change the transaction’s status on any provider: it is reported as a dispute_created / dispute_updated webhook event (section 11).
[!IMPORTANT]
The Webhook Fulfillment Rule:
Never provision database access, grant licenses, or ship goods based solely on the user hitting the return URL (success_url?tid=...). The return URL can be spoofed or abandoned by the user. True financial finality occurs exclusively when the gateway’s signed server-to-server webhook is verified and processed by Kirak’s after_webhook hook.
Full and partial refunds are executed via refund_payment. The operation enforces database record locking and validates remaining balances before calling the gateway:
# Partial refund:
result =await kirak.payments.refund_payment({
"provider": "stripe",
"payment_id": "pi_3NXXXXXXXXXXXXXX",
"amount": 1000, # $10.00 USD partial refund
"currency": "USD",
"idempotency_key": "refund-tx-9921-part1",
})
# Full refund (omit amount):
result =await kirak.payments.refund_payment({
"provider": "stripe",
"payment_id": "pi_3NXXXXXXXXXXXXXX",
"idempotency_key": "refund-tx-9921-full",
})
Balance Check: If amount exceeds the remaining refundable balance ($\text{charged total} - \text{settled refunds} - \text{refunds in flight}$), Kirak rejects the call with REFUND_EXCEEDS_REMAINING (400) without calling the gateway.
Idempotency Protection: The refund request is recorded in payments_refunds before the gateway call is executed. Replays with the same idempotency_key return the original refund status without duplicate financial movement.
The result’s status is the same on every provider: succeeded (the refund went through and is recorded), requested (the gateway accepted it; its webhook records it later) or failed. The gateway’s own status is in gateway_status (Stripe succeeded / pending, Razorpay processed, PayPal completed…).
payments_subscriptions.status, and the status in the result of cancel_subscription, update_subscription, pause_subscription and resume_subscription, is one of these on every provider. They are Stripe’s names, in lower case as Stripe writes them; each provider’s own statuses are mapped onto them, so an app checks one set whatever the provider.
status
Meaning
Can still charge
incomplete
Started; the first payment or the buyer’s approval is not done yet
No
trialing
In place; the first charge comes later (a trial, or a start date in the future)
Yes
active
Renewing. A cancel scheduled for the period end keeps it active with cancel_at_period_end
Yes
past_due
A renewal failed and the gateway is retrying it
Yes
unpaid
The retries ran out; the subscription stays until it is paid or canceled
Yes
paused
Billing paused (pause_subscription, or the provider’s portal)
Yes
canceled
Ended: canceled, expired or completed. Final
No
A subscription that can still charge blocks an account close (409 ACTIVE_SUBSCRIPTION). To check that a user is paying, check status in (active, trialing).
How each provider’s statuses map:
Provider
Its status -> Kirak’s
Stripe
The same names; incomplete_expired -> canceled; an active subscription with pause_collection set -> paused
Paddle
The same names
PayPal
APPROVAL_PENDING, APPROVED -> incomplete; SUSPENDED -> paused (also when PayPal suspends after too many failed payments); CANCELLED, EXPIRED -> canceled
Paystack
non-renewing -> active with cancel_at_period_end; attention -> past_due; cancelled, complete, completed -> canceled
A cancel at the period end does not change the subscription’s status: it stays active (the user keeps what they paid for) until expires_on, then ends. payments_subscriptions.cancel_at_period_end says a cancel is scheduled, so an app can show “Your plan ends on 4 December” instead of “Renews on 4 December” and offer to keep it.
Moment
status
cancel_at_period_end
Renewing normally
active
false
Cancel scheduled (cancel_subscription with at_period_end: true, or in the provider’s own portal)
active
true
resume_subscription before the period ends
active
false
The period ends
canceled (the provider’s event)
true
Kirak sets the flag as soon as it schedules a cancel, and the provider’s subscription webhook keeps it in sync (Stripe cancel_at_period_end or cancel_at, Paddle scheduled_change, Square canceled_date, Paystack subscription.not_renew). Razorpay sends no event for a cycle-end cancel, so there only Kirak’s own cancel_subscription sets it. Square always cancels at the period end, so every Square cancel sets it.
resume_subscription makes a subscription renew normally again. It resumes a paused subscription and removes a scheduled cancel (or a scheduled pause on Paddle), and its result lists what it undid:
undid is empty when nothing was stopping the subscription. An ended subscription answers 409 SUBSCRIPTION_ENDED: start a new one. Razorpay cannot undo a cancel scheduled for the cycle end, so that case answers 501 NOT_SUPPORTED there. Flutterwave, Mercado Pago, PayPal and Paystack cannot schedule a cancel, so their resume_subscription only un-pauses.
initiate_payment with type: "subscription" charges the plan named by subscription_plan_id and never an amount the request carries, so that plan has to exist at the provider first. ensure_plan creates it, which means an app can define its plans in its own code instead of clicking them into the provider’s dashboard and copying ids back:
answer =await kirak.payments.ensure_plan({
"key": "pro_monthly_2900", # durable identity; include the amount
"name": "Pro",
"amount": 2900, # smallest unit, as everywhere else
"currency": "usd",
"interval": "month",
"interval_count": 1,
})
plan_id = answer["data"]["plan_id"]# pass as subscription_plan_id
It is find-or-create on key, permanently: the same key always resolves to the same plan, so a deploy that runs it on every boot creates nothing after the first time and data["created"] says which happened. That guarantee comes from a durable identity stored on the provider’s object (Stripe’s lookup_key), not from an idempotency key, which expires - Stripe keeps one 24 hours - and would let a later run create a duplicate plan.
A plan’s price cannot be edited at most providers, so a new price is a new key: keep the amount in it, as above, and leave the old plan in place for the subscribers already on it. product_key (default: key) names the object grouping one plan’s prices where the provider splits them that way, so several amounts can share one product that buyers see by name.
Two things gate it:
payments.plan_catalog must be true in kirak.json. It creates billable objects on the provider account, so it is off by default and otherwise answers 403 PLAN_CATALOG_DISABLED.
The provider must implement SupportsPlanCatalog, which needs that permanent find-or-create; only stripe does today, and the rest answer 501 NOT_SUPPORTED.
Like refunds and disputes, it is admin or system only.
UpdateDB -->RecordEvt["Insert Event ID into payments_webhook_events"]
RecordEvt -->FireHook["Fire after_webhook Hook"]
FireHook -->Return200["Return HTTP 200 OK to Gateway"]
[!NOTE]
Deliberate Unscoped System Context:
Once gateway cryptographic verification succeeds, Kirak explicitly sets the request execution context to SYSTEM_USER. This allows your after_webhook handlers to write records, create invoices, and update balances across models without encountering permission barriers. Prior to verification, before_webhook runs as untrusted guest.
[!NOTE]
How a webhook is matched to its payment: Razorpay, PayPal and Paddle send Kirak’s reference to the gateway and check it on each webhook, so an event from another Kirak database on the same gateway account is not taken for this one. Stripe and Square match on the row id (db_transaction_id) only. Row ids repeat across Kirak databases, so two Kirak databases sharing one gateway account can take each other’s events there. Omise’s payment link id is unique on its own. A single Kirak database per gateway account is not affected.
For gateways supporting disputes (SupportsDisputeRead and SupportsDisputeEvidence), chargebacks can be inspected and contested programmatically:
The status of get_dispute and submit_dispute_evidence, and the dispute_status of a dispute_created / dispute_updated webhook event, is one of these on every provider (Stripe’s names, in lower case). The gateway’s own is kept in gateway_status (webhook: gateway_dispute_status); a status Kirak does not know is null there, with the gateway’s kept.
status
Meaning
needs_response
Open: evidence or an answer is due
under_review
Answered or contested; the bank or gateway decides
won
Decided for the merchant
lost
Decided for the buyer, or accepted
closed
Ended without a decision Kirak can read from the status (an inquiry closed; PayPal and Paystack resolved, whose outcome is in the provider’s own field)
Provider
Its status -> Kirak’s
Stripe
The same names; warning_needs_response -> needs_response, warning_under_review -> under_review, warning_closed, prevented -> closed
Kirak guards financial records when users request account termination:
Active Obligations Block Closure:kirak.payments.check_account_close(user_id) checks for open billing obligations. If the user has active subscriptions (active, trialing, past_due, paused) or an active merchant account, account closure is blocked with 409 ACTIVE_SUBSCRIPTION or 409 ACTIVE_MERCHANT_ACCOUNT.
Purge Boundary:
When an account is deleted via kirak.payments.purge_account(user_id):
payment_methods and payment_customers are permanently deleted.
payments_transactions, payments_subscriptions, and payments_refunds are preserved in the database to satisfy statutory legal audit requirements, tax compliance, and chargeback evidence periods.
The payments module mounts standard REST endpoints alongside Python operations:
Method
Endpoint
Description
Access Control
POST
/payments/initiate
Start hosted checkout or subscription
Authenticated User (IP Rate Limited 20/min)
GET
/payments/providers
Discover active instances & capabilities
Authenticated User
POST
/payments/webhook/{instance}
Universal webhook ingest point
Public (Gateway Signature Verified)
POST
/payments/methods/setup
Hosted setup page to save card
Authenticated User
POST
/payments/methods
Attach client-side token
Authenticated User
GET
/payments/methods?user_id=
List saved payment methods
Owner or Admin
DELETE
/payments/methods/{id}
Revoke saved payment method
Owner or Admin
POST
/payments/methods/{id}/default
Set default payment method
Owner or Admin
POST
/payments/connect/onboard
Start Stripe Connect merchant onboarding
Authenticated User / Admin
POST
/payments/connect/onboard/refresh
Regenerate expired onboarding link
Owner or Admin
GET
/payments/connect/account-status
Sync & fetch live merchant account status
Owner or Admin
POST
/payments/connect/checkout
Create checkout on behalf of merchant
Authenticated User (IP Rate Limited 20/min)
PUT
/payments/connect/merchant-fee
Set platform fee rate (0-100%)
Admin or System Only
[!NOTE]
verify_payment, refund_payment, get_billing_portal, subscription operations (cancel, update, pause), disputes, and charge_off_session are exposed directly as Python operations on kirak.payments. Custom HTTP endpoints can wrap these operations with your application’s domain logic.
Gateways deliver webhooks at least once and not always in order. PaymentProvider has two helpers
for writing a transaction’s status from a webhook, so a custom provider does not complete a payment
twice or move a settled payment back:
Method
Use it for
Returns
await self.claim_completion(transaction_id, data)
Marking a transaction completed. The check and the write are one conditional update, so two deliveries of the same event cannot both complete it
True when this call completed it; False when it was already completed or refunded. Raises TRANSACTION_NOT_FOUND (404) when the transaction does not exist
Recording any other status (for example processing or failed)
True when the row was written; False when it is already completed or refunded, or does not exist
When claim_completion returns False, add "already_processed": True to the webhook result.
Payments then reports no event for that delivery, so the completed hook does not run twice
(after_webhook still runs):