OCTA Gov Integrations Gateway — API v1

Base URL: https://gov.medcoreapp.tech (deployment setting PUBLIC_DOMAIN). All bodies are JSON (UTF-8). All responses are {"success": true, "data": …} or {"success": false, "error": "…"}. Error messages are in Arabic and safe to show to end users.

Overview

The gateway connects HR/ERP systems (MedCore, OCTAPOS, any ERP) to Saudi labour and immigration platforms — Qiwa, Muqeem and Mudad — and tracks every recurring compliance obligation: iqama expiries, exit/re-entry and final-exit visas, Qiwa contract documentation, and the monthly wage-protection (WPS) upload.

Honesty rule. None of these agencies publishes a public API. The gateway never invents an endpoint or field name. Each agency runs in one of three modes per establishment:

ModeWhat it doesStatus
filePublished file format where one exists (Mudad: WPS wages file per the HRSD specification), otherwise a status log with reminders; the action itself is done on the agency portal and recorded hereLive
apiDirect integration through the agency/partner channel contracted in the establishment's nameRefuses to run (409 channel_not_ready) until the agency documentation is received and an adapter is written to it
sandboxDeterministic simulation for development and demosEvery reference starts with SANDBOX- and every result carries "simulated": true

Sources used (see GET /v1/agencies):

Authentication

HeaderUse
X-API-Key: ogg_…Server-to-server (MedCore, OCTAPOS, subscribed systems)
Authorization: Bearer <token>Dashboard sessions (/portal/login)

Internal OCTA apps get a key from POST /admin/apps (or manage.py create-app) and have no subscription limits. Every resource is scoped to the calling app: an id belonging to another app returns 404, never 403.

Rate limit: RATE_LIMIT_PER_MINUTE per app (default 600) → 429.

Conventions

StatusMeaning
400Invalid input
401Bad or revoked key / expired session
402Subscription inactive or quota reached (sandbox is always free)
403Not allowed (e.g. the creator trying to approve)
404Not found or belongs to another app
409State conflict, hash mismatch, or code: "channel_not_ready"
429Rate limited
502Agency channel error

Establishments

POST /v1/tenants — create or update.

{"external_ref": "hospital-12", "name": "…", "cr_number": "1010…", "approvals_required": 1}

approvals_required is 1–3 approvers (none of whom may be the creator).

{"alert_days": {"iqama_expiry": [90,60,30,14,7,0], "exit_reentry": [7,3,0], "final_exit": [7,0],
                "qiwa_contract": [60,30,7], "wps_month": [10,5,1,0]},
 "wps": {"salary_due_day": 27}}

salary_due_day null = last day of the month (a configurable default, not a regulation).

POST /v1/tenants/{tid}/approvers — {"ref": "user:57", "name": "HR Manager", "max_amount": "500000.00" | null, "member_id": null, "active": true}. max_amount applies to WPS runs. GET lists them.

Channels

POST /v1/tenants/{tid}/channels — one channel per agency per establishment (re-posting changes mode/config; changing mode drops stored secrets).

{"agency": "qiwa" | "muqeem" | "mudad", "mode": "file" | "api" | "sandbox", "config": {…}}

Mudad in file mode needs the establishment's own data — there are no defaults:

config keyWPS fieldRule
sarie_bank_id[DEST-ID]4 uppercase letters — from the establishment's bank (SARIE table)
estb_id[ESTB-ID]up to 10 digits
mol_estb_id[MOL-ESTBID]2–15 digits
establishment_iban[BANK-ACC]Saudi IBAN (24)
layout.bank_only_fields—empty (all 14 columns, bank columns blank) or establishment_only — confirm with the bank (the spec is ambiguous)
layout.line_ending—CRLF or LF — confirm with the bank
layout.language—ar or en (one language per file)

Employees

POST /v1/tenants/{tid}/employees — one object, or {"employees": [ … up to 2000 ]}. The whole request is validated before anything is written.

{"external_ref": "emp-301", "name_ar": "…", "name_en": "…", "id_number": "2xxxxxxxxx",
 "iban": "SA…", "iqama_expiry": "2027-03-01", "nationality": "EGY", "occupation": "…",
 "hire_date": "2024-01-01", "status": "active" | "terminated"}

id_number: 10 digits, starting with 1 (national ID → Saudi) or 2 (iqama). Unique per establishment. Creating an employee derives obligations: qiwa_contract for everyone and iqama_expiry for iqama holders with an expiry date.

Obligations

