Lead Validation International C# Code Snippet

using LVIService;

namespace lead_validation_international_dot_net.SOAP
{
    /// <summary>
    /// Provides functionality to call the ServiceObjects Lead Validation International SOAP service's ValidateLeadInternational operation,
    /// retrieving lead validation information (e.g., name, address, phone, email, and business details) with fallback to a backup endpoint
    /// for reliability in live mode.
    /// </summary>
    public class ValidateLeadInternational
    {
        private const string LiveBaseUrl = "https://sws.serviceobjects.com/LVI/SOAP.svc/SOAP";
        private const string BackupBaseUrl = "https://swsbackup.serviceobjects.com/LVI/SOAP.svc/SOAP";
        private const string TrailBaseUrl = "https://trial.serviceobjects.com/LVI/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 ValidateLeadInternational(bool isLive)
        {
            _timeoutMs = 10000;
            _isLive = isLive;

            if (_isLive)
            {
                _primaryUrl = LiveBaseUrl;
                _backupUrl = BackupBaseUrl;
            }
            else
            {
                _primaryUrl = TrailBaseUrl;
                _backupUrl = TrailBaseUrl;
            }

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

        /// <summary>
        /// Asynchronously calls the ServiceObjects Lead Validation International SOAP endpoint to validate lead information,
        /// such as name, address, phone numbers, email, and business details. Attempts the primary endpoint first and falls
        /// back to the backup endpoint if the primary call fails or returns a fatal error (Error.TypeCode == "3"). Enforces
        /// a timeout using a CancellationToken to prevent hangs.
        /// </summary>
        /// <param name="FullName">The contact’s full name. e.g. Jane Doe</param>
        /// <param name="Salutation">Salutation of the contact. Dr, Esq, Mr, Mrs etc</param>
        /// <param name="FirstName">First name of the contact. e.g. Jane</param>
        /// <param name="LastName">Last name of the contact. e.g. Doe</param>
        /// <param name="BusinessName">The contacts company. e.g. Service Objects</param>
        /// <param name="BusinessDomain">Website domain associated with the business. e.g. serviceobjects.com</param>
        /// <param name="BusinessEIN">Represents the Company Tax Number. Used for Tax exempt checks for US leads.</param>
        /// <param name="Address1">The address 1 of the contact or business address.</param>
        /// <param name="Address2">The address 2 of the contact or business address.</param>
        /// <param name="Address3">The address 3 of the contact or business address.</param>
        /// <param name="Address4">The address 4 of the contact or business address.</param>
        /// <param name="Address5">The address 5 of the contact or business address.</param>
        /// <param name="Locality">The city of the contact’s postal address.</param>
        /// <param name="AdminArea">The state of the contact’s postal address.</param>
        /// <param name="PostalCode">The zip code of the contact’s postal address.</param>
        /// <param name="Country">The country of the contact’s postal address. e.g. United States, US or USA</param>
        /// <param name="Phone2">The secondary phone number.</param>
        /// <param name="Email">The contact’s email address.</param>
        /// <param name="IPAddress">The contact’s IP address in IPv4. (IPv6 coming in a future release)</param>
        /// <param name="Gender">Male, Female or Neutral</param>
        /// <param name="DateOfBirth">The contact’s date of birth</param>
        /// <param name="UTCCaptureTime">The time the lead was submitted</param>
        /// <param name="OutputLanguage">Language field indicating what language some of the output information will be.</param>
        /// <param name="TestType">The name of the type of validation you want to perform on this contact.</param>
        /// <param name="LicenseKey">Your license key to use the service.</param>
        /// <returns>A <see cref="Task{ContactInternational}"/> containing a <see cref="ContactInternational"/> object with lead validation details or an error.</returns>
        /// <exception cref="Exception">Thrown if both primary and backup endpoints fail.</exception>
        public async Task<ContactInternational> InvokeAsync(string FullName, string Salutation, string FirstName, string LastName,
             string BusinessName, string BusinessDomain, string BusinessEIN, string Address1, string Address2, string Address3,
             string Address4, string Address5, string Locality, string AdminArea, string PostalCode, string Country,
             string Phone1, string Phone2, string Email, string IPAddress, string Gender, string DateOfBirth, string UTCCaptureTime,
             string OutputLanguage, string TestType, string LicenseKey)
        {
            LVISoapServiceClient clientPrimary = null;
            LVISoapServiceClient clientBackup = null;

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

                ContactInternational response = await clientPrimary.ValidateLeadInternationalAsync(
                    FullName, Salutation, FirstName, LastName,
                    BusinessName, BusinessDomain, BusinessEIN,
                    Address1, Address2, Address3, Address4, Address5,
                    Locality, AdminArea, PostalCode, Country,
                    Phone1, Phone2, Email, IPAddress,
                    Gender, DateOfBirth, UTCCaptureTime,
                    OutputLanguage, TestType, LicenseKey).ConfigureAwait(false);

                if (response == null || (response.Error != null && response.Error.TypeCode == "3"))
                {
                    throw new InvalidOperationException("Primary endpoint returned null or a fatal TypeCode=3 error for ValidateLeadInternational");
                }
                return response;
            }
            catch (Exception primaryEx)
            {
                // If primary fails, try Backup
                try
                {
                    clientBackup = new LVISoapServiceClient();
                    clientBackup.Endpoint.Address = new System.ServiceModel.EndpointAddress(_backupUrl);
                    clientBackup.InnerChannel.OperationTimeout = TimeSpan.FromMilliseconds(_timeoutMs);

                    ContactInternational response = await clientBackup.ValidateLeadInternationalAsync(
                    FullName, Salutation, FirstName, LastName,
                    BusinessName, BusinessDomain, BusinessEIN,
                    Address1, Address2, Address3, Address4, Address5,
                    Locality, AdminArea, PostalCode, Country,
                    Phone1, Phone2, Email, IPAddress,
                    Gender, DateOfBirth, UTCCaptureTime,
                    OutputLanguage, TestType, LicenseKey).ConfigureAwait(false);
                    return response;
                }
                catch (Exception backupEx)
                {
                    // If backup also fails, wrap both exceptions
                    throw new Exception(
                        $"Both primary and backup endpoints failed.\n" +
                        $"Primary error: {primaryEx.Message}\n" +
                        $"Backup error: {backupEx.Message}");
                }
                finally
                {
                    clientBackup?.Close();
                }
            }
            finally
            {
                clientPrimary?.Close();
            }
        }

    }
}

