Skip to main content
Malaysia (Based in KL) +60 1135153545 info@sysencore.com
Enterprise AI & IT Engineering WhatsApp Chat
Document Identifier: TA-ASSET-02

Classification: Technical Authority Researched Draft

Version: 1.0 (Draft)

Publication Status: Published as an architecture explanation. Internal source notes are not on this website.

Author: SysEncore Engineering Practice

2. Executive Summary

Integrating Malaysia's Inland Revenue Board (LHDN / IRBM) MyInvois system into an e-commerce platform involves a fundamental architectural shift. E-invoicing is not simply an additional field in a checkout form or an extra API call appended to an existing payment script. It introduces a statutory reporting workflow with regulatory validation, digital-signature, and API requirements that need to be accounted for in the system design.

The most critical architectural failure observed in early e-commerce integrations is tight coupling: attempting to generate, sign, and submit an e-invoice to LHDN synchronously within the customer's HTTP checkout request. This naive pattern introduces external network latency, exposes the store’s conversion funnel to upstream government gateway downtime, and risks leaving payment and tax records in conflicting, unrecoverable states.

This technical blueprint outlines a recommended decoupled, event-driven architecture for Malaysian e-commerce operations. By separating the Payment State from the E-Invoice State, enforcing database-level idempotency, and routing invoice payloads through an asynchronous worker queue, engineering teams can build a more resilient integration while keeping the e-invoicing workflow aligned with applicable LHDN requirements.

3. Who This Guide Is For

This architecture guide is designed for:

  • Technical Founders & CTOs: Designing scalable systems for Malaysian mid-market e-commerce, retail, and multichannel brand operations.
  • Senior Backend Engineers & Solutions Architects: Implementing custom PHP, Node.js, Laravel, or Python billing backends that interface with payment gateways and the MyInvois API.
  • E-Commerce Technical Leads: Managing high-volume WooCommerce, Magento, Shopify, or custom headless checkouts who need to navigate LHDN compliance deadlines.
  • IT & Finance Directors: Auditing operational risk, reconciliation integrity, and tax reporting workflows across digital sales channels.
Reading Note: This document separates statutory requirements from architectural recommendations. A separate source register is not published on this website, so a regulatory detail here should be checked against current LHDN guidance before implementation.

4. The E-Commerce Transaction Lifecycle

To understand where statutory e-invoicing belongs, we must first examine the standard lifecycle of an online purchase in Malaysia:

Architecture Flow Specification (Mermaid)Diagram Source
sequenceDiagram
    autonumber
    actor Customer
    participant Store as E-Commerce Storefront
    participant DB as Internal Order DB
    participant Gateway as Payment Gateway / Acquirer
    participant Bank as Bank Rail (FPX / Card / DuitNow)

    Customer->>Store: Submit Checkout Order
    Store->>DB: Create Order (Status: Pending Payment)
    Store->>Gateway: Initialize Payment Request
    Gateway-->>Customer: Redirect to Bank / Payment Modal
    Customer->>Bank: Authorize & Complete Payment
    Bank-->>Gateway: Settlement Confirmation
    Gateway->>Store: Asynchronous Webhook (Status: Paid)
    Store->>DB: Transition Order (Status: Processing / Paid)
    Store-->>Customer: Render Order Confirmation Page

In a production environment:

  1. The Order is Created: The customer establishes intent. The system creates an order record in state Pending Payment.
  1. Payment is Authorized: The customer interacts with the payment gateway or local banking rail (FPX, credit/debit card, or DuitNow QR via an acquirer).
  1. Payment is Confirmed Asynchronously: Webhooks notify the store of payment success. The order transitions to Processing or Paid.
  1. Order Confirmation is Immediate: The customer receives immediate visual confirmation and an order receipt on-screen.

Where Naive Integrations Fail

In naive implementations, developers attempt to invoke the LHDN MyInvois API inside the synchronous payment callback or checkout response. If the statutory API experiences network jitter, rate limiting, or temporary maintenance, the customer's browser hangs, the payment webhook times out, and the checkout flow crashes—even though the customer's bank account was successfully debited.

5. Where MyInvois Fits