Kinds and statuses are the gateway's own tracking model — not agency field values.

kindagencystatusesdue_date
qiwa_contractqiwanot_started, submitted, awaiting_employee, documented, rejected, endedcontract end
iqama_expirymuqeemvalid, renewal_requested, renewed, expirediqama expiry
exit_reentrymuqeemissued, departed, extended, returned, cancelled, expired_not_returnedreturn-by
final_exitmuqeemissued, departed, cancelledleave-by
wps_monthmudadpending, file_ready, sent_to_bank, bank_processed, uploaded, compliant, non_compliantupload deadline = salary due date + 30 days
{"status": "documented", "actor": "user:12", "note": "…", "evidence_ref": "…",
 "new_expiry": "2027-11-01",      // iqama_expiry → renewed
 "new_due_date": "2026-12-20"}    // exit_reentry → extended

Date-driven changes run in the sweeper: an iqama past its date becomes expired; an exit/re-entry still departed/extended after its return-by date becomes expired_not_returned.

Alerts

Raised once per (obligation, due date, threshold). Levels: info (>30 days), warning (≤30), critical (≤3 or overdue). A Saudi employee whose contract is not documented raises nitaqat_not_counted:*.

Operations (maker-checker)

An operation is a request to an agency. Lifecycle:

pending_approval ──approve×N──► approved ──execute──► executing ──► executed | failed
       └──return──► returned        pending_approval/approved ──cancel──► cancelled

The payload is encrypted and hashed at creation; approvers approve the hash they saw, and execution sends the same payload. An api channel that is not ready refuses at creation with 409 channel_not_ready.

POST /v1/tenants/{tid}/operations

{"external_ref": "erv-2026-0091", "op": "exit_reentry.issue", "created_by": "user:12",
 "payload": {"employee_id": "…", "return_by": "2026-12-20"}}
oppayload
contract.submitemployee_id, start_date, end_date?
iqama.renewemployee_id, months (1–60, default 12)
exit_reentry.issueemployee_id, return_by
exit_reentry.extendvisa_ref, return_by
exit_reentry.cancelvisa_ref
final_exit.issueemployee_id, leave_by?
final_exit.cancelvisa_ref

POST /v1/tenants/{tid}/wps/runs — builds the WPS wages file per the HRSD specification and creates a wps.submit operation.

{"external_ref": "wps-2026-11", "created_by": "user:12", "period": "2026-11",
 "file_ref": "WPS202611A", "value_date": "2026-11-27", "debit_date": null,
 "lines": [{"employee_ref": "emp-301", "basic": "6000.00", "housing": "1500.00",
            "other_earnings": "0.00", "deductions": "0.00", "description": "…"}]}

Rules enforced: net = basic + housing + other − deductions (> 0); header total = sum of lines; file_ref ≤16 alphanumerics and unique per establishment; value date not before today; debit date between today and value date; ID starts with 1 or 2; no duplicate employee; names in the file's single language; comma decimal separator in the file. The bank signs the processed file — the gateway does not.

Audit

Webhooks

POST /v1/webhook — {"url": "https://…"} returns the signing secret once.

Events: obligation.updated, alert.raised, operation.updated. Headers: X-Octa-Event, X-Octa-Delivery, X-Octa-Timestamp (ms), X-Octa-Signature = hex HMAC-SHA256 of {timestamp}.{raw body}. Reject if the timestamp is older than 5 minutes. Retries: 1 min, 5 min, 15 min, 1 h, 6 h. Payloads never contain ID numbers or IBANs.

{"event": "alert.raised", "tenant_id": "…", "tenant_ref": "hospital-12",
 "alert": {"code": "iqama_expiry:2026-12-09:d30", "level": "warning", "message_ar": "…", "due_date": "2026-12-09"}}

Agencies

GET /v1/agencies — public profiles: modes, published facts with source links, and pending_fields (everything still awaiting the agency's own documentation). api_ready is false for all agencies in this version.

Subscriptions

Billing unit: one establishment with at least one non-sandbox channel. Prices come from the owner's pricing.json (GET /portal/plans); without it plans show "contact us". Provisioning after payment on the OCTA site uses POST /provision and POST /billing/webhook (HMAC on {timestamp}.{body}, 5-minute window) — the same contract as the ZATCA gateway.

Python client

clients/octa_gov_client.py — depends only on requests; rejects floats before sending; GovGatewayError.code == "channel_not_ready" for channels awaiting documentation; verify_webhook(secret, headers, raw_body).