# KRA eTIMS Integration for Kenyan E-commerce: Technical Architecture, API Workflows, and Compliance
Summary: A KRA eTIMS integration enables Kenyan e-commerce platforms to transmit electronic sales receipts directly to the Kenya Revenue Authority. Under Section 23A of the Tax Procedures Act and Section 16(2) of the Income Tax Act, electronic invoicing is required for valid business expense deductions. Stores deploy compliance via Online Sales Control Unit (OSCU) APIs or Virtual Sales Control Unit (VSCU) middleware, using asynchronous message queues to process M-Pesa Daraja payments without delaying checkout.
---
Kenyan digital commerce has transitioned from retrospective tax reporting to real-time fiscal telemetry. For online retailers operating across Nairobi, Mombasa, Kisumu, and regional distribution corridors, transmitting sales records to the Kenya Revenue Authority (KRA) is now an architectural requirement embedded directly into checkout carts, payment webhooks, and fulfillment systems. A reliable eTIMS integration balances strict statutory tax compliance with e-commerce conversion rates: fiscal API downtimes must never block shoppers from completing orders, yet generating non-fiscalized receipts exposes businesses to regulatory penalties and causes corporate B2B customers to abandon the platform.
---
The Statutory Mandate: Sections 23A and 16(2)
The legal foundation for electronic tax invoicing in Kenya is established by Section 23A of the Tax Procedures Act (TPA) 2015. Under this statute, every entity conducting business in Kenya must issue electronic tax invoices and maintain transactional records through an electronic tax invoice management system (eTIMS) approved by the Commissioner.
The commercial impact on digital retailers stems from Section 16(2)(a)(v) of the Income Tax Act (Cap. 470):
Any expenditure incurred by a taxpayer is disallowed for income tax deduction purposes unless supported by a valid electronic tax invoice generated via an eTIMS-compliant system.
This provision makes fiscal compliance a commercial necessity for any store catering to corporate buyers. When an enterprise client purchases office electronics, wholesale supplies, or software licenses from an online store that issues a conventional PDF receipt devoid of an official KRA Control Unit (CU) number and cryptographic QR verification URL, the purchasing company cannot deduct that expenditure on its corporate income tax return. Consequently, corporate procurement teams systematically filter out vendors unable to issue verified eTIMS receipts.
Under Section 86 of the Tax Procedures Act, failure to issue electronic tax invoices or operate an approved electronic tax system attracts statutory administrative penalties based on the underlying tax due, alongside potential default interest on unpaid liabilities. To enforce compliance, KRA automated systems match the buyer PINs declared in corporate tax returns against real-time invoice telemetry ingested through the KRA eTIMS API, rapidly surfacing discrepancies and unverified suppliers.
---
Architecture Topologies: OSCU vs. VSCU
Engineering teams connecting a Trader Invoicing System (TIS), custom web platform, or ERP to KRA select between two primary deployment topologies: the Online Sales Control Unit (OSCU) and the Virtual Sales Control Unit (VSCU).
Online Sales Control Unit (OSCU)
OSCU is a direct server-to-server cloud integration. The e-commerce backend constructs JSON transaction payloads and submits them directly to KRA's public API gateway (https://etims-api.kra.go.ke) over HTTPS.
- Advantages: Eliminates local daemon infrastructure. Highly compatible with modern serverless architectures (such as AWS Lambda, Google Cloud Run) and managed container clusters.
- Limitations: Directly exposed to public wide-area network (WAN) conditions. During monthly tax filing surges, KRA public gateway latency can spike significantly, making synchronous integration in the consumer checkout flow a severe conversion hazard.
Virtual Sales Control Unit (VSCU)
VSCU relies on a software daemon provided by KRA (a Java runtime service) deployed in the merchant's private VPC or hosting environment, typically binding to http://localhost:8088.
- Advantages: The daemon manages cryptographic signing keys locally within the merchant's secure boundary. The application submits payloads to the local daemon endpoint over loopback, receiving the fiscal signature and Control Unit invoice number with near-instantaneous local inter-process communication (IPC) before the daemon synchronizes records with KRA cloud infrastructure asynchronously.
- Limitations: Requires managing persistent container or virtual machine infrastructure, allocating system resources, and establishing proactive health monitoring for the local Java process.
Architectural Comparison Matrix
| Metric | Online Sales Control Unit (OSCU) | Virtual Sales Control Unit (VSCU) |
|---|---|---|
| Communication Layer | HTTPS REST direct to KRA Gateway (etims-api.kra.go.ke) | Local REST to Internal Daemon (localhost:8088) |
| Signing & Latency | Public WAN round-trip dependent | Near-instantaneous local cryptographic signing |
| Offline Resilience | Application-level queuing required (e.g., Redis, SQS) | Native offline buffering inside local VSCU daemon |
| Infrastructure Footprint | Stateless (Runs in existing API or serverless functions) | Dedicated container or VM (1–2 vCPU, 2GB RAM Linux runtime) |
| Cryptographic Storage | KRA communication key (cmcKey) in secrets manager | Local certificate store managed by Java daemon |
| Recommended Fit | Lean e-commerce platforms, serverless, moderate order flow | High-volume flash sales, ERP systems, wholesale distribution |
---
Event-Driven Checkout Pipelines with M-Pesa Daraja
According to the Central Bank of Kenya (CBK) National Payments System data and Communications Authority of Kenya (CAK) reports, mobile money is the dominant payment instrument in Kenya's digital economy, with Safaricom M-Pesa serving as the primary consumer settlement channel. E-commerce platforms accept these transactions either directly through Safaricom's Daraja 2.0 API (Lipa na M-Pesa Online / STK Push) or via payment aggregators such as Pesapal, DPO Pay, and Flutterwave.
The Latency Trap of Synchronous Invoicing
Attempting to invoke the eTIMS API synchronously inside the payment callback handler creates dangerous single points of failure:
1. Safaricom Daraja API developer guidelines stipulate that payment notification webhooks should receive an immediate HTTP 200 OK acknowledgment. If callback handling exceeds gateway timeout limits, the payment engine marks the notification as failed and triggers automated retry cycles, which can cause duplicate balance debits or inventory allocation errors.
2. If the KRA public gateway experiences latency or transient connectivity drops, the webhook process blocks. The customer remains stuck on an unconfirmed checkout screen, increasing cart abandonment.
3. Tight coupling between tax submission and order placement means any KRA downtime immediately halts store sales.
Resilient Asynchronous Queue Architecture
Production storefronts decouple payment processing from invoice fiscalization using an asynchronous event-driven worker queue.
sequenceDiagram
autonumber
actor Customer
participant Storefront as Web / Mobile App
participant Daraja as Safaricom M-Pesa
participant Webhook as Webhook Handler
participant Queue as Redis Queue
participant Worker as Fiscal Worker
participant eTIMS as KRA eTIMS Gateway
participant DB as Orders DB
Customer->>Storefront: Select M-Pesa & Place Order
Storefront->>Daraja: Trigger STK Push (Daraja 2.0)
Daraja->>Customer: Prompt for Mobile Money PIN
Customer->>Daraja: Authenticate Transaction
Daraja->>Webhook: Post Payment Callback (ResultCode: 0)
Webhook->>DB: Mark Order Status = PAID
Webhook->>Queue: Push FiscalizationJob(OrderId)
Webhook-->>Daraja: Return HTTP 200 OK (< 200ms)
Storefront->>Customer: Confirm Payment & Order Success
Queue->>Worker: Consume FiscalizationJob
Worker->>eTIMS: POST /saveSales (Payload with M-Pesa Ref)
eTIMS-->>Worker: Return CU Inv Number, Signature, QR Link
Worker->>DB: Store CU Number & QR Code
Worker->>Customer: Send Email/SMS Receipt with QR CodeWhen architecting production checkout backends, engineering teams often collaborate with experienced specialists in app development in Kenya to implement fault-tolerant message queuing, idempotency controls, and reliable fiscalization microservices.
Production Queue Worker Implementation
Below is a Node.js/TypeScript example illustrating an asynchronous BullMQ worker that processes settled orders, constructs eTIMS payloads, and handles retries with exponential backoff:
import { Worker, Job } from 'bullmq';
import axios from 'axios';
import { db } from './lib/db';
import { generateFiscalPayload } from './lib/etimsFormatter';
interface FiscalizationData {
orderId: string;
mpesaReceiptNumber: string;
}
export const fiscalWorker = new Worker<FiscalizationData>(
'etims-fiscalization',
async (job: Job<FiscalizationData>) => {
const { orderId, mpesaReceiptNumber } = job.data;
const order = await db.order.findUnique({
where: { id: orderId },
include: { items: true, customer: true }
});
if (!order || order.fiscalStatus === 'COMPLETED') {
return { status: 'skipped', reason: 'already_fiscalized_or_missing' };
}
const payload = generateFiscalPayload(order, mpesaReceiptNumber);
const response = await axios.post(
process.env.ETIMS_GATEWAY_URL + '/saveSales',
payload,
{
headers: {
'Content-Type': 'application/json',
tin: process.env.KRA_PIN!,
bhfId: process.env.KRA_BRANCH_ID!,
cmcKey: process.env.KRA_CMC_KEY!
},
timeout: 10000
}
);
if (response.data.resultCd === '000') {
await db.order.update({
where: { id: orderId },
data: {
fiscalStatus: 'COMPLETED',
cuInvoiceNumber: response.data.data.curInvcNo,
fiscalSignature: response.data.data.rcptSign,
qrCodeUrl: response.data.data.qrCodeUrl
}
});
return { status: 'success', cuInvoiceNo: response.data.data.curInvcNo };
}
throw new Error(`eTIMS submission failed: ${response.data.resultMsg}`);
},
{
connection: { host: process.env.REDIS_HOST, port: 6379 },
concurrency: 5,
limiter: { max: 10, duration: 1000 } // Respect KRA rate limits
}
);---
Step-by-Step KRA eTIMS API Integration Workflow
A complete integration with the KRA eTIMS API requires executing four primary REST operations in sequence.
Step 1: Device Initialization (`/selectInitOsdcInfo`)
Before submitting transactions, the Trader Invoicing System binds its assigned device serial number (dvcSrlNo) to the merchant's Taxpayer Identification Number (tin) and branch identifier (bhfId) to acquire an encrypted communication key (cmcKey).
- Endpoint:
POST /selectInitOsdcInfo
{
"tin": "P051234567Z",
"bhfId": "00",
"dvcSrlNo": "WH-VSCU-NRB-01"
}Store the returned cmcKey in a hardware security module (HSM) or secrets manager. All subsequent HTTP calls pass the authorization context in request headers:
Content-Type: application/json
tin: P051234567Z
bhfId: 00
cmcKey: a9c2e4f7108b3d6...encrypted_keyStep 2: Item Master Data Sync (`/saveItem`)
Every catalog product must be synchronized with KRA classification codes before it can appear on an electronic sales invoice. Products map to standard United Nations Standard Products and Services Code (UNSPSC) values (itemClsCd) and corresponding tax rate categories (taxTyCd).
- Endpoint:
POST /saveItem
{
"tin": "P051234567Z",
"bhfId": "00",
"itemCd": "SKU-KEY-01",
"itemClsCd": "43211507",
"itemNm": "Wireless Mechanical Keyboard",
"itemTyCd": "1",
"qtyUnitCd": "U",
"taxTyCd": "A",
"dftPrc": 8500.00,
"useYn": "Y"
}Tax Rate Codes: A = Standard 16% VAT, B = Zero-Rated (0%), C = Exempt, D = Special / Non-VAT rate.
Step 3: Fiscal Sales Invoice Transmission (`/saveSales`)
Once payment confirmation is received by the webhook, the queue worker compiles the order into a finalized fiscal sales document.
- Endpoint:
POST /saveSales
{
"tin": "P051234567Z",
"bhfId": "00",
"invoicerTin": "P051234567Z",
"custTin": "P059876543A",
"custNm": "Nairobi Tech Ventures Ltd",
"salesTyCd": "N",
"rcptTyCd": "S",
"pmtTyCd": "03",
"salesSttsCd": "02",
"cfmDt": "20261105153000",
"salesDt": "20261105",
"totItemCnt": 1,
"totTaxblAmt": 7327.59,
"totTaxAmt": 1172.41,
"totAmt": 8500.00,
"remark": "M-Pesa Ref: QK88AB99CD",
"itemList": [
{
"itemSeq": 1,
"itemCd": "SKU-KEY-01",
"itemClsCd": "43211507",
"itemNm": "Wireless Mechanical Keyboard",
"qty": 1.00,
"unitPrc": 8500.00,
"splyAmt": 7327.59,
"taxTyCd": "A",
"taxAmt": 1172.41,
"totAmt": 8500.00
}
]
}Field Specifications: rcptTyCd: "S" represents an original Sale, whereas "C" indicates a Credit Note; pmtTyCd: "03" denotes Mobile Money (M-Pesa); custTin: mandatory for B2B tax receipts, omitted for standard retail consumers.
Step 4: Cryptographic Verification and QR Code Generation
Upon successful validation, KRA responds with cryptographic receipt tokens:
{
"resultCd": "000",
"resultMsg": "SUCCESS",
"data": {
"rcptNo": 451,
"curInvcNo": "KRA002000000000451",
"intrlData": "8B4F1A9D3E6C2B5F",
"rcptSign": "MEQCIF...signature_hash...==",
"qrCodeUrl": "https://etims.kra.go.ke/common/link/etims/receipt/index.html?data=..."
}
}The e-commerce platform stores the returned Control Unit (CU) Invoice Number and embeds the dynamic KRA QR Code URL onto the customer's downloadable PDF receipt and order confirmation email.
---
Edge Cases: Returns, Credit Notes, and Split Orders
E-commerce operations frequently involve post-purchase adjustments. Under KRA regulations, invoices submitted to eTIMS are immutable ledger entries and cannot be edited or deleted.
1. Credit Notes: When an order is cancelled or items are returned, post a payload to /saveSales with rcptTyCd: "C", referencing the original fiscal invoice through origInvcNo and origInvcDt. This offsets the merchant's gross VAT balance on iTax.
2. M-Pesa Reversals: If an M-Pesa transaction is reversed or refunded through Safaricom after dispatch, the store's reconciliation pipeline must detect the event and trigger an automated eTIMS credit note to maintain financial ledger accuracy.
3. Split Warehouses: When orders ship from different regional fulfillment hubs on separate dates, best practice is to issue distinct fiscal invoices upon physical dispatch of each consignment rather than an aggregated invoice prior to fulfillment.
---
Data Protection Compliance (ODPC & Kenya DPA 2019)
Collecting customer tax identifiers, phone numbers, and delivery addresses places digital merchants under the regulatory purview of the Office of the Data Protection Commissioner (ODPC) pursuant to the Kenya Data Protection Act 2019.
- Data Minimization: Avoid requiring KRA PIN collection for individual consumers during retail checkout. KRA regulations do not require individual personal tax identifiers for standard retail transactions below commercial reporting thresholds. Capture corporate PINs strictly when B2B buyers explicitly request a business tax invoice.
- Cryptographic Security: Transmit all API payloads over TLS 1.3 and encrypt communication keys (
cmcKey) using strong symmetric encryption such as AES-256 in secrets storage. - Record Retention: Section 23 of the Tax Procedures Act mandates that transactional and accounting records be preserved for at least five years. Maintain encrypted audit logs to satisfy statutory tax inspections and ODPC data governance requirements.
---
Implementation Budget and Architectural Trade-Offs
Deploying an eTIMS integration requires balancing custom software engineering against third-party middleware connectors.
Evaluation Matrix
| Approach | Engineering Complexity | Infrastructure Footprint | Architectural Control | Maintenance Profile |
|---|---|---|---|---|
| Custom OSCU Integration | Moderate (REST client & queue worker) | Serverless functions or existing app servers | Full codebase ownership and schema control | Update API client upon KRA endpoint contract revisions |
| Custom VSCU Integration | High (Daemon deployment & IPC) | Dedicated internal container or VPC host | Complete local signing control and offline capability | Monitor Java runtime daemon uptime, disk logs, and updates |
| Pre-built Connectors & Middleware | Low (Plugin setup & API credentials) | Vendor-managed cloud infrastructure | Dependent on provider features and roadmap | Monitor third-party plugin releases and platform compatibility |
Payment Gateways and Integration Strategies
- Payment Gateways (Pesapal, DPO Pay, Flutterwave): These services handle customer checkout settlement across M-Pesa, debit/credit cards, and mobile wallets, delivering payment transaction receipts and webhook callbacks to your store. Because payment gateways do not automatically submit eTIMS sales invoices to KRA out-of-the-box, e-commerce engineering teams must capture the gateway transaction reference and pass it to an eTIMS fiscalization queue worker or dedicated connector.
- Direct KRA VSCU Deployment: Well-suited for high-volume custom architectures built on Laravel, Node.js, Python, or Go, as well as enterprise ERPs managing thousands of monthly order lines where offline resilience and local cryptographic execution are primary priorities.
- Direct OSCU Microservice: Recommended for modular, cloud-native storefronts seeking stateless deployments without the burden of containerized daemon management.
---
Frequently Asked Questions
Can Kenyan e-commerce businesses issue ordinary PDF invoices without eTIMS validation?
Under Section 23A of the Tax Procedures Act and Section 16(2) of the Income Tax Act, business invoices must carry verifiable eTIMS data. Unvalidated receipts cannot be deducted as allowable expenses by commercial buyers, and non-compliant merchants face statutory penalties and administrative sanctions under Section 86 of the Tax Procedures Act.
How does an integration handle KRA API gateway downtime during peak sales?
With an Online Sales Control Unit (OSCU), systems buffer outgoing invoices in an asynchronous message queue (such as Redis BullMQ or AWS SQS) and retry submissions using exponential backoff and dead-letter queues. With a Virtual Sales Control Unit (VSCU), the local daemon cryptographically signs the invoice locally within milliseconds and automatically syncs records to KRA once cloud connectivity is restored.
Are small businesses operating via social media exempt from eTIMS?
All registered business entities operating in Kenya must comply with electronic tax invoicing requirements. The Kenya Revenue Authority provides simplified solutions such as eTIMS Lite via the eCitizen portal and USSD code *222# for micro-enterprises and informal traders. However, dedicated e-commerce web storefronts require automated API integration to process orders at scale.
How are shipping fees and promotional discounts handled in eTIMS?
Shipping charges are registered as individual service line items mapped to the appropriate UNSPSC service code and standard 16% VAT classification. Cart-level discounts are calculated proportionally across applicable line items before generating net taxable values. Gift vouchers and promotional credits are treated as cash equivalents, with tax calculated only when the voucher is redeemed for taxable goods.
---
Sources
- Kenya Revenue Authority (KRA) - eTIMS Portal & Technical Specifications
- Kenya Law - Tax Procedures Act, No. 29 of 2015
- Kenya Law - Income Tax Act (Cap. 470)
- Safaricom Daraja API Developer Portal
- Office of the Data Protection Commissioner (ODPC) - Data Protection Act 2019
- Central Bank of Kenya - National Payments System Overview