Skip to content

Payments Module

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 decouples your domain logic and billing workflows from gateway-specific APIs, SDK quirks, and payload structures.

flowchart TD
subgraph ClientLayer["Client & Browser Layer"]
User["End User / Browser"]
Admin["Admin / System Worker"]
end
subgraph KirakRuntime["Kirak Payments Runtime"]
Router["Payments Router (/payments/*)"]
CostRL["Cost Rate Limiter (20 req/min)"]
Dispatch["Module Dispatch & Auth Guard"]
Hooks["Lifecycle Hooks (before / after)"]
ProviderSet["ProviderSet (Lazy Instance Cache)"]
Dedup["2-Layer Webhook Deduplication"]
end
subgraph Gateways["Supported Gateway Providers"]
direction TB
G1["Stripe & Stripe Connect"]
G2["Razorpay & Square"]
G3["PayPal & Paddle"]
G4["Paystack & Flutterwave"]
G5["Mercado Pago & Xendit"]
G6["Airwallex, Omise, Telr"]
end
subgraph StorageLayer["Persistence Layer"]
DBTx["payments_transactions"]
DBSub["payments_subscriptions"]
DBMeth["payments_payment_methods"]
DBEvt["payments_webhook_events"]
DBRef["payments_refunds"]
end
User -->|"POST /payments/initiate"| CostRL
CostRL --> Router
Admin -->|"Python SDK / Internal Calls"| Dispatch
Router --> Dispatch
Dispatch --> Hooks
Hooks --> ProviderSet
ProviderSet --> Gateways
Gateways -->|"Signed Webhook POST /payments/webhook/{instance}"| Router
Router --> Dedup
Dedup -->|"Persist & Reconcile"| StorageLayer
Dedup -->|"Run as SYSTEM"| Hooks

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):
pip install "kirak[payments-razorpay]" # Razorpay
pip install "kirak[payments-square]" # Square
# Or install all payment extras at once:
pip install "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.

Declare the module in kirak.json:

{
"modules": ["payments"],
"payments": {
"default_provider": "stripe",
"require_auth": true,
"success_url": "/payment/success",
"cancel_url": "/payment/cancel",
"providers": {
"stripe": {
"type": "stripe"
},
"razorpay": {
"type": "razorpay"
}
}
}
}

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).

Built-in type Gateway Description Documentation Guide
stripe Stripe Checkout, Elements, Subscriptions, Invoicing, Billing Portal, Disputes Stripe Guide
razorpay Razorpay Payment Links, Subscriptions, e-Mandates, UPI, Disputes Razorpay Guide
square Square Orders, Payment Links, Subscriptions, Saved Cards, Disputes Square Guide
paypal PayPal Orders API v2, Billing Agreements, Subscriptions, Vault, Disputes PayPal Guide
paddle Paddle Billing (Merchant of Record), Subscriptions, Portal, Disputes Paddle Guide
paystack Paystack Standard, Subscriptions, Manage Link, Saved Cards, Disputes Paystack Guide
flutterwave Flutterwave API v3 Standard, Subscriptions, Saved Cards, Chargebacks Flutterwave Guide
mercadopago Mercado Pago Checkout Pro, Preapproval Subscriptions, Disputes Mercado Pago Guide
xendit Xendit Invoices (Cards, Virtual Accounts, E-wallets, QRIS), Refunds Xendit Guide
airwallex Airwallex Hosted Payment Links, Global Currencies, Refunds, Disputes Airwallex Guide
omise Omise (Opn Payments) Links, PromptPay, Credit Cards, Disputes Omise Guide
telr Telr Hosted Payment Page (MENA / GCC currencies), Transaction Advice Telr Guide
stripe_connect Stripe Connect Marketplace (Express Onboarding, Direct / Destination Charges) Stripe Connect Guide
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).

razorpay (pip install "kirak[payments-razorpay]") – Razorpay payments, subscriptions, saved payment methods (mandates) and disputes.

Credential check (check()): GET /v1/payments?count=1.

