Welcome to the system documentation. Select a topic from the sidebar to learn more.

Quick Start

Get up and running quickly with our step-by-step guides.

Get Started

Video Tutorials

Watch our video tutorials to see the system in action.

Watch Videos

Python Code Samples of Clearing Api - Documentation

About These Samples - Python Implementation

This page demonstrates various ZATCA standard invoice clearing scenarios with ready-to-use JSON samples and Python code to implement each scenario.

Basic Simplified Invoice

A minimal simplified invoice with one standard-rated item (15% VAT).

{
  "UnitId": "TST-C22FF20EFD-DIANA152",
  "InvoiceNo": "STD-000532",
  "DocType": "TAXINVOICE",
  "DocForm": "INVOICE",
  "IssueDate": "2025-08-16",
  "IssueTime": "20:26:00",
  "DocCurrency": "SAR",
  "PaymentMethod": "Cash",
  "CustomerName": "B2B Customer",
  "InvoiceLines": [
    {
      "LineNo": 1,
      "ItemName": "Laptop Dell Precision 7560",
      "Quantity": 1,
      "UnitCode": "NOS",
      "TaxCategory": "S",
      "TaxRate": 15,
      "ItemPrice": 4500,
      "Currency": "SAR"
    }
  ]
}

Python Implementation

import requests
import json
from datetime import datetime

class ZatcaStandardInvoiceClient:
    def __init__(self, base_url, jwt_token):
        self.base_url = base_url
        self.jwt_token = jwt_token
        self.headers = {
            'Authorization': f'Bearer {jwt_token}',
            'Content-Type': 'application/json'
        }

    def clear_invoice(self, invoice_data):
        endpoint = f"{self.base_url}/api/ZatcaIntegration/ClearInvoice"
        response = requests.post(endpoint, json=invoice_data, headers=self.headers)
        response.raise_for_status()
        return response.json()

    def create_basic_invoice(self):
        return {
            "UnitId": "TST-C22FF20EFD-DIANA152",
            "InvoiceNo": "STD-000532",
            "DocType": "TAXINVOICE",
            "DocForm": "INVOICE",
            "IssueDate": datetime.now().strftime("%Y-%m-%d"),
            "IssueTime": datetime.now().strftime("%H:%M:%S"),
            "DocCurrency": "SAR",
            "PaymentMethod": "Cash",
            "CustomerName": "B2B Customer",
            "InvoiceLines": [
                {
                    "LineNo": 1,
                    "ItemName": "Laptop Dell Precision 7560",
                    "Quantity": 1,
                    "UnitCode": "NOS",
                    "TaxCategory": "S",
                    "TaxRate": 15,
                    "ItemPrice": 4500,
                    "Currency": "SAR"
                }
            ]
        }

# Example usage
if __name__ == "__main__":
    BASE_URL = "https://www.pristineinvoice.com"
    JWT_TOKEN = "your_jwt_token_here"
    
    client = ZatcaStandardInvoiceClient(BASE_URL, JWT_TOKEN)
    
    try:
        # Create and send basic invoice
        basic_invoice = client.create_basic_invoice()
        response = client.clear_invoice(basic_invoice)
        
        print("Basic invoice submitted successfully!")
        print(f"UUID: {response.get('Uuid')}")
        print(f"QR Code: {response.get('QrCodeValue')}")
        print(f"ICV: {response.get('Icv')}")
        
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except Exception as err:
        print(f"An error occurred: {err}")

Invoice with Document-Level Allowances - Sample 02

An invoice with document-level discounts and charges applied to the total amount.

{
  "UnitId": "TST-C22FF20EFD-DIANA152",
  "InvoiceNo": "STD-2023-532",
  "DocType": "TAXINVOICE",
  "DocForm": "INVOICE",
  "Note": "Standard invoice with document-level allowances",
  "IssueDate": "2025-08-16",
  "IssueTime": "20:30:00",
  "DocCurrency": "SAR",
  "PaymentMethod": "CreditCard",
  "CustomerName": "B2B Customer",
  "AllowanceCharges": [
    {
      "Type": "ALLOWANCE",
      "Reason": "Corporate Discount",
      "Amount": 200.00,
      "TaxRate": 15.00,
      "TaxCategory": "S"
    },
    {
      "Type": "CHARGE",
      "Reason": "Installation Fee",
      "Amount": 150.00,
      "TaxRate": 15.00,
      "TaxCategory": "S"
    }
  ],
  "InvoiceLines": [
    {
      "LineNo": 1,
      "ItemName": "Workstation PC",
      "Quantity": 3,
      "UnitCode": "NOS",
      "TaxCategory": "S",
      "TaxRate": 15,
      "ItemPrice": 3500,
      "Currency": "SAR"
    }
  ]
}

