# addCgInvoice

## Overview

The `addCgInvoice` command generates an invoice or receipt for an existing transaction that has been processed through the Hyp platform. This command integrates with the EZcount invoicing system to create legally compliant invoices for Israeli tax purposes, including proper VAT handling, discount management, and itemized billing.

Invoice generation is crucial for businesses that need to provide customers with official documentation for their transactions, enabling proper accounting, tax compliance, and professional customer communication. The invoice can be delivered via email, SMS, or accessed through a generated URL.

## Use cases

* **Post-transaction invoice generation**: Create invoices after successful payment transactions (see [Issuing Invoices](/enterprise/documents-and-invoicing/issuing-invoices.md))
* **Receipt issuance**: Generate official receipts for completed payments for tax compliance
* **Multi-item invoicing**: Create detailed invoices with multiple line items, descriptions, and prices
* **VAT/tax documentation**: Properly handle Israeli VAT requirements and other tax considerations
* **Discount documentation**: Document discounts and promotional pricing in official invoices
* **Customer communication**: Send invoice links to customers via email or SMS automatically
* **Accounting integration**: Generate invoices that integrate with business accounting systems
* **Retroactive invoice creation**: Issue invoices for past transactions

## Request structure

For a comprehensive overview of the API request format and authentication, see [API Request & Response General Structure](/enterprise/introduction/request-and-response-general-structure.md).

Send a standard Hyp API request to your assigned server endpoint with the `addCgInvoice` command in the `int_in` parameter.

{% hint style="success" %}
**Server Endpoints**: Use the server endpoint provided during merchant onboarding (e.g., `https://your-hyp-environment-url/xpo/Relay`).
{% endhint %}

### XML payload structure

```xml
<ashrait>
    <request>
        <version>2000</version>
        <language>Eng</language>
        <command>addCgInvoice</command>
        <requestId/>
        <addCgInvoice>
            <invoiceAtranId>{transactionId}</invoiceAtranId>
            <invoice>
                <invoiceCreationMethod>wait</invoiceCreationMethod>
                <invoiceDate/>
                <invoiceSubject>Invoice Subject</invoiceSubject>
                <invoiceDiscount/>
                <invoiceDiscountRate/>
                <invoiceItemCode>11010</invoiceItemCode>
                <invoiceItemDescription>Product or Service Description</invoiceItemDescription>
                <invoiceItemQuantity>1</invoiceItemQuantity>
                <invoiceItemPrice>10000</invoiceItemPrice>
                <invoiceTaxRate/>
                <invoiceComments/>
                <companyInfo>Customer Name</companyInfo>
                <sendMail>1</sendMail>
                <mailTo>customer@example.com</mailTo>
                <isItemPriceWithTax>1</isItemPriceWithTax>
                <ccDate>2025-01-01</ccDate>
                <invoiceSignature/>
            </invoice>
        </addCgInvoice>
    </request>
</ashrait>
```

## Required parameters

<details>

<summary><strong>invoiceAtranId</strong> - Transaction identifier for invoice</summary>

**Type**: String (Numeric)\
**Required**: Yes\
**Description**: The transaction ID (tranId) of the payment transaction for which to generate an invoice

**Example**: `123456789`

**Usage Notes**:

* Must reference a valid, completed transaction
* Transaction must exist in the system
* Can be obtained from transaction response or inquiry

</details>

<details>

<summary><strong>invoice</strong> - Invoice details container</summary>

**Type**: Complex Object\
**Required**: Yes\
**Description**: Container element for all invoice-specific parameters and details

**Contains**: All invoice configuration parameters, items, customer details, and delivery options

</details>

## Invoice parameters (within the `invoice` element)

<details>

<summary><strong>invoiceCreationMethod</strong> - Invoice creation method</summary>

**Type**: String (Enum)\
**Required**: Yes\
**Description**: Specifies how the invoice should be created

**Valid Values**: `post` (asynchronous), `wait` (synchronous)\
**Example**: `wait`

**Usage Notes**:

* `post` - Asynchronous invoice creation with immediate response
* `wait` - Synchronous invoice creation, waits for completion
* Use `wait` for immediate confirmation of invoice creation

</details>

<details>

<summary><strong>invoiceDate</strong> - Invoice date</summary>

**Type**: String (Date, YYYY-MM-DD format)\
**Required**: Yes\
**Description**: The date for the invoice

**Default**: Current date if empty\
**Example**: `2025-01-01`

**Usage Notes**:

* Use YYYY-MM-DD format
* Leave empty to use the current date
* Cannot be a future date

</details>

<details>

<summary><strong>invoiceSubject</strong> - Invoice subject line</summary>

**Type**: String (Alpha Numeric and Space, max 255)\
**Required**: Yes\
**Description**: Subject line or title for the invoice

