# getCardNo

## Overview

The `getCardNo` command retrieves the masked card number associated with a stored card token. This command allows merchants to display recognizable card information to customers while maintaining PCI compliance by working with tokenized card data.

## Use cases

Use `getCardNo` when you need to:

* Display masked card numbers to customers in account management interfaces
* Show saved payment methods for customer selection during checkout
* Retrieve card information for transaction verification purposes
* Provide customers with card details for their own records
* Implement saved card management features in your application

## 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 `getCardNo` 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>getCardNo</command>
        <getCardNo>
            <terminalNumber>{{terminal}}</terminalNumber>
            <cardId>1092880571131111</cardId>
        </getCardNo>
    </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>cardId</strong> - string</summary>

The card identifier token obtained from a previous transaction or tokenization process.

**Example**: `1092880571131111`

</details>

## Response structure

### Success response

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>getCardNo</command>
        <dateTime>2025-08-19 10:45</dateTime>
        <requestId />
        <tranId>119550939</tranId>
        <result>000</result>
        <message>Permitted transaction</message>
        <userMessage>Permitted transaction</userMessage>
        <additionalInfo />
        <version>2000</version>
        <language>Eng</language>
        <getCardNo>
            <terminalNumber>0882804010</terminalNumber>
            <cardNo>xxxxxxxxxxxx1111</cardNo>
            <cardExpiration />
            <cardBrand code="2">Visa</cardBrand>
            <id />
            <cardBin>411111</cardBin>
            <cardMask>411111******1111</cardMask>
            <cardLength>16</cardLength>
            <cardData1 />
            <cardData2 />
            <cardData3 />
            <cardData4 />
            <cardData5 />
        </getCardNo>
    </response>
</ashrait>
```

**Key Response Fields:**

* `cardNo`: Masked card number (e.g., `xxxxxxxxxxxx1111`)
* `cardMask`: Alternative masking format (e.g., `411111******1111`)
* `cardBin`: Bank Identification Number (first 6 digits)
* `cardBrand`: Card brand with code (e.g., Visa, MasterCard)
* `cardLength`: Total length of the card number
* `cardExpiration`: Card expiration date (may be empty for security)

### Error response

```xml
<?xml version='1.0'?>
<ashrait>
    <response>
        <command>getCardNo</command>
        <dateTime>2025-08-20 10:06</dateTime>
        <requestId />
        <tranId>119575614</tranId>
        <result>342</result>
        <message>Card id was not found</message>
        <userMessage>Card id was not found</userMessage>
        <additionalInfo>cardId 10928805171131111 was not found</additionalInfo>
        <version>2000</version>
        <language>Eng</language>
        <getCardNo />
    </response>
</ashrait>
```

## Code examples

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

```bash
#!/bin/bash

# Retrieve masked card number from token
XML_PAYLOAD='<ashrait><request><version>2000</version><command>getCardNo</command><getCardNo><terminalNumber>{{terminal}}</terminalNumber><cardId>{{cardId}}</cardId></getCardNo></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 get_card_number(username, password, terminal, card_token):
    """
    Retrieve masked card number from stored token
    """
    # Build XML request
    ashrait = ET.Element("ashrait")
    request = ET.SubElement(ashrait, "request")
    
    ET.SubElement(request, "version").text = "2000"
    ET.SubElement(request, "command").text = "getCardNo"
    
    get_card_no = ET.SubElement(request, "getCardNo")
    ET.SubElement(get_card_no, "terminalNumber").text = terminal
    ET.SubElement(get_card_no, "cardId").text = card_token
    
    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_no = root.find(".//cardNo").text
            card_exp = root.find(".//cardExpiration").text
            card_brand = root.find(".//cardBrand").text
            print(f"Card Number: {card_no}")
            print(f"Expiration: {card_exp}")
            print(f"Brand: {card_brand}")
            return {
                "success": True,
                "card_number": card_no,
                "expiration": card_exp,
                "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 = get_card_number(
    username="your_username",
    password="your_password",
    terminal="1234567",
    card_token="ENCRYPTED_TOKEN_HERE"
)