Lead Validation International Python Code Snippet

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

class ValidateLeadInternational:
    def __init__(self, license_key: str, is_live: bool, timeout_ms: int = 10000):
        """
        license_key: Service Objects GeoPhone license key.
        is_live: whether to use live or trial endpoints
        timeout_ms: SOAP call timeout in milliseconds
        """
        self._timeout_s = timeout_ms / 1000.0  # Convert to seconds
        self._is_live = is_live
        self.license_key = license_key

        # WSDL URLs for primary and backup endpoints 
        self._primary_wsdl = (
            "https://sws.serviceobjects.com/LVI/soap.svc?wsdl"
            if is_live else
            "https://trial.serviceobjects.com/LVI/soap.svc?wsdl"
        )
        self._backup_wsdl = (
            "https://swsbackup.serviceobjects.com/LVI/soap.svc?wsdl"
            if is_live else
            "https://trial.serviceobjects.com/LVI/soap.svc?wsdl"
        )

    def validate_lead_international(
                                  self,
                                  full_name: str,
                                  salutation: str,
                                  first_name: str,
                                  last_name: str,
                                  business_name: str,
                                  business_domain: str,
                                  business_EIN: str,
                                  address_line1: str,
                                  address_line2: str,
                                  address_line3: str,
                                  address_line4: str,
                                  address_line5: str,
                                  locality: str,
                                  admin_area: str,
                                  postal_code: str,
                                  country: str,
                                  phone1: str,
                                  phone2: str,
                                  email: str,
                                  ip_address: str,
                                  gender: str,
                                  date_of_birth: str,
                                  utc_capture_time: str,
                                  output_language: str,
                                  test_type: str
                                ) -> Object:
        """
        Call LVI ValidateLeadInternational API to retrieve phone number information.

        Parameters:
              full_name: The contact's full name. e.g. Jane Doe
              salutation: Salutation of the contact. Dr, Esq, Mr, Mrs etc
              first_name: First name of the contact. e.g. Jane
              last_name: Last name of the contact. e.g. Doe
              business_name: The contact's company. e.g. Service Objects
              business_domain: Website domain associated with the business. e.g. serviceobjects.com
              business_EIN: Represents the Company Tax Number. Used for Tax exempt checks for US leads.
              address_line1: The address 1 of the contact or business address.
              address_line2: The address 2 of the contact or business address.
              address_line3: The address 3 of the contact or business address.
              address_line4: The address 4 of the contact or business address.
              address_line5: The address 5 of the contact or business address.
              locality: The city of the contact's postal address.
              admin_area: The state of the contact's postal address.
              postal_code: The zip code of the contact's postal address.
              country: The country of the contact's postal address. e.g. United States, US or USA
              phone1: The contact's primary phone number.
              phone2: The contact's secondary phone number.
              email: The contact's email address.
              ip_address: The contact's IP address in IPv4. (IPv6 coming in a future release)
              gender: Male, Female or Neutral
              date_of_birth: The contact's date of birth
              utc_capture_time: The time the lead was submitted
              output_language: Language field indicating what language some of the output information will be.
              test_type: The name of the type of validation you want to perform on this contact.
              license_key: Your license key to use the service.
              is_live: Value to determine whether to use the live or trial servers
              timeout_seconds: Timeout, in seconds, for the call to the service.

        Returns:
              dict: Parsed JSON response with phone information or error details.
        """


        # Common kwargs for both calls
        call_kwargs = dict(
            FullName=full_name,
            Salutation=salutation,
            FirstName=first_name,
            LastName=last_name,
            BusinessName=business_name,
            BusinessDomain=business_domain,
            BusinessEIN=business_EIN,
            Address1=address_line1,
            Address2=address_line2,
            Address3=address_line3,
            Address4=address_line4,
            Address5=address_line5,
            Locality=locality,
            AdminArea=admin_area,
            PostalCode=postal_code,
            Country=country,
            Phone1=phone1,
            Phone2=phone2,
            Email=email,
            IPAddress=ip_address,
            Gender=gender, 
            DateOfBirth=date_of_birth,
            UTCCaptureTime=utc_capture_time,
            OutputLanguage=output_language,
            TestType=test_type,
            LicenseKey=self.license_key,
        )

        # Attempt primary
        try:
            client = Client(self._primary_wsdl, timeout=self._timeout_s)

                # Override endpoint URL if needed:
            response = client.service.ValidateLeadInternational(**call_kwargs)

            # If response is None or fatal error code, 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 fatal Error.TypeCode=4")

            return response

        except (WebFault, ValueError, Exception) as primary_ex:
                # Attempt backup
            try:
                client = Client(self._backup_wsdl, timeout=self._timeout_s)
                response = client.service.ValidateLeadInternational(**call_kwargs)
                return response
            except (WebFault,Exception) as backup_ex:
                # Raise a combined error if both attempts fail
                msg = (
                    "Both primary and backup endpoints failed.\n"
                    f"Primary error: {str(primary_ex)}\n"
                    f"Backup error: {str(backup_ex)}"
                )
                raise RuntimeError(msg)

