# getSessionId

## getSessionId

### Overview

The `getSessionId` command generates a session identifier that can be used for authentication in subsequent API calls. This command provides an alternative authentication method to username/password credentials, allowing for session-based authentication in integration scenarios where maintaining a session is preferable to sending credentials with every request.

Session IDs are particularly useful for applications that make multiple API calls directly from remote clients like POS (קופה) software. Using a session ID allows a POS device to authenticate with a temporary session while the username and password are safely secured in the POS back-office. Additionally, you can determine the scope of the session by setting specific values for fields like `command`, `validation`, and `transactionType` — limiting what operations the session is permitted to perform.

### Use cases

* **Session-based authentication**: Establish a session for API calls without repeatedly sending username/password. The generated identifier is single-use and valid for 10 minutes. To perform additional actions, a new sessionId request must be made each time.
* **Security enhancement**: Reduce credential exposure by using temporary session tokens. You can also limit the session's scope by restricting it to specific commands, validation types, and transaction types (see [Scope parameters](#scope-parameters)).
* **Application integration**: Integrate with systems that prefer session-based authentication patterns
* **Temporary access**: Provide time-limited access tokens for specific operations
* **Third-party integration**: Enable secure API access for partner systems without sharing permanent credentials

### Request structure

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

Send a standard Hyp API request to your assigned server endpoint with the `getSessionId` 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 %}

\### 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) |

**Example HTTP Request Body:**

```
user=your_username&password=your_password&int_in=%3Cashrait%3E%3Crequest%3E%3Cversion%3E2000%3C%2Fversion%3E...
```

#### XML payload structure

```xml
<ashrait>
    <request>
        <version>2000</version>
        <language>Eng</language>
        <dateTime/>
        <requestId/>
        <command>getSessionId</command>
        <getSessionId>
            <terminalNumber>{terminalNumber}</terminalNumber>
            <scope>
                <scopeCmd>doDeal</scopeCmd>
                <validation>autoComm</validation>
                <transactionType>Credit</transactionType>
            </scope>
        </getSessionId>
    </request>
</ashrait>
```

### Command parameters

#### Required parameters

<details>

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

**Type**: String (Numeric, 10 digits)\
**Required**: Yes\
**Description**: The unique terminal number assigned during merchant onboarding

**Example**: `0882819014`

**Usage Notes**:

* Must match your assigned terminal number
* Used for session identification and authorization scope
* Available in your merchant dashboard
* Session will be associated with this specific terminal

</details>

#### Scope parameters

The `scope` parameter allows you to limit the operations that can be performed using the generated session ID. By defining a scope, you can use child parameters to restrict the session to a specific command, validation method, and/or transaction type. This makes sure that the session token is only used for its intended purpose.

Here's an example of a `scope` block that combines all three descendant parameters to limit the session to a specific transaction profile:

```xml

<ashrait>
    <request>
        <version>2000</version>
        <language>ENG</language>
        <dateTime/>
        <command>getSessionId</command>
        <requestid/>
        <getSessionId>
            <scope>
                <scopeCmd>doDeal</scopeCmd>
                <validation>autoComm</validation>
                <transactionType>Credit</transactionType>
            </scope>
        </getSessionId>
    </request>
</ashrait>
```

<details>

<summary><strong>scopeCmd</strong> - The command permitted for this session</summary>

**Type**: String\
**Required**: No (unless `validation` or `transactionType` is specified)\
**Description**: Specifies the API command that this session identifier is authorized to execute (e.g., `doDeal`).

**Valid Values**: `doDeal`, `addCgInvoice`, `cancelDeal`, `inquireInvoice`, `refundCgInvoice`, `refundDeal`, `transmitInquire`, `transmitTerminal`

**Example**: `doDeal`

**Usage Notes**:

* Limits the session to only perform the specified command
* **Mandatory** if either `validation` or `transactionType` is provided in the scope
* If omitted, the session may be used for any permitted command on the terminal

</details>

<details>

<summary><strong>validation</strong> - The validation method permitted for this session</summary>

**Type**: String\
**Required**: No\
**Description**: Specifies the validation method that must be used when performing a transaction with this session (e.g., `Normal`).

