# getExternalCardId

## Overview

The `getExternalCardId` command transfers external card tokens from other payment processors or systems into the Hyp platform. This command enables merchants to migrate stored card tokens between different payment systems while maintaining PCI compliance.

## Use cases

Use `getExternalCardId` when you need to:

* Migrate stored card tokens from another payment processor to Hyp
* Import existing customer payment methods during system transitions
* Consolidate card tokens from multiple payment systems
* Transfer card data between different merchant accounts or processors
* Maintain customer-saved payment methods during platform changes

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

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

### XML request structure

```xml
<ashrait>
    <request>
        <command>getExternalCardId</command>
        <user>[username]</user>
        <password>[password]</password>
        <terminalNumber>[terminal]</terminalNumber>
        <cardDataX>[external_card_token]</cardDataX>
        <externalCGGId>[external_system_id]</externalCGGId>
        <id>[transaction_id]</id>
    </request>
</ashrait>
```

## Required parameters

<details>

<summary><strong>user</strong> - string</summary>

Your merchant username for API authentication.

</details>

<details>

<summary><strong>password</strong> - string</summary>

Your merchant password for API authentication.

</details>

<details>

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

The terminal number associated with your merchant account.

</details>

<details>

<summary><strong>cardDataX</strong> - string</summary>

The external card token from the source payment system that needs to be transferred.

</details>

<details>

<summary><strong>externalCGGId</strong> - string</summary>

The identifier of the external payment system or processor from which the token is being transferred.

</details>

<details>

<summary><strong>id</strong> - string</summary>

A unique identifier for this request, used for tracking and logging purposes.

</details>

## Optional parameters

<details>

<summary><strong>cardExpiration</strong> - string (MMYY)</summary>

The expiration date associated with the external card token. Format: MMYY (e.g., "1225" for December 2025).

</details>

## Response structure

### Success response

```xml
<ashrait>
    <response>
        <result>000</result>
        <message>Success</message>
        <cardId>[hyp_card_token]</cardId>
        <cardNo>[masked_card_number]</cardNo>
        <cardExpiration>[card_expiration]</cardExpiration>
        <cardBrand>[card_brand]</cardBrand>
    </response>
</ashrait>
```

### Error response

```xml
<ashrait>
    <response>
        <result>001</result>
        <message>Invalid external token or system not supported</message>
    </response>
</ashrait>
```

## Code examples

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

```bash
#!/bin/bash

# Transfer external card token to Hyp
curl -X POST https://your-hyp-environment-url/xpo/Relay \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "cgGateway" \
  --data-urlencode "txnId=12345" \
  --data-urlencode "amount=100.00" \
  --data-urlencode "currency=ILS" \
  --data-urlencode "cardId=12345" \
  --data-urlencode "int_in=<?xml version='1.0' encoding='UTF-8'?>
<ashrait>
    <request>
        <command>getExternalCardId</command>
        <user>your_username</user>
        <password>your_password</password>
        <terminalNumber>1234567</terminalNumber>
        <cardDataX>EXTERNAL_TOKEN_HERE</cardDataX>
        <externalCGGId>EXTERNAL_SYSTEM_001</externalCGGId>
        <id>TRANSFER_$(date +%s)</id>
    </request>
</ashrait>"

```

{% endtab %}

{% tab title="Python" %}

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

