惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
IT之家
IT之家
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
N
News | PayPal Newsroom
Cloudbric
Cloudbric
Webroot Blog
Webroot Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Simon Willison's Weblog
Simon Willison's Weblog
Spread Privacy
Spread Privacy
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Vulnerabilities – Threatpost
Attack and Defense Labs
Attack and Defense Labs
C
Cyber Attacks, Cyber Crime and Cyber Security
Cisco Talos Blog
Cisco Talos Blog
C
Cybersecurity and Infrastructure Security Agency CISA
H
Hackread – Cybersecurity News, Data Breaches, AI and More
P
Proofpoint News Feed
阮一峰的网络日志
阮一峰的网络日志
S
Secure Thoughts
T
Tor Project blog
Latest news
Latest news
aimingoo的专栏
aimingoo的专栏
V2EX - 技术
V2EX - 技术
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
Securelist
T
Tenable Blog
N
Netflix TechBlog - Medium
Google Online Security Blog
Google Online Security Blog
博客园 - Franky
T
Troy Hunt's Blog
量子位
大猫的无限游戏
大猫的无限游戏
T
Threat Research - Cisco Blogs
T
The Exploit Database - CXSecurity.com
MongoDB | Blog
MongoDB | Blog
H
Heimdal Security Blog
D
Docker
W
WeLiveSecurity
Stack Overflow Blog
Stack Overflow Blog
G
Google Developers Blog
博客园 - 叶小钗
腾讯CDC
The Hacker News
The Hacker News
WordPress大学
WordPress大学
人人都是产品经理
人人都是产品经理
Project Zero
Project Zero
Martin Fowler
Martin Fowler

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Integrating Pakistani Businesses with the FBR Digital Invoicing API
Waseem ur Re · 2026-05-17 · via DEV Community

If you build or maintain software for Pakistani businesses, FBR Digital Invoicing integration is now in your backlog whether you wanted it or not. Under SRO 709(I)/2025, every sales-tax-registered person in Pakistan must transmit invoices to FBR in real time via the Digital Invoicing API operated by PRAL (Pakistan Revenue Automation).

This post is the practical developer walkthrough I wish existed when I first built integrations against this API. We'll cover the architecture, the auth flow, the JSON payload, sandbox testing for the 28 mandatory scenarios, retry logic for FBR's outages, and the going-to-production checklist.

The architecture in 30 seconds

Your app → PRAL Digital Invoicing API → FBR core system
              ↓
        IRN + QR code returned to you
              ↓
        Print on the customer's invoice

Enter fullscreen mode Exit fullscreen mode

Three endpoints matter:

  • validateinvoicedata — pre-flight check before live submission
  • postinvoicedata — actual invoice submission, returns IRN + QR code
  • cancelinvoicedata — cancellation within the 72-hour correction window (post April 2026)

You authenticate with a bearer token issued via the FBR IRIS portal per registered NTN.

Step 1: Get your bearer token

  1. Log in to iris.fbr.gov.pk with the business's CNIC/NTN
  2. Navigate to Digital InvoicingIntegration Mode
  3. Select "Proceed with PRAL as Licensed Integrator"
  4. The portal generates a bearer token tied to that NTN

