# inquireInvoice

## Overview

The `inquireInvoice` command retrieves information about previously generated invoices from the EZcount system. This command allows merchants to fetch invoice data, download links, and status information for invoices created through the platform.

{% hint style="info" %}
**Polling Endpoint**: This is essentially a polling endpoint that checks the status of invoice generation. Use it to monitor the progress of invoice creation, especially when invoices are generated asynchronously. It functions as a long-poll endpoint for tracking invoice completion status.
{% endhint %}

## Use cases

Use `inquireInvoice` when you need to:

* Retrieve the download link for a previously generated invoice
* Check the status of an invoice created through `addCgInvoice`
* Access invoice metadata such as invoice number and generation date
* Obtain a merchant copy of the original customer invoice
* Verify invoice details for reconciliation purposes

## Request structure

{% hint style="info" %}
For general API request structure and authentication, see [API Request & Response General Structure](/enterprise/introduction/request-and-response-general-structure.md).
{% endhint %}

The `inquireInvoice` command uses the following endpoint:

**POST** `https://your-hyp-environment-url/xpo/Relay`

### HTTP request format

The request must be sent as a POST request with `application/x-www-form-urlencoded` content type, containing three required body parameters:

| Parameter    | Type   | Description                                                             |
| ------------ | ------ | ----------------------------------------------------------------------- |
| **user**     | string | Your merchant username for API authentication                           |
| **password** | string | Your merchant password for API authentication                           |
| **int\_in**  | string | XML payload containing the command and parameters (see structure below) |

### XML request structure

```xml
<ashrait>
    <request>
        <version>2000</version>
        <language>ENG</language>
        <command>inquireInvoice</command>
        <terminalNumber>{{terminal}}</terminalNumber>
        <inquireInvoice>
            <invoice>
                <invoiceAtranId>119427572</invoiceAtranId>
            </invoice>
        </inquireInvoice>
    </request>
</ashrait>
```

## Required parameters

<details>

<summary><strong>terminalNumber</strong> - string</summary>

The terminal number associated with your merchant account.

</details>

<details>

<summary><strong>invoiceAtranId</strong> - string</summary>

The unique transaction ID returned when the invoice was created. This is the preferred and most reliable method for invoice identification.

**Example**: `119427572`

</details>

## Response structure

### Success response example

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>inquireInvoice</command>
        <dateTime>2025-08-27 09:15</dateTime>
        <requestId />
        <tranId>119717831</tranId>
        <result>000</result>
        <message>Permitted transaction</message>
        <userMessage>Permitted transaction</userMessage>
        <additionalInfo />
        <version>2000</version>
        <language>Eng</language>
        <inquireInvoice>
            <status>000</status>
            <statusText>Permitted transaction</statusText>
            <originalInvoice>
                <invoiceCreationMethod>wait</invoiceCreationMethod>
                <invoiceResponseCode>100</invoiceResponseCode>
                <invoiceResponseName>Proper Invoice Request</invoiceResponseName>
                <invoiceDocNumber>146655</invoiceDocNumber>
                <invoiceDocUrl>https://demo.ezcount.co.il/front/documents/get/b765564e-9ad7-4b5a-95b3-d79a9dbd9f21/copy_en</invoiceDocUrl>
                <invoiceAtranId>119717805</invoiceAtranId>
                <invoiceCreationDate>2025-08-27 09:15:07</invoiceCreationDate>
                <mailTo>customer@example.com</mailTo>
                <invoiceCreationCode>000</invoiceCreationCode>
                <cancelTransaction>0</cancelTransaction>
            </originalInvoice>
        </inquireInvoice>
    </response>