Python Implementation

class ZatcaStandardInvoiceClient:
    # ... (previous methods remain the same)

    def create_invoice_with_document_allowances(self):
        return {
            "UnitId": "TST-C22FF20EFD-DIANA152",
            "InvoiceNo": "STD-2023-532",
            "DocType": "TAXINVOICE",
            "DocForm": "INVOICE",
            "Note": "Standard invoice with document-level allowances",
            "IssueDate": datetime.now().strftime("%Y-%m-%d"),
            "IssueTime": datetime.now().strftime("%H:%M:%S"),
            "DocCurrency": "SAR",
            "PaymentMethod": "CreditCard",
            "CustomerName": "B2B Customer",
            "AllowanceCharges": [
                {
                    "Type": "ALLOWANCE",
                    "Reason": "Corporate Discount",
                    "Amount": 200.00,
                    "TaxRate": 15.00,
                    "TaxCategory": "S"
                },
                {
                    "Type": "CHARGE",
                    "Reason": "Installation Fee",
                    "Amount": 150.00,
                    "TaxRate": 15.00,
                    "TaxCategory": "S"
                }
            ],
            "InvoiceLines": [
                {
                    "LineNo": 1,
                    "ItemName": "Workstation PC",
                    "Quantity": 3,
                    "UnitCode": "NOS",
                    "TaxCategory": "S",
                    "TaxRate": 15,
                    "ItemPrice": 3500,
                    "Currency": "SAR"
                }
            ]
        }

# Example usage
if __name__ == "__main__":
    client = ZatcaStandardInvoiceClient(BASE_URL, JWT_TOKEN)
    
    try:
        # Create and send invoice with document allowances
        allowance_invoice = client.create_invoice_with_document_allowances()
        response = client.clear_invoice(allowance_invoice)
        
        print("Invoice with document allowances submitted successfully!")
        print(f"Status: {response.get('Status')}")
        print(f"Message: {response.get('Message')}")
        
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
        if http_err.response:
            print(f"Response content: {http_err.response.text}")

Mixed Tax Categories Invoice - Sample 03

An invoice containing items with different tax categories (Standard, Zero-rated, and Exempt).

{
  "UnitId": "TST-C22FF20EFD-DIANA152",
  "InvoiceNo": "STD-2023-523",
  "DocType": "TAXINVOICE",
  "DocForm": "INVOICE",
  "IssueDate": "2025-08-16",
  "IssueTime": "20:35:00",
  "DocCurrency": "SAR",
  "PaymentMethod": "BankTransfer",
  "CustomerName": "B2B Customer",
  "InvoiceLines": [
    {
      "LineNo": 1,
      "ItemName": "IT Consulting Services",
      "Quantity": 40,
      "UnitCode": "HUR",
      "TaxCategory": "S",
      "TaxRate": 15,
      "ItemPrice": 250,
      "Currency": "SAR"
    },
    {
      "LineNo": 2,
      "ItemName": "International Shipping",
      "Quantity": 5,
      "UnitCode": "BOX",
      "TaxCategory": "Z",
      "TaxRate": 0,
      "ItemPrice": 750,
      "Currency": "SAR",
      "VatExemptionCode": "VATEX-SA-34-4",
      "VatExemptionReason": "International transport services"
    },
    {
      "LineNo": 3,
      "ItemName": "Medical Equipment",
      "Quantity": 8,
      "UnitCode": "PCE",
      "TaxCategory": "E",
      "TaxRate": 0,
      "ItemPrice": 1200,
      "Currency": "SAR",
      "VatExemptionCode": "VATEX-SA-MED",
      "VatExemptionReason": "Medical equipment exempt under VAT regulations"
    }
  ]
}

Python Implementation

