# refundCgInvoice

## Overview

The `refundCgInvoice` command processes refunds for invoices generated through the EZcount system. This command creates a credit note that cancels or partially refunds the original invoice while maintaining proper tax compliance and audit trails.

## Use cases

Use `refundCgInvoice` when you need to:

* Process full refunds for customer returns or cancellations
* Handle partial refunds for damaged or incomplete orders
* Generate credit notes for tax compliance purposes
* Maintain proper documentation for financial reconciliation
* Reverse invoice charges while preserving audit trails

## Request structure

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

The `refundCgInvoice` 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>refundCgInvoice</command>
        <refundCgInvoice>
            <invoiceAtranId>119443246</invoiceAtranId>
            <invoice>
                <createInvoice>1</createInvoice>
            </invoice>
        </refundCgInvoice>
    </request>
</ashrait>
```

## Required parameters

<details>

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

The unique invoice transaction ID returned from the original addCgInvoice call. This is the identifier for the invoice to be refunded.

**Example**: `119443246`

</details>

<details>

<summary><strong>createInvoice</strong> - string</summary>

Indicates whether to create a credit note for the refund. Set to \`1\` to generate the credit document.

**Valid Values**: `1` (create credit note)

</details>

## Response structure

### Success response

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>refundCgInvoice</command>
        <dateTime>2025-08-13 12:22</dateTime>
        <requestId />
        <tranId>119445298</tranId>
        <result>000</result>
        <message>Permitted transaction</message>
        <userMessage>Permitted transaction</userMessage>
        <additionalInfo />
        <version>2000</version>
        <language>Eng</language>
        <refundCgInvoice>
            <invoice>
                <invoiceCreationMethod>wait</invoiceCreationMethod>
                <invoiceResponseCode>100</invoiceResponseCode>
                <invoiceResponseName>Proper Invoice Request</invoiceResponseName>
                <invoiceDocNumber>23961</invoiceDocNumber>
                <invoiceDocUrl>https://demo.ezcount.co.il/front/documents/get/4acae6f9-e907-472c-8254-792ec0c15a2c/copy_en</invoiceDocUrl>
                <invoiceAtranId>119445264</invoiceAtranId>
                <invoiceCreationDate>1755076924</invoiceCreationDate>
                <mailTo>customer@example.com</mailTo>
                <invoiceCreationCode>000</invoiceCreationCode>
            </invoice>
        </refundCgInvoice>
    </response>
</ashrait>
```

**Key Response Fields**:

* `result`: `000` indicates successful API call
* `invoiceCreationCode`: `000` indicates successful credit note creation
* `invoiceResponseCode`: `100` indicates proper invoice request
* `invoiceDocNumber`: The generated credit note number
* `invoiceDocUrl`: Direct link to view/download the credit note

### Error responses

#### Example 1: No invoice found for source transaction

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>refundCgInvoice</command>
        <dateTime>2025-08-13 12:19</dateTime>
        <requestId />
        <tranId>119445219</tranId>
        <result>000</result>
        <message>Permitted transaction</message>
        <userMessage>Permitted transaction</userMessage>
        <additionalInfo />
        <version>2000</version>
        <language>Eng</language>
        <refundCgInvoice>
            <invoice>
                <invoiceCreationMethod />
                <invoiceResponseCode />
                <invoiceResponseName>No invoice was produced source transaction</invoiceResponseName>
                <invoiceDocNumber />
                <invoiceDocUrl />
                <invoiceAtranId>119443246</invoiceAtranId>
                <invoiceCreationDate>1755076765</invoiceCreationDate>
                <mailTo />
                <invoiceCreationCode>673</invoiceCreationCode>
            </invoice>
        </refundCgInvoice>
    </response>
</ashrait>
```

#### Example 2: Transaction type mismatch

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>refundCgInvoice</command>
        <dateTime>2025-08-13 12:21</dateTime>
        <requestId />
        <tranId>119445266</tranId>
        <result>675</result>
        <message>Deal type does not match invoice type</message>
        <userMessage>Deal type does not match invoice type</userMessage>
        <additionalInfo>RefundCgInvoice command was sent when the transaction type is a debit transaction</additionalInfo>
        <version>2000</version>
        <language>Eng</language>
        <refundCgInvoice>
            <invoice>
                <createInvoice>1</createInvoice>
            </invoice>
        </refundCgInvoice>
    </response>
</ashrait>
```

## Code examples

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

```bash
#!/bin/bash

# Full refund of an invoice
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>
        <version>2000</version>
        <language>ENG</language>
        <command>refundCgInvoice</command>
        <refundCgInvoice>
            <invoiceAtranId>119443246</invoiceAtranId>
            <invoice>
                <createInvoice>1</createInvoice>
            </invoice>
        </refundCgInvoice>
    </request>
</ashrait>"

```