</ashrait>
```

**Key Fields in Success Response:**

* `invoiceResponseCode`: `100` indicates successful invoice retrieval
* `invoiceResponseName`: "Proper Invoice Request" confirms success
* `invoiceDocNumber`: The invoice number in the EZcount system
* `invoiceDocUrl`: Direct download link for the invoice PDF
* `invoiceCreationCode`: `000` indicates no errors during creation
* `invoiceCreationDate`: When the invoice was generated

### Error response example

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>inquireInvoice</command>
        <dateTime>2025-08-27 09:16</dateTime>
        <requestId />
        <tranId>119717840</tranId>
        <result>000</result>
        <message>Permitted transaction</message>
        <userMessage>Permitted transaction</userMessage>
        <additionalInfo />
        <version>2000</version>
        <language>Eng</language>
        <inquireInvoice>
            <status>000</status>
            <statusText>Permitted transaction</statusText>
            <originalInvoice>
                <invoiceCreationMethod />
                <invoiceResponseCode />
                <invoiceResponseName>Invoice not found</invoiceResponseName>
                <invoiceDocNumber />
                <invoiceDocUrl />
                <invoiceAtranId>119712205</invoiceAtranId>
                <invoiceCreationDate />
                <mailTo />
                <invoiceCreationCode>671</invoiceCreationCode>
                <cancelTransaction />
            </originalInvoice>
        </inquireInvoice>
    </response>
</ashrait>
```

**Key Fields in Error Response:**

* Note that `result` is still `000` (API call succeeded)
* The actual error is in the invoice-specific fields:
  * `invoiceResponseName`: "Invoice not found" describes the error
  * `invoiceCreationCode`: `671` is the specific invoice error code
  * Most fields are empty when the invoice is not found

## Code examples

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

```bash
#!/bin/bash

# Invoice inquiry by invoiceAtranId
curl -X POST https://your-hyp-environment-url/xpo/Relay \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "user=your_username" \
  --data-urlencode "password=your_password" \
  --data-urlencode "int_in=<ashrait>
    <request>
        <command>inquireInvoice</command>
        <terminalNumber>1234567</terminalNumber>
        <inquireInvoice>
            <invoice>
                <invoiceAtranId>119427572</invoiceAtranId>
            </invoice>
        </inquireInvoice>
    </request>
</ashrait>"

```

{% endtab %}

{% tab title="Python" %}

```py
import requests
import xml.etree.ElementTree as ET

def inquire_invoice(username, password, terminal, invoice_atran_id):
    """
    Retrieve invoice information from EZcount system
    """
    # Build XML request
    ashrait = ET.Element("ashrait")
    request = ET.SubElement(ashrait, "request")
    
    ET.SubElement(request, "command").text = "inquireInvoice"
    ET.SubElement(request, "terminalNumber").text = terminal
    
    # Add inquireInvoice section with invoice details
    inquire_invoice = ET.SubElement(request, "inquireInvoice")
    invoice = ET.SubElement(inquire_invoice, "invoice")
    ET.SubElement(invoice, "invoiceAtranId").text = invoice_atran_id
    
    xml_string = ET.tostring(ashrait, encoding='unicode')
    
    # Send request with user/password as separate parameters
    response = requests.post(
        "https://your-hyp-environment-url/xpo/Relay",
        data={
            "user": username,
            "password": password,
            "int_in": xml_string
        },
        headers={
            "Content-Type": "application/x-www-form-urlencoded"
        }
    )
    
    if response.status_code == 200:
        # Parse response
        root = ET.fromstring(response.text)
        result = root.find(".//result").text
        
        if result == "000":
            # Check for invoice-specific errors
            invoice_creation_code = root.find(".//invoiceCreationCode").text
            invoice_response_name = root.find(".//invoiceResponseName").text
            
            if invoice_creation_code in ["000", "100"]:
                invoice_url = root.find(".//invoiceDocUrl").text
                invoice_number = root.find(".//invoiceDocNumber").text
                print(f"Invoice found: {invoice_number}")
                print(f"Download URL: {invoice_url}")
                return {
                    "success": True, 
                    "invoice_url": invoice_url,
                    "invoice_number": invoice_number
                }
            else:
                print(f"Invoice error: {invoice_response_name} (Code: {invoice_creation_code})")
                return {
                    "success": False, 
                    "error": invoice_response_name,
                    "error_code": invoice_creation_code
                }
        else:
            message = root.find(".//message").text
            print(f"Error: {message}")
            return {"success": False, "error": message}
    else:
        return {"success": False, "error": f"HTTP {response.status_code}"}

# Example usage
result = inquire_invoice(
    username="your_username",
    password="your_password", 
    terminal="1234567",
    invoice_atran_id="119427572"
)

```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;