class ZatcaStandardInvoiceClient:
    # ... (previous methods remain the same)

    def create_mixed_tax_invoice(self):
        return {
            "UnitId": "TST-C22FF20EFD-DIANA152",
            "InvoiceNo": "STD-2023-523",
            "DocType": "TAXINVOICE",
            "DocForm": "INVOICE",
            "IssueDate": datetime.now().strftime("%Y-%m-%d"),
            "IssueTime": datetime.now().strftime("%H:%M:%S"),
            "DocCurrency": "SAR",
            "PaymentMethod": "BankTransfer",
            "CustomerName": "B2B Customer",
            "InvoiceLines": [
                {
                    "LineNo": 1,
                    "ItemName": "IT Consulting Services",
                    "Quantity": 40,
                    "UnitCode": "HUR",
                    "TaxCategory": "S",
                    "TaxRate": 15,
                    "ItemPrice": 250,
                    "Currency": "SAR"
                },
                {
                    "LineNo": 2,
                    "ItemName": "International Shipping",
                    "Quantity": 5,
                    "UnitCode": "BOX",
                    "TaxCategory": "Z",
                    "TaxRate": 0,
                    "ItemPrice": 750,
                    "Currency": "SAR",
                    "VatExemptionCode": "VATEX-SA-34-4",
                    "VatExemptionReason": "International transport services"
                },
                {
                    "LineNo": 3,
                    "ItemName": "Medical Equipment",
                    "Quantity": 8,
                    "UnitCode": "PCE",
                    "TaxCategory": "E",
                    "TaxRate": 0,
                    "ItemPrice": 1200,
                    "Currency": "SAR",
                    "VatExemptionCode": "VATEX-SA-MED",
                    "VatExemptionReason": "Medical equipment exempt under VAT regulations"
                }
            ]
        }

# Example usage
if __name__ == "__main__":
    client = ZatcaStandardInvoiceClient(BASE_URL, JWT_TOKEN)
    
    try:
        # Create and send mixed tax invoice
        mixed_tax_invoice = client.create_mixed_tax_invoice()
        response = client.clear_invoice(mixed_tax_invoice)
        
        print("Mixed tax invoice submitted successfully!")
        print(f"Hash: {response.get('Hash')}")
        print(f"UUID: {response.get('Uuid')}")
        
    except requests.exceptions.RequestException as req_err:
        print(f"Request failed: {req_err}")
    except json.JSONDecodeError as json_err:
        print(f"Failed to parse response: {json_err}")

Credit Note with Reference - Sample 04

A credit note referencing the original invoice being credited.

{
  "UnitId": "TST-C22FF20EFD-DIANA152",
  "InvoiceNo": "STD-CN-2023-524",
  "DocType": "TAXINVOICE",
  "DocForm": "CREDITNOTE",
  "Note": "Return of defective equipment",
  "IssueDate": "2025-08-16",
  "IssueTime": "20:40:00",
  "DocCurrency": "SAR",
  "PaymentMethod": "Credit",
  "CustomerName": "B2B Customer",
  "PreviousInvoiceRef": "STD-INV-2023-045",
  "InvoiceLines": [
    {
      "LineNo": 1,
      "ItemName": "Defective Server Rack",
      "Quantity": 1,
      "UnitCode": "PCE",
      "TaxCategory": "S",
      "TaxRate": 15,
      "ItemPrice": 8500,
      "Currency": "SAR"
    }
  ]
}

Python Implementation

class ZatcaStandardInvoiceClient:
    # ... (previous methods remain the same)

    def create_credit_note(self):
        return {
            "UnitId": "TST-C22FF20EFD-DIANA152",
            "InvoiceNo": "STD-CN-2023-524",
            "DocType": "TAXINVOICE",
            "DocForm": "CREDITNOTE",
            "Note": "Return of defective equipment",
            "IssueDate": datetime.now().strftime("%Y-%m-%d"),
            "IssueTime": datetime.now().strftime("%H:%M:%S"),
            "DocCurrency": "SAR",
            "PaymentMethod": "Credit",
            "CustomerName": "B2B Customer",
            "PreviousInvoiceRef": "STD-INV-2023-045",
            "InvoiceLines": [
                {
                    "LineNo": 1,
                    "ItemName": "Defective Server Rack",
                    "Quantity": 1,
                    "UnitCode": "PCE",
                    "TaxCategory": "S",
                    "TaxRate": 15,
                    "ItemPrice": 8500,
                    "Currency": "SAR"
                }
            ]
        }

