FastTax C# Code Snippet

using System;
using System.Threading.Tasks;
using FTReference;

namespace fast_tax_dot_net.SOAP
{
    /// <summary>
    /// Provides functionality to call the ServiceObjects FastTax (FT) SOAP service's GetBestMatch operation,
    /// retrieving tax rate information (e.g., total tax rate, city, county, state rates) for a given US address
    /// with fallback to a backup endpoint for reliability in live mode.
    /// </summary>
    public class GetBestMatchValidation
    {
        private const string LiveBaseUrl = "https://sws.serviceobjects.com/ft/soap.svc/SOAP";
        private const string BackupBaseUrl = "https://swsbackup.serviceobjects.com/ft/soap.svc/SOAP";
        private const string TrialBaseUrl = "https://trial.serviceobjects.com/ft/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 GetBestMatchValidation(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 the best available tax rate match for a given US address, including total tax rate,
        /// state, county, city, and district rates, along with additional information like IsUnincorporated status.
        /// </summary>
        /// <param name="Address">Address line of the address to get tax rates for (e.g., "123 Main Street").</param>
        /// <param name="Address2">Secondary address line (e.g., "Apt 4B"). Optional.</param>
        /// <param name="City">The city of the address (e.g., "New York"). Optional if zip is provided.</param>
        /// <param name="State">The state of the address (e.g., "NY"). Optional if zip is provided.</param>
        /// <param name="Zip">The ZIP code of the address. Optional if city and state are provided.</param>
        /// <param name="TaxType">The type of tax to look for ("sales" or "use").</param>
        /// <param name="LicenseKey">The license key to authenticate the API request.</param>
        public async Task<BestMatchResponse> GetBestMatch(string Address, string Address2, string City, string State, string Zip, string TaxType, string LicenseKey)
        {
            SOAPClient clientPrimary = null;
            SOAPClient clientBackup = null;

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

                BestMatchResponse response = await clientPrimary.GetBestMatchAsync(
                    Address, Address2, City, State, Zip, TaxType, LicenseKey).ConfigureAwait(false);

                if (_isLive && !IsValid(response))
                {
                    throw new InvalidOperationException("Primary endpoint returned null or a fatal Number=4 error for GetBestMatch");
                }
                return response;
            }
            catch (Exception primaryEx)
            {

                try
                {
                    clientBackup = new SOAPClient();
                    clientBackup.Endpoint.Address = new System.ServiceModel.EndpointAddress(_backupUrl);
                    clientBackup.InnerChannel.OperationTimeout = TimeSpan.FromMilliseconds(_timeoutMs);

                    return await clientBackup.GetBestMatchAsync(
                        Address, Address2, City, State, Zip, TaxType, 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(BestMatchResponse response) => response?.Error == null || response.Error.Number != "4";
    }
}

FastTax Python Code Snippet

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


class GetBestMatchSoap:
    def __init__(self, license_key: str, is_live: bool = True, timeout_ms: int = 15000):
        """
        license_key: Service Objects FT 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/ft/soap.svc?wsdl"
            if is_live
            else "https://trial.serviceobjects.com/ft/soap.svc?wsdl"
        )
        self._backup_wsdl = (
            "https://swsbackup.serviceobjects.com/ft/soap.svc?wsdl"
            if is_live
            else "https://trial.serviceobjects.com/ft/soap.svc?wsdl"
        )

    def get_best_match(
        self,
        address: str,
        address2: str,
        city: str,
        state: str,
        zip: str,
        tax_type: str,
    ) -> Object:
        """
        Calls the GetBestMatch SOAP  API to retrieve the information.

        Parameters:
            address: Address line of the address to get tax rates for (e.g., "123 Main Street").
            address2: Secondary address line (e.g., "Apt 4B"). Optional.
            city: The city of the address (e.g., "New York"). Optional if zip is provided.
            state: The state of the address (e.g., "NY"). Optional if zip is provided.
            zip: The ZIP code of the address. Optional if city and state are provided.
            tax_type: The type of tax to look for ("sales" or "use").
            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 tax rate details or error.
        """

        # Common kwargs for both calls
        call_kwargs = dict(
            Address=address,
            Address2=address2,
            City=city,
            State=state,
            Zip=zip,
            TaxType=tax_type,
            LicenseKey=self.license_key,
        )

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

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

            return response

        except (WebFault, ValueError, Exception) as primary_ex:
            # Attempt backup
            try:
                client = Client(self._backup_wsdl)
                response = client.service.GetBestMatch(**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)

FastTax NodeJS Code Snippet

import { soap } from 'strong-soap';

/**
 * <summary>
 * A class that provides functionality to call the ServiceObjects FastTax (FT) SOAP service's GetBestMatch endpoint,
 * retrieving tax rate information (e.g., total tax rate, city, county, state rates) for a given US address with fallback to a backup endpoint for reliability in live mode.
 * </summary>
 */
class GetBestMatchSoap {
    /**
     * <summary>
     * Initializes a new instance of the GetBestMatchSoap class with the provided input parameters,
     * setting up primary and backup WSDL URLs based on the live/trial mode.
     * </summary>
     * @param {string} Address - Address line of the address to get tax rates for (e.g., "123 Main Street").
     * @param {string} Address2 - Secondary address line (e.g., "Apt 4B"). Optional.
     * @param {string} City - The city of the address (e.g., "New York"). Optional if zip is provided.
     * @param {string} State - The state of the address (e.g., "NY"). Optional if zip is provided.
     * @param {string} Zip - The ZIP code of the address. Optional if city and state are provided.
     * @param {string} TaxType - The type of tax to look for ("sales" or "use").
     * @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.
     * @throws {Error} Thrown if LicenseKey is empty or null.
     */
    constructor(Address, Address2, City, State, Zip, TaxType, LicenseKey, isLive = true, timeoutSeconds = 15) {

        this.args = {
            Address,
            Address2,
            City,
            State,
            Zip,
            TaxType,
            LicenseKey
        };

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

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

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

    /**
     * <summary>
     * Asynchronously calls the GetBestMatch 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 {Promise<Object>} A promise that resolves to an object containing tax rate details or an error.
     * @throws {Error} Thrown if both primary and backup calls fail, with detailed error messages.
     */
    async invokeAsync() {
        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 object.
     * </summary>
     * @param {string} wsdlUrl - The WSDL URL of the SOAP service endpoint (primary or backup).
     * @param {Object} args - The arguments to pass to the GetBestMatch 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.GetBestMatch(args, (err, result) => {
                    const response = result?.GetBestMatchResult;
                    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}`));
                    }
                });
            });
        });
    }

    /**
     * <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 {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.Number !== '4');
    }
}

export { GetBestMatchSoap };