```

{% 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 CardNumberRetrieval {
    
    public static class CardInfo {
        public boolean success;
        public String cardNumber;
        public String expiration;
        public String brand;
        public String error;
        
        public CardInfo(boolean success, String cardNumber, String expiration, 
                       String brand, String error) {
            this.success = success;
            this.cardNumber = cardNumber;
            this.expiration = expiration;
            this.brand = brand;
            this.error = error;
        }
    }
    
    public static CardInfo getCardNumber(String username, String password, String terminal,
                                        String cardToken) {
        try {
            // Build XML request
            StringBuilder xml = new StringBuilder();
            xml.append("<ashrait>");
            xml.append("<request>");
            xml.append("<version>2000</version>");
            xml.append("<command>getCardNo</command>");
            xml.append("<getCardNo>");
            xml.append("<terminalNumber>").append(terminal).append("</terminalNumber>");
            xml.append("<cardId>").append(cardToken).append("</cardId>");
            xml.append("</getCardNo>");
            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 cardNo = doc.getElementsByTagName("cardNo").item(0).getTextContent();
                    String cardExp = doc.getElementsByTagName("cardExpiration").item(0).getTextContent();
                    String cardBrand = doc.getElementsByTagName("cardBrand").item(0).getTextContent();
                    System.out.println("Card Number: " + cardNo);
                    System.out.println("Expiration: " + cardExp);
                    System.out.println("Brand: " + cardBrand);
                    return new CardInfo(true, cardNo, cardExp, cardBrand, null);
                } else {
                    String message = doc.getElementsByTagName("message").item(0).getTextContent();
                    System.out.println("Error: " + message);
                    return new CardInfo(false, null, null, null, message);
                }
            } else {
                return new CardInfo(false, null, null, null, "HTTP " + conn.getResponseCode());
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return new CardInfo(false, null, null, null, e.getMessage());
        }
    }
    
    public static void main(String[] args) {
        CardInfo info = getCardNumber(
            "your_username",
            "your_password",
            "1234567",
            "ENCRYPTED_TOKEN_HERE"
        );
        
        if (info.success) {
            System.out.println("Success! Card: " + info.cardNumber);
        } else {
            System.out.println("Failed: " + info.error);
        }
    }
}

```

{% endtab %}

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

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

function getCardNumber(username, password, terminal, cardToken) {
    return new Promise((resolve, reject) => {
        // Build XML request
        const xml = `<ashrait>
    <request>
        <version>2000</version>
        <command>getCardNo</command>
        <getCardNo>
            <terminalNumber>${terminal}</terminalNumber>
            <cardId>${cardToken}</cardId>
        </getCardNo>
    </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 cardNo = doc.getElementsByTagName('cardNo')[0]?.textContent;
                        const cardExp = doc.getElementsByTagName('cardExpiration')[0]?.textContent;
                        const cardBrand = doc.getElementsByTagName('cardBrand')[0]?.textContent;
                        console.log(`Card Number: ${cardNo}`);
                        console.log(`Expiration: ${cardExp}`);
                        console.log(`Brand: ${cardBrand}`);
                        resolve({
                            success: true,
                            cardNumber: cardNo,
                            expiration: cardExp,
                            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 getCardNumber(
            'your_username',
            'your_password',
            '1234567',
            'ENCRYPTED_TOKEN_HERE'
        );
        
        if (result.success) {
            console.log('Success! Card:', result.cardNumber);
        } else {
            console.log('Failed:', result.error);
        }
    } catch (error) {
        console.error('Error:', error.message);
    }
})();
```

{% endtab %}
{% endtabs %}

## Error codes

| Code | Description                                                | Solution                                                             |
| ---- | ---------------------------------------------------------- | -------------------------------------------------------------------- |
| 000  | Permitted transaction                                      | Card information retrieved successfully                              |
| 325  | Invalid XML format                                         | Check XML structure and ensure all required fields are present       |
| 342  | Card id was not found                                      | Verify the cardId token is valid and corresponds to an existing card |
| 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                           |
| 462  | Wrong value in header                                      | Verify terminal number is correct and authorized                     |

## Related commands

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

## Best practices

1. **Use for display purposes only** - Never store the retrieved card numbers; use tokens for all processing
2. **Implement proper access controls** - Ensure only authorized users can retrieve card information
3. **Cache card information temporarily** - Avoid repeated API calls for the same card tokens within a session
4. **Handle expired tokens gracefully** - Card tokens may expire and should be refreshed through new tokenization
5. **Mask sensitive information** - The returned card number is already masked, and you need to ensure proper display in your UI
6. **Validate token integrity** - Check that card tokens haven't been corrupted before making requests


---

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