# getCardId

## Overview

The `getCardId` command creates a secure card token from card number information. This command enables merchants to tokenize credit card data for secure storage and future use while maintaining PCI DSS compliance by converting sensitive card data into non-sensitive tokens.

## Use cases

Use `getCardId` when you need to:

* Tokenize credit card information for secure storage and future transactions
* Convert card numbers into tokens for recurring payment processing
* Enable saved payment method functionality for customers
* Implement secure card-on-file services
* Reduce PCI DSS compliance scope by storing tokens instead of card numbers

## 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 `getCardId` command uses the following endpoint:

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

### Request parameters

| Parameter | Type   | Description                                              |
| --------- | ------ | -------------------------------------------------------- |
| user      | string | Username for API authentication (body parameter)         |
| password  | string | Password for API authentication (body parameter)         |
| int\_in   | string | XML payload containing the request data (body parameter) |

### XML request structure

```xml
<ashrait>
    <request>
        <version>2000</version>
        <command>getCardId</command>
        <getCardId>
            <terminalNumber>[terminal]</terminalNumber>
            <cardNo>[card_number]</cardNo>
        </getCardId>
    </request>
</ashrait>
```

### Command parameters

#### Required parameters

<details>

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

The terminal number associated with your merchant account.

</details>

<details>

<summary><strong>cardNo</strong> - string</summary>

The credit card number to be tokenized. Should be 8-19 digits without spaces or hyphens.

</details>

## Response structure

### Success response

```xml
<?xml version='1.0'?>

<ashrait>
    <response>
        <command>getCardId</command>
        <dateTime>2025-08-04 14:25</dateTime>
        <requestId />
        <tranId>119252261</tranId>
        <result>000</result>
        <message>Permitted transaction</message>
        <userMessage>Permitted transaction</userMessage>
        <additionalInfo />
        <version>2000</version>
        <language>Eng</language>
        <getCardId>
            <extendedStatus />
            <extendedStatusText />
            <extendedUserMessage />
            <terminalNumber>0882804010</terminalNumber>
            <cardNo>xxxx2312</cardNo>
            <cardExpiration />
            <cardId>1095069824442312</cardId>
            <id />
            <creditCompany code="1">Isracard</creditCompany>
            <cardBrand code="5">Isracard</cardBrand>
            <cardAcquirer code="1">Isracard</cardAcquirer>
            <cardName>Isracard</cardName>
            <cardType code="00" />
            <cardBin>12</cardBin>
            <cardMask>12**2312</cardMask>
            <cardLength>8</cardLength>
            <cardData1 />
            <cardData2 />
            <cardData3 />
            <cardData4 />
            <cardData5 />
        </getCardId>
    </response>
</ashrait>
```

### Error response

```xml
<?xml version='1.0'?>

<ashrait>
    <response>
        <command>getCardId</command>
        <dateTime>2025-08-04 14:31</dateTime>
        <requestId />
        <tranId>119252391</tranId>
        <result>414</result>
        <message>An XML field or an INT_IN parameter is too short/ long</message>
        <userMessage>An XML field or an INT_IN parameter is too short/ long</userMessage>
        <additionalInfo>Invalid field length (7) for field: cardNo, 8-19 (1231212)</additionalInfo>
        <version>2000</version>
        <language>Eng</language>
        <getCardId>
            <extendedStatus />
            <extendedStatusText />
            <extendedUserMessage />
            <terminalNumber>0882804010</terminalNumber>
            <cardExpiration />
            <cardId />
            <id />
            <creditCompany code="" />
            <cardBrand code="" />
            <cardAcquirer code="" />
            <cardName />
            <cardType code="" />
            <cardBin>12</cardBin>
            <cardMask>12*1212</cardMask>
            <cardLength>7</cardLength>
            <cardData1 />
            <cardData2 />
            <cardData3 />
            <cardData4 />
            <cardData5 />
        </getCardId>
    </response>
</ashrait>
```

## Code examples

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

```bash
#!/bin/bash

# Tokenize a credit card for secure storage
XML_PAYLOAD='<ashrait><request><version>2000</version><command>getCardId</command><getCardId><terminalNumber>{{terminal}}</terminalNumber><cardNo>{{cardNo}}</cardNo></getCardId></request></ashrait>'

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=${XML_PAYLOAD}"

```

{% endtab %}

{% tab title="Python" %}

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

def tokenize_card(username, password, terminal, card_number):
    """
    Tokenize credit card information for secure storage
    """
    # Build XML request
    ashrait = ET.Element("ashrait")
    request = ET.SubElement(ashrait, "request")
    
    ET.SubElement(request, "version").text = "2000"
    ET.SubElement(request, "command").text = "getCardId"
    
    get_card_id = ET.SubElement(request, "getCardId")
    ET.SubElement(get_card_id, "terminalNumber").text = terminal
    ET.SubElement(get_card_id, "cardNo").text = card_number
    
    xml_string = ET.tostring(ashrait, encoding='unicode')
    
    # Send request
    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":
            card_id = root.find(".//cardId").text
            masked_card = root.find(".//cardNo").text
            card_brand = root.find(".//cardBrand").text
            print(f"Card tokenized successfully!")
            print(f"Card Token: {card_id}")
            print(f"Masked Number: {masked_card}")
            print(f"Brand: {card_brand}")
            return {
                "success": True,
                "card_token": card_id,
                "masked_number": masked_card,
                "brand": card_brand
            }
        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 = tokenize_card(
    username="your_username",
    password="your_password",
    terminal="1234567",
    card_number="4111111111111111"
)