**Example**: `Monthly Subscription Invoice`

**Usage Notes**:

* Maximum 255 characters
* Supports Hebrew characters
* Appears as the main invoice title

</details>

### Item parameters

<details>

<summary><strong>invoiceItemCode</strong> - Item code (makat)</summary>

**Type**: String (Numeric, max 500)\
**Required**: Yes\
**Description**: Product or service code identifier

**Example**: `11010`

**Usage Notes**:

* Used for inventory tracking
* Maximum 500 characters
* For multiple items, separate with pipe symbol (`|`)

</details>

<details>

<summary><strong>invoiceItemDescription</strong> - Item description</summary>

**Type**: String (Alpha Numeric and Space, max 500)\
**Required**: Yes\
**Description**: Description of the product or service

**Example**: `Premium Monthly Subscription`

**Usage Notes**:

* Clear, customer-friendly descriptions are recommended
* Supports Hebrew characters
* For multiple items, separate with pipe symbol (`|`)
* Maximum 500 characters

</details>

<details>

<summary><strong>invoiceItemQuantity</strong> - Item quantity</summary>

**Type**: String (Numeric, XXX.XX format)\
**Required**: Yes\
**Description**: Number of units for this line item

**Example**: `1`, `3`, `2.5`

**Usage Notes**:

* Supports decimal quantities for partial units
* Must be greater than 0
* For multiple items, separate with pipe symbol (`|`)

</details>

<details>

<summary><strong>invoiceItemPrice</strong> - Unit price in agorot/cents</summary>

**Type**: String (Numeric, max 500)\
**Required**: Yes\
**Description**: Price per unit in currency subunits (agorot for ILS)

**Example**: `10000` (represents 100.00 ILS)

**Usage Notes**:

* Price is per unit before quantity multiplication
* VAT/tax calculated separately if applicable
* For multiple items, separate with pipe symbol (`|`)
* Must match transaction amount validation rules

</details>

<details>

<summary><strong>invoiceItemMaam</strong> - Item VAT indicator</summary>

**Type**: String (Numeric, 0|1)\
**Required**: No\
**Description**: Per-item VAT inclusion indicator

**Valid Values**: `0` (without VAT), `1` (with VAT)\
**Example**: `1`

**Usage Notes**:

* Controls VAT display for individual items
* For multiple items, separate with pipe symbol (`|`)
* Must match the count of other item parameters

</details>

### Multiple items support

Creating invoices with multiple items is supported by using pipe-separated (`|`) values in the following fields:

* `invoiceItemCode`
* `invoiceItemDescription`
* `invoiceItemQuantity`
* `invoiceItemPrice`
* `invoiceItemMaam`

**Example for two items:**

```xml
<invoiceItemCode>11010|551</invoiceItemCode>
<invoiceItemDescription>Product A|Product B</invoiceItemDescription>
<invoiceItemQuantity>2|1</invoiceItemQuantity>
<invoiceItemPrice>5000|3000</invoiceItemPrice>
<invoiceItemMaam>1|0</invoiceItemMaam>
```

**Important**: All item fields must have the same number of pipe-separated values.

## Optional invoice parameters

<details>

<summary><strong>invoiceDiscount</strong> - Invoice discount amount</summary>

**Type**: String (Numeric)\
**Required**: No\
**Description**: Fixed discount amount in agorot/cents

**Default**: `0`\
**Example**: `1000` (represents 10.00 ILS discount)

**Usage Notes**:

* Cannot be used together with `invoiceDiscountRate`
* Applied to total invoice amount
* Reduces taxable amount

</details>

<details>

<summary><strong>invoiceDiscountRate</strong> - Invoice discount percentage</summary>

**Type**: String (Percentage, XXX.XX format)\
**Required**: No\
**Description**: Percentage discount rate

**Default**: `0.00`\
**Example**: `10.00` (represents 10% discount)

**Usage Notes**:

* Cannot be used together with `invoiceDiscount`
* Applied to total invoice amount
* Use decimal format (10.00 for 10%)

</details>

<details>

<summary><strong>invoiceTaxRate</strong> - Tax rate percentage</summary>

**Type**: String (Percentage, XXX.XX format)\
**Required**: No\
**Description**: Tax rate to apply to invoice items

**Example**: `17.00` (represents 17% VAT)

**Usage Notes**:

* Specify as percentage (17.00 for 17%)
* Leave empty to use system default
* 0 for tax-exempt transactions

</details>

<details>

<summary><strong>invoiceComments</strong> - Invoice comments</summary>

**Type**: String (Alpha Numeric and Space, max 255)\
**Required**: No\
**Description**: Additional comments or notes for the invoice

**Example**: `Thank you for your business`

**Usage Notes**:

* Maximum 255 characters
* Supports Hebrew characters
* Appears on the invoice as additional information