Name Where Required / default Description
success_url kirak.json default /payment/success Redirect after a successful payment; a path is prefixed with base_url. Overrides payments.success_url.
cancel_url kirak.json default /payment/cancel Redirect after a cancelled payment; a path is prefixed with base_url. Overrides payments.cancel_url.
timeout kirak.json default 15 Seconds one gateway call may take before it fails with 502.
KIRAK_PAYMENT_<INSTANCE>_KEY_ID environment required Razorpay key ID (rzp_live_… or rzp_test_…).
KIRAK_PAYMENT_<INSTANCE>_KEY_SECRET environment required Razorpay key secret.
KIRAK_PAYMENT_<INSTANCE>_WEBHOOK_SECRET environment Webhook secret; needed to verify webhooks.

square (pip install "kirak[payments-square]") – Square payments, subscriptions, saved cards and disputes.

Credential check (check()): GET /v2/locations/<location_id>.

Name Where Required / default Description
timeout kirak.json default 15 Seconds one gateway call may take before it fails with 502.
location_id kirak.json required Square location that takes the payments.
environment kirak.json default sandbox “sandbox” or “production”.
webhook_notification_url kirak.json The exact public URL Square posts webhooks to; part of the signature check.
success_url kirak.json default /payment/success Redirect after a successful payment; a path is prefixed with base_url. Overrides payments.success_url.
cancel_url kirak.json default /payment/cancel Redirect after a cancelled payment; a path is prefixed with base_url. Overrides payments.cancel_url.
KIRAK_PAYMENT_<INSTANCE>_ACCESS_TOKEN environment required Square access token (production or sandbox).
KIRAK_PAYMENT_<INSTANCE>_WEBHOOK_SIGNATURE_KEY environment Webhook signature key; needed to verify webhooks.

paypal (no extra install) – PayPal Checkout: one-time payments, subscriptions, vaulted PayPal accounts, off-session charges and disputes.

Credential check (check()): POST /v1/oauth2/token; then GET the webhook named by webhook_id.

Name Where Required / default Description
timeout kirak.json default 15 Seconds one gateway call may take before it fails with 502.
environment kirak.json default sandbox “sandbox” or “live”.
success_url kirak.json default /payment/success Redirect after a successful payment; a path is prefixed with base_url. Overrides payments.success_url.
cancel_url kirak.json default /payment/cancel Redirect after a cancelled payment; a path is prefixed with base_url. Overrides payments.cancel_url.
KIRAK_PAYMENT_<INSTANCE>_CLIENT_ID environment required PayPal REST app client ID.
KIRAK_PAYMENT_<INSTANCE>_CLIENT_SECRET environment required PayPal REST app secret.
KIRAK_PAYMENT_<INSTANCE>_WEBHOOK_ID environment ID of the webhook registered in the app; needed to verify webhooks.

paddle (no extra install) – Paddle Billing (merchant of record): one-time payments, subscriptions and one-time charges on a subscription.

Credential check (check()): GET /event-types.

Name Where Required / default Description
timeout kirak.json default 15 Seconds one gateway call may take before it fails with 502.
environment kirak.json default sandbox “sandbox” or “production”.
default_tax_category kirak.json default standard Tax category of the product created for a payment without price_id.
checkout_url kirak.json Approved page that loads Paddle.js; the account’s default payment link otherwise.
KIRAK_PAYMENT_<INSTANCE>_API_KEY environment required Paddle API key.
KIRAK_PAYMENT_<INSTANCE>_WEBHOOK_SECRET environment Secret of the notification destination; needed to verify webhooks.

paystack (no extra install) – Paystack: one-time payments, subscriptions, saved cards, off-session charges and disputes (read-only).

Credential check (check()): GET /balance.

Name Where Required / default Description
timeout kirak.json default 15 Seconds one gateway call may take before it fails with 502.
environment kirak.json default test “test” or “live”; must match the secret key.
success_url kirak.json default /payment/success Redirect after a successful payment; a path is prefixed with base_url. Overrides payments.success_url.
KIRAK_PAYMENT_<INSTANCE>_SECRET_KEY environment required Paystack secret key (sk_test_… or sk_live_…); also verifies webhooks.

flutterwave (no extra install) – Flutterwave (API v3): one-time payments, subscriptions, saved cards, off-session charges and disputes (read-only).

Credential check (check()): GET /v3/balances.

Name Where Required / default Description
timeout kirak.json default 15 Seconds one gateway call may take before it fails with 502.
environment kirak.json default test “test” or “live”; must match the secret key.
country kirak.json Two-letter country code of the account; needed for off-session charges.
success_url kirak.json default /payment/success Redirect after a successful payment; a path is prefixed with base_url. Overrides payments.success_url.
KIRAK_PAYMENT_<INSTANCE>_SECRET_KEY environment required Flutterwave secret key (FLWSECK_TEST-… or FLWSECK-…).
KIRAK_PAYMENT_<INSTANCE>_SECRET_HASH environment required Secret hash set on the webhook; verifies webhooks.

