# cancelDeal

## Overview

The `cancelDeal` command cancels a payment transaction that has not yet been transmitted to Shva (Israel's payment processor). This operation can only be performed on transactions that remain in "Approved, pending transmission" status.

Unlike refunds, cancellations must be for the full transaction amount and can only be performed before the daily transmission to Shva (typically occurring around 11:00 PM). Once transmitted, you must use [`refundDeal`](/enterprise/api-reference/refunddeal.md) instead.

{% hint style="info" %}
**Best Practice**: Prefer `cancelDeal` only when your business logic requires that no refunds are performed. In most cases, use [`refundDeal`](/enterprise/api-reference/refunddeal.md) instead, as it automatically determines whether to cancel or refund based on transmission status.
{% endhint %}

## Use cases

* **Cancel pre-transmission transactions**: Cancel transactions before Shva transmission (typically before 11:00 PM daily cutoff)
* **Two-phase commit cancellations**: Cancel approval (J5) requests in [two-phase commits](/enterprise/two-phase-commits/overview.md)
* **Full-amount reversals**: Only full transaction amounts can be cancelled (partial cancellations not supported)
* **Payment page cancellations**: Handle cancellations from [payment page integration](/enterprise/payment-page-integration/integrating-hyps-payment-page-and-accepting-payment.md)

## 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 `cancelDeal` 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>
        <requestId/>
        <command>cancelDeal</command>
        <cancelDeal>
            <!-- At least one of the following required: tranId, cgUid, or orgUid -->
            <tranId>{transactionId}</tranId>
            <!-- OR <cgUid>{cgIdentifier}</cgUid> -->
            <!-- OR <ashraitEmvData><orgUid>{originalUid}</orgUid></ashraitEmvData> -->
            
            <!-- Optional parameters -->
            <terminalNumber>{terminalNumber}</terminalNumber>
        </cancelDeal>
    </request>
</ashrait>
```

## Required parameters

**At least one of the following three parameters must be provided:**

<details>

<summary><strong>tranId</strong> - Transaction ID</summary>

**Type**: String\
**Required**: At least one lookup parameter required\
**Description**: Unique transaction request ID for a specific transaction step

**Example**: `118374610`

**Usage Notes**:

* When provided, other lookup elements are ignored
* Most specific identifier for a transaction step
* Returned in response from the original transaction

</details>

<details>

<summary><strong>cgUid</strong> - CG identifier</summary>

**Type**: String\
**Required**: At least one lookup parameter required\
**Description**: CG identifier shared across related transactions (e.g., original charge and refunds)

**Example**: `118374610`

**Usage Notes**:

* Links related transactions together
* Useful for tracking transaction chains
* Returned in response from the original transaction

</details>

<details>

<summary><strong>orgUid</strong> - Original UID</summary>

**Type**: String\
**Required**: At least one lookup parameter required\
**Description**: Ashrait protocol unique assigned transaction ID

**Example**:

```xml
<ashraitEmvData>
    <orgUid>25062617340908828192261</orgUid>
</ashraitEmvData>
```

**Usage Notes**:

* Must be wrapped in `ashraitEmvData` element
* Unique identifier from Shva payment processor
* Used for direct transaction reference

</details>

## Optional parameters

<details>

<summary><strong>terminalNumber</strong> - Your merchant terminal identifier</summary>

**Type**: String\
**Required**: No\
**Description**: The unique terminal number assigned during merchant onboarding

**Example**: `0882819014`

**Usage Notes**:

* Must match your assigned terminal number
* Used for transaction lookup and authorization
* Available in your merchant dashboard

</details>

<details>

<summary><strong>user</strong> - User field</summary>

**Type**: String (1–19 characters) **Required**: No\
**Description**: Custom user identifier

**Example**: `customer123`

**Usage Notes**:

* If provided, overrides the value specified in the original transaction
* Useful for merchant-specific tracking
* Free-text field for merchant use

</details>

<details>

<summary><strong>shiftId1, shiftId2, shiftId3</strong> - Shift identifiers for transaction grouping</summary>

**Type**: String\
**Required**: No\
**Description**: Optional shift identifiers for transaction organization and reporting

**Usage Notes**:

* If provided, overrides the value specified in the original transaction
* Used for internal transaction grouping
* Helpful for reconciliation and reporting

</details>

## Response structure

### Successful response

A successful `cancelDeal` response contains transaction details and confirmation of cancellation:

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>cancelDeal</command>
        <dateTime>2025-06-26 20:20</dateTime>
        <requestId/>
        <tranId>118374656</tranId>
        <result>000</result>
        <message>Permitted transaction</message>
        <userMessage>Permitted transaction</userMessage>
        <version>2000</version>
        <language>ENG</language>
        <cancelDeal>
            <status>000</status>
            <statusText>Permitted transaction</statusText>
            <terminalNumber>0882819014</terminalNumber>
            <transactionType code="52">Cancel</transactionType>
            <total>36500</total>
            <cgUid>118374610</cgUid>
            <!-- Additional transaction details -->
        </cancelDeal>
    </response>
</ashrait>
```

**Key Response Fields**:

* `result`: `000` indicates successful cancellation
* `tranId`: New transaction ID for the cancellation
* `transactionType`: Shows `Cancel` (code 52)
* `total`: Amount that was cancelled
* `cgUid`: Links to original transaction

### Error response

Error responses include specific error codes and messages. The response contains many fields, most of which will be empty for error cases. The key fields to focus on are `result`, `message`, `userMessage`, `status`, and `statusText`:

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>cancelDeal</command>
        <dateTime>2025-08-20 10:27</dateTime>
        <requestId />
        <tranId>119576367</tranId>
        <result>312</result>
        <message>There is no transaction found for canceling</message>
        <userMessage>There is no transaction found for canceling</userMessage>
        <additionalInfo />
        <version>2000</version>
        <language>Eng</language>
        <cancelDeal>
            <status>312</status>
            <statusText>There is no transaction found for canceling</statusText>
            <extendedStatus />
            <extendedStatusText />
            <extendedUserMessage />
            <terminalNumber>0882814011</terminalNumber>
            <cardBin />
            <cardMask />
            <cardLength>0</cardLength>
            <cardNo />
            <cardName />
            <cardExpiration />
            <cardType code="" />
            <extendedCardType code="" />
            <creditCompany code="" />
            <cardBrand code="" />
            <cardAcquirer code="" />
            <serviceCode />
            <transactionType code="" />
            <creditType code="" />
            <currency code="" />
            <baseCurrency />
            <baseAmount />
            <transactionCode code="" />
            <total />
            <firstPayment />
            <periodicalPayment />
            <numberOfPayments />
            <clubId />
            <validation code="" />
            <idStatus code="" />
            <cvvStatus code="" />
            <authSource code="" />
            <authNumber />
            <fileNumber />
            <slaveTerminalNumber />
            <slaveTerminalSequence />
            <eci />
            <clientIp />
            <email />
            <cavv code="" />
            <user />
            <addonData />
            <supplierNumber />
            <id />
            <shiftId1 />
            <shiftId2 />
            <shiftId3 />
            <shiftTxnDate />
            <cgUid />
            <cardHash />
            <ashraitEmvData>
                <mti>100</mti>
            </ashraitEmvData>
            <extendedTranCode />
            <sendNotification />
        </cancelDeal>
    </response>
</ashrait>
```

{% hint style="info" %}
**Note**: Error responses include the full structure with many empty fields. Focus on the `result`, `status`, and message fields for error handling.
{% endhint %}

## Code examples

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

```bash
#!/bin/bash

# Example 1: Cancel using tranId
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>
        <requestId/>
        <command>cancelDeal</command>
        <cancelDeal>
            <tranId>118374610</tranId>
        </cancelDeal>
    </request>
</ashrait>
EOF
)"