**Valid Values**: `AutoComm`, `Verify`, `Normal`, `Token`, `TxnSetup`, `AutoCommHold`, `AutoCommRelease`

**Example**: `autoComm`

**Usage Notes**:

* Restricts the session to the specified validation type
* If this parameter is specified, you must also specify `scopeCmd`

</details>

<details>

<summary><strong>transactionType</strong> - The transaction type permitted for this session</summary>

**Type**: String\
**Required**: No\
**Description**: Specifies the transaction type that this session identifier is authorized to perform (e.g., `Credit`).

**Valid Values**: `Debit`, `Credit`, `Forced`, `CashBack`, `Cash`, `RecurringDebit`, `BalanceEnquiry`,`Load`, `Discharge`

**Example**: `Credit`

**Usage Notes**:

* Restricts the session to the specified transaction type
* If this parameter is specified, you must also specify `scopeCmd`

</details>

### Response structure

#### Successful response

A successful `getSessionId` response contains the generated session identifier:

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>getSessionId</command>
        <dateTime>2025-08-06 11:07</dateTime>
        <requestId />
        <tranId>119295603</tranId>
        <result>000</result>
        <message>Permitted transaction</message>
        <userMessage>Permitted transaction</userMessage>
        <additionalInfo />
        <version>2000</version>
        <language>Eng</language>
        <getSessionId>
            <sessionId>3e4cb361-0465-44db-9d46-bd393f0e120d</sessionId>
            <sessionExpiration>600</sessionExpiration>
            <sessionReUse>1</sessionReUse>
        </getSessionId>
    </response>
</ashrait>
```

**Key Response Fields**:

* `result`: `000` indicates successful session creation
* `sessionId`: The generated session identifier to use in subsequent API calls (UUID format)
* `sessionExpiration`: Session timeout in seconds (600 = 10 minutes)
* `sessionReUse`: Whether the session can be reused (1 = yes, 0 = no)

#### Error response

Error responses include specific error codes and messages:

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>getSessionId</command>
        <dateTime>2025-08-06 11:22</dateTime>
        <requestId />
        <tranId>119295893</tranId>
        <result>405</result>
        <message>SSL HTTPS customers are not permitted to access the system</message>
        <userMessage>Please contact System Administration</userMessage>
        <additionalInfo>Merchant authentication error!</additionalInfo>
        <version>2000</version>
        <language>Eng</language>
        <getSessionId>
            <sessionId />
            <sessionExpiration />
            <sessionReUse />
        </getSessionId>
    </response>
</ashrait>
```

**Note**: Even in error responses, the `getSessionId` element is included but with empty fields.

### Code examples\`\`\`bash

\#!/bin/bash

## Generate session ID

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' 2000 Eng getSessionId 0882819014 EOF )"

## Example of using session ID in subsequent API call

## Note: Replace sessionId parameter with the actual session ID received above

curl -X POST <https://your-hyp-environment-url/xpo/Relay\\>
-H "Content-Type: application/x-www-form-urlencoded"\
-d "sessionId=a1b2c3d4e5f6789012345abcdef67890"\
-d "int\_in=$(cat <<'EOF' 2000 Eng inquireTransactions 0882819014 customer123 EOF )" `</div><div data-gb-custom-block data-tag="tab" data-title='Java'>`java import java.io.*; import java.net.*; import java.nio.charset.StandardCharsets;