Lead Validation International NodeJS Code Snippet

import { soap } from "strong-soap";

/**
 * <summary>
 * A class that provides functionality to call the ServiceObjects Lead Validation International SOAP service's ValidateLeadInternational endpoint,
 * retrieving lead validation information with fallback to a backup endpoint for reliability in live mode.
 * </summary>
 */
class ValidateLeadInternationalSoap {
    /**
    * <summary>    
    * Initializes a new instance of the ValidateLeadInternationalSoap class with the provided input parameters,
    * setting up primary and backup WSDL URLs based on the live/trial mode.
    * </summary>
    * @param {string} fullName - The contact’s full name. e.g. Jane Doe
    * @param {string} salutation - Salutation of the contact. Dr, Esq, Mr, Mrs etc
    * @param {string} firstName - First name of the contact. e.g. Jane
    * @param {string} lastName - Last name of the contact. e.g. Doe
    * @param {string} businessName - The contact's company. e.g. Service Objects
    * @param {string} businessDomain - Website domain associated with the business. e.g. serviceobjects.com
    * @param {string} businessEIN - Represents the Company Tax Number. Used for Tax exempt checks for US leads.
    * @param {string} addressLine1 - The address 1 of the contact or business address.
    * @param {string} addressLine2 - The address 2 of the contact or business address.
    * @param {string} addressLine3 - The address 3 of the contact or business address.
    * @param {string} addressLine4 - The address 4 of the contact or business address.
    * @param {string} addressLine5 - The address 5 of the contact or business address.
    * @param {string} locality - The city of the contact’s postal address.
    * @param {string} adminArea - The state of the contact’s postal address.
    * @param {string} postalCode - The zip code of the contact’s postal address.
    * @param {string} country - The country of the contact’s postal address. e.g. United States, US or USA
    * @param {string} phone1 - The contact’s primary phone number.
    * @param {string} phone2 - The contact’s secondary phone number.
    * @param {string} email - The contact’s email address.
    * @param {string} ipAddress - The contact’s IP address in IPv4. (IPv6 coming in a future release)
    * @param {string} gender - Male, Female or Neutral
    * @param {string} dateOfBirth - The contact’s date of birth
    * @param {string} utcCaptureTime - The time the lead was submitted
    * @param {string} outputLanguage - Language field indicating what language some of the output information will be.
    * @param {string} testType - The name of the type of validation you want to perform on this contact.
    * @param {string} licenseKey - Your license key to use the service.
    * @param {boolean} isLive - Value to determine whether to use the live or trial servers
    * @param {number} timeoutSeconds - Timeout, in seconds, for the call to the service.
    * 
    * @returns {Promise<LVIResponse>} - A promise that resolves to an LVIResponse object.
    */
    constructor(
        fullName, salutation, firstName, lastName, businessName, businessDomain, businessEIN,
        address1, address2, address3, address4, address5, aocality, adminArea, postalCode, country,
        phone1, phone2, email, ipAddress, gender, dateOfBirth, utcCaptureTime, outputLanguage, testType, licenseKey,
        isLive, timeoutSeconds
    ) {

        this.args = {
            fullName, salutation, firstName, lastName, businessName, businessDomain, businessEIN,
            address1, address2, address3, address4, address5, aocality, adminArea, postalCode, country,
            phone1, phone2, email, ipAddress, gender, dateOfBirth, utcCaptureTime, outputLanguage, testType, licenseKey
        };

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

        this.liveBaseUrl = "https://sws.serviceobjects.com/LVI/soap.svc?wsdl";
        this.backupBaseUrl = "https://swsbackup.serviceobjects.com/LVI/soap.svc?wsdl";
        this.trialBaseUrl = "https://trial.serviceobjects.com/LVI/soap.svc?wsdl";

        this._primaryWsdl = this.isLive ? this.liveBaseUrl : this.trialBaseUrl;
        this._backupWsdl = this.isLive ? this.backupBaseUrl : this.trialBaseUrl;
    }

    /**
     * <summary>
     * Asynchronously calls the ValidateLeadInternational SOAP endpoint, attempting the primary endpoint
     * first and falling back to the backup if the response is invalid (Error.Number == "4") in live mode
     * or if the primary call fails.
     * </summary>
     * <returns type="Promise<LVIResponse>">A promise that resolves to an LVIResponse object containing lead validation details or an error.</returns>
     * <exception cref="Error">Thrown if both primary and backup calls fail, with detailed error messages.</exception>
     */
    async validateLeadInternational() {
        try {
            const primaryResult = await this._callSoap(this._primaryWsdl, this.args);

            if (this.isLive && !this._isValid(primaryResult)) {
                console.warn("Primary returned Error.Number == '4', 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}`);
            }
        }
    }

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

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

    /**
     * <summary>
     * Checks if a SOAP response is valid by verifying that it exists and either has no Error object
     * or the Error.Number is not equal to '4'.
     * </summary>
     * <param name="response" type="LVIResponse">The LVIResponse object to validate.</param>
     * <returns type="boolean">True if the response is valid, false otherwise.</returns>
     */
    _isValid(response) {
        return response && (!response.Error || response.Error.TypeCode !== "4");
    }
}

export { ValidateLeadInternationalSoap };