# Example usage
if __name__ == "__main__":
    client = ZatcaStandardInvoiceClient(BASE_URL, JWT_TOKEN)
    
    try:
        # Create and send credit note
        credit_note = client.create_credit_note()
        response = client.clear_invoice(credit_note)
        
        print("Credit note submitted successfully!")
        print(f"Status: {response.get('Status')}")
        print(f"ICV: {response.get('Icv')}")
        
    except Exception as err:
        print(f"Error submitting credit note: {err}")

Debit Note with Reference - Sample 05

A debit note referencing the original invoice being debited.

{
  "UnitId": "TST-C22FF20EFD-DIANA152",
  "InvoiceNo": "STD-DN-2023-525",
  "DocType": "TAXINVOICE",
  "DocForm": "DEBITNOTE",
  "Note": "Additional services rendered",
  "IssueDate": "2025-08-16",
  "IssueTime": "20:45:00",
  "DocCurrency": "SAR",
  "PaymentMethod": "DebitTransfer",
  "CustomerName": "B2B Customer",
  "PreviousInvoiceRef": "STD-INV-2023-045",
  "InvoiceLines": [
    {
      "LineNo": 1,
      "ItemName": "Additional Support Hours",
      "Quantity": 10,
      "UnitCode": "HUR",
      "TaxCategory": "S",
      "TaxRate": 15,
      "ItemPrice": 200,
      "Currency": "SAR"
    }
  ]
}

Python Implementation

class ZatcaStandardInvoiceClient:
    # ... (previous methods remain the same)

    def create_debit_note(self):
        return {
            "UnitId": "TST-C22FF20EFD-DIANA152",
            "InvoiceNo": "STD-DN-2023-525",
            "DocType": "TAXINVOICE",
            "DocForm": "DEBITNOTE",
            "Note": "Additional services rendered",
            "IssueDate": datetime.now().strftime("%Y-%m-%d"),
            "IssueTime": datetime.now().strftime("%H:%M:%S"),
            "DocCurrency": "SAR",
            "PaymentMethod": "DebitTransfer",
            "CustomerName": "B2B Customer",
            "PreviousInvoiceRef": "STD-INV-2023-045",
            "InvoiceLines": [
                {
                    "LineNo": 1,
                    "ItemName": "Additional Support Hours",
                    "Quantity": 10,
                    "UnitCode": "HUR",
                    "TaxCategory": "S",
                    "TaxRate": 15,
                    "ItemPrice": 200,
                    "Currency": "SAR"
                }
            ]
        }

# Example usage
if __name__ == "__main__":
    client = ZatcaStandardInvoiceClient(BASE_URL, JWT_TOKEN)
    
    try:
        # Create and send debit note
        debit_note = client.create_debit_note()
        response = client.clear_invoice(debit_note)
        
        print("Debit note submitted successfully!")
        print(f"QR Code: {response.get('QrCodeValue')}")
        print(f"Message: {response.get('Message')}")
        
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except Exception as err:
        print(f"An error occurred: {err}")

Invoice with Line-Level Allowances - Sample 06

An invoice with discounts applied at the line-item level.

{
  "UnitId": "TST-C22FF20EFD-DIANA152",
  "InvoiceNo": "STD-2023-526",
  "DocType": "TAXINVOICE",
  "DocForm": "INVOICE",
  "IssueDate": "2025-08-16",
  "IssueTime": "20:50:00",
  "DocCurrency": "SAR",
  "PaymentMethod": "Cash",
  "CustomerName": "B2B Customer",
  "InvoiceLines": [
    {
      "LineNo": 1,
      "ItemName": "Conference Table",
      "Quantity": 3,
      "UnitCode": "PCE",
      "TaxCategory": "S",
      "TaxRate": 15,
      "ItemPrice": 1200,
      "Currency": "SAR",
      "AllowanceCharges": [
        {
          "Type": "ALLOWANCE",
          "Reason": "Corporate discount",
          "Amount": 150
        },
        {
          "Type": "ALLOWANCE",
          "Reason": "Early payment discount",
          "Amount": 75
        }
      ]
    }
  ]
}

Python Implementation

