Phone Exchange C# Code Snippet

using PE2Reference;

namespace phone_exchange_2_dot_net.SOAP
{
    /// <summary>
    /// Provides functionality to call the ServiceObjects Phone Exchange (PE2) SOAP service's GetExchangeInfo operation,
    /// retrieving phone exchange information (e.g., carrier, line type, ported status) for a given phone number
    /// with fallback to a backup endpoint for reliability in live mode.
    /// </summary>
    public class GetExchangeInfoValidation
    {
        private const string LiveBaseUrl = "https://sws.serviceobjects.com/pe2/soap.svc/SOAP";
        private const string BackupBaseUrl = "https://swsbackup.serviceobjects.com/pe2/soap.svc/SOAP";
        private const string TrialBaseUrl = "https://trial.serviceobjects.com/pe2/soap.svc/SOAP";

        private readonly string _primaryUrl;
        private readonly string _backupUrl;
        private readonly int _timeoutMs;
        private readonly bool _isLive;

        /// <summary>
        /// Initializes URLs/timeout/IsLive.
        /// </summary>
        public GetExchangeInfoValidation(bool isLive)
        {
            _timeoutMs = 10000;
            _isLive = isLive;

            _primaryUrl = isLive ? LiveBaseUrl : TrialBaseUrl;
            _backupUrl = isLive ? BackupBaseUrl : TrialBaseUrl;

            if (string.IsNullOrWhiteSpace(_primaryUrl))
                throw new InvalidOperationException("Primary URL not set.");
            if (string.IsNullOrWhiteSpace(_backupUrl))
                throw new InvalidOperationException("Backup URL not set.");
        }

        /// <summary>
        /// This operation returns phone exchange information for a given phone number, including carrier,
        /// line type, ported status, SMS/MMS addresses, and location details.
        /// </summary>
        /// <param name="PhoneNumber">The phone number to validate (e.g., "1234567890").</param>
        /// <param name="LicenseKey">The license key to authenticate the API request.</param>
        public async Task<ExchangeInfoResponse> GetExchangeInfo(string PhoneNumber, string LicenseKey)
        {
            PE2SoapClient clientPrimary = null;
            PE2SoapClient clientBackup = null;

            try
            {
                // Attempt Primary
                clientPrimary = new PE2SoapClient();
                clientPrimary.Endpoint.Address = new System.ServiceModel.EndpointAddress(_primaryUrl);
                clientPrimary.InnerChannel.OperationTimeout = TimeSpan.FromMilliseconds(_timeoutMs);

                ExchangeInfoResponse response = await clientPrimary.GetExchangeInfoAsync(PhoneNumber, LicenseKey).ConfigureAwait(false);

                if (_isLive && !IsValid(response))
                {
                    throw new InvalidOperationException("Primary endpoint returned null or a fatal TypeCode=3 error for GetExchangeInfo");
                }
                return response;
            }
            catch (Exception primaryEx)
            {
                try
                {
                    clientBackup = new PE2SoapClient();
                    clientBackup.Endpoint.Address = new System.ServiceModel.EndpointAddress(_backupUrl);
                    clientBackup.InnerChannel.OperationTimeout = TimeSpan.FromMilliseconds(_timeoutMs);

                    return await clientBackup.GetExchangeInfoAsync(PhoneNumber, LicenseKey).ConfigureAwait(false);
                }
                catch (Exception backupEx)
                {
                    throw new InvalidOperationException(
                        $"Both primary and backup endpoints failed.\n" +
                        $"Primary error: {primaryEx.Message}\n" +
                        $"Backup error: {backupEx.Message}");
                }
                finally
                {
                    clientBackup?.Close();
                }
            }
            finally
            {
                clientPrimary?.Close();
            }
        }

        private static bool IsValid(ExchangeInfoResponse response) => response?.Error == null || response.Error.TypeCode != "3";
    }
}

Phone Exchange Python Code Snippet

from suds.client import Client
from suds import WebFault
from suds.sudsobject import Object


class GetExchangeInfoSoap:
    def __init__(self, license_key: str, is_live: bool = True, timeout_ms: int = 15000):
        """
        Initialize the GetExchangeInfoSoap client for ServiceObjects Phone Exchange (PE2) API.

        Parameters:
            license_key: ServiceObjects PE2 license key.
            is_live: Whether to use live or trial endpoints.
            timeout_ms: SOAP call timeout in milliseconds.
        """
        self.is_live = is_live
        self.timeout = timeout_ms / 1000.0
        self.license_key = license_key

        # WSDL URLs
        self._primary_wsdl = (
            "https://sws.serviceobjects.com/pe2/soap.svc?wsdl"
            if is_live
            else "https://trial.serviceobjects.com/pe2/soap.svc?wsdl"
        )
        self._backup_wsdl = (
            "https://swsbackup.serviceobjects.com/pe2/soap.svc?wsdl"
            if is_live
            else "https://trial.serviceobjects.com/pe2/soap.svc?wsdl"
        )

    def get_exchange_info(
        self,
        phone_number: str,
    ) -> Object:
        """
        Calls the GetExchangeInfo SOAP API to retrieve phone exchange information for a US/Canada phone number.

        Parameters:
            phone_number: The phone number to validate (e.g., "8051234567").
            license_key: Your ServiceObjects license key.
            is_live: Determines whether to use the live or trial servers.
            timeout_ms: Timeout, in milliseconds, for the call to the service.

        Returns:
            suds.sudsobject.Object: SOAP response containing phone exchange details or error.
        """
        # Common kwargs for both calls
        call_kwargs = dict(
            PhoneNumber=phone_number,
            LicenseKey=self.license_key,
        )

        # Attempt primary
        try:
            client = Client(self._primary_wsdl, timeout=self.timeout)
            # Override endpoint URL if needed:
            # client.set_options(location=self._primary_wsdl.replace('?wsdl','/soap'))
            response = client.service.GetExchangeInfo(**call_kwargs)

            # If response invalid or Error.TypeCode == "3", trigger fallback
            if response is None or (
                hasattr(response, "Error")
                and response.Error
                and response.Error.TypeCode == "3"
            ):
                raise ValueError("Primary returned no result or Error.TypeCode=3")

            return response

        except (WebFault, ValueError, Exception) as primary_ex:
            # Attempt backup
            try:
                client = Client(self._backup_wsdl)
                response = client.service.GetExchangeInfo(**call_kwargs)
                if response is None:
                    raise ValueError("Backup returned no result")
                return response
            except (WebFault, Exception) as backup_ex:
                msg = (
                    "Both primary and backup endpoints failed.\n"
                    f"Primary error: {str(primary_ex)}\n"
                    f"Backup error: {str(backup_ex)}"
                )
                raise RuntimeError(msg)