{% endtab %}

{% tab title="Python" %}

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

def refund_invoice(username, password, invoice_atran_id):
    """
    Process a refund for an EZcount invoice
    """
    # Build XML request
    ashrait = ET.Element("ashrait")
    request = ET.SubElement(ashrait, "request")
    
    ET.SubElement(request, "version").text = "2000"
    ET.SubElement(request, "language").text = "ENG"
    ET.SubElement(request, "command").text = "refundCgInvoice"
    
    refund_cg_invoice = ET.SubElement(request, "refundCgInvoice")
    ET.SubElement(refund_cg_invoice, "invoiceAtranId").text = invoice_atran_id
    
    invoice = ET.SubElement(refund_cg_invoice, "invoice")
    ET.SubElement(invoice, "createInvoice").text = "1"
    
    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":
            credit_note_url = root.find(".//creditNoteUrl").text
            credit_note_number = root.find(".//creditNoteNumber").text
            refund_amount = root.find(".//refundAmount").text
            print(f"Refund processed: {refund_amount}")
            print(f"Credit note: {credit_note_number}")
            print(f"Download URL: {credit_note_url}")
            return {
                "success": True,
                "credit_note_url": credit_note_url,
                "credit_note_number": credit_note_number,
                "refund_amount": refund_amount
            }
        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 = refund_invoice(
    username="your_username",
    password="your_password",
    invoice_atran_id="119443246"
)