class ZatcaStandardInvoiceClient:
    # ... (previous methods remain the same)

    def create_invoice_with_line_allowances(self):
        return {
            "UnitId": "TST-C22FF20EFD-DIANA152",
            "InvoiceNo": "STD-2023-526",
            "DocType": "TAXINVOICE",
            "DocForm": "INVOICE",
            "IssueDate": datetime.now().strftime("%Y-%m-%d"),
            "IssueTime": datetime.now().strftime("%H:%M:%S"),
            "DocCurrency": "SAR",
            "PaymentMethod": "Cash",
            "CustomerName": "B2B Customer",
            "InvoiceLines": [
                {
                    "LineNo": 1,
                    "ItemName": "Conference Table",
                    "Quantity": 3,
                    "UnitCode": "PCE",
                    "TaxCategory": "S",
                    "TaxRate": 15,
                    "ItemPrice": 1200,
                    "Currency": "SAR",
                    "AllowanceCharges": [
                        {
                            "Type": "ALLOWANCE",
                            "Reason": "Corporate discount",
                            "Amount": 150
                        },
                        {
                            "Type": "ALLOWANCE",
                            "Reason": "Early payment discount",
                            "Amount": 75
                        }
                    ]
                }
            ]
        }

# Example usage
if __name__ == "__main__":
    client = ZatcaStandardInvoiceClient(BASE_URL, JWT_TOKEN)
    
    try:
        # Create and send invoice with line allowances
        line_allowance_invoice = client.create_invoice_with_line_allowances()
        response = client.clear_invoice(line_allowance_invoice)
        
        print("Invoice with line allowances submitted successfully!")
        print(f"Status: {response.get('Status')}")
        print(f"Hash: {response.get('Hash')}")
        
    except Exception as err:
        print(f"Error submitting invoice: {err}")

Sample with Full JSON Attributes Set - Sample 07

This sample demonstrates all possible attributes for a comprehensive invoice.

{
  "UnitId": "TST-C22FF20EFD-DIANA152",
  "InvoiceNo": "STD-000101",
  "DocType": "TAXINVOICE",
  "DocForm": "INVOICE",
  "Note": "Corporate customer sale with prepayments",
  "IssueDate": "2025-07-17",
  "IssueTime": "03:06:14",
  "DocCurrency": "SAR",
  "ActualDelivery": "2025-07-17",
  "LatestDelivery": "2025-07-17",
  "PaymentMethod": "BankTransfer",
  "CustomerName": "B2B Customer",
  "PreviousInvoiceRef": "STD-INV-00020",
  "AllowanceCharges": [
    {
      "Type": "ALLOWANCE",
      "Reason": "Annual Contract Discount",
      "Amount": 500.00,
      "TaxRate": 15.00,
      "TaxCategory": "S"
    },
    {
      "Type": "CHARGE",
      "Reason": "Emergency Service Fee",
      "Amount": 300.00,
      "TaxRate": 15.00,
      "TaxCategory": "S"
    }
  ],
  "InvoiceLines": [
    {
      "LineNo": 1,
      "ItemName": "Annual Software License",
      "Quantity": 1,
      "UnitCode": "LIC",
      "TaxCategory": "S",
      "TaxRate": 15,
      "ItemPrice": 15000,
      "Currency": "SAR",
      "BaseQuantity": 1,
      "BaseUnitCode": "LIC",
      "AllowanceCharges": [
        {
          "Type": "ALLOWANCE",
          "Reason": "Multi-year commitment",
          "Amount": 1500
        }
      ]
    },
    {
      "LineNo": 2,
      "ItemName": "Premium Support Package",
      "Quantity": 1,
      "UnitCode": "PKG",
      "TaxCategory": "S",
      "TaxRate": 15,
      "ItemPrice": 5000,
      "Currency": "SAR",
      "BaseQuantity": 1,
      "BaseUnitCode": "PKG"
    }
  ],
  "PrePayments": [
    {
      "Amount": 7500,
      "Quantity": 1,
      "UnitCode": "PCE",
      "ItemName": "Initial Deposit",
      "TaxCategory": "S",
      "Rate": "15",
      "Currency": "SAR",
      "BaseQuantity": 1,
      "BaseUnit": "PCE",
      "PrePaidInvoiceNo": "STD-PP-000454",
      "PrePaidInvoiceIssueDate": "2025-07-10",
      "PrePaidInvoiceIssueTime": "06:08:14"
    }
  ]
}

Python Implementation