Phone Exchange NodeJS Code Snippet

import { soap } from 'strong-soap'
/**
 * A class that provides functionality to call the ServiceObjects Phone Exchange (PE2) SOAP service's GetExchangeInfo endpoint,
 * retrieving phone exchange information (e.g., carrier, line type, location) for a given phone number with fallback to a backup endpoint for reliability in live mode.
 */
class GetExchangeInfoSoap {
    /**
     * Initializes a new instance of the GetExchangeInfoSoap class with the provided input parameters,
     * setting up primary and backup WSDL URLs based on the live/trial mode.
     * @param {string} PhoneNumber - The phone number to validate (e.g., "8055551234").
     * @param {string} LicenseKey - Your license key to use the service.
     * @param {boolean} [isLive=true] - Value to determine whether to use the live or trial servers.
     * @param {number} [timeoutSeconds=15] - Timeout, in seconds, for the call to the service.
     * @throws {Error} Thrown if LicenseKey is empty or null.
     */
    constructor(PhoneNumber, LicenseKey, isLive = true, timeoutSeconds = 15) {

        this.args = {
            PhoneNumber,
            LicenseKey
        };

        this.isLive = isLive;
        this.timeoutSeconds = timeoutSeconds;

        this.LiveBaseUrl = 'https://sws.serviceobjects.com/PE2/soap.svc?wsdl';
        this.BackupBaseUrl = 'https://swsbackup.serviceobjects.com/PE2/soap.svc?wsdl';
        this.TrialBaseUrl = 'https://trial.serviceobjects.com/PE2/soap.svc?wsdl';

        this._primaryWsdl = this.isLive ? this.LiveBaseUrl : this.TrialBaseUrl;
        this._backupWsdl = this.isLive ? this.BackupBaseUrl : this.TrialBaseUrl;
    }

    /**
     * Asynchronously calls the GetExchangeInfo SOAP endpoint, attempting the primary endpoint
     * first and falling back to the backup if the response is invalid (Error.TypeCode == '3') in live mode
     * or if the primary call fails.
     * @returns {Promise<PE2Response>} A promise that resolves to a PE2Response object containing exchange info or an error.
     * @throws {Error} Thrown if both primary and backup calls fail, with detailed error messages.
     */
    async getExchangeInfoSoap() {
        try {
            const primaryResult = await this._callSoap(this._primaryWsdl, this.args);

            if (this.isLive && !this._isValid(primaryResult)) {
                console.warn("Primary returned Error.TypeCode == '3', falling back to backup...");
                const backupResult = await this._callSoap(this._backupWsdl, this.args);
                return backupResult;
            }

            return primaryResult;
        } catch (primaryErr) {
            try {
                const backupResult = await this._callSoap(this._backupWsdl, this.args);
                return backupResult;
            } catch (backupErr) {
                throw new Error(`Both primary and backup calls failed:\nPrimary: ${primaryErr.message}\nBackup: ${backupErr.message}`);
            }
        }
    }

    /**
     * Performs a SOAP service call to the specified WSDL URL with the given arguments,
     * creating a client and processing the response into an object.
     * @param {string} wsdlUrl - The WSDL URL of the SOAP service endpoint (primary or backup).
     * @param {Object} args - The arguments to pass to the GetExchangeInfo method.
     * @returns {Promise<Object>} A promise that resolves to an object containing the SOAP response data.
     * @throws {Error} Thrown if the SOAP client creation fails, the service call fails, or the response cannot be parsed.
     */
    _callSoap(wsdlUrl, args) {
        return new Promise((resolve, reject) => {
            soap.createClient(wsdlUrl, { timeout: this.timeoutSeconds * 1000 }, (err, client) => {
                if (err) return reject(err);

                client.GetExchangeInfo(args, (err, result) => {
                    const response = result?.GetExchangeInfoResult;
                    try {
                        if (!response) {
                            return reject(new Error('SOAP response is empty or undefined.'));
                        }
                        resolve(response);
                    } catch (parseErr) {
                        reject(new Error(`Failed to parse SOAP response: ${parseErr.message}`));
                    }
                });
            });
        });
    }

    /**
     * Checks if a SOAP response is valid by verifying that it exists and either has no Error object
     * or the Error.TypeCode is not equal to '3'.
     * @param {Object} response - The response object to validate.
     * @returns {boolean} True if the response is valid, false otherwise.
     */
    _isValid(response) {
        return response && (!response.Error || response.Error.TypeCode !== '3');
    }
}

export { GetExchangeInfoSoap };