The token is opaque and long-lived (it doesn't expire frequently). Store it encrypted — under no circumstances commit it to source control or log it in plain text. AES-256 at rest is the minimum standard.

Step 2: Construct the invoice payload

FBR expects a strict JSON structure. Here's a minimal but complete payload for a B2B taxable supply:

{
  "invoiceType": "Sale Invoice",
  "invoiceDate": "2026-05-16",
  "sellerNTNCNIC": "1234567",
  "sellerBusinessName": "Acme Trading (Pvt) Ltd",
  "sellerProvince": "Punjab",
  "sellerAddress": "Plot 12, Lahore",
  "buyerNTNCNIC": "7654321",
  "buyerBusinessName": "Beta Industries (Pvt) Ltd",
  "buyerProvince": "Sindh",
  "buyerAddress": "Industrial Area, Karachi",
  "buyerRegistrationType": "Registered",
  "invoiceRefNo": "ACM-2026-0001",
  "items": [
    {
      "hsCode": "1234.5678",
      "productDescription": "Industrial pump model X-200",
      "rate": "18%",
      "uoM": "Numbers, pieces, units",
      "quantity": 5,
      "totalValues": 50000,
      "valueSalesExcludingST": 42372.88,
      "fixedNotifiedValueOrRetailPrice": 0,
      "salesTaxApplicable": 7627.12,
      "salesTaxWithheldAtSource": 0,
      "extraTax": 0,
      "furtherTax": 0,
      "sroScheduleNo": "",
      "fedPayable": 0,
      "discount": 0,
      "saleType": "Goods at Standard Rate (default)",
      "sroItemSerialNo": ""
    }
  ]
}

Enter fullscreen mode Exit fullscreen mode

Critical fields to get right:

  • sellerNTNCNIC and buyerNTNCNIC — exactly as registered with FBR; mismatches return validation errors
  • hsCode — must match the actual product category (FBR validates against their HS Code database)
  • rate — string format with % sign, not a number
  • saleType — one of FBR's predefined values (e.g., "Goods at Standard Rate (default)", "3rd Schedule Goods", "Steel Melting and Re-Rolling")
  • valueSalesExcludingST and salesTaxApplicable — must mathematically reconcile to totalValues

If your software can't render these from your existing invoice data model, you have an integration bug, not an FBR problem.

Step 3: Submit the invoice

curl -X POST 'https://gw.fbr.gov.pk/di_data/v1/di/postinvoicedata' \
  -H 'Authorization: Bearer YOUR_PRAL_TOKEN' \
  -H 'Content-Type: application/json' \
  -d @invoice.json

Enter fullscreen mode Exit fullscreen mode

Or in Python:

import requests
import os

PRAL_TOKEN = os.environ['PRAL_BEARER_TOKEN']
ENDPOINT = 'https://gw.fbr.gov.pk/di_data/v1/di/postinvoicedata'

response = requests.post(
    ENDPOINT,
    headers={
        'Authorization': f'Bearer {PRAL_TOKEN}',
        'Content-Type': 'application/json'
    },
    json=invoice_payload,
    timeout=30
)

if response.status_code == 200:
    result = response.json()
    irn = result['invoiceNumber']
    qr_code = result['QRCode']  # base64-encoded image
    # Persist IRN + QR code with your invoice record
else:
    # Handle error (see error handling section below)
    pass

Enter fullscreen mode Exit fullscreen mode

Step 4: Print the IRN and QR code

The IRN and QR code must appear on the invoice you give the customer. Without them, the invoice is legally invalid — even if you have a paper copy.

Your invoice template needs:

  • The IRN clearly labelled (e.g., "FBR Reference: 12345678901234")
  • The QR code rendered at minimum 2cm × 2cm with sufficient contrast
  • A note: "Verify this invoice at fbr.gov.pk/online-invoice-verification"

Most stack PDFs use libraries like ReportLab (Python) or PDFKit (Node) to embed the base64 QR code directly.

Step 5: Sandbox first, always

FBR provides a sandbox environment at https://gw.fbr.gov.pk/di_data/v1/di/postinvoicedata_sb for testing. You must pass all 28 mandatory test scenarios before going to production.

The 28 scenarios fall into seven categories:

  1. Standard sales (5 scenarios) — basic B2B/B2C at 18%
  2. Third Schedule goods (3 scenarios) — retail-price-based tax
  3. Reduced-rate and zero-rated supplies (4 scenarios) — 1%/5%/10%/15% rates plus zero-rated exports
  4. Exempt supplies (2 scenarios) — Sixth Schedule items
  5. Further tax and withholding (4 scenarios) — 3% further tax for unregistered buyers
  6. Returns, debit and credit notes (4 scenarios) — linkage to original IRN
  7. Special cases (6 scenarios) — multi-currency, FED on services, advance payments, exports

Most integration failures happen on scenarios 3 (reduced rates) and 6 (returns linkage). Build automated tests for these first.

Step 6: Error handling and retry logic

FBR's API isn't always up. You need queue-and-retry logic in production.

A reasonable pattern:

class FBRSubmissionService:
    MAX_RETRIES = 5
    RETRY_DELAYS = [1, 5, 30, 120, 600]  # seconds, exponential

    def submit_invoice(self, invoice_id):
        invoice = Invoice.objects.get(id=invoice_id)
        payload = self.build_payload(invoice)

        for attempt, delay in enumerate(self.RETRY_DELAYS):
            try:
                resp = requests.post(
                    self.endpoint,
                    headers={'Authorization': f'Bearer {self.token}'},
                    json=payload,
                    timeout=30
                )

                if resp.status_code == 200:
                    result = resp.json()
                    invoice.irn = result['invoiceNumber']
                    invoice.qr_code = result['QRCode']
                    invoice.status = 'submitted'
                    invoice.save()
                    return True

                if resp.status_code == 400:
                    # Validation error — log + don't retry
                    invoice.status = 'validation_error'
                    invoice.error_details = resp.json()
                    invoice.save()
                    return False

                if resp.status_code in (500, 502, 503, 504):
                    # Transient error — retry
                    time.sleep(delay)
                    continue

            except requests.Timeout:
                time.sleep(delay)
                continue

        # Exhausted retries — flag for manual review
        invoice.status = 'requires_manual_review'
        invoice.save()
        return False

Enter fullscreen mode Exit fullscreen mode

Critical patterns:

  • Idempotency — your invoiceRefNo should be unique per submission so FBR won't double-process
  • Persistent queue — if your app crashes, pending submissions should resume on restart (use a database-backed queue, not in-memory)
  • Audit log — every submission attempt, response, retry should be logged with timestamps for compliance review
  • Alerting — set up alerts when invoices spend more than 1 hour in 'pending' state

Step 7: The 72-hour correction window

Under the April 2026 Sales Tax General Order No. 01 of 2026, invoices can be cancelled, deleted, or edited within 72 hours of issuance without Commissioner approval. After 72 hours, you need prior approval — slow.

Your software needs:

  • A timestamp-driven "editable" flag on every invoice
  • A correction endpoint that resubmits with reference to the original IRN
  • A clear UI hint that says "X hours remaining to edit without approval"

Don't let users edit invoices after 72 hours via your normal flow — force them through the Commissioner-approval path.

Step 8: Production deployment checklist

Before flipping the production switch:

  • [ ] All 28 sandbox scenarios passed
  • [ ] Bearer token stored encrypted (AES-256 at rest)
  • [ ] Token not logged in plain text anywhere
  • [ ] Idempotent invoiceRefNo generation
  • [ ] Queue-and-retry with exponential backoff
  • [ ] Persistent queue (survives app restart)
  • [ ] Audit log of every API call
  • [ ] Alerting on stuck invoices (>1 hour pending)
  • [ ] Monitoring of API response time (95th percentile)
  • [ ] Daily reconciliation: invoice counts you sent vs counts in FBR's portal
  • [ ] Backup plan for FBR downtime (when systems will queue locally and replay)
  • [ ] Per-business sandbox/production toggle if you serve multiple clients
  • [ ] QR code rendering tested on actual printed invoices (contrast, scannability)

Most integrations break in production on the reconciliation step — your audit log says you sent 1,000 invoices today, but FBR's portal shows 998. The missing two were rejected silently for some edge case. Catch these daily.

Step 9: Should you build this or use a managed platform?

Honest math:

  • Building it yourself: ~80–200 hours upfront, plus 5–15 hours per month maintenance (FBR updates the API several times a year)
  • Using a managed platform: Rs 1,500–8,000/month per business, zero engineering time

For a single-business integration, building yourself is defensible — you control everything, no vendor lock-in. For multi-business scenarios (tax consultants managing 10–100 clients), managed platforms always win on time-to-value.

I run Tallied, which handles this for Pakistani tax consultants. We charge Rs 1,500 per client business per month (wholesale tier) with white-label custom domains and a multi-client dashboard. For developers evaluating: we use the exact same PRAL API documented above, but consolidate multi-business token management, queue-and-retry, and the 28 sandbox scenarios into one interface.

For more context on the regulatory side of FBR Digital Invoicing — who must integrate, deadlines, penalties under Section 33, and how to choose the right software — see the full guide and the software comparison on the Tallied blog.

Closing notes for developers

The FBR Digital Invoicing API is well-designed by Pakistani government API standards — versioned, JSON-based, OAuth-token authenticated, with a real sandbox. The 28 scenarios are tedious but mostly straightforward. The biggest production gotchas are silent rejection, FBR downtime, and managing tokens across multiple registered persons if you're building multi-tenant.

Build idempotent. Log everything. Reconcile daily. Encrypt the token. Run all 28 scenarios in CI.

And if you ever ship anything in production against this API: print the IRN large enough that the chai-walla at your customer's office can read it. The compliance officer scanning your invoice with a phone camera will thank you.