public class GetSessionIdExample {

```
public static class SessionResult {
    public boolean success;
    public String sessionId;
    public String expirationTime;
    public String error;
}

public static SessionResult getSessionId(String terminalNumber) throws IOException {
    String serverUrl = "https://your-hyp-environment-url/xpo/Relay";
    String username = "your_username";
    String password = "your_password";
    
    SessionResult result = new SessionResult();
    
    // Build XML payload
    String xmlPayload = 
        "<ashrait>" +
            "<request>" +
                "<version>2000</version>" +
                "<language>Eng</language>" +
                "<dateTime/>" +
                "<requestId/>" +
                "<command>getSessionId</command>" +
                "<getSessionId>" +
                    "<terminalNumber>" + terminalNumber + "</terminalNumber>" +
                "</getSessionId>" +
            "</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.sessionId = extractValue(responseText, "sessionId");
            result.expirationTime = extractValue(responseText, "expirationTime");
        } else {
            result.success = false;
            result.error = extractValue(responseText, "userMessage");
        }
    }
    
    return result;
}

public static String makeSessionApiCall(String sessionId, String xmlPayload) throws IOException {
    String serverUrl = "https://your-hyp-environment-url/xpo/Relay";
    
    // Build POST data using session ID instead of username/password
    String postData = "sessionId=" + URLEncoder.encode(sessionId, StandardCharsets.UTF_8) +
                     "&int_in=" + URLEncoder.encode(xmlPayload, StandardCharsets.UTF_8);
    
    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));
    }
    
    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(connection.getInputStream()))) {
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        return response.toString();
    }
}

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 {
    // Get session ID
    SessionResult sessionResult = getSessionId("0882819014");
    
    if (sessionResult.success) {
        System.out.println("Session created successfully!");
        System.out.println("Session ID: " + sessionResult.sessionId);
        System.out.println("Expires: " + sessionResult.expirationTime);
        
        // Use session ID for subsequent API call
        String inquiryXml = 
            "<ashrait>" +
                "<request>" +
                    "<version>2000</version>" +
                    "<language>Eng</language>" +
                    "<command>inquireTransactions</command>" +
                    "<inquireTransactions>" +
                        "<terminalNumber>0882819014</terminalNumber>" +
                        "<user>customer123</user>" +
                    "</inquireTransactions>" +
                "</request>" +
            "</ashrait>";
        
        String inquiryResponse = makeSessionApiCall(sessionResult.sessionId, inquiryXml);
        System.out.println("API call with session: " + (inquiryResponse.contains("000") ? "Success" : "Failed"));
    } else {
        System.out.println("Session creation failed: " + sessionResult.error);
    }
}
```

} `</div><div data-gb-custom-block data-tag="tab" data-title='Python'>`python import requests from urllib.parse import urlencode from xml.etree import ElementTree as ET

def get\_session\_id(terminal\_number): """Generate a session ID for API authentication"""

```
server_url = "https://your-hyp-environment-url/xpo/Relay"
username = "your_username"
password = "your_password"

# Build XML payload
xml_payload = f"""
<ashrait>
    <request>
        <version>2000</version>
        <language>Eng</language>
        <dateTime/>
        <requestId/>
        <command>getSessionId</command>
        <getSessionId>
            <terminalNumber>{terminal_number}</terminalNumber>
        </getSessionId>
    </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':
        session_data = root.find('.//getSessionId')
        
        return {
            'success': True,
            'session_id': session_data.find('sessionId').text if session_data.find('sessionId') is not None else '',
            'expiration_time': session_data.find('expirationTime').text if session_data.find('expirationTime') is not None else '',
            '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}"
    }
```

def make\_session\_api\_call(session\_id, xml\_payload): """Make an API call using session ID authentication"""

```
server_url = "https://your-hyp-environment-url/xpo/Relay"

# Prepare POST data using session ID instead of username/password
post_data = {
    'sessionId': session_id,
    'int_in': xml_payload.strip()
}

try:
    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:
    return f"Request failed: {e}"
```

## Example usage

if **name** == "**main**": # Get session ID session\_result = get\_session\_id("0882819014")

```
if session_result['success']:
    print("Session created successfully!")
    print(f"Session ID: {session_result['session_id']}")
    print(f"Expires: {session_result['expiration_time']}")
    
    # Use session ID for subsequent API call
    inquiry_xml = """
    <ashrait>
        <request>
            <version>2000</version>
            <language>Eng</language>
            <command>inquireTransactions</command>
            <inquireTransactions>
                <terminalNumber>0882819014</terminalNumber>
                <user>customer123</user>
            </inquireTransactions>
        </request>
    </ashrait>
    """
    
    inquiry_response = make_session_api_call(session_result['session_id'], inquiry_xml)
    success = '000' in inquiry_response
    print(f"API call with session: {'Success' if success else 'Failed'}")
    
    if not success:
        print(f"Response: {inquiry_response}")
else:
    print(f"Session creation failed: {session_result['error']}")
```