public class InvoiceInquiry {
    
    public static class InvoiceResult {
        public boolean success;
        public String invoiceUrl;
        public String invoiceNumber;
        public String error;
        
        public InvoiceResult(boolean success, String invoiceUrl, String invoiceNumber, String error) {
            this.success = success;
            this.invoiceUrl = invoiceUrl;
            this.invoiceNumber = invoiceNumber;
            this.error = error;
        }
    }
    
    public static InvoiceResult inquireInvoice(String username, String password, String terminal, 
                                              String invoiceAtranId) {
        try {
            // Build XML request
            StringBuilder xml = new StringBuilder();
            xml.append("<ashrait>");
            xml.append("<request>");
            xml.append("<command>inquireInvoice</command>");
            xml.append("<terminalNumber>").append(terminal).append("</terminalNumber>");
            xml.append("<inquireInvoice>");
            xml.append("<invoice>");
            xml.append("<invoiceAtranId>").append(invoiceAtranId).append("</invoiceAtranId>");
            xml.append("</invoice>");
            xml.append("</inquireInvoice>");
            xml.append("</request>");
            xml.append("</ashrait>");
            
            // Send HTTP request with user/password as separate parameters
            URL url = new URL("https://your-hyp-environment-url/xpo/Relay");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setDoOutput(true);
            
            String postData = "user=" + URLEncoder.encode(username, "UTF-8") +
                            "&password=" + URLEncoder.encode(password, "UTF-8") +
                            "&int_in=" + URLEncoder.encode(xml.toString(), "UTF-8");
            
            try (OutputStream os = conn.getOutputStream()) {
                os.write(postData.getBytes("UTF-8"));
            }
            
            // Parse response
            if (conn.getResponseCode() == 200) {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(conn.getInputStream());
                
                String result = doc.getElementsByTagName("result").item(0).getTextContent();
                
                if ("000".equals(result)) {
                    // Check for invoice-specific errors
                    String invoiceCreationCode = doc.getElementsByTagName("invoiceCreationCode").item(0).getTextContent();
                    String invoiceResponseName = doc.getElementsByTagName("invoiceResponseName").item(0).getTextContent();
                    
                    if ("000".equals(invoiceCreationCode) || "100".equals(invoiceCreationCode)) {
                        String invoiceUrl = doc.getElementsByTagName("invoiceDocUrl").item(0).getTextContent();
                        String invoiceNumber = doc.getElementsByTagName("invoiceDocNumber").item(0).getTextContent();
                        System.out.println("Invoice found: " + invoiceNumber);
                        System.out.println("Download URL: " + invoiceUrl);
                        return new InvoiceResult(true, invoiceUrl, invoiceNumber, null);
                    } else {
                        System.out.println("Invoice error: " + invoiceResponseName + " (Code: " + invoiceCreationCode + ")");
                        return new InvoiceResult(false, null, null, invoiceResponseName);
                    }
                } else {
                    String message = doc.getElementsByTagName("message").item(0).getTextContent();
                    System.out.println("Error: " + message);
                    return new InvoiceResult(false, null, null, message);
                }
            } else {
                return new InvoiceResult(false, null, null, "HTTP " + conn.getResponseCode());
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return new InvoiceResult(false, null, null, e.getMessage());
        }
    }
    
    public static void main(String[] args) {
        InvoiceResult result = inquireInvoice(
            "your_username",
            "your_password",
            "1234567",
            "119427572"
        );
        
        if (result.success) {
            System.out.println("Success! Invoice URL: " + result.invoiceUrl);
        } else {
            System.out.println("Failed: " + result.error);
        }
    }
}

```

{% endtab %}

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

```js
const https = require('https');
const querystring = require('querystring');
const { DOMParser } = require('xmldom');

function inquireInvoice(username, password, terminal, invoiceAtranId) {
    return new Promise((resolve, reject) => {
        // Build XML request
        let xml = `<ashrait>
    <request>
        <command>inquireInvoice</command>
        <terminalNumber>${terminal}</terminalNumber>
        <inquireInvoice>
            <invoice>
                <invoiceAtranId>${invoiceAtranId}</invoiceAtranId>
            </invoice>
        </inquireInvoice>
    </request>
</ashrait>`;

        // Prepare POST data with user/password as separate parameters
        const postData = querystring.stringify({
            user: username,
            password: password,
            int_in: xml
        });

        // HTTP request options
        const options = {
            hostname: 'cguat2.creditguard.co.il',
            path: '/xpo/Relay',
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(postData)
            }
        };

        // Send request
        const req = https.request(options, (res) => {
            let responseData = '';

            res.on('data', (chunk) => {
                responseData += chunk;
            });

            res.on('end', () => {
                try {
                    // Parse XML response
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(responseData, 'text/xml');
                    
                    const result = doc.getElementsByTagName('result')[0]?.textContent;
                    
                    if (result === '000') {
                        // Check for invoice-specific errors
                        const invoiceCreationCode = doc.getElementsByTagName('invoiceCreationCode')[0]?.textContent;
                        const invoiceResponseName = doc.getElementsByTagName('invoiceResponseName')[0]?.textContent;
                        
                        if (invoiceCreationCode === '000' || invoiceCreationCode === '100') {
                            const invoiceUrl = doc.getElementsByTagName('invoiceDocUrl')[0]?.textContent;
                            const invoiceNumber = doc.getElementsByTagName('invoiceDocNumber')[0]?.textContent;
                            console.log(`Invoice found: ${invoiceNumber}`);
                            console.log(`Download URL: ${invoiceUrl}`);
                            resolve({
                                success: true,
                                invoiceUrl: invoiceUrl,
                                invoiceNumber: invoiceNumber
                            });
                        } else {
                            console.log(`Invoice error: ${invoiceResponseName} (Code: ${invoiceCreationCode})`);
                            resolve({
                                success: false,
                                error: invoiceResponseName,
                                errorCode: invoiceCreationCode
                            });
                        }
                    } else {
                        const message = doc.getElementsByTagName('message')[0]?.textContent;
                        console.log(`Error: ${message}`);
                        resolve({
                            success: false,
                            error: message
                        });
                    }
                } catch (error) {
                    reject(error);
                }
            });
        });

        req.on('error', (error) => {
            reject(error);
        });

        // Send POST data
        req.write(postData);
        req.end();
    });
}

