Commission Ledger API
The HTTP API is a JSON API that powers the Commission Ledger portal. It is consumed by the bundled browser front end, but any client that can hold a cookie session works. Amounts are handled in the account currency (KES) and stored to two decimal places.
Conventions
| Aspect | Behaviour |
|---|---|
| Base URL | https://kountoo.co.ke/api — served through api.php |
| Content type | Request and response bodies are JSON (application/json; charset=utf-8), except the CSV export |
| Body size limit | 1 MiB for POST/PUT/PATCH; larger bodies are rejected with 413 |
| Authentication | PHP session cookie issued by POST /api/auth/login. No bearer tokens |
| CSRF | All non-GET requests must either carry a same-origin Origin header or an X-CSRF-Token header with the token returned by login |
| Roles | admin and client; every endpoint states its allowed roles |
| IDs | Path IDs are UUIDs; malformed IDs are rejected with 400 Invalid ID. |
| Errors | Non-success responses are {"error": "<message>"} |
| CORS | Same-origin by default. Cross-origin requests must match an exact origin in CORS_ALLOWED_ORIGINS; wildcard origins are never accepted, and requests are credentialed |
Common responses
204— CORS pre-flight (OPTIONS) acknowledgement, no body.401— No session, or the session user is inactive:{"error": "Please sign in."}403— Role check failed (Forbidden.), CSRF/CORS rejection, or the account still hasmustChangePasswordset and the path is not/api/me,/api/auth/passwordor/api/auth/logout.404— Endpoint or record not found.409— Conflicting state: duplicate record, cycle already calculated, open request, insufficient ledger balance, or a database constraint violation.413— Request body over 1 MiB.500— Unexpected server or database failure. Details are logged server-side only, never returned.
Authentication
Sign in
Body:
{
"email": "jane@example.com",
"password": "..."
}
On success the session starts, the cookie is set, and the session ID is regenerated.
200—{"user": {"id", "full_name", "email", "role", "mustChangePassword"}, "csrfToken": "64 hex chars"}401—Invalid email or password.
csrfToken — it is required for non-GET requests from clients that do not send an Origin header.Sign out
200—{"ok": true}, destroys the session.
Request a password reset
Body: {"email": "jane@example.com"}. Creates a reset request for the administrator. The response is identical whether or not the email exists.
200—{"message": "If the account is eligible, a request has been sent to the administrator."}
At most one pending request per client, and at most one request per 24 hours.
Change password
Body: {"password": "…"} — minimum 12 characters. Also clears the mustChangePassword flag.
200—{"ok": true}
Current session
200—{"user": {…}, "csrfToken": "…"}(same shape as login)
Read profile
200—{"user": {…}}
Update profile
{
"name": "Jane Doe",
"email": "jane@example.com",
"avatarType": "male",
"password": "optional, min 12 chars"
}
200—{"ok": true}400—Enter a valid name and email.orPassword must be at least 12 characters.
System
Health check
Verifies database connectivity.
200—{"status": "ok", "database": "ok"}503—{"status": "degraded", "database": "unavailable"}
Client portal (role: client)
Dashboard overview
Returns everything the client dashboard renders.
{
"capital": 150000.0,
"investments": [{ "amount", "invested_at", "eligible_on",
"expected_payout_on", "expected_commission" }],
"payouts": [{ "amount", "cycle_number", "payout_on",
"investment_amount", "invested_at" }],
"paymentMethod": { "method", "account_name", "mpesa_number",
"bank_name", "bank_account" },
"payoutRequest": { "id", "status", "requested_at" } | null
}
Open a payout request
201—{"ok": true}409—You already have an open payout request.orThere are no eligible investments awaiting payout.
Update payment method
Body: {"method": "M-Pesa" | "Bank Account", "accountName": "…"} plus, for M-Pesa, mpesaNumber; for a bank account, bankName and bankAccount. Legacy snake_case keys (account_name, mpesa_number, bank_name, bank_account) are also accepted. Upserts the client's single payment method.
200—{"ok": true}400—Invalid payment details./Complete the selected payment details.
Client management (role: admin)
List clients
Only active client accounts are returned, ordered by full name.
{
"clients": [{
"id", "full_name", "email", "active", "avatar_type", "capital",
"method", "mpesa_number", "bank_account",
"investments": [{ "amount", "invested_at" }]
}]
}
Create a client
Body: {"name": "…", "email": "…"}. Creates a client with a one-time temporary password, or re-activates a previously deleted (inactive) client with the same email.
201—{"client": {"id", "full_name", "email"}, "temporaryPassword": "12 hex chars"}200— same shape plus"restored": truewhen an inactive client was restored400—Enter a valid name and email.409—A client with this email already exists.
Record capital
Body: {"amount": 25000, "investmentMode": "single" | "separate"}. single adds the amount to the client's most recent confirmed investment (creating one if none exists); the default separate creates a new confirmed investment dated today.
201—{"ok": true}400—Amount must be greater than zero./Invalid ID.404—Client not found.
Deactivate a client
200—{"ok": true}404—Client not found.
Issue a temporary password
Issues a new temporary password and clears the client's pending password-reset requests.
200—{"temporaryPassword": "12 hex chars"}404—Client not found.
List password reset requests
200—{"requests": [{"id", "requested_at", "user_id", "full_name", "email"}]}
Ledger & dashboard (role: admin)
List transactions
200—{"transactions": [{…, "created_by_name", "reversal_id"}]}, newest first.
Record a transaction
Body: {"type": "Capital In" | "Dividend In" | "Payout Out", "party": "…", "amount": 5000, "reference"?: "…", "notes"?: "…"}
201—{"ok": true}400—Invalid transaction.
Reverse a transaction
Creates the offsetting entry (Payout Out → Capital In, otherwise Payout Out) and links it via reversal_of. Atomic; each transaction can be reversed once.
201—{"ok": true}404—Transaction not found./Transaction has already been reversed.
Ledger balance
200—{"balance": 0.0}— sum ofCapital In/Dividend InminusPayout Out.
Dashboard totals
200—{"clients": int, "capital": 0.0, "pendingPayouts": 0.0, "cycle": {"payout_on"} | null}
Analytics
{
"paidOutThisMonth": 0.0,
"pendingLiability": 0.0,
"feesCollectedThisMonth": 0.0,
"topClients": [{ "full_name", "email", "total_paid" }]
}
Fee rules (role: admin)
List fee rules
200—{"feeRules": [{"id", "name", "type": "flat" | "tiered", "flat_rate", "tiers", "active", …}]}, newest first.
Create a fee rule
Flat rule: {"type": "flat", "name": "…", "flatRate": 5, "activate"?: true} — rate 0–100.
Tiered rule: {"type": "tiered", "name": "…", "tiers": [{"min": 0, "max"?: 50000, "rate": 5}], "activate"?: true} — tiers must have increasing, non-overlapping ranges and rates 0–100. Rates are percentages.
201—{"ok": true}400—Invalid fee rule./Rate must be between 0 and 100./Tiered rules require tiers./Tiers must have increasing non-overlapping ranges and rates from 0 to 100.
When activate is true, the previously active rule is deactivated in the same transaction.
Activate a fee rule
200—{"ok": true}404—Fee rule not found.(only one rule can be active at a time)
Delete a fee rule
Deletes an inactive rule; active rules are silently not deleted.
200—{"ok": true}
Payout cycles (role: admin)
List payout cycles
200—{"cycles": [{"id", "cycle_number", "starts_on", "payout_on", …}]}, newest payout date first.
Create a payout cycle
Body: {"startsOn": "2026-11-01", "payoutOn": "2026-11-30"} — payoutOn must be after startsOn. The cycle number is assigned under a PostgreSQL advisory lock to prevent duplicates.
201—{"ok": true}400—Enter a valid start date and a payout date after it.
Calculate payouts
Calculates a payout for every confirmed investment of active clients whose 45-day eligibility date falls on or before the cycle's payout date. The active fee rule's fee plus 16% VAT on the fee are deducted. Atomic — all payouts or none.
200—{"payouts": [{"id", "amount": "12.00"}]}404—Cycle or active fee rule not found.409—Payouts have already been calculated for this cycle.
Settlement & payout requests (role: admin)
List payouts
Query parameter status defaults to pending; anything else is rejected. Sorted by cycle payout date.
200—{"payouts": [{…, "full_name", "payout_on", "investment_amount", "invested_at"}]}400—Invalid payout status.
Mark a payout as paid
Marks a pending payout as paid under an advisory lock, verifies the ledger balance covers the amount, and records a Payout Out transaction. Atomic.
200—{"ok": true}409—Pending payout not found./Insufficient ledger balance.
List payout requests
200—{"requests": [{"id", "client_id", "status", "requested_at", "full_name", "email"}]}
Resolve a payout request
200—{"ok": true}
Export (role: admin)
Returns the full transaction ledger as a CSV download. Formula-like cell values are prefixed with ' to protect against CSV injection.
200—text/csv; charset=utf-8withContent-Disposition: attachment; filename="commission-ledger.csv", columns:Date,Type,Party,Amount,Reference,Notes
Example session
# 1. Sign in and capture the session cookie and CSRF token
curl -c cookies.txt -H 'Content-Type: application/json' \
-d '{"email":"admin@example.com","password":"..."}' \
https://kountoo.co.ke/api/auth/login
# 2. Use the session for GETs (CSRF token not required)
curl -b cookies.txt https://kountoo.co.ke/api/dashboard
# 3. Use the session plus CSRF header for state-changing calls
TOKEN=... # csrfToken from the login response
curl -b cookies.txt -X POST \
-H 'Content-Type: application/json' \
-H "X-CSRF-Token: $TOKEN" \
-d '{"name":"Jane Doe","email":"jane@example.com"}' \
https://kountoo.co.ke/api/clients