Documentation
Integration Guide

SaudiVatPro Developer Documentation

Integrate ZATCA Phase 2 compliance directly into your custom applications and ERP systems.

REST APIB2BB2CZATCA Phase 2Wave 24

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

1. Get your API key

Sign up and generate your API key from the Dashboard.

2

2. Send your first invoice

POST your order to our API — we handle signing & ZATCA submission.

3

3. Verify clearance

Receive the cleared invoice UUID, QR code, and signed XML instantly.

Getting Started Checklist
0 / 7 done

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.

bash
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.

json
{
  "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.

Server-side only

Live Key (svp_live_…)

Use for all production requests. Never expose in client-side code or public repositories.

X-API-Key: svp_live_…
Client-side safe

Sandbox Key (svp_demo_…)

Safe for testing. Generates real-looking but non-submitted ZATCA invoices — no compliance risk.

X-API-Key: svp_demo_…

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.

1

Your server calls POST /v1/orders

2

ZATCA responds within 5 s → invoice is marked cleared immediately

3

ZATCA is slow or down → invoice is marked queued, auto-retried

4

You always receive a UUID — your checkout never blocks

Retry policy: up to 5 attempts over 2 hours using exponential back-off.

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:

SymptomLikely CauseFix
Invoice stuck in "queued" statusCSID certificate expiredRenew CSID from Dashboard → Onboarding
401 Unauthorized on every requestMissing or malformed auth headerSend X-API-Key header, not Authorization: Bearer
Invoice stuck in "needs_data" statusB2B invoice missing buyerVatNumber or buyerCityOpen the invoice in the dashboard and use the Repair form to add buyer details
BV-000001 duplicate reference errororderReference already usedUse a globally unique orderReference per invoice
XSD-000010 schema validation failureRequired field missing or wrong formatCheck required fields — buyerVatNumber, unitPrice, vatRate
PDF download returns 404Invoice not yet clearedWait for status to become cleared before fetching PDF

Submit an Order

Submit order details. We build, sign, and submit the ZATCA invoice automatically.

POST/v1/orders
json
{
  "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
    }
  ]
}
json
{
  "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.

POST/invoices/{invoiceId}/credit-note

Full 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.

bash
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"
  }'
json
{
  "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.
Retry only after a failed submission. Use the credit note's own ID—not the original invoice ID—with POST /invoices/{creditNoteId}/retry

Invoice 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.

Live invoice type previewPOST /v1/orders
Select invoice type

Standard invoice — cleared by ZATCA in real-time before the invoice is shared with the buyer.

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.

json
{
  "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 }]
}
FeatureB2B (Standard)B2C (Simplified)
ZATCA ProcessingCleared in real-time before deliveryReported automatically within 24 hours
API ResponseSynchronous — waits for ZATCA clearance (~1–2 s)Immediate — local ID returned instantly
Buyer VAT FieldsRequired (VAT number, name, address)Not required
invoiceType field"invoiceType": "standard""invoiceType": "simplified"
Typical use caseBusiness-to-business sales, ERP orders, wholesaleRetail, 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.

FieldTypeB2BNotes
orderReferencestringRequiredMust be globally unique per merchant
invoiceTypeenumOptional"standard" or "simplified". Auto-set when buyerVatNumber is present.
paymentMeansenumOptional10=Cash, 48=Card, 30=Bank transfer, 42=Bank account. Defaults to Cash.
buyerNamestringRequiredLegal name of the buying entity
buyerVatNumberstringRequired15 digits, starting and ending with 3 (e.g. 310122393500003)
buyerStreetstringRecommendedStreet name — included in UBL XML
buyerBuildingNumberstringRecommendedBuilding number — included in UBL XML
buyerDistrictstringRecommendedDistrict or neighbourhood
buyerCitystringRequiredCity name — required by ZATCA for clearance
buyerPostalCodestringRecommended5-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.

POST/v1/webhooks/orders
json
{
  "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.

GET/invoices/:id/pdf
http
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Disposition: attachment; filename="invoice_inv_8f7d6e5c.pdf"
Content-Length: 48291

Error Codes

ZATCA returns structured rejection codes. Common codes and how to fix them:

CodeMeaningFix
BV-000001Duplicate invoice referenceUse a unique orderReference per invoice
BV-000002Missing buyer VAT numberAdd buyerVatNumber for B2B invoices
BV-000003Invalid VAT number formatMust be 15 digits starting with 3
BV-000004Invoice date in the futureUse current UTC timestamp for invoiceDate
XSD-000010XML schema validation failedCheck required fields; review Issues dashboard
CSID-EXPCSID certificate expiredRenew CSID from Dashboard → Onboarding

Rate Limits

The API enforces per-key rate limits. Exceeding limits returns HTTP 429 with a Retry-After header.

PlanRequests / minInvoices / year
Trial6010,000
ProfessionalPopular30010,000+
EnterpriseCustomUnlimited

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.

Free · No sign-up

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.

Open the tool →

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.

bash
npm install saudivatpro-qrtool
typescript
import { 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);
FunctionWhat it doesReturns
encodeTlvPhaseOne(fields)Builds a ZATCA Phase 1 TLV payload from the 5 mandatory fields and returns a base64 stringstring (base64)
decodeTlv(base64)Parses a Phase 1 or Phase 2 base64 QR string into structured fields with labels and raw valuesParsedQR
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

New

WooCommerce 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.

bash
npm install saudivatpro-ecommerce-sdk
typescript
import { 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
MethodWhat 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

New

Saudi 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.1

Published on npm as saudi-vat-pro-mcp

View on npm

Run without installing globally

bash
npx -y saudi-vat-pro-mcp
View source on GitHubRegistry ID: io.github.Morouna1/saudi-vat-pro

Claude Desktop setup

Add this to your claude_desktop_config.json (~/Library/Application Support/Claude/ on macOS, %APPDATA%\Claude\ on Windows):

json
{
  "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_status before 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 idempotencyKey when retrying one credit-note request so a network retry cannot create a duplicate refund.

Example conversation

Create a ZATCA invoice for Acme Trading Co, VAT 310000000000006, Riyadh. 1,500 SAR consulting fee at 15% VAT.
You
AI
Invoice created and cleared by ZATCA ✓ Invoice: INV-2026-0142 · Total: 1,725.00 SAR · VAT: 225.00 SAR Status: cleared · ZATCA UUID: 8fb21b4a-…
Issue a full credit note against that invoice — the client cancelled.
You
AI
Credit note issued and cleared ✓ CN-2026-0143 · Refund: 1,725.00 SAR · Reason: Order Cancellation

Available tools

ToolDescriptionKey inputs
list_invoicesList invoices with optional filtersstatus, invoiceType, search, page
get_invoiceFull detail with line items, ZATCA status, and event timelineid
create_invoiceCreate an invoice and run the available ZATCA pipeline; always inspect the returned statusinvoiceType, lines, buyer…
create_credit_noteIssue an idempotent full or partial credit note within the refundable balanceinvoiceId, idempotencyKey, lines?
retry_invoiceRe-run the ZATCA pipeline for a failed invoiceid
explain_invoice_errorAI explanation of why an invoice failed with suggested fixesid
get_zatca_statusZATCA certificate (CSID) enrollment state and readinessnone
get_merchant_profileBusiness profile, VAT number, and default settingsnone
get_dashboard_summaryCompliance health summary with invoice counts and VAT totalsnone

Get your API key from Settings → API Keys. Full parameter reference and setup instructions are in the GitHub repository.