```

{% 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 CardTokenization {
    
    public static class TokenizationResult {
        public boolean success;
        public String cardToken;
        public String maskedNumber;
        public String brand;
        public String error;
        
        public TokenizationResult(boolean success, String cardToken, String maskedNumber, 
                                String brand, String error) {
            this.success = success;
            this.cardToken = cardToken;
            this.maskedNumber = maskedNumber;
            this.brand = brand;
            this.error = error;
        }
    }
    
    public static TokenizationResult tokenizeCard(String username, String password, String terminal,
                                                String cardNumber) {
        try {
            // Build XML request
            StringBuilder xml = new StringBuilder();
            xml.append("<ashrait>");
            xml.append("<request>");
            xml.append("<version>2000</version>");
            xml.append("<command>getCardId</command>");
            xml.append("<getCardId>");
            xml.append("<terminalNumber>").append(terminal).append("</terminalNumber>");
            xml.append("<cardNo>").append(cardNumber).append("</cardNo>");
            xml.append("</getCardId>");
            xml.append("</request>");
            xml.append("</ashrait>");
            
            // Send HTTP request
            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 cardId = doc.getElementsByTagName("cardId").item(0).getTextContent();
                    String maskedCard = doc.getElementsByTagName("cardNo").item(0).getTextContent();
                    String cardBrand = doc.getElementsByTagName("cardBrand").item(0).getTextContent();
                    System.out.println("Card tokenized successfully!");
                    System.out.println("Card Token: " + cardId);
                    System.out.println("Masked Number: " + maskedCard);
                    System.out.println("Brand: " + cardBrand);
                    return new TokenizationResult(true, cardId, maskedCard, cardBrand, null);
                } else {
                    String message = doc.getElementsByTagName("message").item(0).getTextContent();
                    System.out.println("Error: " + message);
                    return new TokenizationResult(false, null, null, null, message);
                }
            } else {
                return new TokenizationResult(false, null, null, null, "HTTP " + conn.getResponseCode());
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return new TokenizationResult(false, null, null, null, e.getMessage());
        }
    }
    
    public static void main(String[] args) {
        TokenizationResult result = tokenizeCard(
            "your_username",
            "your_password",
            "1234567",
            "4111111111111111"
        );
        
        if (result.success) {
            System.out.println("Success! Card token: " + result.cardToken);
        } 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 tokenizeCard(username, password, terminal, cardNumber) {
    return new Promise((resolve, reject) => {
        // Build XML request
        const xml = `<ashrait>
    <request>
        <version>2000</version>
        <command>getCardId</command>
        <getCardId>
            <terminalNumber>${terminal}</terminalNumber>
            <cardNo>${cardNumber}</cardNo>
        </getCardId>
    </request>
</ashrait>`;

        // Prepare POST data
        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 cardId = doc.getElementsByTagName('cardId')[0]?.textContent;
                        const maskedCard = doc.getElementsByTagName('cardNo')[0]?.textContent;
                        const cardBrand = doc.getElementsByTagName('cardBrand')[0]?.textContent;
                        console.log('Card tokenized successfully!');
                        console.log(`Card Token: ${cardId}`);
                        console.log(`Masked Number: ${maskedCard}`);
                        console.log(`Brand: ${cardBrand}`);
                        resolve({
                            success: true,
                            cardToken: cardId,
                            maskedNumber: maskedCard,
                            brand: cardBrand
                        });
                    } 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 tokenizeCard(
            'your_username',
            'your_password',
            '1234567',
            '4111111111111111'
        );
        
        if (result.success) {
            console.log('Success! Card token:', result.cardToken);
        } else {
            console.log('Failed:', result.error);
        }
    } catch (error) {
        console.error('Error:', error.message);
    }
})();
```

{% endtab %}
{% endtabs %}

## Error codes

| Code | Description                                                | Solution                                                     |
| ---- | ---------------------------------------------------------- | ------------------------------------------------------------ |
| 000  | Success                                                    | Card tokenized successfully                                  |
| 039  | Incorrect control number                                   | Card number value is not valid - check card number           |
| 325  | Invalid XML format                                         | Verify XML structure is properly formatted                   |
| 405  | SSL HTTPS customers are not permitted to access the system | User/password authentication failed                          |
| 414  | An XML field or an INT\_IN parameter is too short/long     | Check field lengths - cardNo should be 8-19 digits           |
| 462  | Wrong value in header                                      | Terminal number is incorrect - verify terminal configuration |

## Related commands

* [`doDeal`](/enterprise/api-reference/dodeal.md) - Process payments using generated tokens

## Best practices

1. **Validate card numbers** - Use Luhn algorithm validation before tokenization to avoid unnecessary API calls
2. **Handle expiration validation** - Ensure expiration dates are not in the past before tokenization
3. **Store tokens securely** - Even though tokens are non-sensitive, store them securely in your database
4. **Implement token refresh** - Tokens may expire and need to be refreshed periodically
5. **Never log card numbers** - Ensure sensitive card data is never logged or stored after tokenization
6. **Use HTTPS always** - All tokenization requests must use secure HTTPS connections
7. **Test with various card types** - Validate that your implementation works with different card brands
8. **Implement duplicate detection** - Avoid creating multiple tokens for the same card number


---

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