mercadopago (no extra install) – Mercado Pago: Checkout Pro payments, subscriptions (preapprovals) and disputes (read-only).

Credential check (check()): GET /users/me.

Name Where Required / default Description
timeout kirak.json default 15 Seconds one gateway call may take before it fails with 502.
environment kirak.json default sandbox “sandbox” or “production”.
success_url kirak.json default /payment/success Redirect after a successful payment; a path is prefixed with base_url. Overrides payments.success_url.
KIRAK_PAYMENT_<INSTANCE>_ACCESS_TOKEN environment required Mercado Pago access token.
KIRAK_PAYMENT_<INSTANCE>_WEBHOOK_SECRET environment required Secret signature of the webhook; verifies webhooks.

xendit (no extra install) – Xendit Invoices: one-time payments and refunds.

Credential check (check()): GET /balance.

Name Where Required / default Description
timeout kirak.json default 15 Seconds one gateway call may take before it fails with 502.
environment kirak.json default test “test” or “live”; must match the secret key.
success_url kirak.json default /payment/success Redirect after a successful payment; a path is prefixed with base_url. Overrides payments.success_url.
KIRAK_PAYMENT_<INSTANCE>_SECRET_KEY environment required Xendit secret API key (xnd_development_… or xnd_production_…).
KIRAK_PAYMENT_<INSTANCE>_CALLBACK_TOKEN environment required Callback verification token; verifies webhooks.

airwallex (no extra install) – Airwallex Payment Links: one-time payments, refunds and disputes (read-only).

Credential check (check()): POST /api/v1/authentication/login.

Name Where Required / default Description
timeout kirak.json default 15 Seconds one gateway call may take before it fails with 502.
environment kirak.json default sandbox “sandbox” or “production”.
KIRAK_PAYMENT_<INSTANCE>_CLIENT_ID environment required Airwallex API client ID.
KIRAK_PAYMENT_<INSTANCE>_API_KEY environment required Airwallex API key.
KIRAK_PAYMENT_<INSTANCE>_WEBHOOK_SECRET environment required Secret of the webhook; verifies webhooks.

omise (no extra install) – Omise (Opn Payments) Links: one-time payments, refunds and disputes (read-only).

Credential check (check()): GET /account.

Name Where Required / default Description
timeout kirak.json default 15 Seconds one gateway call may take before it fails with 502.
environment kirak.json default test “test” or “live”; must match the secret key.
KIRAK_PAYMENT_<INSTANCE>_SECRET_KEY environment required Omise secret key (skey_test_… or skey_…).
KIRAK_PAYMENT_<INSTANCE>_WEBHOOK_SECRET environment Base64 webhook secret; without it each webhook is verified by reading its event back.

telr (no extra install) – Telr Hosted Payment Page: one-time payments; refunds made in the Telr admin are recorded.

Credential check (check()): None: Telr has no read-only call; the offline checks run.

Name Where Required / default Description
timeout kirak.json default 15 Seconds one gateway call may take before it fails with 502.
store_id kirak.json required Numeric Telr store ID.
environment kirak.json default test “test” or “live”.
success_url kirak.json required Absolute URL Telr returns the buyer to after paying, declining or cancelling.
KIRAK_PAYMENT_<INSTANCE>_AUTH_KEY environment required Authentication key of the Hosted Payment Page.
KIRAK_PAYMENT_<INSTANCE>_ADVICE_SECRET environment required Secret key of the transaction advice; verifies webhooks.
  1. Default Instance: Calls omitting the "provider" parameter automatically use default_provider.
  2. Explicit Routing: Pass "provider": "<instance_name>" in operation parameters to route to a specific gateway instance.
  3. Allow-List Isolation: Only instances declared in kirak.json can be invoked. Unknown names fail immediately with PROVIDER_NOT_CONFIGURED (400).
  4. 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).
  5. 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';
COMMIT;

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:

# Inspect configured capabilities in Python:
capabilities = await kirak.payments.list_providers()
{
"status": "success",
"data": {
"providers": [
{
"name": "stripe",
"type": "stripe",
"capabilities": [
"billing_portal",
"dispute_evidence",
"dispute_read",
"disputes",
"off_session",
"pause",
"payment_method_attach",
"payment_method_setup",
"payment_methods",
"subscription_cancel",
"subscription_lifecycle",
"subscription_update",
"subscriptions"
]
},
{
"name": "xendit",
"type": "xendit",
"capabilities": []
}
]
}
}
Full Capability Matrix by Gateway Type (Click to Expand)
Gateway Type Subscriptions Pause / Resume Billing Portal Saved Methods Off-Session Read Disputes Dispute Evidence
stripe Yes Yes Yes Yes Yes Yes Yes
razorpay Yes Yes No Yes Yes Yes Yes
square Yes Yes No Yes Yes Yes Yes
paypal Yes Yes No Yes Yes Yes Yes
paddle Yes Yes Yes No Partial No No
paystack Yes No Yes Yes Yes Yes No
flutterwave Yes No No Yes Yes Yes No
mercadopago Yes Yes No No No Yes No
xendit No No No No No No No
airwallex No No No No No Yes No
omise No No No No No Yes No
telr No No No No No No No
stripe_connect No No No Yes Yes No No

5. Authentication, Ownership & Cost Protection

Section titled “5. Authentication, Ownership & Cost Protection”
  1. Identity & Ownership Enforcement (require_auth):
    • Enabled by default ("require_auth": true).
    • "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.
  2. 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.
  3. 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

Section titled “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).
  • CURRENCY_EXPONENTS: Gateway-specific exponent overrides (e.g. Stripe requires {"ISK": 2, "UGX": 2}, Paystack requires {"XOF": 2, "RWF": 2}, Mercado Pago requires {"COP": 0}).
# Correct usage: integer minor units
amount = 2999 # $29.99 USD

[!WARNING] Amount Validation Rules:

  • 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).

7.1 Initiating Payments (initiate_payment)

Section titled “7.1 Initiating Payments (initiate_payment)”

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
"idempotency_key": "checkout-order-4421", # Recommended: prevents duplicate sessions
})
checkout_url = result["data"]["url"]
transaction_id = result["data"]["transaction_id"]

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:

PRICES = {
"plan_starter": 1900,
"plan_pro": 4900,
"plan_enterprise": 19900,
}
@kirak.payments.hook("before_initiate_payment")
def enforce_server_pricing(params):
plan_key = params.get("payment_meta", {}).get("plan_id")
if not plan_key or plan_key not in PRICES:
raise KirakException("Invalid plan selected", code="INVALID_PLAN", status_code=400)
# Overwrite client parameters with authoritative database/catalog values
params["amount"] = PRICES[plan_key]
params["currency"] = "USD"
return params

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.


sequenceDiagram
autonumber
actor Customer as User / Browser
participant AppFrontend as Web / Mobile App
participant KirakAPI as Kirak Backend
participant Gateway as Payment Gateway
participant WebhookHandler as after_webhook Hook
Customer->>AppFrontend: Click "Buy Now"
AppFrontend->>KirakAPI: POST /payments/initiate
KirakAPI->>Gateway: Create Checkout Session
Gateway-->>KirakAPI: Checkout URL
KirakAPI-->>AppFrontend: Return URL + transaction_id (pending)
AppFrontend->>Gateway: Redirect Buyer to Checkout Page
Customer->>Gateway: Submits Credit Card & Approves Payment
rect rgb(255, 235, 235)
Note over Customer,KirakAPI: UNTRUSTED / INCOMPLETE PATH (Return URL)
Gateway-->>Customer: Redirect to success_url?tid=...
Customer->>AppFrontend: Loads Success Page
AppFrontend->>KirakAPI: GET /payments/verify (Optional Status Check)
KirakAPI-->>AppFrontend: Status: pending / processing
Note over AppFrontend: DO NOT fulfill order here!
end
rect rgb(235, 255, 235)
Note over Gateway,WebhookHandler: AUTHORITATIVE FINANCIAL FULFILLMENT PATH
Gateway->>KirakAPI: POST /payments/webhook/{service} (Signed Webhook)
KirakAPI->>KirakAPI: Verify HMAC Signature with Webhook Secret
KirakAPI->>KirakAPI: Check Deduplication (payments_webhook_events)
KirakAPI->>KirakAPI: Check Paid Amount == Expected Amount
KirakAPI->>KirakAPI: Transition Context to SYSTEM_USER
KirakAPI->>KirakAPI: Update Transaction to completed
KirakAPI->>WebhookHandler: Fire after_webhook (event: "payment_completed")
WebhookHandler->>WebhookHandler: Grant Entitlement / Provision Service
KirakAPI-->>Gateway: HTTP 200 OK
end

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…).