# Example 2: Cancel using cgUid with optional terminalNumber
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>
        <requestId/>
        <command>cancelDeal</command>
        <cancelDeal>
            <cgUid>118374610</cgUid>
            <terminalNumber>0882819014</terminalNumber>
        </cancelDeal>
    </request>
</ashrait>
EOF
)"
```

{% endtab %}

{% tab title="Java" %}

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

public class CancelDealExample {
    public static void main(String[] args) throws IOException {
        String serverUrl = "https://your-hyp-environment-url/xpo/Relay";
        String username = "your_username";
        String password = "your_password";
        
        String xmlPayload = 
            "<ashrait>" +
                "<request>" +
                    "<version>2000</version>" +
                    "<language>Eng</language>" +
                    "<dateTime/>" +
                    "<requestId/>" +
                    "<command>cancelDeal</command>" +
                    "<cancelDeal>" +
                        "<terminalNumber>0882819014</terminalNumber>" +
                        "<cgUid>118374610</cgUid>" +
                    "</cancelDeal>" +
                "</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);
            }
            System.out.println(response.toString());
        }
    }
}
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
from urllib.parse import urlencode

def cancel_deal(terminal_number, cg_uid):
    """Cancel a transaction using CG identifier"""
    
    server_url = "https://your-hyp-environment-url/xpo/Relay"
    username = "your_username"
    password = "your_password"
    
    xml_payload = f"""
    <ashrait>
        <request>
            <version>2000</version>
            <language>ENG</language>
                <requestId/>
            <command>cancelDeal</command>
            <cancelDeal>
                <terminalNumber>{terminal_number}</terminalNumber>
                <cgUid>{cg_uid}</cgUid>
            </cancelDeal>
        </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()
        return response.text
        
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
        return None

# Example usage
if __name__ == "__main__":
    result = cancel_deal("0882819014", "118374610")
    if result:
        print("Cancellation response:")
        print(result)
```