LHDN MyInvois is a statutory validation and audit registry, not a transactional gateway. Its purpose is to validate tax compliance, assign a unique Universal Unique Identifier (UUID), and record e-Invoice information as part of Malaysia's statutory e-Invoicing process.

Architecture Matrix / State TaxonomyASCII Blueprint
┌────────────────────────────────────────────────────────────────────────┐
│                   SEPARATION OF CONCERNS MATRIX                        │
├───────────────────────────────┬────────────────────────────────────────┤
│ Transactional E-Commerce Layer│ Statutory Compliance Layer             │
│ (Storefront, Gateway, Cart)   │ (LHDN MyInvois Portal & REST API)      │
├───────────────────────────────┼────────────────────────────────────────┤
│ • Millisecond responsiveness  │ • Batch & queued submission            │
│ • Maximum checkout conversion │ • Cryptographic XAdES signature check  │
│ • Ephemeral session state     │ • Strict UBL 2.1 schema validation     │
│ • Commercial order receipt    │ • Validated legal tax invoice (UUID)   │
│ • Immediate buyer satisfaction│ • 72-hour cancellation window          │
└───────────────────────────────┴────────────────────────────────────────┘

Core Principle: The main design concern is keeping payment processing independent from e-Invoice submission. The statutory compliance workflow should run downstream of verified payment capture and database persistence, managed asynchronously via background queues.

The recommended SysEncore architecture employs an event-driven, decoupled pipeline. An internal transaction record is committed first, emitting an event that triggers asynchronous invoice compilation, cryptographic signing, submission, and status polling.

System Architecture Diagram

Architecture Flow Specification (Mermaid)Diagram Source
graph TD
    subgraph Client [Customer Domain]
        A[Customer Browser / App]
    end

    subgraph Storefront [E-Commerce Platform]
        B[Storefront Controller]
        C[(Order & Transaction DB)]
        D[Payment Webhook Handler]
    end

    subgraph Payments [Payment Infrastructure]
        E[Payment Gateway / Acquirer<br>Curlec / Billplz / Stripe MY]
    end

    subgraph AsyncQueue [Decoupled Processing Queue]
        F[Message Broker / Queue<br>Redis / BullMQ / DB Queue]
        G[E-Invoice Worker Service]
        H[X.509 Cryptographic Signer<br>Enveloped XAdES]
    end

    subgraph Statutory [MyInvois Integration Boundary]
        I[LHDN MyInvois API v1.0]
        J[Asynchronous Validation Engine]
    end

    subgraph Reconciliation [Reconciliation & ERP]
        K[Status Polling Reconciler]
        L[Finance / ERP System]
    end

    A -->|1. Submit Order| B
    B -->|2. Create Pending Order| C
    B -->|3. Redirect Payment| E
    E -->|4. Async Payment Webhook| D
    D -->|5. Update Order: PAID| C
    D -->|6. Enqueue E-Invoice Job| F
    F -->|7. Consume Job| G
    G -->|8. Fetch Order Data| C
    G -->|9. Sign Payload| H
    G -->|10. Submit Batch/Doc| I
    I -->|11. Return Submission UID| G
    G -->|12. Update Invoice: SUBMITTED| C
    I -->|13. Async Validation| J
    K -->|14. Poll Status 300 RPM max| J
    K -->|15. Update Status: VALID / INVALID| C
    C -->|16. Sync Validated Invoice| L

End-to-End Architectural Data Flow

  1. Checkout & Order Creation: The customer places an order. The order is stored in the database with status pending_payment.
  1. Payment Authorization: The customer pays via a payment gateway/acquirer.
  1. Webhook Verification: The gateway sends an HTTP POST webhook with cryptographic signature validation (e.g. HMAC-SHA256).
  1. State Transition: The order transitions to paid inside a database transaction enforcing row-level locking.
  1. Event Emission: An OrderPaid event is dispatched, placing an e-invoice generation payload onto a durable worker queue (e.g. Redis, RabbitMQ, or database-backed queue).
  1. Payload Compilation: The background worker extracts order data and maps it into the OASIS UBL 2.1 XML or structured JSON format.
  1. Digital Signature Application: The payload is signed with an enveloped XAdES signature using the merchant's X.509 digital certificate.
  1. Batch or Individual Submission: The worker dispatches the document via POST /api/v1.0/documentsubmissions/.
  1. Submission UID Ingestion: The submission response provides a submissionUID, which the integration can use to track the subsequent validation process.
  1. Asynchronous Status Reconciliation: A scheduled reconciliation worker checks the submission status at a controlled interval, following the current MyInvois API guidance and the integration's rate-limit budget.
  1. Final Persistence: The validated invoice UUID and LHDN validation timestamp are stored in the order database and synchronized with back-office ERP systems.