def transfer_external_card_token(username, password, terminal, external_token, 
                                external_system_id, request_id=None, expiration=None):
    """
    Transfer external card token to Hyp platform
    """
    # Generate unique request ID if not provided
    if not request_id:
        request_id = f"TRANSFER_{int(time.time())}"
    
    # Build XML request
    ashrait = ET.Element("ashrait")
    request = ET.SubElement(ashrait, "request")
    
    ET.SubElement(request, "command").text = "getExternalCardId"
    ET.SubElement(request, "user").text = username
    ET.SubElement(request, "password").text = password
    ET.SubElement(request, "terminalNumber").text = terminal
    ET.SubElement(request, "cardDataX").text = external_token
    ET.SubElement(request, "externalCGGId").text = external_system_id
    ET.SubElement(request, "id").text = request_id
    
    # Add expiration if provided
    if expiration:
        ET.SubElement(request, "cardExpiration").text = expiration
    
    xml_string = ET.tostring(ashrait, encoding='unicode')
    
    # Send request
    response = requests.post(
        "https://your-hyp-environment-url/xpo/Relay",
        data={
            "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
            card_no = root.find(".//cardNo").text
            card_exp = root.find(".//cardExpiration").text
            card_brand = root.find(".//cardBrand").text
            print(f"Token transferred successfully!")
            print(f"New Hyp Card ID: {card_id}")
            print(f"Card Number: {card_no}")
            print(f"Expiration: {card_exp}")
            print(f"Brand: {card_brand}")
            return {
                "success": True,
                "card_id": card_id,
                "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 = transfer_external_card_token(
    username="your_username",
    password="your_password",
    terminal="1234567",
    external_token="EXTERNAL_TOKEN_HERE",
    external_system_id="EXTERNAL_SYSTEM_001",
    request_id="TRANSFER_123456789"
)

```

{% 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 ExternalCardTokenTransfer {
    
    public static class TransferResult {
        public boolean success;
        public String cardId;
        public String cardNumber;
        public String expiration;
        public String brand;
        public String error;
        
        public TransferResult(boolean success, String cardId, String cardNumber, 
                            String expiration, String brand, String error) {
            this.success = success;
            this.cardId = cardId;
            this.cardNumber = cardNumber;
            this.expiration = expiration;
            this.brand = brand;
            this.error = error;
        }
    }
    
    public static TransferResult transferExternalCardToken(String username, String password, String terminal,
                                                         String externalToken, String externalSystemId, 
                                                         String requestId, String expiration) {
        try {
            // Generate request ID if not provided
            if (requestId == null || requestId.isEmpty()) {
                requestId = "TRANSFER_" + System.currentTimeMillis();
            }
            
            // Build XML request
            StringBuilder xml = new StringBuilder();
            xml.append("<?xml version='1.0' encoding='UTF-8'?>");
            xml.append("<ashrait>");
            xml.append("<request>");
            xml.append("<command>getExternalCardId</command>");
            xml.append("<user>").append(username).append("</user>");
            xml.append("<password>").append(password).append("</password>");
            xml.append("<terminalNumber>").append(terminal).append("</terminalNumber>");
            xml.append("<cardDataX>").append(externalToken).append("</cardDataX>");
            xml.append("<externalCGGId>").append(externalSystemId).append("</externalCGGId>");
            xml.append("<id>").append(requestId).append("</id>");
            
            // Add expiration if provided
            if (expiration != null && !expiration.isEmpty()) {
                xml.append("<cardExpiration>").append(expiration).append("</cardExpiration>");
            }
            
            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 = "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 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("Token transferred successfully!");
                    System.out.println("New Hyp Card ID: " + cardId);
                    System.out.println("Card Number: " + cardNo);
                    System.out.println("Expiration: " + cardExp);
                    System.out.println("Brand: " + cardBrand);
                    return new TransferResult(true, cardId, cardNo, cardExp, cardBrand, null);
                } else {
                    String message = doc.getElementsByTagName("message").item(0).getTextContent();
                    System.out.println("Error: " + message);
                    return new TransferResult(false, null, null, null, null, message);
                }
            } else {
                return new TransferResult(false, null, null, null, null, "HTTP " + conn.getResponseCode());
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return new TransferResult(false, null, null, null, null, e.getMessage());
        }
    }
    
    public static void main(String[] args) {
        TransferResult result = transferExternalCardToken(
            "your_username",
            "your_password",
            "1234567",
            "EXTERNAL_TOKEN_HERE",
            "EXTERNAL_SYSTEM_001",
            "TRANSFER_123456789",
            null
        );
        
        if (result.success) {
            System.out.println("Success! New Card ID: " + result.cardId);
        } 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 transferExternalCardToken(username, password, terminal, externalToken, 
                                  externalSystemId, requestId = null, expiration = null) {
    return new Promise((resolve, reject) => {
        // Generate request ID if not provided
        if (!requestId) {
            requestId = `TRANSFER_${Date.now()}`;
        }
        
        // Build XML request
        let xml = `<?xml version='1.0' encoding='UTF-8'?>
<ashrait>
    <request>
        <command>getExternalCardId</command>
        <user>${username}</user>
        <password>${password}</password>
        <terminalNumber>${terminal}</terminalNumber>
        <cardDataX>${externalToken}</cardDataX>
        <externalCGGId>${externalSystemId}</externalCGGId>
        <id>${requestId}</id>`;

        // Add expiration if provided
        if (expiration) {
            xml += `<cardExpiration>${expiration}</cardExpiration>`;
        }

        xml += `
    </request>
</ashrait>`;

        // Prepare POST data
        const postData = querystring.stringify({
            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 cardNo = doc.getElementsByTagName('cardNo')[0]?.textContent;
                        const cardExp = doc.getElementsByTagName('cardExpiration')[0]?.textContent;
                        const cardBrand = doc.getElementsByTagName('cardBrand')[0]?.textContent;
                        console.log('Token transferred successfully!');
                        console.log(`New Hyp Card ID: ${cardId}`);
                        console.log(`Card Number: ${cardNo}`);
                        console.log(`Expiration: ${cardExp}`);
                        console.log(`Brand: ${cardBrand}`);
                        resolve({
                            success: true,
                            cardId: cardId,
                            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 transferExternalCardToken(
            'your_username',
            'your_password',
            '1234567',
            'EXTERNAL_TOKEN_HERE',
            'EXTERNAL_SYSTEM_001',
            'TRANSFER_123456789'
        );
        
        if (result.success) {
            console.log('Success! New Card ID:', result.cardId);
        } else {
            console.log('Failed:', result.error);
        }
    } catch (error) {
        console.error('Error:', error.message);
    }
})();
```

{% endtab %}
{% endtabs %}

## Error codes

| Code | Description                                               | Solution                                                                                                                                                                        |
| ---- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 000  | Permitted transaction                                     | External token transferred successfully                                                                                                                                         |
| 425  | Failed to get response from external server               | This error occurs after a timeout was reached and the local gateway failed to get response from the remote gateway. Check network connectivity and external server availability |
| 426  | Failed to find external server details for sharing cardid | The externalCGGId request parameter could not be found in CG Gateway configuration. Verify the external system ID is correct                                                    |
| 452  | No privileges found for sharing cardid                    | The username sent in the request is not authorized to use this command. [Contact support](mailto:cg-support@hyp.co.il) to enable permissions for token sharing                  |

## Related commands

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

## Best practices

1. **Coordinate with external systems** - Ensure the source system supports token transfers and provides valid tokens
2. **Validate external system IDs** - Confirm the externalCGGId is correct for your source payment processor
3. **Handle transfer failures gracefully** - External token transfers may fail due to network issues or system incompatibilities
4. **Map customer records** - Maintain mapping between original and new card tokens for customer account updates
5. **Test transfers thoroughly** - Validate that transferred tokens work correctly for payments before going live
6. **Batch transfer operations** - For large migrations, process tokens in batches to avoid overwhelming systems
7. **Monitor transfer success rates** - Track which external systems have higher transfer failure rates for troubleshooting


---

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