Transaction statuses (payments_transactions.payment_status)

Section titled “Transaction statuses (payments_transactions.payment_status)”
payment_status Meaning
pending Started; the buyer has not paid yet
processing 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",
})
  1. 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.
  2. 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…).


7.4 Customer Billing Portal (get_billing_portal)

Section titled “7.4 Customer Billing Portal (get_billing_portal)”

Generates a hosted customer management portal URL where customers can view past invoices, update credit cards, or cancel subscriptions:

portal = await kirak.payments.get_billing_portal({
"user_id": "usr_9921",
"return_url": "https://app.example.com/billing",
"provider": "stripe",
})
redirect_url = portal["data"]["portal_url"]

Supported by: Stripe, Paddle, and Paystack.


8. Capability-Gated Subscription Management

Section titled “8. Capability-Gated Subscription Management”

Gateways implementing subscription mixins allow programmatic lifecycle management directly from backend code or admin panels:

stateDiagram-v2
[*] --> incomplete: initiate_payment (type="subscription")
incomplete --> active: webhook: the first payment
incomplete --> trialing: webhook: in place, first charge later
trialing --> active: webhook: the first charge
state active {
[*] --> CurrentPeriod
CurrentPeriod --> CurrentPeriod: webhook: subscription_renewed
}
active --> past_due: webhook: payment_failed
past_due --> active: webhook: payment_succeeded (Recovery)
past_due --> unpaid: the gateway's retries ran out
unpaid --> active: webhook: paid
unpaid --> canceled: canceled
past_due --> canceled: the gateway gave up and canceled
active --> paused: pause_subscription()
paused --> active: resume_subscription()
active --> active: update_subscription(new_plan_id)
active --> active: cancel_subscription(at_period_end=True) sets cancel_at_period_end, resume_subscription() clears it
active --> canceled: Billing period ends with cancel_at_period_end
active --> canceled: cancel_subscription(at_period_end=False)
canceled --> [*]

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
Razorpay created -> incomplete; authenticated -> trialing; pending -> past_due; halted -> unpaid; cancelled, completed, expired -> canceled
Square PENDING -> trialing; DEACTIVATED, CANCELED -> canceled
Mercado Pago pending -> incomplete; authorized -> active; paused -> paused; cancelled -> canceled
Flutterwave active -> active; cancelled -> canceled
# 1. Cancel Subscription
await kirak.payments.cancel_subscription({
"subscription_id": "sub_1NXXXXXXXXXXXXXX",
"at_period_end": True, # Cancel at end of current paid cycle
})
# 2. Update Plan or Quantity
await kirak.payments.update_subscription({
"subscription_id": "sub_1NXXXXXXXXXXXXXX",
"new_plan_id": "price_pro_annual",
"quantity": 5,
})
# 3. Pause Billing
await kirak.payments.pause_subscription({
"subscription_id": "sub_1NXXXXXXXXXXXXXX",
})
# 4. Resume: un-pause, and undo a cancel scheduled for the period end
await kirak.payments.resume_subscription({
"subscription_id": "sub_1NXXXXXXXXXXXXXX",
})

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:

{"subscription_id": "sub_1N...", "status": "active", "undid": ["pause", "scheduled_cancel"]}

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.

Creating the Plans Themselves (ensure_plan)

Section titled “Creating the Plans Themselves (ensure_plan)”

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.


9. Saved Payment Methods & Off-Session Charges

Section titled “9. Saved Payment Methods & Off-Session Charges”

Kirak allows saving customer payment methods (cards, mandates, vaulted accounts) securely at the gateway for subsequent headless charges (usage billing, overages, top-ups). Card details never touch your server.

Saving a payment method legally requires customer consent for future off-session charges:

# Method A: Save during one-time checkout
await kirak.payments.initiate_payment({
"user_id": "usr_9921",
"amount": 1500,
"currency": "USD",
"name": "Initial Token Deposit",
"type": "one_time",
"save_payment_method": True,
"consent": {"text_version": "terms_v2_2026"},
})
# Method B: Hosted setup session without charging
result = await kirak.payments.setup_payment_method({
"user_id": "usr_9921",
"provider": "stripe",
"consent": {"text_version": "terms_v2_2026"},
})
setup_url = result["data"]["url"]
# Method C: Attach client-side token (e.g. Stripe.js PaymentMethod)
await kirak.payments.attach_payment_method({
"user_id": "usr_9921",
"payment_method_token": "pm_1NXXXXXXXXXXXXXX",
"provider": "stripe",
"consent": {"text_version": "terms_v2_2026"},
})

9.2 Charging Off-Session (charge_off_session)

Section titled “9.2 Charging Off-Session (charge_off_session)”

Charging a saved method without the customer present is strictly Admin / System only:

result = await kirak.payments.charge_off_session({
"user_id": "usr_9921",
"amount": 4200, # $42.00 USD
"currency": "USD",
"name": "Overage Compute Usage - October",
"idempotency_key": "metered-usage-oct-usr9921", # REQUIRED
# "payment_method_id": 14, # Optional: defaults to user's default saved card
})
status = result["data"]["status"]
# Outcomes:
# - "completed" / "processing": Charge accepted. Webhook will confirm.
# - "requires_action": 3-D Secure authentication required. Send result["data"]["action_url"] to user.
# - "failed": Card declined. See result["data"]["decline_code"].

Kirak automatically mounts a unified webhook listener route: $$\text{POST /payments/webhook/}{instance}$$

flowchart TD
Req["Incoming POST /payments/webhook/{instance}"] --> SigCheck{"Verify Gateway Signature Header"}
SigCheck -- "Invalid / Missing" --> Fail400["HTTP 400 Bad Request (Logged)"]
SigCheck -- "Verified" --> Dedup1{"Check payments_webhook_events"}
Dedup1 -- "Event ID Exists" --> Skip["Acknowledge HTTP 200 (already_processed: true)"]
Dedup1 -- "New Event" --> Elevate["Elevate Context to SYSTEM_USER"]
Elevate --> StatusCheck{"Check Transaction Status"}
StatusCheck -- "Already Settled" --> Skip
StatusCheck -- "Active / Pending" --> UpdateDB["Update Transaction / Subscription Record"]
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.

Your after_webhook hook receives a provider-neutral event name in data["event"]:

@kirak.payments.hook("after_webhook")
async def handle_payment_events(result):
data = result["data"]
event = data.get("event")
if event == "payment_completed":
user_id = data["user_id"]
tx_id = data["transaction_id"]
amount = data.get("amount")
# Fulfill customer order safely:
await kirak.create("orders", {"user_id": user_id, "tx_id": tx_id, "status": "paid"})
elif event == "subscription_renewed":
# Extend billing period:
await kirak.update("users", {"id": data["user_id"]}, {"plan_status": "active"})
elif event == "subscription_cancelled":
# Downgrade user:
await kirak.update("users", {"id": data["user_id"]}, {"plan_status": "free"})
elif event == "payment_amount_mismatch":
# Client attempted price tampering:
logger.error(f"Price mismatch on tx {data['transaction_id']}: paid {data['paid_amount']} vs expected {data['expected_amount']}")
return result
Normalized Event Name Description
payment_completed One-time checkout or off-session charge confirmed by gateway
payment_failed One-time payment or off-session charge declined or abandoned
subscription_renewed Recurring cycle billing succeeded (Stripe invoice, Razorpay charged, etc.)
subscription_updated Subscription plan, quantity, or terms modified
subscription_past_due Recurring billing failed; grace period or retry underway
subscription_cancelled Subscription terminated at provider or via customer portal
refund_completed Refund confirmed and settled at gateway
dispute_created Customer bank filed a chargeback against a payment
dispute_updated Chargeback evidence reviewed or dispute status modified
payment_amount_mismatch Paid amount does not match stored unit price $\times$ quantity
payment_method_saved Reusable payment method vaulted successfully
payment_method_removed Saved method revoked at gateway

To keep the deduplication table performant, schedule periodic cleanup of old webhook records:

# Scheduled job (e.g. daily):
deleted_count = await kirak.payments.prune_webhook_events(older_than_days=30)