7. Payment State vs E-Invoice State

A common design issue in billing systems is treating payment capture and tax validation as a single composite state. In reality, they represent independent lifecycle domains:

Architecture Matrix / State TaxonomyASCII Blueprint
┌────────────────────────────────────────────────────────────────────────┐
│                   SEPARATE STATE LIFECYCLE DOMAINS                     │
├───────────────────────────────┬────────────────────────────────────────┤
│ Payment State Machine         │ E-Invoice State Machine                │
├───────────────────────────────┼────────────────────────────────────────┤
│ • UNPAID                      │ • NOT_QUEUED                           │
│ • AUTHORIZATION_PENDING       │ • QUEUED_FOR_SUBMISSION                │
│ • CAPTURED / PAID             │ • SUBMITTED (Awaiting LHDN Validation) │
│ • FAILED                      │ • VALID (Assigned LHDN UUID)           │
│ • REFUNDED                    │ • INVALID (Rejected with Error Code)   │
│ • PARTIALLY_REFUNDED          │ • CANCELLED (Within 72h Window)        │
│ • CHARGEBACK_DISPUTED         │ • REJECTED (Buyer Action Within 72h)   │
│                               │ • CONSOLIDATED_BATCH_QUEUED (Monthly)  │
└───────────────────────────────┴────────────────────────────────────────┘

Relational Schema Blueprint (Separate State Tracking)

To prevent data ambiguity, internal relational schemas must maintain explicit, separate columns for order payment status and statutory e-invoice status:

The following schema is illustrative rather than a prescribed production schema. The exact model will depend on the existing order, payment, customer, and ERP domains.