class ZatcaStandardInvoiceClient:
    # ... (previous methods remain the same)

    def create_comprehensive_invoice(self):
        return {
            "UnitId": "TST-C22FF20EFD-DIANA152",
            "InvoiceNo": "STD-000101",
            "DocType": "TAXINVOICE",
            "DocForm": "INVOICE",
            "Note": "Corporate customer sale with prepayments",
            "IssueDate": "2025-07-17",
            "IssueTime": "03:06:14",
            "DocCurrency": "SAR",
            "ActualDelivery": "2025-07-17",
            "LatestDelivery": "2025-07-17",
            "PaymentMethod": "BankTransfer",
            "CustomerName": "B2B Customer",
            "PreviousInvoiceRef": "STD-INV-00020",
            "AllowanceCharges": [
                {
                    "Type": "ALLOWANCE",
                    "Reason": "Annual Contract Discount",
                    "Amount": 500.00,
                    "TaxRate": 15.00,
                    "TaxCategory": "S"
                },
                {
                    "Type": "CHARGE",
                    "Reason": "Emergency Service Fee",
                    "Amount": 300.00,
                    "TaxRate": 15.00,
                    "TaxCategory": "S"
                }
            ],
            "InvoiceLines": [
                {
                    "LineNo": 1,
                    "ItemName": "Annual Software License",
                    "Quantity": 1,
                    "UnitCode": "LIC",
                    "TaxCategory": "S",
                    "TaxRate": 15,
                    "ItemPrice": 15000,
                    "Currency": "SAR",
                    "BaseQuantity": 1,
                    "BaseUnitCode": "LIC",
                    "AllowanceCharges": [
                        {
                            "Type": "ALLOWANCE",
                            "Reason": "Multi-year commitment",
                            "Amount": 1500
                        }
                    ]
                },
                {
                    "LineNo": 2,
                    "ItemName": "Premium Support Package",
                    "Quantity": 1,
                    "UnitCode": "PKG",
                    "TaxCategory": "S",
                    "TaxRate": 15,
                    "ItemPrice": 5000,
                    "Currency": "SAR",
                    "BaseQuantity": 1,
                    "BaseUnitCode": "PKG"
                }
            ],
            "PrePayments": [
                {
                    "Amount": 7500,
                    "Quantity": 1,
                    "UnitCode": "PCE",
                    "ItemName": "Initial Deposit",
                    "TaxCategory": "S",
                    "Rate": "15",
                    "Currency": "SAR",
                    "BaseQuantity": 1,
                    "BaseUnit": "PCE",
                    "PrePaidInvoiceNo": "STD-PP-000454",
                    "PrePaidInvoiceIssueDate": "2025-07-10",
                    "PrePaidInvoiceIssueTime": "06:08:14"
                }
            ]
        }

# Example usage
if __name__ == "__main__":
    client = ZatcaStandardInvoiceClient(BASE_URL, JWT_TOKEN)
    
    try:
        # Create and send comprehensive invoice
        comprehensive_invoice = client.create_comprehensive_invoice()
        response = client.clear_invoice(comprehensive_invoice)
        
        print("Comprehensive invoice submitted successfully!")
        print(f"Status: {response.get('Status')}")
        print(f"Message: {response.get('Message')}")
        print(f"UUID: {response.get('Uuid')}")
        print(f"QR Code: {response.get('QrCodeValue')}")
        
    except Exception as err:
        print(f"Error submitting comprehensive invoice: {err}")

Complete Python Client Example

Complete Implementation with All Methods

import requests
import json
from datetime import datetime
from typing import Dict, List, Optional, Union