</details>

<details>

<summary><strong>companyInfo</strong> - Customer information</summary>

**Type**: String (Alpha Numeric and Space, max 255)\
**Required**: Yes\
**Description**: Customer full details and information

**Example**: `John Smith, ABC Company`

**Usage Notes**:

* Used for invoice addressing
* Supports Hebrew characters
* Maximum 255 characters
* Required for proper invoice generation

</details>

<details>

<summary><strong>sendMail</strong> - Email delivery flag</summary>

**Type**: String (Numeric, 0|1)\
**Required**: No\
**Description**: Whether to automatically send invoice by email

**Valid Values**: `0` (don't send), `1` (send email)\
**Default**: `0`\
**Example**: `1`

**Usage Notes**:

* Requires valid `mailTo` parameter
* Sends an invoice link automatically
* Email template configured in EZcount

</details>

<details>

<summary><strong>mailTo</strong> - Customer email address</summary>

**Type**: String (Email format, max 80 characters)\
**Required**: Yes (when sendMail=1)\
**Description**: Email address for invoice delivery

**Format**: `x@x.x`\
**Example**: `customer@example.com`

**Usage Notes**:

* Must be a valid email format
* Required when `sendMail` is set to 1
* Invoice link will be sent to this address
* Maximum 80 characters

</details>

<details>

<summary><strong>isItemPriceWithTax</strong> - Price includes tax indicator</summary>

**Type**: String (Numeric, 0|1)\
**Required**: Yes\
**Description**: Indicates whether item prices include tax

**Valid Values**: `0` (price without tax), `1` (price with tax)\
**Example**: `1`

**Usage Notes**:

* Affects tax calculation method
* Must be consistent for all items
* Required for proper tax handling

</details>

<details>

<summary><strong>ccDate</strong> - Payment date</summary>

**Type**: String (Date, YYYY-MM-DD format)\
**Required**: Yes\
**Description**: The date when payment was processed

**Example**: `2025-01-01`

**Usage Notes**:

* Use YYYY-MM-DD format
* Should match the transaction date
* Required for invoice generation

</details>

<details>

<summary><strong>invoiceSignature</strong> - Digital signature</summary>

**Type**: String (Binary base 64 data)\
**Required**: No\
**Description**: Digital signature for the invoice

**Usage Notes**:

* Binary base 64 encoded data
* Currently not supported (FFU - For Future Use)
* Leave empty if not used

</details>

<details>

<summary><strong>invoiceType</strong> - Invoice document type</summary>

**Type**: String (Enum)\
**Required**: No\
**Description**: Type of financial document to create

**Valid Values**: `tax`, `taxreceipt`, `receipt`, `receiptdonation`, `order`, `pricequote`, `incomesplitting`, `contributionwithinco`, `invoicetransaction`, `transactionaccount`\
**Default**: Taken from terminal configuration\
**Example**: `tax`

**Usage Notes**:

* Only supported when the invoice vendor is EZcount
* When absent, the type is taken from the configuration
* Choose based on business requirements

</details>

<details>

<summary><strong>DocNotMaam</strong> - Tax field display indicator</summary>

**Type**: String (Numeric, 0|1)\
**Required**: No\
**Description**: Controls whether tax fields are displayed on invoice

**Valid Values**: `1` (tax included), `2` (tax not included)\
**Default**: `1`\
**Example**: `1`

**Usage Notes**:

* Value 1: tax fields included in display
* Value 2: tax fields not included in display
* When DocNotMaam=1, isItemPriceWithTax should be 0
* Default behavior when absent is DocNotMaam=1

</details>

## Response structure

### Successful response

A successful `addCgInvoice` response contains invoice generation details and access information:

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>addCgInvoice</command>
        <dateTime>2025-08-12 13:37</dateTime>
        <requestId />
        <tranId>119427416</tranId>
        <result>000</result>
        <message>Permitted transaction</message>
        <userMessage>Permitted transaction</userMessage>
        <additionalInfo />
        <version>2000</version>
        <language>Eng</language>
        <addCgInvoice>
            <invoice>
                <invoiceCreationMethod>wait</invoiceCreationMethod>
                <invoiceResponseCode>100</invoiceResponseCode>
                <invoiceResponseName>Proper Invoice Request</invoiceResponseName>
                <invoiceDocNumber>145834</invoiceDocNumber>
                <invoiceDocUrl>https://demo.ezcount.co.il/front/documents/get/e69c25f6-ed52-4490-9c33-5008cd7bb2fb/copy_en</invoiceDocUrl>
                <invoiceAtranId>118569552</invoiceAtranId>
                <invoiceCreationDate>1754995020</invoiceCreationDate>
                <mailTo>customer@example.com</mailTo>
                <invoiceCreationCode>000</invoiceCreationCode>
            </invoice>
        </addCgInvoice>
    </response>
</ashrait>
```

**Key Response Fields**:

* `result`: `000` indicates successful API call
* `invoiceCreationCode`: `000` indicates successful invoice creation
* `invoiceResponseCode`: `100` indicates proper invoice request
* `invoiceDocNumber`: System-generated invoice number
* `invoiceDocUrl`: Direct link to view/download invoice
* `invoiceAtranId`: Transaction ID for which the invoice was created
* `invoiceCreationDate`: Timestamp of invoice creation

### Error response

Error responses include specific error codes and messages:

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>addCgInvoice</command>
        <dateTime>2025-08-12 13:41</dateTime>
        <requestId />
        <tranId>119427569</tranId>
        <result>000</result>
        <message>Permitted transaction</message>
        <userMessage>Permitted transaction</userMessage>
        <additionalInfo />
        <version>2000</version>
        <language>Eng</language>
        <addCgInvoice>
            <invoice>
                <invoiceCreationMethod>wait</invoiceCreationMethod>
                <invoiceResponseCode>670</invoiceResponseCode>
                <invoiceResponseName>Invoice Validation Failed: invoice total does not match transaction total</invoiceResponseName>
                <invoiceDocNumber />
                <invoiceDocUrl />
                <invoiceAtranId>119427567</invoiceAtranId>
                <invoiceCreationDate>1754995297</invoiceCreationDate>
                <mailTo>customer@example.com</mailTo>
                <invoiceCreationCode>670</invoiceCreationCode>
            </invoice>
        </addCgInvoice>
    </response>
</ashrait>
```

## Code examples

{% tabs %}
{% tab title="cURL" %}

```bash
#!/bin/bash

# Create invoice for transaction
curl -X POST https://your-hyp-environment-url/xpo/Relay \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "user=your_username" \
  -d "password=your_password" \
  -d "int_in=$(cat <<'EOF'
<ashrait>
    <request>
        <version>2000</version>
        <language>Eng</language>
        <dateTime/>
        <requestId/>
        <command>addCgInvoice</command>
        <addCgInvoice>
            <terminalNumber>0882819014</terminalNumber>
            <invoiceAtranId>123456789</invoiceAtranId>
            <invoice>
                <createInvoice>1</createInvoice>
                <invoiceType>invoice</invoiceType>
                <customerName>John Smith</customerName>
                <customerEmail>john@example.com</customerEmail>
                <sendEmail>true</sendEmail>
                <language>ENG</language>
                <items>
                    <item>
                        <description>Premium Monthly Subscription</description>
                        <quantity>1</quantity>
                        <price>10000</price>
                    </item>
                </items>
            </invoice>
        </addCgInvoice>
    </request>
</ashrait>
EOF
)"

# Create multi-item invoice with discount
curl -X POST https://your-hyp-environment-url/xpo/Relay \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "user=your_username" \
  -d "password=your_password" \
  -d "int_in=$(cat <<'EOF'
<ashrait>
    <request>
        <version>2000</version>
        <language>Eng</language>
        <dateTime/>
        <requestId/>
        <command>addCgInvoice</command>
        <addCgInvoice>
            <terminalNumber>0882819014</terminalNumber>
            <invoiceAtranId>123456789</invoiceAtranId>
            <invoice>
                <createInvoice>1</createInvoice>
                <invoiceType>invoiceReceipt</invoiceType>
                <customerName>Jane Doe</customerName>
                <customerEmail>jane@example.com</customerEmail>
                <customerPhone>+972501234567</customerPhone>
                <sendEmail>true</sendEmail>
                <sendSms>true</sendSms>
                <items>
                    <item>
                        <description>Product A</description>
                        <quantity>2</quantity>
                        <price>5000</price>
                        <discount>500</discount>
                    </item>
                    <item>
                        <description>Product B</description>
                        <quantity>1</quantity>
                        <price>3000</price>
                    </item>
                </items>
            </invoice>
        </addCgInvoice>
    </request>
</ashrait>
EOF
)"
```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class AddCgInvoiceExample {
    
    public static class InvoiceResult {
        public boolean success;
        public String invoiceNumber;
        public String invoiceUrl;
        public String invoiceId;
        public String totalAmount;
        public String vatAmount;
        public boolean emailSent;
        public boolean smsSent;
        public String error;
    }
    
    public static class InvoiceItem {
        public String description;
        public int quantity;
        public int price;
        public Integer discount;
        
        public InvoiceItem(String description, int quantity, int price) {
            this.description = description;
            this.quantity = quantity;
            this.price = price;
        }
        
        public InvoiceItem withDiscount(int discount) {
            this.discount = discount;
            return this;
        }
    }
    
    public static InvoiceResult createInvoice(String terminalNumber, String transactionId, 
                                            String customerName, String customerEmail,
                                            List<InvoiceItem> items, boolean sendEmail) throws IOException {
        String serverUrl = "https://your-hyp-environment-url/xpo/Relay";
        String username = "your_username";
        String password = "your_password";
        
        InvoiceResult result = new InvoiceResult();
        
        // Build items XML
        StringBuilder itemsXml = new StringBuilder("<items>");
        for (InvoiceItem item : items) {
            itemsXml.append("<item>")
                    .append("<description>").append(item.description).append("</description>")
                    .append("<quantity>").append(item.quantity).append("</quantity>")
                    .append("<price>").append(item.price).append("</price>");
            if (item.discount != null) {
                itemsXml.append("<discount>").append(item.discount).append("</discount>");
            }
            itemsXml.append("</item>");
        }
        itemsXml.append("</items>");
        
        // Build XML payload
        String xmlPayload = 
            "<ashrait>" +
                "<request>" +
                    "<version>2000</version>" +
                    "<language>Eng</language>" +
                    "<dateTime/>" +
                    "<requestId/>" +
                    "<command>addCgInvoice</command>" +
                    "<addCgInvoice>" +
                        "<terminalNumber>" + terminalNumber + "</terminalNumber>" +
                        "<invoiceAtranId>" + transactionId + "</invoiceAtranId>" +
                        "<invoice>" +
                            "<createInvoice>1</createInvoice>" +
                            "<invoiceType>invoice</invoiceType>" +
                            "<customerName>" + customerName + "</customerName>" +
                            "<customerEmail>" + customerEmail + "</customerEmail>" +
                            "<sendEmail>" + sendEmail + "</sendEmail>" +
                            itemsXml.toString() +
                        "</invoice>" +
                    "</addCgInvoice>" +
                "</request>" +
            "</ashrait>";
        
        // Build POST data
        String postData = "user=" + URLEncoder.encode(username, StandardCharsets.UTF_8) +
                         "&password=" + URLEncoder.encode(password, StandardCharsets.UTF_8) +
                         "&int_in=" + URLEncoder.encode(xmlPayload, StandardCharsets.UTF_8);
        
        // Send request
        URL url = new URL(serverUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setDoOutput(true);
        
        try (OutputStream os = connection.getOutputStream()) {
            os.write(postData.getBytes(StandardCharsets.UTF_8));
        }
        
        // Read response
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            
            // Parse response (simplified - use proper XML parser in production)
            String responseText = response.toString();
            if (responseText.contains("<result>000</result>")) {
                result.success = true;
                result.invoiceNumber = extractValue(responseText, "invoiceNumber");
                result.invoiceUrl = extractValue(responseText, "invoiceUrl");
                result.invoiceId = extractValue(responseText, "invoiceId");
                result.totalAmount = extractValue(responseText, "totalAmount");
                result.vatAmount = extractValue(responseText, "vatAmount");
                result.emailSent = responseText.contains("<emailSent>true</emailSent>");
                result.smsSent = responseText.contains("<smsSent>true</smsSent>");
            } else {
                result.success = false;
                result.error = extractValue(responseText, "userMessage");
            }
        }
        
        return result;
    }
    
    private static String extractValue(String xml, String tagName) {
        String startTag = "<" + tagName + ">";
        String endTag = "</" + tagName + ">";
        int start = xml.indexOf(startTag);
        if (start != -1) {
            start += startTag.length();
            int end = xml.indexOf(endTag, start);
            if (end != -1) {
                return xml.substring(start, end);
            }
        }
        return "";
    }
    
    public static void main(String[] args) throws IOException {
        // Create single item invoice
        List<InvoiceItem> items = new ArrayList<>();
        items.add(new InvoiceItem("Premium Monthly Subscription", 1, 10000));
        
        InvoiceResult result = createInvoice("0882819014", "123456789", 
                                           "John Smith", "john@example.com", 
                                           items, true);
        
        if (result.success) {
            System.out.println("Invoice created successfully!");
            System.out.println("Invoice Number: " + result.invoiceNumber);
            System.out.println("Invoice URL: " + result.invoiceUrl);
            System.out.println("Total Amount: " + result.totalAmount);
            System.out.println("VAT Amount: " + result.vatAmount);
            System.out.println("Email Sent: " + result.emailSent);
        } else {
            System.out.println("Invoice creation failed: " + result.error);
        }
        
        // Create multi-item invoice with discount
        List<InvoiceItem> multiItems = new ArrayList<>();
        multiItems.add(new InvoiceItem("Product A", 2, 5000).withDiscount(500));
        multiItems.add(new InvoiceItem("Product B", 1, 3000));
        
        InvoiceResult multiResult = createInvoice("0882819014", "123456790", 
                                                 "Jane Doe", "jane@example.com", 
                                                 multiItems, true);
        
        if (multiResult.success) {
            System.out.println("Multi-item invoice created: " + multiResult.invoiceNumber);
        }
    }
}
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
from urllib.parse import urlencode
from xml.etree import ElementTree as ET
from typing import List, Dict, Optional

class InvoiceItem:
    def __init__(self, description: str, quantity: int, price: int, discount: int = None):
        self.description = description
        self.quantity = quantity
        self.price = price
        self.discount = discount

def create_invoice(terminal_number: str, transaction_id: str, 
                  customer_name: str, customer_email: str,
                  items: List[InvoiceItem], 
                  send_email: bool = False,
                  send_sms: bool = False,
                  customer_phone: str = None,
                  invoice_type: str = "invoice") -> Dict:
    """Create an invoice for a transaction"""
    
    server_url = "https://your-hyp-environment-url/xpo/Relay"
    username = "your_username"
    password = "your_password"
    
    # Build items XML
    items_xml = "<items>"
    for item in items:
        items_xml += f"""
            <item>
                <description>{item.description}</description>
                <quantity>{item.quantity}</quantity>
                <price>{item.price}</price>
                {f'<discount>{item.discount}</discount>' if item.discount else ''}
            </item>
        """
    items_xml += "</items>"
    
    # Build XML payload
    xml_payload = f"""
    <ashrait>
        <request>
            <version>2000</version>
            <language>Eng</language>
            <dateTime/>
            <requestId/>
            <command>addCgInvoice</command>
            <addCgInvoice>
                <terminalNumber>{terminal_number}</terminalNumber>
                <invoiceAtranId>{transaction_id}</invoiceAtranId>
                <invoice>
                    <createInvoice>1</createInvoice>
                    <invoiceType>{invoice_type}</invoiceType>
                    <customerName>{customer_name}</customerName>
                    <customerEmail>{customer_email}</customerEmail>
                    {f'<customerPhone>{customer_phone}</customerPhone>' if customer_phone else ''}
                    <sendEmail>{'true' if send_email else 'false'}</sendEmail>
                    <sendSms>{'true' if send_sms else 'false'}</sendSms>
                    {items_xml}
                </invoice>
            </addCgInvoice>
        </request>
    </ashrait>
    """
    
    # Prepare POST data
    post_data = {
        'user': username,
        'password': password,
        'int_in': xml_payload.strip()
    }
    
    try:
        # Send request
        response = requests.post(
            server_url,
            data=post_data,
            headers={'Content-Type': 'application/x-www-form-urlencoded'},
            timeout=30
        )
        
        response.raise_for_status()
        
        # Parse XML response
        root = ET.fromstring(response.text)
        result_code = root.find('.//result').text
        
        if result_code == '000':
            invoice_data = root.find('.//addCgInvoice')
            
            return {
                'success': True,
                'invoice_number': invoice_data.find('invoiceNumber').text if invoice_data.find('invoiceNumber') is not None else '',
                'invoice_url': invoice_data.find('invoiceUrl').text if invoice_data.find('invoiceUrl') is not None else '',
                'invoice_id': invoice_data.find('invoiceId').text if invoice_data.find('invoiceId') is not None else '',
                'total_amount': invoice_data.find('totalAmount').text if invoice_data.find('totalAmount') is not None else '',
                'vat_amount': invoice_data.find('vatAmount').text if invoice_data.find('vatAmount') is not None else '',
                'email_sent': invoice_data.find('emailSent').text == 'true' if invoice_data.find('emailSent') is not None else False,
                'sms_sent': invoice_data.find('smsSent').text == 'true' if invoice_data.find('smsSent') is not None else False,
                'message': root.find('.//userMessage').text
            }
        else:
            return {
                'success': False,
                'error_code': result_code,
                'error': root.find('.//userMessage').text
            }
            
    except requests.exceptions.RequestException as e:
        return {
            'success': False,
            'error': f"Request failed: {e}"
        }
    except ET.ParseError as e:
        return {
            'success': False,
            'error': f"XML parsing failed: {e}"
        }

# Example usage
if __name__ == "__main__":
    # Create single item invoice
    items = [
        InvoiceItem("Premium Monthly Subscription", 1, 10000)
    ]
    
    result = create_invoice(
        terminal_number="0882819014",
        transaction_id="123456789",
        customer_name="John Smith",
        customer_email="john@example.com",
        items=items,
        send_email=True
    )
    
    if result['success']:
        print("Invoice created successfully!")
        print(f"Invoice Number: {result['invoice_number']}")
        print(f"Invoice URL: {result['invoice_url']}")
        print(f"Total Amount: {result['total_amount']} agorot")
        print(f"VAT Amount: {result['vat_amount']} agorot")
        print(f"Email Sent: {result['email_sent']}")
    else:
        print(f"Invoice creation failed: {result['error']}")
    
    # Create multi-item invoice with discount and SMS
    multi_items = [
        InvoiceItem("Product A", 2, 5000, discount=500),
        InvoiceItem("Product B", 1, 3000),
        InvoiceItem("Service Fee", 1, 1500)
    ]
    
    multi_result = create_invoice(
        terminal_number="0882819014",
        transaction_id="123456790",
        customer_name="Jane Doe",
        customer_email="jane@example.com",
        customer_phone="+972501234567",
        items=multi_items,
        send_email=True,
        send_sms=True,
        invoice_type="invoiceReceipt"
    )
    
    if multi_result['success']:
        print(f"\nMulti-item invoice created: {multi_result['invoice_number']}")
        print(f"Total with discounts: {multi_result['total_amount']} agorot")
    else:
        print(f"Multi-item invoice failed: {multi_result['error']}")
    
    # Create VAT-exempt invoice
    vat_exempt_items = [
        InvoiceItem("Export Service", 1, 20000)
    ]
    
    # Note: VAT exemption would be configured in EZcount settings
    exempt_result = create_invoice(
        terminal_number="0882819014",
        transaction_id="123456791",
        customer_name="International Corp",
        customer_email="intl@example.com",
        items=vat_exempt_items,
        send_email=True
    )
    
    if exempt_result['success']:
        print(f"\nVAT-exempt invoice created: {exempt_result['invoice_number']}")
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const https = require('https');
const querystring = require('querystring');
const { parseStringPromise } = require('xml2js');

class InvoiceItem {
    constructor(description, quantity, price, discount = null) {
        this.description = description;
        this.quantity = quantity;
        this.price = price;
        this.discount = discount;
    }
}

function createInvoice(terminalNumber, transactionId, customerDetails, items, options = {}) {
    return new Promise((resolve, reject) => {
        const serverUrl = 'https://your-hyp-environment-url/xpo/Relay';
        const username = 'your_username';
        const password = 'your_password';
        
        // Build items XML
        let itemsXml = '<items>';
        items.forEach(item => {
            itemsXml += `
                <item>
                    <description>${item.description}</description>
                    <quantity>${item.quantity}</quantity>
                    <price>${item.price}</price>
                    ${item.discount ? `<discount>${item.discount}</discount>` : ''}
                </item>
            `;
        });
        itemsXml += '</items>';
        
        // Build XML payload
        const xmlPayload = `
        <ashrait>
            <request>
                <version>2000</version>
                <language>Eng</language>
                <dateTime/>
                <requestId/>
                <command>addCgInvoice</command>
                <addCgInvoice>
                    <terminalNumber>${terminalNumber}</terminalNumber>
                    <invoiceAtranId>${transactionId}</invoiceAtranId>
                    <invoice>
                        <createInvoice>1</createInvoice>
                        <invoiceType>${options.invoiceType || 'invoice'}</invoiceType>
                        <customerName>${customerDetails.name}</customerName>
                        <customerEmail>${customerDetails.email}</customerEmail>
                        ${customerDetails.phone ? `<customerPhone>${customerDetails.phone}</customerPhone>` : ''}
                        <sendEmail>${options.sendEmail ? 'true' : 'false'}</sendEmail>
                        <sendSms>${options.sendSms ? 'true' : 'false'}</sendSms>
                        ${options.language ? `<language>${options.language}</language>` : ''}
                        ${itemsXml}
                    </invoice>
                </addCgInvoice>
            </request>
        </ashrait>
        `;
        
        // Prepare POST data
        const postData = querystring.stringify({
            user: username,
            password: password,
            int_in: xmlPayload.trim()
        });
        
        const requestOptions = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(postData)
            }
        };
        
        const req = https.request(serverUrl, requestOptions, async (res) => {
            let responseData = '';
            
            res.on('data', (chunk) => {
                responseData += chunk;
            });
            
            res.on('end', async () => {
                try {
                    if (res.statusCode === 200) {
                        // Parse XML response
                        const result = await parseStringPromise(responseData);
                        const response = result.ashrait.response[0];
                        const resultCode = response.result[0];
                        
                        if (resultCode === '000') {
                            const invoiceData = response.addCgInvoice ? response.addCgInvoice[0] : {};
                            
                            resolve({
                                success: true,
                                invoiceNumber: invoiceData.invoiceNumber ? invoiceData.invoiceNumber[0] : '',
                                invoiceUrl: invoiceData.invoiceUrl ? invoiceData.invoiceUrl[0] : '',
                                invoiceId: invoiceData.invoiceId ? invoiceData.invoiceId[0] : '',
                                totalAmount: invoiceData.totalAmount ? invoiceData.totalAmount[0] : '',
                                vatAmount: invoiceData.vatAmount ? invoiceData.vatAmount[0] : '',
                                emailSent: invoiceData.emailSent ? invoiceData.emailSent[0] === 'true' : false,
                                smsSent: invoiceData.smsSent ? invoiceData.smsSent[0] === 'true' : false,
                                message: response.userMessage[0]
                            });
                        } else {
                            resolve({
                                success: false,
                                errorCode: resultCode,
                                error: response.userMessage[0]
                            });
                        }
                    } else {
                        reject(new Error(`HTTP ${res.statusCode}: ${responseData}`));
                    }
                } catch (parseError) {
                    reject(new Error(`XML parsing failed: ${parseError.message}`));
                }
            });
        });
        
        req.on('error', (error) => {
            reject(error);
        });
        
        req.write(postData);
        req.end();
    });
}