{% endtab %}

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

```javascript
const https = require('https');
const querystring = require('querystring');

function cancelDeal(terminalNumber, cgUid) {
    return new Promise((resolve, reject) => {
        const serverUrl = 'https://your-hyp-environment-url/xpo/Relay';
        const username = 'your_username';
        const password = 'your_password';
        
        const xmlPayload = `
        <ashrait>
            <request>
                <version>2000</version>
                <language>ENG</language>
                        <requestId/>
                <command>cancelDeal</command>
                <cancelDeal>
                    <terminalNumber>${terminalNumber}</terminalNumber>
                    <cgUid>${cgUid}</cgUid>
                </cancelDeal>
            </request>
        </ashrait>
        `;
        
        // Prepare POST data
        const postData = querystring.stringify({
            user: username,
            password: password,
            int_in: xmlPayload.trim()
        });
        
        const options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(postData)
            }
        };
        
        const req = https.request(serverUrl, options, (res) => {
            let responseData = '';
            
            res.on('data', (chunk) => {
                responseData += chunk;
            });
            
            res.on('end', () => {
                if (res.statusCode === 200) {
                    resolve(responseData);
                } else {
                    reject(new Error(`HTTP ${res.statusCode}: ${responseData}`));
                }
            });
        });
        
        req.on('error', (error) => {
            reject(error);
        });
        
        req.write(postData);
        req.end();
    });
}

// Example usage
async function example() {
    try {
        const result = await cancelDeal('0882819014', '118374610');
        console.log('Cancellation response:');
        console.log(result);
    } catch (error) {
        console.error('Cancellation failed:', error.message);
    }
}

example();
```

{% endtab %}
{% endtabs %}

## Error codes

| Error Code | Description                              | Resolution                                                                            |
| ---------- | ---------------------------------------- | ------------------------------------------------------------------------------------- |
| **310**    | No debit deal matches the credit deal    | Verify lookup parameters match an existing transaction                                |
| **312**    | No transaction found for canceling       | Check transaction ID and lookup criteria                                              |
| **313**    | Transaction has already been transmitted | Use `refundDeal` instead for transmitted transactions                                 |
| **314**    | Transaction has already been canceled    | Transaction was previously cancelled successfully                                     |
| **317**    | Missing required parameters              | Ensure at least one lookup element is provided                                        |
| **319**    | Terminal not permitted to cancel         | [Contact support](mailto:cg-support@hyp.co.il) to enable cancellation permissions     |
| **320**    | Credit transaction already performed     | Cannot cancel transactions that already have credits                                  |
| **332**    | Multiple transactions found              | Use more specific lookup criteria or enable "Block multiple matches" terminal setting |

## Related commands

* [**`refundDeal`**](/enterprise/api-reference/refunddeal.md) - Refund transmitted transactions (automatically falls back to cancel when appropriate)
* [**`doDeal`**](/enterprise/api-reference/dodeal.md) - Process initial payment transactions
* [**Request Structure**](/enterprise/introduction/request-and-response-general-structure.md) - General API request format
* [**Refunds & Cancellations**](/enterprise/additional-payment-scenarios/refunds-and-cancellations.md) - Detailed guide on when to use each operation


---

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