class ZatcaStandardInvoiceClient:
    """
    A client for interacting with the ZATCA Standard Invoice API.
    
    This client handles the creation and submission of standard invoices to ZATCA's
    e-invoicing system according to Saudi Arabian tax regulations.
    """
    
    def __init__(self, base_url: str, jwt_token: str):
        """
        Initialize the ZATCA API client.
        
        Args:
            base_url: The base URL of the ZATCA API endpoint
            jwt_token: JWT token for authentication
        """
        self.base_url = base_url.rstrip('/')
        self.jwt_token = jwt_token
        self.headers = {
            'Authorization': f'Bearer {jwt_token}',
            'Content-Type': 'application/json'
        }
    
    def clear_invoice(self, invoice_data: Dict) -> Dict:
        """
        Submit a standard invoice to ZATCA for clearance.
        
        Args:
            invoice_data: Dictionary containing the invoice data
            
        Returns:
            Dictionary containing the API response
            
        Raises:
            HTTPError: If the API request fails
            ValueError: If the response cannot be parsed
        """
        endpoint = f"{self.base_url}/api/ZatcaIntegration/ClearInvoice"
        
        try:
            response = requests.post(
                endpoint,
                json=invoice_data,
                headers=self.headers,
                timeout=30  # 30 seconds timeout
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            error_msg = f"API request failed: {str(e)}"
            if hasattr(e, 'response') and e.response is not None:
                error_msg += f"\nResponse status: {e.response.status_code}"
                try:
                    error_details = e.response.json()
                    error_msg += f"\nError details: {json.dumps(error_details, indent=2)}"
                except ValueError:
                    error_msg += f"\nResponse text: {e.response.text}"
            raise requests.exceptions.HTTPError(error_msg) from e
    
    # All the invoice creation methods from previous examples would be included here
    # (create_basic_invoice, create_invoice_with_document_allowances, etc.)
    
    @staticmethod
    def validate_invoice_data(invoice_data: Dict) -> bool:
        """
        Validate the invoice data structure before submission.
        
        Args:
            invoice_data: The invoice data to validate
            
        Returns:
            bool: True if valid, False otherwise
            
        Note: This is a basic validation. Implement more thorough checks as needed.
        """
        required_fields = [
            'UnitId', 'InvoiceNo', 'DocType', 'DocForm', 
            'IssueDate', 'IssueTime', 'DocCurrency', 'PaymentMethod',
            'InvoiceLines'
        ]
        
        for field in required_fields:
            if field not in invoice_data:
                return False
                
        if not isinstance(invoice_data['InvoiceLines'], list) or len(invoice_data['InvoiceLines']) == 0:
            return False
            
        return True

def main():
    """Example usage of the ZATCA Standard Invoice Client."""
    # Configuration - replace with your actual values
    BASE_URL = "https://www.pristineinvoice.com"
    JWT_TOKEN = "your_jwt_token_here"
    
    # Initialize client
    client = ZatcaStandardInvoiceClient(BASE_URL, JWT_TOKEN)
    
    try:
        # Example 1: Basic standard invoice
        print("\nSubmitting basic standard invoice...")
        basic_invoice = client.create_basic_invoice()
        basic_response = client.clear_invoice(basic_invoice)
        print(f"Basic invoice submitted. UUID: {basic_response.get('Uuid')}")
        
        # Example 2: Invoice with document allowances
        print("\nSubmitting invoice with document allowances...")
        allowance_invoice = client.create_invoice_with_document_allowances()
        allowance_response = client.clear_invoice(allowance_invoice)
        print(f"Invoice with allowances submitted. QR Code: {allowance_response.get('QrCodeValue')}")
        
        # Example 3: Mixed tax invoice
        print("\nSubmitting mixed tax invoice...")
        mixed_tax_invoice = client.create_mixed_tax_invoice()
        mixed_tax_response = client.clear_invoice(mixed_tax_invoice)
        print(f"Mixed tax invoice submitted. Hash: {mixed_tax_response.get('Hash')}")
        
        # Example 4: Credit note
        print("\nSubmitting credit note...")
        credit_note = client.create_credit_note()
        credit_response = client.clear_invoice(credit_note)
        print(f"Credit note submitted. ICV: {credit_response.get('Icv')}")
        
        # Example 5: Debit note
        print("\nSubmitting debit note...")
        debit_note = client.create_debit_note()
        debit_response = client.clear_invoice(debit_note)
        print(f"Debit note submitted. Status: {debit_response.get('Status')}")
        
        # Example 6: Invoice with line allowances
        print("\nSubmitting invoice with line allowances...")
        line_allowance_invoice = client.create_invoice_with_line_allowances()
        line_allowance_response = client.clear_invoice(line_allowance_invoice)
        print(f"Invoice with line allowances submitted. Message: {line_allowance_response.get('Message')}")
        
        # Example 7: Comprehensive invoice
        print("\nSubmitting comprehensive invoice...")
        comprehensive_invoice = client.create_comprehensive_invoice()
        comprehensive_response = client.clear_invoice(comprehensive_invoice)
        print(f"Comprehensive invoice submitted. UUID: {comprehensive_response.get('Uuid')}")
        
    except requests.exceptions.HTTPError as http_err:
        print(f"\nHTTP Error occurred: {http_err}")
    except json.JSONDecodeError as json_err:
        print(f"\nJSON parsing error: {json_err}")
    except Exception as err:
        print(f"\nUnexpected error: {err}")

if __name__ == "__main__":
    main()
}