// Example usage
async function example() {
    try {
        // Create single item invoice
        const items = [
            new InvoiceItem('Premium Monthly Subscription', 1, 10000)
        ];
        
        const result = await createInvoice(
            '0882819014',
            '123456789',
            {
                name: 'John Smith',
                email: 'john@example.com'
            },
            items,
            {
                sendEmail: true
            }
        );
        
        if (result.success) {
            console.log('Invoice created successfully!');
            console.log(`Invoice Number: ${result.invoiceNumber}`);
            console.log(`Invoice URL: ${result.invoiceUrl}`);
            console.log(`Total Amount: ${result.totalAmount} agorot`);
            console.log(`VAT Amount: ${result.vatAmount} agorot`);
            console.log(`Email Sent: ${result.emailSent}`);
        } else {
            console.log(`Invoice creation failed: ${result.error}`);
        }
        
        // Create multi-item invoice with discount
        const multiItems = [
            new InvoiceItem('Product A', 2, 5000, 500),
            new InvoiceItem('Product B', 1, 3000),
            new InvoiceItem('Service Fee', 1, 1500)
        ];
        
        const multiResult = await createInvoice(
            '0882819014',
            '123456790',
            {
                name: 'Jane Doe',
                email: 'jane@example.com',
                phone: '+972501234567'
            },
            multiItems,
            {
                sendEmail: true,
                sendSms: true,
                invoiceType: 'invoiceReceipt',
                language: 'HEB'
            }
        );
        
        if (multiResult.success) {
            console.log(`\nMulti-item invoice created: ${multiResult.invoiceNumber}`);
            console.log(`Total with discounts: ${multiResult.totalAmount} agorot`);
            console.log(`SMS Sent: ${multiResult.smsSent}`);
        } else {
            console.log(`Multi-item invoice failed: ${multiResult.error}`);
        }
        
    } catch (error) {
        console.error('Operation failed:', error.message);
    }
}