```

{% 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 InvoiceRefund {
    
    public static class RefundResult {
        public boolean success;
        public String creditNoteUrl;
        public String creditNoteNumber;
        public String refundAmount;
        public String error;
        
        public RefundResult(boolean success, String creditNoteUrl, String creditNoteNumber, 
                          String refundAmount, String error) {
            this.success = success;
            this.creditNoteUrl = creditNoteUrl;
            this.creditNoteNumber = creditNoteNumber;
            this.refundAmount = refundAmount;
            this.error = error;
        }
    }
    
    public static RefundResult refundInvoice(String username, String password, String invoiceAtranId) {
        try {
            // Build XML request
            StringBuilder xml = new StringBuilder();
            xml.append("<ashrait>");
            xml.append("<request>");
            xml.append("<version>2000</version>");
            xml.append("<language>ENG</language>");
            xml.append("<command>refundCgInvoice</command>");
            xml.append("<refundCgInvoice>");
            xml.append("<invoiceAtranId>").append(invoiceAtranId).append("</invoiceAtranId>");
            xml.append("<invoice>");
            xml.append("<createInvoice>1</createInvoice>");
            xml.append("</invoice>");
            xml.append("</refundCgInvoice>");
            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)) {
                    String creditNoteUrl = doc.getElementsByTagName("creditNoteUrl").item(0).getTextContent();
                    String creditNoteNumber = doc.getElementsByTagName("creditNoteNumber").item(0).getTextContent();
                    String refundAmount = doc.getElementsByTagName("refundAmount").item(0).getTextContent();
                    System.out.println("Refund processed: " + refundAmount);
                    System.out.println("Credit note: " + creditNoteNumber);
                    System.out.println("Download URL: " + creditNoteUrl);
                    return new RefundResult(true, creditNoteUrl, creditNoteNumber, refundAmount, null);
                } else {
                    String message = doc.getElementsByTagName("message").item(0).getTextContent();
                    System.out.println("Error: " + message);
                    return new RefundResult(false, null, null, null, message);
                }
            } else {
                return new RefundResult(false, null, null, null, "HTTP " + conn.getResponseCode());
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return new RefundResult(false, null, null, null, e.getMessage());
        }
    }
    
    public static void main(String[] args) {
        RefundResult result = refundInvoice(
            "your_username",
            "your_password",
            "119443246"
        );
        
        if (result.success) {
            System.out.println("Success! Credit note URL: " + result.creditNoteUrl);
        } 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 refundInvoice(username, password, invoiceAtranId) {
    return new Promise((resolve, reject) => {
        // Build XML request
        let xml = `<ashrait>
    <request>
        <version>2000</version>
        <language>ENG</language>
        <command>refundCgInvoice</command>
        <refundCgInvoice>
            <invoiceAtranId>${invoiceAtranId}</invoiceAtranId>
            <invoice>
                <createInvoice>1</createInvoice>
            </invoice>
        </refundCgInvoice>
    </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') {
                        const creditNoteUrl = doc.getElementsByTagName('creditNoteUrl')[0]?.textContent;
                        const creditNoteNumber = doc.getElementsByTagName('creditNoteNumber')[0]?.textContent;
                        const refundAmount = doc.getElementsByTagName('refundAmount')[0]?.textContent;
                        console.log(`Refund processed: ${refundAmount}`);
                        console.log(`Credit note: ${creditNoteNumber}`);
                        console.log(`Download URL: ${creditNoteUrl}`);
                        resolve({
                            success: true,
                            creditNoteUrl: creditNoteUrl,
                            creditNoteNumber: creditNoteNumber,
                            refundAmount: refundAmount
                        });
                    } 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 refundInvoice(
            'your_username',
            'your_password',
            '119443246'
        );
        
        if (result.success) {
            console.log('Success! Credit note URL:', result.creditNoteUrl);
        } else {
            console.log('Failed:', result.error);
        }
    } catch (error) {
        console.error('Error:', error.message);
    }
})();
```

{% endtab %}
{% endtabs %}

## Error codes

{% hint style="info" %}
All invoice-related error codes are returned in the `invoiceResponseCode` and `invoiceResponseName` tags.
{% endhint %}

### CG Gateway invoice error codes

| Code | Description                                 | Solution                                   |
| ---- | ------------------------------------------- | ------------------------------------------ |
| 668  | Cannot Create Invoice                       | Check invoice parameters and retry         |
| 669  | Currency not supported for invoice creation | Verify currency is supported for invoicing |
| 670  | Invoice Validation Failed                   | Check that invoice values are valid        |
| 671  | Invoice not found                           | Verify the invoice identifier is correct   |

### Invoice vendor response codes

| Code | Description                             | Solution                                         |
| ---- | --------------------------------------- | ------------------------------------------------ |
| 100  | Success                                 | Invoice operation completed successfully         |
| 101  | UsernameInvalid                         | Check username for invoice system                |
| 102  | CompanyCodeAlreadyExists                | Company code already exists in system            |
| 103  | CompanyCodeDoesNotExist                 | Verify company code exists                       |
| 104  | CompanyCodeInvalidFormat                | Company code must be numeric                     |
| 105  | DocumentInvalidSubject                  | Subject line is invalid                          |
| 106  | DocumentDoesNotExist                    | Document number was not found                    |
| 107  | SendEmailAborted                        | E-mailing document failed                        |
| 108  | EmailInvalid                            | Check email format                               |
| 109  | CultureInvalid                          | Invalid culture setting                          |
| 110  | KeyInvalid                              | Invalid key provided                             |
| 111  | AccountExpired                          | Account has expired                              |
| 112  | DocumentInvalidItemNumber               | Multiple items in wrong format                   |
| 113  | DocumentInvalidQuantity                 | Quantity must be numeric                         |
| 114  | DocumentInvalidPrice                    | Price must be numeric                            |
| 116  | DocumentDoesNotExistForSpecifiedCompany | Document doesn't exist for company               |
| 117  | CurrencyConversionServiceNotAvailable   | Currency service unavailable                     |
| 118  | InvalidItemCode                         | Unacceptable item code                           |
| 119  | CurrencyInWrongFormat                   | Currency must be 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                       | Cash amount must be double                       |
| 125  | CheckInvalidAmount                      | Check amount must be double                      |
| 126  | CCInvalidAmount                         | Credit card amount must be double                |
| 127  | TransInvalidAmount                      | Transaction amount must be double                |
| 128  | CheckInvalidDateFormatDDMMYY            | Check date format must be DDMMYY                 |
| 129  | CCInvalidDateFormatDDMMYY               | CC date format must be DDMMYY                    |
| 130  | TransInvalidDateFormatDDMMYY            | Transaction date format must be DDMMYY           |
| 131  | PaymentTotalMustBeEqualToInvoiceTotal   | Payment must equal invoice total                 |
| 132  | TaxRateInTheDocsIsNotEqual              | Tax rate mismatch in documents                   |
| 133  | ClientCompanyNameAlreadyExists          | Company name already exists                      |
| 134  | ClientTicketAlreadyExists               | Client ticket already exists                     |

{% hint style="warning" %}
Invoice vendor response messages are always returned in English.
{% endhint %}

## Related commands

* [`addCgInvoice`](/creditguard/api-reference/addcginvoice.md) - Create new invoices
* [`inquireInvoice`](/creditguard/api-reference/inquireinvoice.md) - Query invoice information
* [`refundDeal`](/creditguard/api-reference/refunddeal.md) - Process transaction refunds
* [`doDeal`](/creditguard/api-reference/dodeal.md) - Process payments with automatic invoice generation

## Best practices

1. **Use invoiceAtranId** - This is the most reliable identifier for refund processing
2. **Always create credit notes** - Set createInvoice to 1 to generate proper documentation
3. **Support partial refunds** - Allow customers to refund partial amounts for damaged or incomplete orders
4. **Validate refund amounts** - Ensure refund amounts don't exceed the original invoice total
5. **Store credit note information** - Keep track of credit note numbers and URLs for customer service
6. **Handle tax implications** - Credit notes properly handle VAT and tax reversals for compliance


---

# 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/creditguard/api-reference/refundcginvoice.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.
