LHDN MyInvois Website Architecture: How Online Checkouts Generate Compliant e-Invoices
A technical breakdown of how e-Commerce checkouts validate buyer TIN/BRN, connect to LHDN MyInvois APIs, and deliver validated QR codes to buyers.
The death of the static PDF invoice in Malaysian e-Commerce
For decades, e-commerce stores operating in Malaysia operated on a straightforward checkout model: a customer completed an online payment via credit card or FPX, and the server triggered an automated email containing a static PDF receipt or HTML order confirmation.
That workflow is fundamentally obsolete under the statutory rollout of the Lembaga Hasil Dalam Negeri (LHDN / hasil.gov.my) MyInvois mandate.
Under the national e-Invoicing guidelines, mandatory e-Invoicing has been phased in by annual turnover since August 2024, and by 2026 covers every business down to RM1 million in annual turnover; businesses below that threshold are currently exempt from the mandate, though they may opt in voluntarily (Crowe Malaysia — Latest e-Invoice Implementation Timeline). For an in-scope business, online retail checkouts, digital B2B portals, and recurring SaaS subscriptions must be validated near real-time through LHDN's central API platform. A compliant transaction requires transmitting the relevant fields from LHDN's e-Invoice Guideline (up to 55 mandatory and optional data fields, depending on the transaction) in a standardized UBL 2.1 XML or JSON format, cryptographically signed using a digital certificate, validated by LHDN, and returned with a unique Document UUID and a verifiable validation QR code (IRBM e-Invoice Guideline, Appendix 1).
For software engineers and e-commerce directors, integrating MyInvois is not simply a matter of installing a third-party plugin. It requires architectural discipline: if your checkout flow makes synchronous calls to government APIs during the payment loop, your conversion rate will crater the first time the external gateway experiences latency.
Here is the architectural blueprint for designing a resilient, high-speed, LHDN-compliant checkout system.
The Core Pitfall: Synchronous vs. Asynchronous Integration
The most dangerous engineering error when integrating LHDN MyInvois into an e-commerce checkout is coupling the invoice generation directly to the payment gateway webhook.
Consider what occurs in a synchronous architecture:
- Buyer submits payment via PayNet FPX (Maybank2u, CIMB Clicks, etc.).
- The payment gateway (e.g., Stripe, Curlec, ToyyibPay) sends a webhook to your server confirming settlement.
- Your server immediately opens an outbound HTTPS request to the LHDN MyInvois API to validate the invoice.
- LHDN's API, experiencing peak-hour traffic or end-of-month congestion, takes 8 to 15 seconds to validate the payload.
- The incoming payment gateway webhook times out (most gateways enforce a 5-second timeout window).
- The payment is marked as "Failed" or dropped into a deadlock state, despite the customer's bank account being debited.
The Solution: The Event-Driven Asynchronous Queue Architecture
To keep the checkout experience unaffected by a slow or unavailable government API, the checkout payment loop must be completely decoupled from the LHDN validation pipeline using an asynchronous queue:
[Customer Checkout] ──> [Payment Gateway (FPX/Card)]
│
▼ (Webhook 200 OK)
[Order Marked as "Paid"] ──> [Customer Sees Success Page]
│
▼ (Publish Event)
[Redis / Database Message Queue]
│
▼ (Worker Consumption)
[LHDN Worker Service]
│
┌──────────────────────┴──────────────────────┐
▼ (Token Cache) ▼ (Payload Assembly)
[OAuth 2.0 Auth] [55 Mandatory UBL Fields]
│ │
└──────────────────────┬──────────────────────┘
▼ (POST /api/v1.0/documentsubmissions)
[LHDN MyInvois API]
│
▼ (Returns Document UUID + QR URL)
[PDF Stamped with Official QR Code]
│
▼ (Async Email / Account Portal)
[Customer Receives Validated e-Invoice]
Step-by-Step Technical Implementation
1. Buyer Information Capture at Checkout
Your checkout form must capture the necessary tax parameters without creating excessive friction for standard B2C consumers.
- B2B Buyers: Require input fields for the buyer's Tax Identification Number (TIN) (e.g.,
C1234567890), their 12-digit Business Registration Number (BRN) in SSM's current format (e.g.,202401012345), and their SST registration number (if applicable). - B2C Consumers: General consumers who do not require a personal tax invoice can be processed under LHDN's standard general public TIN (
EI00000000010) using consolidated e-Invoicing, submitted within 7 days of each calendar month's end (MyInvois SDK — Submit Documents). - Validation Engine: Run client-side and server-side regex validation on TIN and BRN formats before payment submission to eliminate downstream API schema rejections.
2. Authentication and Token Caching
The LHDN MyInvois API uses OAuth 2.0 Client Credentials flow. Requesting a new bearer token for every individual transaction is an anti-pattern that triggers upstream rate-limiting (HTTP 429 Too Many Requests).
Cache your bearer token in Redis or memory, refreshing it only five minutes before expiration:
interface TokenCache {
accessToken: string;
expiresAt: number;
}
let cachedToken: TokenCache | null = null;
export async function getLhdnBearerToken(): Promise<string> {
const now = Math.floor(Date.now() / 1000);
if (cachedToken && cachedToken.expiresAt > now + 300) {
return cachedToken.accessToken;
}
const response = await fetch("https://api.myinvois.hasil.gov.my/connect/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: process.env.LHDN_CLIENT_ID!,
client_secret: process.env.LHDN_CLIENT_SECRET!,
grant_type: "client_credentials",
scope: "InvoicingAPI",
}),
});
if (!response.ok) {
throw new Error(`LHDN Auth Failure: ${response.statusText}`);
}
const data = await response.json();
cachedToken = {
accessToken: data.access_token,
expiresAt: now + data.expires_in,
};
return cachedToken.accessToken;
}
3. Payload Assembly and Digital Signing
The document payload must conform strictly to LHDN's UBL 2.1 JSON schema. Key sections include:
- Supplier & Buyer Details: Validated TIN, registration numbers, registered addresses, and Malaysian MSIC codes (Malaysia Standard Industrial Classification).
- Line Items & Classification: Itemized descriptions mapped to appropriate tax classification codes (e.g., standard rate 8% SST, zero-rated, or exempt).
- Cryptographic Signature: Enterprise implementations require signing the document digest using a certified software certificate (X.509) issued by an accredited Malaysian Certification Authority (such as Pos Digicert or MSC Trustgate).
4. Handling Document Submission and QR Verification
Submit the signed payload to the LHDN document submission endpoint (/api/v1.0/documentsubmissions).
Upon successful validation, LHDN returns:
- A unique Document UUID (e.g.,
LHDN-12345678-ABCD-EF01). - A Long Validation URL pointing to LHDN's official verification portal.
Your backend service generates an on-the-fly QR code encoding this validation URL and embeds it into the customer's downloadable PDF invoice:
import QRCode from "qrcode";
export async function generateLhdnInvoiceQr(validationUrl: string): Promise<string> {
// Generate Data URL representing the verifiable LHDN QR code
return await QRCode.toDataURL(validationUrl, {
errorCorrectionLevel: "M",
margin: 2,
width: 200,
});
}
When scanned by the buyer or tax authorities using any standard smartphone camera, the QR code redirects immediately to the government portal, displaying the real-time validation status of the transaction.
Managing API Failures: Circuit Breakers & Dead-Letter Queues
External government APIs experience scheduled maintenance, schema updates, and unscheduled downtime. Your e-commerce architecture must be engineered to fail safely without losing transaction history.
- Exponential Backoff with Jitter: When the LHDN API returns a 5xx server error, retry the submission using randomized exponential backoff (e.g., wait 2s, 8s, 32s, with randomized jitter) to avoid hammering a recovering server.
- Dead-Letter Queue (DLQ): If a document fails validation repeatedly after five attempts (often due to an invalid buyer TIN or malformed postal code), route the payload into an isolated Dead-Letter Queue. An automated alert notifies your finance operations team to review and correct the metadata manually without interrupting order fulfillment.
- Consolidated Invoicing Fallback: For general retail checkouts, store individual transaction logs and execute a batch consolidation job at the end of the monthly cycle, submitting a single consolidated e-Invoice to LHDN within seven days of month-end, as permitted under LHDN guidelines.
Enterprise Architecture with JagaWeb
Building resilient integrations with statutory government platforms requires senior engineering expertise. JagaWeb specializes in high-reliability digital infrastructure and enterprise software middleware for the Malaysian market:
- Ownership & Access Review (RM1,500 fixed): We audit your current e-commerce stack, API endpoints, payment webhooks, and database architecture, delivering a comprehensive technical specification for MyInvois integration. The full RM1,500 fee is credited toward follow-on development within 12 months.
- Custom Middleware & Web Applications (from RM30,000 fixed-scope or RM13,000/month System Improvement): We design, build, and deploy production-grade LHDN MyInvois middleware, connecting bespoke web applications, ERPs, and WooCommerce stores to government tax APIs with full cryptographic signing and dead-letter queues. Our sister systems—Daralwahi, UrusHQ, and Trexon Energy—run on these exact architectural principles.
- JagaWeb Care (RM450/month): We provide ongoing infrastructure care, uptime monitoring, security patching, and webhook health audits to ensure your e-commerce platform processes transactions smoothly around the clock.
Modernize your online checkout infrastructure with architectures designed for regulatory compliance and enterprise-grade reliability.
Ready to verify who owns your website?
Replace uncertainty with a decision-ready ownership and access report. The fixed Ownership & Access Review is RM1,500 before SST and includes a 30-day action plan.