example();
```

{% endtab %}
{% endtabs %}

## Error codes

| Error Code | Description            | Resolution                                                                    |
| ---------- | ---------------------- | ----------------------------------------------------------------------------- |
| **000**    | Success                | Invoice created successfully                                                  |
| **003**    | Invalid merchant       | Verify terminal number and merchant configuration                             |
| **044**    | Invalid terminal       | Check terminal configuration and invoice permissions                          |
| **456**    | Amount mismatch        | Ensure invoice items total matches transaction amount                         |
| **457**    | Transaction not found  | Verify transaction ID exists and belongs to terminal                          |
| **458**    | Invoice already exists | Check if invoice was already created for this transaction                     |
| **459**    | EZcount not configured | Terminal must be configured with EZcount integration                          |
| **099**    | General error          | Check parameters and [contact support](mailto:cg-support@hyp.co.il) if needed |

## Related commands

* [**`doDeal`**](/enterprise/api-reference/dodeal.md) - Process transactions that can later have invoices generated
* [**`inquireInvoice`**](/enterprise/api-reference/inquireinvoice.md) - Query invoice details and status after creation
* [**`refundCgInvoice`**](/enterprise/api-reference/refundcginvoice.md) - Create credit notes for refunds with invoice documentation
* [**Request Structure**](/enterprise/introduction/request-and-response-general-structure.md) - General API request format
* [**Issuing Invoices**](/enterprise/documents-and-invoicing/issuing-invoices.md) - Complete guide to invoice generation

{% hint style="info" %}
**Amount Validation**: The system validates that the sum of all invoice items (after discounts and including VAT) matches the original transaction amount. Ensure your calculations are accurate to avoid rejection.
{% endhint %}

{% hint style="warning" %}
**EZcount Configuration Required**: Before using this command, ensure your terminal is properly configured with EZcount integration. [Contact Hyp support](mailto:cg-support@hyp.co.il) for setup assistance.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developers.hyp.co.il/enterprise/api-reference/addcginvoice.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