Relational Schema (MySQL / MariaDB)SQL DDL
CREATE TABLE orders (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    order_number VARCHAR(64) NOT NULL UNIQUE,
    customer_id BIGINT UNSIGNED NOT NULL,
    total_amount DECIMAL(12, 2) NOT NULL,
    tax_amount DECIMAL(12, 2) NOT NULL,
    currency CHAR(3) NOT NULL DEFAULT 'MYR',
    
    -- Transactional Payment State
    payment_status ENUM('pending', 'paid', 'failed', 'refunded') NOT NULL DEFAULT 'pending',
    payment_method VARCHAR(32) NOT NULL,
    payment_gateway_ref VARCHAR(128) NULL,
    paid_at TIMESTAMP NULL,
    
    -- Statutory E-Invoice State
    einvoice_status ENUM(
        'not_applicable',
        'pending_queue',
        'submitted',
        'valid',
        'invalid',
        'cancelled',
        'rejected',
        'consolidated'
    ) NOT NULL DEFAULT 'pending_queue',
    
    einvoice_type ENUM('individual', 'consolidated') NOT NULL DEFAULT 'individual',
    lhdn_submission_uid VARCHAR(64) NULL,
    lhdn_invoice_uuid VARCHAR(64) NULL UNIQUE,
    lhdn_validated_at TIMESTAMP NULL,
    lhdn_error_code VARCHAR(32) NULL,
    lhdn_error_message TEXT NULL,
    
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    
    INDEX idx_orders_payment_status (payment_status),
    INDEX idx_orders_einvoice_status (einvoice_status),
    INDEX idx_orders_submission_uid (lhdn_submission_uid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

8. Asynchronous Processing Model

Why Synchronous Coupling Fails

Calling LHDN's API synchronously inside an e-commerce checkout or payment-processing path introduces several avoidable risks:

  1. Network WAN Latency: Remote API calls over public networks are subject to variable latency. If the statutory gateway takes several seconds to acknowledge a payload, the customer's browser experiences unresponsiveness, leading to high cart abandonment rates.
  1. Third-Party Outage Cascade: If LHDN undergoes scheduled maintenance or temporary gateway degradation, synchronous checkouts fail entirely, halting merchant sales.
  1. Gateway Webhook Timeouts: Payment gateway webhooks typically enforce strict timeout thresholds (often timing out after several seconds). If the webhook handler blocks while submitting to LHDN, the payment provider may flag the delivery as failed and trigger automatic retries, leading to duplicate processing risks.

The Queue-Worker Decoupling Pattern

By isolating e-invoice creation into a background queue:

  • Prompt Acknowledgment: The webhook handler should perform only the minimum work required to validate and persist the event, then acknowledge the payment provider promptly while downstream e-Invoice processing is handled asynchronously.
  • Resilient Retries: If LHDN’s API is momentarily unavailable, the queue worker automatically retries with exponential backoff without disrupting live retail operations.
  • Rate-Limit Throttling: The queue worker can be throttled locally to ensure total outbound submissions never exceed the published 100 Requests Per Minute (RPM) API limit.

9. Idempotency

In distributed e-commerce systems, duplicate delivery needs to be expected. Payment providers may retry webhook notifications when delivery is uncertain, and message queues can also redeliver jobs when processing fails. Without proper idempotency controls, the same order could be processed more than once and potentially submitted to LHDN twice.

1. Inbound Webhook Idempotency

Payment webhook handlers must record every incoming webhook event ID in a dedicated table before executing state changes:

Relational Schema (MySQL / MariaDB)SQL DDL
CREATE TABLE payment_webhook_events (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    event_id VARCHAR(128) NOT NULL UNIQUE,
    gateway VARCHAR(32) NOT NULL,
    payload_hash CHAR(64) NOT NULL,
    status ENUM('processing', 'processed', 'failed') NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

When a webhook arrives:

  • Check if event_id exists. If status is processed, immediately return HTTP 200 OK and terminate.
  • If it does not exist, insert with status processing inside a transaction.

2. Outbound LHDN Duplicate Detection

LHDN MyInvois enforces an immutable duplicate check based on:

$$\text{Issuer TIN} + \text{Document Type Code} + \text{Document Internal Code (Invoice Number)}$$

  • If an e-invoice with the same internal invoice number has already been validated or is currently processing for that TIN, the MyInvois API rejects the second submission with error code 400 Bad Request (DuplicateDocumentException).
  • Architectural Guardrail: The queue worker must verify whether a local lhdn_submission_uid or lhdn_invoice_uuid already exists for that order before making an external HTTP call.

10. Retry and Failure Handling

Not all submission failures are equal. Local throttling should keep outbound traffic within the applicable published API limits, but the worker service must also classify API response codes into transient errors (retryable) and permanent validation errors (non-retryable):

Architecture Matrix / State TaxonomyASCII Blueprint
┌────────────────────────────────────────────────────────────────────────┐
│                   FAILURE CLASSIFICATION & HANDLING                    │
├─────────┬───────────────────────────────┬──────────────────────────────┤
│ Code    │ Root Cause                    │ Architectural Action         │
├─────────┼───────────────────────────────┼──────────────────────────────┤
│ 400     │ Schema / Validation Error     │ Non-retryable. Route to Dead │
│         │ (e.g. invalid buyer TIN)      │ Letter Queue (DLQ). Alert.   │
├─────────┼───────────────────────────────┼──────────────────────────────┤
│ 401     │ Expired / Invalid Token       │ Flush cached token. Re-auth  │
│         │                               │ via /connect/token. Retry.   │
├─────────┼───────────────────────────────┼──────────────────────────────┤
│ 429     │ Rate Limit Exceeded           │ Parse Retry-After header.    │
│         │ (Local limit reached or 429)      │ Sleep worker. Exponential back│
├─────────┼───────────────────────────────┼──────────────────────────────┤
│ 500/502 │ LHDN Internal Server Error /  │ Transient. Retry with        │
│ 503/504 │ Bad Gateway / Gateway Timeout │ exponential backoff & jitter.│
└─────────┴───────────────────────────────┴──────────────────────────────┘

Implementing Retry-After and Exponential Backoff

When LHDN returns HTTP 429 Too Many Requests, the response contains a standard Retry-After header indicating the required wait duration in seconds. The following snippet illustrates a SysEncore architectural implementation pattern for handling HTTP status responses, rate limits, and exponential backoff in worker processes:

Worker Implementation (PHP 8+)Worker Handler
declare(strict_types=1);

function handleLhdnResponse(HttpResponse $response, JobQueue $queue, Job $job): void
{
    $statusCode = $response->getStatusCode();

    if ($statusCode === 429) {
        $retryAfter = (int) ($response->getHeader('Retry-After')[0] ?? 60);
        // Add random jitter (1-5s) to avoid thundering herd problem
        $delay = $retryAfter + random_int(1, 5);
        
        $queue->release($job, $delay);
        return;
    }

    if ($statusCode >= 500) {
        // Exponential backoff: 2^attempts * 10 seconds (max 3 retries)
        $attempts = $job->getAttempts();
        if ($attempts < 3) {
            $delay = (2 ** $attempts) * 10;
            $queue->release($job, $delay);
            return;
        }
        
        // Exceeded retries: route to DLQ
        $queue->fail($job, 'Max server retries exceeded.');
        return;
    }

    if ($statusCode >= 400 && $statusCode < 500) {
        // Permanent business logic / schema failure
        $queue->fail($job, 'Permanent validation error: ' . $response->getBody());
    }
}

11. Status Reconciliation

Because document submission is asynchronous, receiving an initial HTTP 200 acknowledging submission does not mean the invoice is legally valid. It merely confirms that the document was accepted for asynchronous validation.

1. The Polling Reconciler

A reconciliation worker can poll the MyInvois status API to track submissions through the validation lifecycle:

  • Endpoint: GET /api/v1.0/documentsubmissions/{submissionUid}
  • Rate Limit: Maximum 300 RPM per Client ID.
  • Recommended Cadence: The integration can poll the relevant submission-status endpoint at a controlled interval, following the current MyInvois API guidance and the integration's rate-limit budget.
  • Once validated, LHDN assigns the permanent 64-character alphanumeric UUID and updates status to Valid.

2. The 72-Hour Cancellation Window (Statutory Mandate)

Under Section 2.5 of the official LHDN e-Invoice Guideline:

  • Both the supplier and the buyer have a strict 72-hour window from the exact timestamp of validation (dateTimeValidated) to cancel or reject an invoice.
  • Supplier Cancellation: Performed via PUT /api/v1.0/documents/state/{UUID}/state with status "cancelled" and an explicit statutory reason.
  • Post 72-Hour Lockout: Once 72 hours have elapsed, the MyInvois API permanently locks the document state and rejects cancellation requests with error 400 Bad Request.

3. Post-72-Hour Order Returns and Adjustments

When an e-commerce customer initiates an order cancellation, refund, or return after the 72-hour statutory window has expired:

  • Credit Note (02): The merchant must not attempt to delete or cancel the original e-invoice. Instead, the merchant must generate and submit a formal Credit Note referencing the original invoice's LHDN UUID to reverse the tax liability.
  • Refund Note (04): Used if a cash refund is issued to the consumer without returning goods.

12. Consolidated E-Invoice Considerations

In retail consumer e-commerce (B2C), individual consumers frequently do not require a tax invoice for business expense claims. Malaysian statutory guidelines provide a specific mechanism to handle high-volume retail transactions: the Consolidated E-Invoice.

Architecture Matrix / State TaxonomyASCII Blueprint
┌────────────────────────────────────────────────────────────────────────┐
│                   CONSOLIDATED E-INVOICE STATUTORY RULES               │
├───────────────────────────────┬────────────────────────────────────────┤
│ Parameter                     │ Statutory Requirement (Tier 1 Verified)│
├───────────────────────────────┼────────────────────────────────────────┤
│ Target Scope                  │ Walk-in / retail consumers who do not  │
│                               │ request an individual e-invoice.       │
├───────────────────────────────┼────────────────────────────────────────┤
│ Statutory Submission Deadline │ Within seven (7) calendar days after   │
│                               │ the end of the transaction month.      │
├───────────────────────────────┼────────────────────────────────────────┤
│ Mandated Buyer TIN            │ EI00000000010 (General Public TIN)     │
├───────────────────────────────┼────────────────────────────────────────┤
│ Buyer ID Type & Number        │ NA (Not Applicable)                    │
├───────────────────────────────┼────────────────────────────────────────┤
│ Statutory Exclusions          │ Motor vehicle sales (automobiles,      │
│ (Table 3.6 Specific Guideline)│ motorcycles) MUST be issued individually│
└───────────────────────────────┴────────────────────────────────────────┘

Operational Workflow for E-Commerce Stores

  1. Checkout Choice: At checkout, provide a checkbox: "Do you require a formal LHDN Tax Invoice for corporate tax deduction?"
  1. Path A (Buyer Requests Invoice): If checked, prompt for Buyer TIN, Registration/NRIC number, Company Name, and SST Number. Validate TIN via GET /api/v1.0/taxpayer/validate/{tin} and queue for Individual E-Invoice Submission immediately upon payment.
  1. Path B (Standard Consumer): If unchecked, issue standard commercial receipt to the customer. Flag order in database as einvoice_type = 'consolidated'.
  1. Monthly Batch Consolidation: On the 1st or 2nd day of each month, an automated worker aggregates all eligible orders from the preceding calendar month into consolidated UBL 2.1 documents (respecting the 100-doc / 5 MB / 300 KB limits) and submits them before the 7th calendar day statutory deadline.

13. Security and Signing Considerations

All submissions via the MyInvois REST API require cryptographic authentication and digital signatures:

1. The Digital Signature Model: Enveloped XAdES

  • Mandated Standard: Enveloped XAdES (XML Advanced Electronic Signatures) built on the W3C XMLDSig standard and aligned with UBL 2.1 digital signature specifications.
  • Signature Algorithm: RSA with SHA-256 (http://www.w3.org/2001/04/xmldsig-more#rsa-sha256).
  • Digest Algorithm: SHA-256 (http://www.w3.org/2001/04/xmlenc#sha256).
  • Canonicalization: Canonical XML 1.1 (http://www.w3.org/2006/12/xml-c14n11).

2. X.509 Digital Certificate Profile

  • The merchant must obtain a valid corporate X.509 digital certificate from an accredited Malaysian Certification Authority (e.g. Pos Digicert, MSC Trustgate).
  • The certificate must contain the organization's TIN and Business Registration Number (BRN) within its Subject Distinguished Name (DN).
  • Key Usage must include Non-Repudiation.

3. Private Key Security Architecture

  • Never Store in Web Roots: Private keys (.p12 or .pem) must never reside in a web-accessible document directory or be committed to Git repositories.
  • Environment Isolation: Private key passphrases must be injected via secure environment variables (.env) or cloud Key Management Services (AWS KMS, HashiCorp Vault).

4. OAuth 2.0 Token Caching

  • Access tokens requested via POST /connect/token have a lifetime of 3600 seconds (60 minutes).
  • Strict Limit: LHDN limits token generation to 12 Requests Per Minute (RPM).
  • Architectural Mandate: Applications must cache the access token locally (e.g. in Redis or application memory) and reuse it across all submissions until it nears expiration. Requesting a new token per invoice will instantly breach the 12 RPM limit, causing HTTP 429 lockouts.

14. Operational Monitoring

An e-invoicing pipeline needs clear operational visibility. A queue can continue accepting work while individual submissions are failing, so the system should make backlog, validation delays, rate-limit responses, and failed jobs visible to the team responsible for operating it. The following are example operational alert thresholds for a production implementation. They are SysEncore engineering recommendations, not LHDN-mandated limits.

Architecture Matrix / State TaxonomyASCII Blueprint
┌────────────────────────────────────────────────────────────────────────┐
│                   EXAMPLE OPERATIONAL METRICS TO MONITOR                │
├───────────────────────────────┬────────────────────────────────────────┤
│ Metric                        │ Example SysEncore Alert Threshold                      │
├───────────────────────────────┼────────────────────────────────────────┤
│ Queue Backlog Depth           │ > 500 unprocessed jobs                 │
├───────────────────────────────┼────────────────────────────────────────┤
│ Unvalidated Invoice Age       │ Invoices in `submitted` state > 30 mins│
├───────────────────────────────┼────────────────────────────────────────┤
│ Dead Letter Queue (DLQ) Count │ > 0 failed jobs (Requires triage)      │
├───────────────────────────────┼────────────────────────────────────────┤
│ HTTP 429 Rate Limit Hits      │ > 0 occurrences per hour               │
├───────────────────────────────┼────────────────────────────────────────┤
│ 72-Hour Approaching Alert     │ Valid invoices with refund pending > 48│
└───────────────────────────────┴────────────────────────────────────────┘

15. Implementation Checklist

Before deploying an e-commerce to MyInvois integration to production, verify each architectural component against this 12-point operational checklist:

  • 1. Decoupled State Storage: Database schema separates payment_status from einvoice_status.
  • 2. Asynchronous Queue: E-invoice payload generation occurs inside background workers, not in checkout requests.
  • 3. Webhook Idempotency: Payment webhooks enforce unique event ID deduplication.
  • 4. LHDN Duplicate Check: Worker prevents duplicate submissions for the same order and invoice number.
  • 5. Token Caching Active: OAuth bearer token is cached in memory/Redis and reused across the 60-minute window.
  • 6. Rate Limit Throttling: Outbound dispatch is capped locally at or below 100 RPM.
  • 7. Retry-After Parsing: HTTP 429 handlers dynamically read and respect the server's Retry-After header.
  • 8. Dead Letter Queue: Schema validation rejections (HTTP 400) route to an alertable DLQ for manual inspection.
  • 9. Polling Reconciler Scheduled: A reconciliation worker checks submission status at a controlled interval based on the current MyInvois API guidance and the integration's rate-limit budget.
  • 10. 72-Hour Cancellation Rule: Order management UI restricts direct cancellation to 72 hours, enforcing Credit Notes thereafter.
  • 11. Consolidated Monthly Workflow: Scheduled batch aggregation runs automatically within 7 calendar days of month-end using TIN EI00000000010.
  • 12. X.509 Key Isolation: Private signing keys are stored outside web roots with restricted filesystem permissions.

16. What This Means for an Existing E-Commerce System

If your current system sends an e-Invoice request directly from checkout or from a payment webhook, the first question is not which API library to install. The first question is where the e-Invoice workflow belongs in the existing transaction lifecycle.

A practical architecture review should identify:

  • where payment confirmation is persisted;
  • whether webhook delivery is handled safely when the same event is received more than once;
  • where e-Invoice state is stored;
  • whether submission can be retried safely;
  • how validation failures reach the people responsible for operations and finance;
  • how refunds and cancellations map to the e-Invoice workflow; and
  • how the final invoice state is reconciled with the ERP or finance system.

These questions can usually be answered before changing the production checkout flow.

17. Common Architectural Mistakes

Mistake Why It Breaks in Production Correct Engineered Replacement
1. Synchronous Checkout Coupling Causes checkout timeouts and cart drop-offs when LHDN API experiences WAN latency. Decouple via asynchronous queue worker; complete checkout immediately upon payment capture.
2. Requesting Token per Invoice Exceeds the strict 12 RPM login rate limit on /connect/token, locking the integration with HTTP 429. Cache the OAuth token in memory/Redis for 55 minutes and reuse across submissions.
3. Conflating Paid with Valid Treats payment capture as statutory tax validation. Orders show as complete while LHDN quietly rejects invalid tax IDs. Maintain explicit, separate payment_status and einvoice_status columns.
4. Deleting Orders After 72 Hours Violates LHDN regulations and breaks audit trails; MyInvois locks cancellation after 72 hours. Issue an official Credit Note (02) referencing the original UUID for returns after 72 hours.
5. Submitting Micro-Batches Synchronously Consumes API rate limits inefficiently and risks thundering-herd throttling. Batch B2C transactions into scheduled consolidated submissions (up to 100 docs / 5 MB per batch).
6. Hardcoding PayNet API Assumptions Assumes standard merchants can call PayNet banking rails directly without an acquirer. Route all payment capture through accredited Malaysian payment gateways (Curlec, Billplz, Stripe MY).

18. What Must Be Verified Before Implementation

Before beginning custom software development or plugin configuration, the engineering team must confirm five prerequisites:

  1. Taxpayer Implementation Phase: Determine the business's mandatory compliance phase (Phase 1, Phase 2, or Phase 3) based on historical audited revenue, and verify whether any 6-month transitional relaxations apply.
  1. MyInvois Sandbox ERP Credentials: Obtain active client_id and client_secret credentials for the LHDN Pre-Production environment (preprod-api.myinvois.hasil.gov.my) via the MyInvois developer portal.
  1. Accredited CA Digital Certificate: Procure a valid corporate X.509 digital certificate from an accredited Malaysian CA with Non-Repudiation key usage and verified TIN/BRN DN attributes.
  1. Payment Gateway Webhook Support: Confirm that the store’s payment gateway supports reliable asynchronous webhooks with cryptographic HMAC signature verification.
  1. Checkout Buyer Data Capture: Audit whether the e-commerce checkout form captures mandatory buyer fields (TIN, BRN/NRIC, SST registration) when an individual tax invoice is requested.

19. SysEncore Architectural Perspective

For this type of integration, SysEncore generally favours resilience, clear state boundaries, and deliberate data minimisation:

  • Resilience Over Convenience: Customer-facing transaction flows should not depend on the immediate availability of a statutory API. External integrations are better isolated behind durable processing and explicit recovery paths.
  • Defensive API Engineering: External APIs can experience maintenance windows, network failures, and rate throttling. A resilient integration plans for those conditions instead of treating them as exceptional cases.
  • Honest Provenance & Anti-Hype: We distinguish published requirements from engineering recommendations and avoid unsupported performance claims, fictional case studies, or promises of assured compliance outcomes.

20. Appropriate SysEncore CTA

Integrating LHDN MyInvois into an active e-commerce, custom ERP, or multi-channel payment pipeline requires careful architectural alignment between your transactional database, payment gateways, and background queues.

Assess Your E-Commerce & Billing Architecture

If you are evaluating how MyInvois compliance impacts your existing software infrastructure, SysEncore provides focused, practitioner-grade technical reviews:

  • E-Commerce Architecture & Integration Review: A focused technical review covering your checkout data flow, webhook resilience, queue strategy, and LHDN integration approach.
  • Custom Business Automation & ERP Middleware: Designing bespoke, decoupled middleware connecting WooCommerce, Magento, Shopify, or proprietary custom PHP billing systems to MyInvois with full error handling and database reconciliation.
Explore Technical Architecture Review:
Before treating this as a build, read what to settle before connecting two systems. A custom application is not the automatic next step. You can also visit Business Automation or Custom Software Development, or write to info@sysencore.com.

(Disclaimer: SysEncore provides custom software engineering and systems architecture services. This guide provides technical implementation patterns for statutory requirements and does not constitute formal legal or tax advisory).

21. Sources / Evidence Register

The regulatory and technical assertions in this guide are grounded in primary source documentation:

Claim / Topic Primary Source Section / Endpoint Reference Evidence Tier
Statutory Mandate Income Tax Act 1967 (Act 53) Sections 82, 120 Tier 2 (Statute)
Consolidated Invoicing Rules LHDN e-Invoice Specific Guideline v4.9 Section 3.6, Table 3.5, Table 3.6 Tier 1 (LHDN)
72-Hour Cancellation Window LHDN e-Invoice Guideline v4.8 Section 2.5 (dateTimeValidated) Tier 1 (LHDN)
Batch & Payload Limits MyInvois SDK Documentation POST /api/v1.0/documentsubmissions/ (100 docs / 5 MB / 300 KB) Tier 1 (LHDN)
API Rate Limits MyInvois SDK Documentation Rate Limits (100 RPM submit / 12 RPM token / 300 RPM poll) Tier 1 (LHDN)
HTTP 429 & Retry-After MyInvois SDK / RFC 7231 HTTP Status Codes & Error Handling Tier 1 & Tier 5
OAuth 2.0 Token Lifetime MyInvois SDK Specification POST /connect/token (expires_in: 3600s) Tier 1 (LHDN)
Digital Signatures (XAdES) MyInvois Signature Guidelines Enveloped XAdES on W3C XMLDSig (RSA-SHA256, SHA-256) Tier 1 & Tier 5
General Public TIN LHDN e-Invoice Specific Guideline v4.9 Table 3.5 (EI00000000010) Tier 1 (LHDN)
Motor Vehicle Exclusion LHDN e-Invoice Specific Guideline v4.9 Table 3.6 (Prohibited from consolidation) Tier 1 (LHDN)

A separate line-by-line source register is not published on this website. The description above is an architecture explanation, not a certification of a live MyInvois integration.