(Retention cannot be set lower than 7 days to guarantee gateway retry deduplication).


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
PayPal OPEN, WAITING_FOR_SELLER_RESPONSE -> needs_response; WAITING_FOR_BUYER_RESPONSE, UNDER_REVIEW, OTHER -> under_review; RESOLVED -> closed
Square EVIDENCE_REQUIRED, INQUIRY_EVIDENCE_REQUIRED -> needs_response; PROCESSING, INQUIRY_PROCESSING -> under_review; ACCEPTED -> lost; INQUIRY_CLOSED -> closed
Razorpay open -> needs_response; the rest the same names
Paystack awaiting-merchant-feedback -> needs_response; awaiting-bank-feedback, pending -> under_review; resolved, archived -> closed
Airwallex REQUIRES_RESPONSE -> needs_response; CHALLENGED -> under_review; ACCEPTED, EXPIRED -> lost
Omise open -> needs_response; pending -> under_review
Flutterwave initiated -> needs_response; declined (contested) -> under_review; accepted -> lost
Paddle pending_approval -> under_review; approved -> lost; reversed -> won
# 1. Fetch dispute details:
dispute = await kirak.payments.get_dispute({
"dispute_id": "dp_1NXXXXXXXXXXXXXX",
"provider": "stripe",
})
# 2. Submit contest evidence:
await kirak.payments.submit_dispute_evidence({
"dispute_id": "dp_1NXXXXXXXXXXXXXX",
"evidence": {
"customer_communication": "Customer confirmed receipt of goods on Oct 12",
"service_documentation": "Access logs showing IP usage",
},
"provider": "stripe",
})

Kirak guards financial records when users request account termination:

  1. 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.
  2. 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.


You can integrate any proprietary or local payment gateway by subclassing PaymentProvider:

your_app/providers/custom_pay.py
import hmac, hashlib, json
from kirak.payments.providers.base import PaymentProvider
from kirak.core.error_response import create_success_response
from kirak.core.exceptions import ValidationError
class CustomPayProvider(PaymentProvider):
TYPE_NAME = "custom_pay"
SECRET_FIELDS = ("api_key", "webhook_secret")
WEBHOOK_SIGNATURE_HEADER = "x-custompay-signature"
EVENT_MAP = {
"payment.success": "payment_completed",
"payment.declined": "payment_failed",
"refund.success": "refund_completed",
}
def __init__(self, config: dict, payments=None):
super().__init__(config, payments=payments)
self._require("api_key")
self.api_key = config["api_key"]
self.webhook_secret = config.get("webhook_secret", "")
async def initiate_payment(self, params: dict) -> dict:
saved = await self._kirak_create("transactions", {
"user_id": params["user_id"],
"payment_status": "pending",
"transaction_type": params.get("type", "one_time"),
"amount": params["amount"],
"net_amount": params["amount"],
"payment_service": self.instance_name,
"quantity": params.get("quantity", 1),
"payment_email": params.get("payment_email", ""),
})
tx_id = saved.get("data", {}).get("id")
checkout_url = f"https://gateway.custompay.io/pay/{tx_id}"
return create_success_response(data={"url": checkout_url, "transaction_id": tx_id})
async def verify_payment(self, params: dict) -> dict:
return create_success_response(data={"status": "completed"})
async def refund_payment(self, params: dict) -> dict:
return create_success_response(data={"refund_id": "ref_12345"})
async def handle_webhook(self, params: dict) -> dict:
payload = params.get("payload", b"")
signature = params.get("signature", "")
expected = hmac.new(self.webhook_secret.encode(), payload, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature):
raise ValidationError("Invalid webhook signature")
event = json.loads(payload).get("event")
return create_success_response(data={"event_type": event})

Register your custom provider in on_kirak_ready:

main.py
from kirak import create_kirak_app
from your_app.providers.custom_pay import CustomPayProvider
async def on_kirak_ready(kirak):
kirak.payments.register_provider("custom_pay", CustomPayProvider)
app = create_kirak_app(on_kirak_ready=on_kirak_ready)

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
await self.update_unless_settled(transaction_id, data) 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):

async def handle_webhook(self, params: dict) -> dict:
...
data = {"payment_status": "completed", "transaction_id": gateway_ref}
result = {"event_type": event, "transaction_id": tx_id}
if not await self.claim_completion(tx_id, data):
result["already_processed"] = True
return create_success_response(data=result)