SaudiVatPro Developer Documentation
Integrate ZATCA Phase 2 compliance directly into your custom applications and ERP systems.
Overview
The SaudiVatPro API allows you to push raw orders and let our engine handle the complex ZATCA Phase 2 requirements (CSR, XML UBL 2.1 generation, cryptographic signing, and API submission).
- B2B Invoices (Standard): Cleared in real-time. The API returns the signed XML and QR code immediately.
- B2C Invoices (Simplified): Queued and reported within 24 hours automatically.
Quick Start
Get your first invoice cleared by ZATCA in under 5 minutes.
1. Get your API key
Sign up and generate your API key from the Dashboard.
2. Send your first invoice
POST your order to our API — we handle signing & ZATCA submission.
3. Verify clearance
Receive the cleared invoice UUID, QR code, and signed XML instantly.
- Sign up for a SaudiVatPro account
- Generate your API key from Dashboard → API Keys
- Complete CSID onboarding in the Dashboard
- Test your first invoice in sandbox mode
- Switch to your live API key
- Submit your first real invoice via the API
- Monitor clearance status in the Dashboard
Prerequisites
- •A SaudiVatPro account — sign up free
- •A ZATCA-registered business with a valid VAT number (15 digits)
- •Basic familiarity with REST APIs or cURL
2. Send your first invoice
POST a minimal payload to /v1/orders. The API handles XML generation, digital signing, and ZATCA submission in a single call.
curl -X POST https://saudivatpro.com/api/v1/orders \
-H "X-API-Key: svp_live_xxx" \
-H "Content-Type: application/json" \
-d '{
"orderReference": "ORD-2024-105",
"invoiceType": "standard",
"buyerName": "Acme Trading Co",
"buyerVatNumber": "310000000000006",
"buyerCity": "Riyadh",
"lines": [
{ "name": "Consulting", "quantity": 1, "unitPrice": 1500.00, "vatRate": 15 }
]
}'3. Verify clearance
The response includes status: "cleared", a Base64 QR code for printing on the invoice, and the ZATCA UUID. For B2B, clearance happens synchronously before the response is returned.
{
"id": "inv_8f7d6e5c",
"status": "cleared",
"zatcaUuid": "8fb21b4a-6c3e-4d2a-bf7d-2e9f1a0c3d45",
"total": 1725.00,
"vatAmount": 225.00,
"qrCode": "BASE64_QR_STRING",
"zatcaMessage": "CLEARED"
}Authentication
All API requests must include an API key in the header. You can generate keys in your Dashboard under Developers.
Live Key (svp_live_…)
Use for all production requests. Never expose in client-side code or public repositories.
Sandbox Key (svp_demo_…)
Safe for testing. Generates real-looking but non-submitted ZATCA invoices — no compliance risk.
Reliability
SaudiVatPro is engineered to never be a single point of failure in your checkout flow.
Fail-Open Architecture
If ZATCA's portal is slow or unavailable, your customer's checkout still completes. We never throw a blocking error. Orders are queued in our durable store and submitted as soon as ZATCA is reachable again.
Your server calls POST /v1/orders
ZATCA responds within 5 s → invoice is marked cleared immediately
ZATCA is slow or down → invoice is marked queued, auto-retried
You always receive a UUID — your checkout never blocks
Error Codes Reference
When an error does surface (e.g. invalid VAT number, duplicate reference), the API returns a structured error code so your integration can handle it explicitly.
Troubleshooting
Common issues and how to resolve them:
| Symptom | Likely Cause | Fix |
|---|---|---|
| Invoice stuck in "queued" status | CSID certificate expired | Renew CSID from Dashboard → Onboarding |
| 401 Unauthorized on every request | Missing or malformed auth header | Send X-API-Key header, not Authorization: Bearer |
| Invoice stuck in "needs_data" status | B2B invoice missing buyerVatNumber or buyerCity | Open the invoice in the dashboard and use the Repair form to add buyer details |
| BV-000001 duplicate reference error | orderReference already used | Use a globally unique orderReference per invoice |
| XSD-000010 schema validation failure | Required field missing or wrong format | Check required fields — buyerVatNumber, unitPrice, vatRate |
| PDF download returns 404 | Invoice not yet cleared | Wait for status to become cleared before fetching PDF |
Submit an Order
Submit order details. We build, sign, and submit the ZATCA invoice automatically.
/v1/orders{
"orderReference": "ORD-2024-105", // Unique per invoice — required
"invoiceType": "standard", // "standard" (B2B) or "simplified" (B2C)
"paymentMeans": "30", // 10=Cash, 48=Card, 30=Bank transfer, 42=Bank account
// Buyer — required for B2B (standard) invoices
"buyerName": "Acme Trading Co",
"buyerVatNumber": "310000000000006", // 15 digits, starts & ends with 3
"buyerStreet": "Olaya St",
"buyerBuildingNumber": "1234",
"buyerDistrict": "Al Olaya",
"buyerCity": "Riyadh", // Required for clearance
"buyerPostalCode": "12345",
"lines": [
{
"name": "Consulting Services",
"quantity": 10,
"unitPrice": 150.00,
"vatRate": 15 // 15 for standard, 0 for zero-rated/exempt
}
]
}{
"id": "inv_8f7d6e5c",
"status": "cleared",
"total": 1725.00,
"vatAmount": 225.00,
"qrCode": "BASE64_QR_CODE_STRING",
"zatcaUuid": "8fb21b4a-6c3e-4d2a-bf7d-2e9f1a0c3d45",
"zatcaMessage": "CLEARED"
}Refunds & ZATCA Credit Notes
Issue a type 381 ZATCA credit note against any cleared or reported invoice. The credit note keeps the original invoice linkage and follows the same B2B clearance or B2C reporting path as its parent.
/invoices/{invoiceId}/credit-noteFull refund
Omit lines to copy every line, quantity, discount, and VAT treatment from the original invoice.
Partial refund
Send only the positive-amount lines and quantities being refunded. The type 381 document marks them as a credit.
curl -X POST \
https://app.saudivatpro.com/api/invoices/inv_8f7d6e5c/credit-note \
-H "Content-Type: application/json" \
--data '{
"reasonCode": "cancellation",
"note": "Customer cancelled the order",
"idempotencyKey": "refund-ORD-2024-105-full"
}'{
"reasonCode": "return",
"note": "One item returned",
"idempotencyKey": "wc-refund-981",
"lines": [
{
"name": "Premium Hoodie",
"quantity": 1,
"unitPrice": 149.00,
"vatRate": 15
}
]
}What happens after the request
- • The returned document has documentType credit_note and creditNoteOf points to the original invoice.
- • Send a stable idempotencyKey for each external refund. Repeating the same request returns the existing credit note instead of creating a duplicate.
- • The response includes the credit note's ZATCA status. Failed submissions can be retried using the credit note ID.
- • The WooCommerce plugin calls this flow automatically for full and partial WooCommerce refunds and tracks each refund separately.
POST /invoices/{creditNoteId}/retryInvoice Types
Every order you submit is either a Standard (B2B) invoice or a Simplified (B2C) invoice. The type controls whether ZATCA clears it in real-time or queues it for 24-hour reporting — and which fields are required in your request.
B2B — Real-time clearance required
The invoice must be cleared by ZATCA before it reaches the buyer. Our API returns the UUID, signed XML, and QR code synchronously — typically within 1–2 seconds. Buyer VAT number and address fields are mandatory.
{
"orderReference": "ORD-2024-105",
"invoiceType": "standard", // B2B — clears with ZATCA before delivery
"paymentMeans": "30",
// Required for B2B clearance
"buyerName": "Acme Trading Co",
"buyerVatNumber": "310000000000006",
"buyerStreet": "Olaya St",
"buyerBuildingNumber": "1234",
"buyerDistrict": "Al Olaya",
"buyerCity": "Riyadh",
"buyerPostalCode": "12345",
"lines": [{ "name": "Consulting", "quantity": 1, "unitPrice": 1500, "vatRate": 15 }]
}| Feature | B2B (Standard) | B2C (Simplified) |
|---|---|---|
| ZATCA Processing | Cleared in real-time before delivery | Reported automatically within 24 hours |
| API Response | Synchronous — waits for ZATCA clearance (~1–2 s) | Immediate — local ID returned instantly |
| Buyer VAT Fields | Required (VAT number, name, address) | Not required |
| invoiceType field | "invoiceType": "standard" | "invoiceType": "simplified" |
| Typical use case | Business-to-business sales, ERP orders, wholesale | Retail, e-commerce checkout, consumer sales |
B2B Field Reference
Standard (B2B) invoices require clearance by ZATCA before the invoice can be shared with the buyer. The fields below are required for ZATCA to accept the clearance request.
⚡ B2B Auto-detection
If you include a buyerVatNumber in your request, the invoice is automatically treated as Standard (B2B) — even if you set "invoiceType": "simplified". You can omit invoiceType entirely when the VAT number is present.
When no VAT number is detected, the invoice falls back to your Default Invoice Type setting (Settings → Defaults). This is useful for B2B-only merchants who want every invoice to default to Standard without needing to pass "invoiceType": "standard" on every request.
| Field | Type | B2B | Notes |
|---|---|---|---|
| orderReference | string | Required | Must be globally unique per merchant |
| invoiceType | enum | Optional | "standard" or "simplified". Auto-set when buyerVatNumber is present. |
| paymentMeans | enum | Optional | 10=Cash, 48=Card, 30=Bank transfer, 42=Bank account. Defaults to Cash. |
| buyerName | string | Required | Legal name of the buying entity |
| buyerVatNumber | string | Required | 15 digits, starting and ending with 3 (e.g. 310122393500003) |
| buyerStreet | string | Recommended | Street name — included in UBL XML |
| buyerBuildingNumber | string | Recommended | Building number — included in UBL XML |
| buyerDistrict | string | Recommended | District or neighbourhood |
| buyerCity | string | Required | City name — required by ZATCA for clearance |
| buyerPostalCode | string | Recommended | 5-digit Saudi postal code |
Missing Required fields cause ZATCA to reject the clearance request. The invoice lands in needs_data status and an issue is created in your dashboard with repair instructions. Recommended fields are embedded in the UBL XML and improve ZATCA acceptance rates.
Webhook Intake
If your system prefers to send webhooks rather than calling our API synchronously, you can point your webhooks to our intake endpoint.
/v1/webhooks/orders{
"orderReference": "ORD-2024-105",
"invoiceType": "standard",
"buyerName": "Acme Trading Co",
"buyerVatNumber": "310000000000006",
"buyerStreet": "Olaya St",
"buyerBuildingNumber": "1234",
"buyerDistrict": "Al Olaya",
"buyerCity": "Riyadh",
"buyerPostalCode": "12345",
"lines": [
{
"name": "Consulting Services",
"quantity": 10,
"unitPrice": 150.00,
"vatRate": 15
}
]
}Download PDF
Download an invoice PDF with GET /api/invoices/:id/pdf. Authenticate with an active dashboard session or your X-API-Key header. Poll invoice status with GET /api/invoices/:id; only invoices belonging to your account are accessible.
/invoices/:id/pdfHTTP/1.1 200 OK
Content-Type: application/pdf
Content-Disposition: attachment; filename="invoice_inv_8f7d6e5c.pdf"
Content-Length: 48291Error Codes
ZATCA returns structured rejection codes. Common codes and how to fix them:
| Code | Meaning | Fix |
|---|---|---|
| BV-000001 | Duplicate invoice reference | Use a unique orderReference per invoice |
| BV-000002 | Missing buyer VAT number | Add buyerVatNumber for B2B invoices |
| BV-000003 | Invalid VAT number format | Must be 15 digits starting with 3 |
| BV-000004 | Invoice date in the future | Use current UTC timestamp for invoiceDate |
| XSD-000010 | XML schema validation failed | Check required fields; review Issues dashboard |
| CSID-EXP | CSID certificate expired | Renew CSID from Dashboard → Onboarding |
Rate Limits
The API enforces per-key rate limits. Exceeding limits returns HTTP 429 with a Retry-After header.
| Plan | Requests / min | Invoices / year |
|---|---|---|
| Trial | 60 | 10,000 |
| ProfessionalPopular | 300 | 10,000+ |
| Enterprise | Custom | Unlimited |
Free Tools & npm Package
Alongside the REST API, we publish free open-source utilities for working with ZATCA Phase 1 QR codes — both as an interactive browser tool and as a lightweight npm package you can drop into any JavaScript project.
ZATCA QR Toolkit
Decode any ZATCA Phase 1 (or Phase 2) base64 QR string to inspect its TLV fields, or generate a valid QR code from invoice data — all in the browser with live validation.
npm Package
The same encoding, decoding, and validation logic is available as saudivatpro-qrtool — a zero-dependency TypeScript package that works in Node.js, Deno, and any modern browser bundler.
npm install saudivatpro-qrtoolimport { encodeTlvPhaseOne, decodeTlv, validateQr } from 'saudivatpro-qrtool';
// Generate a Phase 1 QR base64 string
const base64 = encodeTlvPhaseOne({
sellerName: 'شركة المثال التجارية',
vatNumber: '300075588700003',
timestamp: '2024-11-20T12:30:00Z',
invoiceTotal: '115.00',
vatAmount: '15.00',
});
// Decode back to structured fields
const { fields, phase } = decodeTlv(base64);
// Validate — returns { valid, errors }
const result = validateQr(base64);| Function | What it does | Returns |
|---|---|---|
| encodeTlvPhaseOne(fields) | Builds a ZATCA Phase 1 TLV payload from the 5 mandatory fields and returns a base64 string | string (base64) |
| decodeTlv(base64) | Parses a Phase 1 or Phase 2 base64 QR string into structured fields with labels and raw values | ParsedQR |
| validateQr(base64) | Runs ZATCA compliance checks (field presence, VAT number format, timestamp, amounts) and returns any errors | { valid, errors } |
The package is MIT-licensed and published on npm. Source code and full API reference are available on GitHub.
Node.js SDK
NewWooCommerce and Magento stores get automatic ZATCA invoicing through our plugins. For everything else — a Shopify custom app, a Salla or Zid integration, or a fully custom cart — saudivatpro-ecommerce-sdk gives any Node.js backend the same hosted compliance engine.
Other "ZATCA Phase 2" packages on npm only hand you raw UBL XML generation and signing — you still run your own CSID onboarding and ZATCA submission, and the compliance risk stays with you. This SDK is a thin typed client for our already-live, production-tested engine: send order data, get back an invoice, QR code, and PDF. No XML, no signing, no CSID in your code.
npm install saudivatpro-ecommerce-sdkimport { SaudiVatProClient } from 'saudivatpro-ecommerce-sdk';
const client = new SaudiVatProClient({ apiKey: process.env.SAUDI_VAT_PRO_API_KEY! });
// Order placed in your store -> ZATCA-compliant invoice out.
const invoice = await client.submitOrder({
orderReference: order.id, // your own ID; also the idempotency key
buyerName: order.customerName,
buyerVatNumber: order.customerVatNumber, // omit for B2C / simplified invoices
lines: order.items.map((item) => ({
name: item.title,
quantity: item.quantity,
unitPrice: item.unitPrice, // SAR, excluding VAT
vatRate: 15,
})),
});
invoice.status; // "pending" | "generated" | "signed" | "reported" | "cleared" | "failed" | "needs_data"
invoice.qrCode; // base64 ZATCA QR code, once generated| Method | What it does |
|---|---|
| submitOrder(order) | Submit a new order for automatic invoicing (idempotent on orderReference) |
| getInvoice(id) / listInvoices(params) | Read invoice status, lines, event timeline, and linked credit/debit notes |
| getInvoiceXml(id) / getInvoicePdf(id) | Fetch the signed UBL XML or a PDF with the embedded QR code |
| issueCreditNote(id, body?) | Full or partial refund as a linked ZATCA credit note |
| verifyWebhookSignature(opts) | Verify the X-SaudiVatPro-Signature header on inbound webhooks |
MIT-licensed and published on npm as saudivatpro-ecommerce-sdk. Source and full reference on GitHub.
AI Agents & MCP
NewSaudi VAT Pro ships an official Model Context Protocol (MCP) server so AI assistants like Claude Desktop, Cursor, and Windsurf can create, submit, and manage ZATCA invoices through natural language — no copy-pasting, no manual API calls.
What is MCP?
The Model Context Protocol is an open standard that lets AI agents call external tools and APIs. Once the Saudi VAT Pro MCP server is installed, your AI assistant can submit invoices to ZATCA, check compliance status, and fix errors — all in plain conversation.
Install the official MCP server
v1.0.1Published on npm as saudi-vat-pro-mcp
Run without installing globally
npx -y saudi-vat-pro-mcpio.github.Morouna1/saudi-vat-proClaude Desktop setup
Add this to your claude_desktop_config.json (~/Library/Application Support/Claude/ on macOS, %APPDATA%\Claude\ on Windows):
{
"mcpServers": {
"saudi-vat-pro": {
"command": "npx",
"args": ["saudi-vat-pro-mcp"],
"env": {
"SAUDI_VAT_PRO_API_KEY": "svp_live_YOUR_KEY_HERE"
}
}
}
}Cursor & Windsurf setup
In Cursor → Settings → MCP (or Windsurf → Cascade → MCP Servers), add the same config block above. Restart the editor and the tools appear automatically.
ZATCA safety rules for AI agents
- Check the environment first. Call
get_zatca_statusbefore issuing invoices. Sandbox submissions are tests only; production is required for live ZATCA submission. - Choose the correct profile. Standard invoices are for B2B and require the buyer name, city, and a 15-digit VAT number that starts and ends with 3. Simplified invoices are only for eligible B2C transactions.
- Apply VAT correctly. Standard-rated lines use category S at 15%. Zero-rated, exempt, and out-of-scope lines require the correct ZATCA VATEX reason code.
- Treat discounts as line totals. The discount value is a fixed amount for the whole line, not a percentage or per-unit discount.
- Inspect every result. Cleared or reported means submitted. Generated, signed, or pending is not final; needs_data, awaiting_buyer_data, or failed requires action.
- Make refunds idempotent. Reuse the same
idempotencyKeywhen retrying one credit-note request so a network retry cannot create a duplicate refund.
Example conversation
Available tools
| Tool | Description | Key inputs |
|---|---|---|
| list_invoices | List invoices with optional filters | status, invoiceType, search, page |
| get_invoice | Full detail with line items, ZATCA status, and event timeline | id |
| create_invoice | Create an invoice and run the available ZATCA pipeline; always inspect the returned status | invoiceType, lines, buyer… |
| create_credit_note | Issue an idempotent full or partial credit note within the refundable balance | invoiceId, idempotencyKey, lines? |
| retry_invoice | Re-run the ZATCA pipeline for a failed invoice | id |
| explain_invoice_error | AI explanation of why an invoice failed with suggested fixes | id |
| get_zatca_status | ZATCA certificate (CSID) enrollment state and readiness | none |
| get_merchant_profile | Business profile, VAT number, and default settings | none |
| get_dashboard_summary | Compliance health summary with invoice counts and VAT totals | none |
Get your API key from Settings → API Keys. Full parameter reference and setup instructions are in the GitHub repository.