`</div><div data-gb-custom-block data-tag="tab" data-title='Node.js'>`javascript const https = require('https'); const querystring = require('querystring'); const { parseStringPromise } = require('xml2js');

function getSessionId(terminalNumber) { return new Promise((resolve, reject) => { const serverUrl = '<https://your-hyp-environment-url/xpo/Relay>'; const username = 'your\_username'; const password = 'your\_password';

```
    // Build XML payload
    const xmlPayload = `
    <ashrait>
        <request>
            <version>2000</version>
            <language>Eng</language>
            <dateTime/>
            <requestId/>
            <command>getSessionId</command>
            <getSessionId>
                <terminalNumber>${terminalNumber}</terminalNumber>
            </getSessionId>
        </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, 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 sessionData = response.getSessionId ? response.getSessionId[0] : {};
                        
                        resolve({
                            success: true,
                            sessionId: sessionData.sessionId ? sessionData.sessionId[0] : '',
                            expirationTime: sessionData.expirationTime ? sessionData.expirationTime[0] : '',
                            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();
});
```

}

function makeSessionApiCall(sessionId, xmlPayload) { return new Promise((resolve, reject) => { const serverUrl = '<https://your-hyp-environment-url/xpo/Relay>';

```
    // Prepare POST data using session ID instead of username/password
    const postData = querystring.stringify({
        sessionId: sessionId,
        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 { // Get session ID const sessionResult = await getSessionId('0882819014');

```
    if (sessionResult.success) {
        console.log('Session created successfully!');
        console.log(`Session ID: ${sessionResult.sessionId}`);
        console.log(`Expires: ${sessionResult.expirationTime}`);
        
        // Use session ID for subsequent API call
        const inquiryXml = `
        <ashrait>
            <request>
                <version>2000</version>
                <language>Eng</language>
                <command>inquireTransactions</command>
                <inquireTransactions>
                    <terminalNumber>0882819014</terminalNumber>
                    <user>customer123</user>
                </inquireTransactions>
            </request>
        </ashrait>
        `;
        
        const inquiryResponse = await makeSessionApiCall(sessionResult.sessionId, inquiryXml);
        const success = inquiryResponse.includes('000');
        console.log(`API call with session: ${success ? 'Success' : 'Failed'}`);
        
        if (!success) {
            console.log(`Response: ${inquiryResponse}`);
        }
    } else {
        console.log(`Session creation failed: ${sessionResult.error}`);
    }
    
} catch (error) {
    console.error('Operation failed:', error.message);
}
```

}

example();

```</div></div>##

| Error Code | Description | Resolution |
|------------|-------------|------------|
| **000** | Permitted transaction | Session ID generated successfully |
| **303** | Gateway general error | Check request format and [contact support](mailto:cg-support@hyp.co.il) if needed |
| **308** | Gateway general error | System error - retry or [contact support](mailto:cg-support@hyp.co.il) |
| **354** | Gateway general error | Configuration issue - verify gateway settings |
| **405** | SSL HTTPS customers are not permitted to access the system | Authentication failure - verify username and password are correct |
| **444** | Gateway general error | Processing error - check request parameters |
| **455** | Merchant does not support session id | Terminal not configured for session support - [contact support](mailto:cg-support@hyp.co.il) to enable |
| **456** | Merchant session timeout | Session has expired - generate a new session ID |
| **457** | Session id generation failed | Unable to create session - retry or check system status |

## Related commands

- **[`doDeal`](doDeal.md)** - Process transactions using session-based authentication
- **[`transmitTerminal`](transmitTerminal.md)** - Initiate transmissions with session authentication
- **[Request Structure](../introduction/request-and-response-general-structure.md)** - General API request format<div data-gb-custom-block data-tag="hint" data-style='info'>**Session Usage**: Once you have a session ID, use it in place of username/password by sending `sessionId` as a form parameter instead of `user` and `password` parameters.</div><div data-gb-custom-block data-tag="hint" data-style='warning'>**Session Security**: Session IDs should be treated as sensitive credentials. Store them securely and ensure they are not logged or exposed in error messages. Sessions may expire and require renewal.</div>
```


---

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