// Example usage
(async () => {
    try {
        const result = await inquireInvoice(
            'your_username',
            'your_password',
            '1234567',
            '119427572'
        );
        
        if (result.success) {
            console.log('Success! Invoice URL:', result.invoiceUrl);
        } else {
            console.log('Failed:', result.error);
        }
    } catch (error) {
        console.error('Error:', error.message);
    }
})();
```

{% endtab %}
{% endtabs %}

## Error codes

### General API error codes

| Code | Description                                                | Solution                                                       |
| ---- | ---------------------------------------------------------- | -------------------------------------------------------------- |
| 000  | Success                                                    | Invoice information retrieved successfully                     |
| 325  | Invalid XML format                                         | Check XML structure and ensure all required fields are present |
| 405  | SSL HTTPS customers are not permitted to access the system | Verify username and password are correct                       |
| 414  | An XML field or an INT\_IN parameter is too short/long     | Check field lengths match API requirements                     |

### Invoice module error codes

**Note**: Invoice-specific errors are returned in the `invoiceResponseCode` and `invoiceResponseName` tags.

#### CG Gateway invoice error codes

| Code | Description                                 | Solution                                            |
| ---- | ------------------------------------------- | --------------------------------------------------- |
| 668  | Cannot Create Invoice                       | Invoice creation failed - check request parameters  |
| 669  | Currency not supported for invoice creation | Only ILS (Israeli Shekel) invoices are supported    |
| 670  | Invoice Validation Failed                   | Check invoice data for invalid values               |
| 671  | Invoice not found                           | Verify the invoice identifier is correct and exists |

#### Invoice vendor response codes

| Code | Description                             | Meaning                                                                                |
| ---- | --------------------------------------- | -------------------------------------------------------------------------------------- |
| 100  | Success                                 | Completed successfully                                                                 |
| 101  | UsernameInvalid                         | Attempted transaction with invalid username                                            |
| 102  | CompanyCodeAlreadyExists                | Attempted to create a company with an existing company code                            |
| 103  | CompanyCodeDoesNotExist                 | Company code does not exist                                                            |
| 104  | CompanyCodeInvalidFormat                | Company code format is not numeric                                                     |
| 105  | DocumentInvalidSubject                  | Subject line is invalid                                                                |
| 106  | DocumentDoesNotExit                     | Document number was not found                                                          |
| 107  | SendEmailAborted                        | E-mailing document failed                                                              |
| 108  | EmailInvalid                            | Invalid e-mail format                                                                  |
| 109  | CultureInvalid                          | Invalid culture                                                                        |
| 110  | KeyInvalid                              | Invalid key                                                                            |
| 111  | AccountExpired                          | Account has expired                                                                    |
| 112  | DocumentInvalidItemNumber               | Multiple items in an invoice are in the wrong format                                   |
| 113  | DocumentInvalidQuantity                 | Quantity format is not numeric                                                         |
| 114  | DocumentInvalidPrice                    | Price format is not numeric                                                            |
| 116  | DocumentDoesNotExistForSpecifiedCompany | The specified document doesn't exist or is incompatible with the company code provided |
| 117  | CurrencyConversionServiceNotAvailable   | Currency conversion service is out of service                                          |
| 118  | InvalidItemCode                         | Unacceptable item code                                                                 |
| 119  | CurrencyInWrongFormat                   | Currency is not an integer                                                             |
| 120  | DocumentMissingItem                     | Quantity, price, description and code must match                                       |
| 121  | DocumentInvalidDateFormatDDMMYY         | Date format must be DDMMYY                                                             |
| 122  | PaymentAmountDoesntMatchInvoice         | Total receivables must be positive                                                     |
| 123  | DocumentAmountInvalid                   | Amount must be double                                                                  |
| 124  | CashInvalidAmount                       | Amount must be double                                                                  |
| 125  | CheckInvalidAmount                      | Amount must be double                                                                  |
| 126  | CCInvalidAmount                         | Amount must be double                                                                  |
| 127  | TransInvalidAmount                      | Amount must be double                                                                  |
| 128  | CheckInvalidDateFormatDDMMYY            | Date format must be DDMMYY                                                             |
| 129  | CCInvalidDateFormatDDMMYY               | Date format must be DDMMYY                                                             |
| 130  | TransInvalidDateFormatDDMMYY            | Date format must be DDMMYY                                                             |
| 131  | PaymentTotalMustBeEqualToInvoiceTotal   | Payment total must be equal to invoice total                                           |
| 132  | TaxRateInTheDocsIsNotEqual              | Tax rate in the docs is not equal                                                      |
| 133  | ClientCompanyNameAlreadyExists          | Client company name already exists                                                     |
| 134  | ClientTicketAlreadyExists               | Client ticket already exists                                                           |

{% hint style="info" %}
**Currency Support**: At this time, only ILS (Israeli Shekel) invoices are supported. Other currencies will be processed but no invoices will be created.
{% endhint %}

{% hint style="info" %}
**Language**: Invoice vendor response messages are always returned in English.
{% endhint %}

## Related commands

* [`addCgInvoice`](/enterprise/api-reference/addcginvoice.md) - Create new invoices
* [`refundCgInvoice`](/enterprise/api-reference/refundcginvoice.md) - Process invoice refunds
* [`doDeal`](/enterprise/api-reference/dodeal.md) - Process payments with automatic invoice generation

## Best practices

1. **Use invoiceAtranId when available** - This is the most reliable identifier for invoice queries
2. **Store invoice identifiers** - Keep track of invoiceAtranId returned from addCgInvoice for future queries
3. **Handle not found errors gracefully** - Invoices may be deleted or expired in the EZcount system
4. **Use for reconciliation** - Regular invoice queries help maintain accurate financial records
5. **Monitor invoice status** - Check invoice status to ensure proper delivery to customers


---

# 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/inquireinvoice.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.
