public ValidateResult Validate(Address address) { // Convert input address data to query string string querystring = string.Empty; querystring += (address.Line1 == null) ? string.Empty : "Line1=" + address.Line1.Replace(" ", "+"); querystring += (address.Line2 == null) ? string.Empty : "&Line2=" + address.Line2.Replace(" ", "+"); querystring += (address.Line3 == null) ? string.Empty : "&Line3=" + address.Line3.Replace(" ", "+"); querystring += (address.City == null) ? string.Empty : "&City=" + address.City.Replace(" ", "+"); querystring += (address.Region == null) ? string.Empty : "&Region=" + address.Region.Replace(" ", "+"); querystring += (address.PostalCode == null) ? string.Empty : "&PostalCode=" + address.PostalCode.Replace(" ", "+"); querystring += (address.Country == null) ? string.Empty : "&Country=" + address.Country.Replace(" ", "+"); // Call the service Uri webAddress = new Uri(svcURL + "address/validate.xml?" + querystring); HttpWebRequest request = WebRequest.Create(webAddress) as HttpWebRequest; request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(accountNum + ":" + license))); request.Method = "GET"; ValidateResult result = new ValidateResult(); try { WebResponse response = request.GetResponse(); XmlSerializer r = new XmlSerializer(result.GetType()); result = (ValidateResult)r.Deserialize(response.GetResponseStream()); address = result.Address; // If the address was validated, take the validated address. } catch (WebException ex) { Stream responseStream = ((HttpWebResponse)ex.Response).GetResponseStream(); StreamReader reader = new StreamReader(responseStream); string responseString = reader.ReadToEnd(); // The service returns some error messages in JSON for authentication/unhandled errors. if (responseString.StartsWith("{") || responseString.StartsWith("[")) { result = new ValidateResult(); result.ResultCode = SeverityLevel.Error; Message msg = new Message(); msg.Severity = result.ResultCode; msg.Summary = "The request was unable to be successfully serviced, please try again or contact Customer Service."; msg.Source = "Avalara.Web.REST"; if (!((HttpWebResponse)ex.Response).StatusCode.Equals(HttpStatusCode.InternalServerError)) { msg.Summary = "The user or account could not be authenticated."; msg.Source = "Avalara.Web.Authorization"; } result.Messages = new Message[1] { msg }; } else { XmlSerializer r = new XmlSerializer(result.GetType()); byte[] temp = Encoding.ASCII.GetBytes(responseString); MemoryStream stream = new MemoryStream(temp); result = (ValidateResult)r.Deserialize(stream); // Inelegant, but the deserializer only takes streams, and we already read ours out. } } return result; }
//This loads the invoice (or return) located at the specified path and returns a GetTaxRequest object for tax calculation. public static GetTaxRequest Load() { GetTaxRequest req = new GetTaxRequest(); //loads the invoice file string[] txtInv = File.ReadAllLines("INV0001.txt"); //Parses header-level data from the invoice file req.DocCode = txtInv[0].Split(':')[1] + DateTime.Now.ToString(); req.CustomerCode = txtInv[1].Split(':')[1]; req.DocDate = "2012-07-07";//txtInv[3].Split(':')[1]; req.DocType = DocType.SalesInvoice; string[] shipto = txtInv[10].Split(':')[1].Split(','); req.Addresses = new Address[2]; //We will need to pass in two addresses, our origin and destination. //Parse our destiniation address Address dest = new Address(); dest.AddressCode = "01"; dest.Line1 = shipto[0]; dest.City = shipto[1]; dest.Region = shipto[2]; dest.PostalCode = shipto[3]; //Add the address to our request object. req.Addresses[0] = new Address(); req.Addresses[0] = dest; //Hardcodes the origin address for the GetTaxRequest. This should be your warehouse or company address, and should not be hardcoded. req.Addresses[1] = new Address(); req.Addresses[1].AddressCode = "02"; req.Addresses[1].Line1 = "PO Box 123"; req.Addresses[1].City = "Bainbridge Island"; req.Addresses[1].Region = "WA"; req.Addresses[1].PostalCode = "98110"; //create array of line items req.Lines = new Line[txtInv.Length - 12]; //Iterate through line items on transaction and add them to the request for (int i = 1; txtInv.Length > 12 + i; i++) { string[] item = txtInv[12 + i].Split(','); req.Lines[i] = new Line(); req.Lines[i].LineNo = item[0]; req.Lines[i].ItemCode = item[1]; req.Lines[i].Qty = Convert.ToDecimal(item[3]); req.Lines[i].Amount = Convert.ToDecimal(item[4]) * req.Lines[i].Qty; req.Lines[i].OriginCode = "02"; req.Lines[i].DestinationCode = "01"; } //Pull the freight line from the header information and add to the request as an additional line item req.Lines[0] = new Line(); req.Lines[0].ItemCode = "Shipping"; req.Lines[0].Qty = 1; req.Lines[0].LineNo = "FR"; req.Lines[0].Amount = Convert.ToDecimal(txtInv[7].Split(':')[1]); req.Lines[0].OriginCode = "02"; req.Lines[0].DestinationCode = "01"; return req; }
public static Address ToValidateAddressRequest(this VirtoCommerce.Domain.Customer.Model.Address address, string companyCode) { var retVal = new Address() { Country = address.CountryName, City = address.City, Line1 = address.Line1, Line2 = address.Line2, Region = address.RegionName, PostalCode = address.PostalCode }; return retVal; }
public ValidateResult Validate(Address address) { // Convert input address data to query string string querystring = string.Empty; querystring += (address.Line1 == null) ? string.Empty : "Line1=" + address.Line1.Replace(" ", "+"); querystring += (address.Line2 == null) ? string.Empty : "&Line2=" + address.Line2.Replace(" ", "+"); querystring += (address.Line3 == null) ? string.Empty : "&Line3=" + address.Line3.Replace(" ", "+"); querystring += (address.City == null) ? string.Empty : "&City=" + address.City.Replace(" ", "+"); querystring += (address.Region == null) ? string.Empty : "&Region=" + address.Region.Replace(" ", "+"); querystring += (address.PostalCode == null) ? string.Empty : "&PostalCode=" + address.PostalCode.Replace(" ", "+"); querystring += (address.Country == null) ? string.Empty : "&Country=" + address.Country.Replace(" ", "+"); // Call the service var webAddress = new Uri(svcURL + "address/validate?" + querystring); var request = WebRequest.Create(webAddress) as HttpWebRequest; request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(accountNum + ":" + license))); request.Method = "GET"; var result = new ValidateResult(); try { using (var response = (HttpWebResponse)request.GetResponse()) { // Get the stream containing content returned by the server. var responseStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. using (var reader = new StreamReader(responseStream)) { result = JsonConvert.DeserializeObject<ValidateResult>(reader.ReadToEnd()); } } } catch (WebException ex) { using (var response = ex.Response) { using (var data = response.GetResponseStream()) { // Open the stream using a StreamReader for easy access. using (var reader = new StreamReader(data)) { result = JsonConvert.DeserializeObject<ValidateResult>(reader.ReadToEnd()); } } } } return result; }
public static void Test() { // Header Level Elements // Required Header Level Elements string accountNumber = ConfigurationManager.AppSettings["AvaTax:AccountNumber"]; string licenseKey = ConfigurationManager.AppSettings["AvaTax:LicenseKey"]; string serviceURL = ConfigurationManager.AppSettings["AvaTax:ServiceUrl"]; AddressSvc addressSvc = new AddressSvc(accountNumber, licenseKey, serviceURL); Address address = new Address(); // Required Request Parameters address.Line1 = "118 N Clark St"; address.City = "Chicago"; address.Region = "IL"; // Optional Request Parameters address.Line2 = "Suite 100"; address.Line3 = "ATTN Accounts Payable"; address.Country = "US"; address.PostalCode = "60602"; ValidateResult validateResult = addressSvc.Validate(address); // Print results Console.WriteLine("ValidateAddressTest Result: " + validateResult.ResultCode.ToString()); if (!validateResult.ResultCode.Equals(SeverityLevel.Success)) { foreach (Message message in validateResult.Messages) { Console.WriteLine(message.Summary); } } else { Console.WriteLine(validateResult.Address.Line1 + " " + validateResult.Address.City + ", " + validateResult.Address.Region + " " + validateResult.Address.PostalCode); } }
public static void Test() { // Header Level Elements // Required Header Level Elements string accountNumber = "1234567890"; string licenseKey = "A1B2C3D4E5F6G7H8"; string serviceURL = "https://development.avalara.net"; AddressSvc addressSvc = new AddressSvc(accountNumber, licenseKey, serviceURL); Address address = new Address(); // Required Request Parameters address.Line1 = "118 N Clark St"; address.City = "Chicago"; address.Region = "IL"; // Optional Request Parameters address.Line2 = "Suite 100"; address.Line3 = "ATTN Accounts Payable"; address.Country = "US"; address.PostalCode = "60602"; ValidateResult validateResult = addressSvc.Validate(address); // Print results Console.WriteLine("ValidateAddressTest Result: " + validateResult.ResultCode.ToString()); if (!validateResult.ResultCode.Equals(SeverityLevel.Success)) { foreach (Message message in validateResult.Messages) { Console.WriteLine(message.Summary); } } else { Console.WriteLine(validateResult.Address.Line1 + " " + validateResult.Address.City + ", " + validateResult.Address.Region + " " + validateResult.Address.PostalCode); } }
public static void Test() { // Header Level Elements // Required Header Level Elements string accountNumber = "1234567890"; string licenseKey = "A1B2C3D4E5F6G7H8"; string serviceURL = "https://development.avalara.net"; TaxSvc taxSvc = new TaxSvc(accountNumber, licenseKey, serviceURL); GetTaxRequest getTaxRequest = new GetTaxRequest(); // Document Level Elements // Required Request Parameters getTaxRequest.CustomerCode = "ABC4335"; getTaxRequest.DocDate = "2014-01-01"; // Best Practice Request Parameters getTaxRequest.CompanyCode = "APITrialCompany"; getTaxRequest.Client = "AvaTaxSample"; getTaxRequest.DocCode = "INV001"; getTaxRequest.DetailLevel = DetailLevel.Tax; getTaxRequest.Commit = false; getTaxRequest.DocType = DocType.SalesInvoice; // Situational Request Parameters // getTaxRequest.CustomerUsageType = "G"; // getTaxRequest.ExemptionNo = "12345"; // getTaxRequest.Discount = 50; // getTaxRequest.TaxOverride = new TaxOverrideDef(); // getTaxRequest.TaxOverride.TaxOverrideType = "TaxDate"; // getTaxRequest.TaxOverride.Reason = "Adjustment for return"; // getTaxRequest.TaxOverride.TaxDate = "2013-07-01"; // getTaxRequest.TaxOverride.TaxAmount = "0"; // Optional Request Parameters getTaxRequest.PurchaseOrderNo = "PO123456"; getTaxRequest.ReferenceCode = "ref123456"; getTaxRequest.PosLaneCode = "09"; getTaxRequest.CurrencyCode = "USD"; // Address Data Address address1 = new Address(); address1.AddressCode = "01"; address1.Line1 = "45 Fremont Street"; address1.City = "San Francisco"; address1.Region = "CA"; Address address2 = new Address(); address2.AddressCode = "02"; address2.Line1 = "118 N Clark St"; address2.Line2 = "Suite 100"; address2.Line3 = "ATTN Accounts Payable"; address2.City = "Chicago"; address2.Region = "IL"; address2.Country = "US"; address2.PostalCode = "60602"; Address address3 = new Address(); address3.AddressCode = "03"; address3.Latitude = (decimal)47.627935; address3.Longitude = (decimal)-122.51702; Address[] addresses = { address1, address2, address3 }; getTaxRequest.Addresses = addresses; // Line Data // Required Parameters Line line1 = new Line(); line1.LineNo = "01"; line1.ItemCode = "N543"; line1.Qty = 1; line1.Amount = 10; line1.OriginCode = "01"; line1.DestinationCode = "02"; // Best Practice Request Parameters line1.Description = "Red Size 7 Widget"; line1.TaxCode = "NT"; // Situational Request Parameters // line1.CustomerUsageType = "L"; // line1.Discounted = true; // line1.TaxIncluded = true; // line1.TaxOverride = new TaxOverrideDef(); // line1.TaxOverride.TaxOverrideType = "TaxDate"; // line1.TaxOverride.Reason = "Adjustment for return"; // line1.TaxOverride.TaxDate = "2013-07-01"; // line1.TaxOverride.TaxAmount = "0"; // Optional Request Parameters line1.Ref1 = "ref123"; line1.Ref2 = "ref456"; Line line2 = new Line(); line2.LineNo = "02"; line2.ItemCode = "T345"; line2.Qty = 3; line2.Amount = 150; line2.OriginCode = "01"; line2.DestinationCode = "03"; line2.Description = "Size 10 Green Running Shoe"; line2.TaxCode = "PC030147"; Line line3 = new Line(); line3.LineNo = "02-FR"; line3.ItemCode = "FREIGHT"; line3.Qty = 1; line3.Amount = 15; line3.OriginCode = "01"; line3.DestinationCode = "03"; line3.Description = "Shipping Charge"; line3.TaxCode = "FR"; Line[] lines = { line1, line2, line3 }; getTaxRequest.Lines = lines; GetTaxResult getTaxResult = taxSvc.GetTax(getTaxRequest); // Print results Console.WriteLine("GetTaxTest Result: " + getTaxResult.ResultCode.ToString()); if (!getTaxResult.ResultCode.Equals(SeverityLevel.Success)) { foreach (Message message in getTaxResult.Messages) { Console.WriteLine(message.Summary); } } else { Console.WriteLine("Document Code: " + getTaxResult.DocCode + " Total Tax: " + getTaxResult.TotalTax); foreach (TaxLine taxLine in getTaxResult.TaxLines ?? Enumerable.Empty<TaxLine>()) { Console.WriteLine(" " + "Line Number: " + taxLine.LineNo + " Line Tax: " + taxLine.Tax.ToString()); foreach (TaxDetail taxDetail in taxLine.TaxDetails ?? Enumerable.Empty<TaxDetail>()) { Console.WriteLine(" " + "Jurisdiction: " + taxDetail.JurisName + "Tax: " + taxDetail.Tax.ToString()); } } } }
//This loads some test data and returns a GetTaxRequest object for tax calculation. //TODO: These values should not be hardcoded in your integration. You will need to map to the values appropriate to your system. public static GetTaxRequest Load() { GetTaxRequest getTaxRequest = new GetTaxRequest(); //Document Level Setup // R: indicates Required Element // O: Indicates Optional Element // // Set the tax document properties - Required unless noted as Optional //getTaxRequest.CompanyCode = "SDK"; // R: Company Code from the Admin Console. This is passed in to the GetTax.Get function, since it is information typically maintained with the credentials. getTaxRequest.Client = "AvaTaxCalcRESTCsharp Sample"; DateTime docDate = DateTime.Today; getTaxRequest.DocCode = "SampleDoc: " + docDate.ToString(); // R: Invoice or document tracking number - Must be unique getTaxRequest.DocType = DocType.SalesInvoice; // R: Typically SalesOrder,SalesInvoice, ReturnInvoice getTaxRequest.DocDate = docDate.ToString("yyyy-MM-dd"); // R: sets reporting date and default tax date getTaxRequest.CustomerCode = "TaxSvcTest"; // R: String - Customer Tracking number or Exemption Customer Code getTaxRequest.DetailLevel = DetailLevel.Tax; // R: Chose Summary, Document, Line or Tax - varying levels of results detail getTaxRequest.Commit = false; // O: Default is "false" - Set to "true" to commit the Document //getTaxRequest.CustomerUsageType="G"; // O: Send for tax exempt transactions only. //getTaxRequest.ExemptionNo="12334"; // O: Send for tax exempt transactions only. //getTaxRequest.Discount=0; // O: Send for document-level discounts only. getTaxRequest.PurchaseOrderNo = "PO 23423"; // O: Specifies the purchase order number associated with the transaction. This value can be used to track single-use exemption certficates. getTaxRequest.ReferenceCode = ""; // O: This is a reportable value that does not affect tax calculation. getTaxRequest.PosLaneCode = ""; // O: This is a reportable value that does not affect tax calculation. //getTaxRequest.TaxOverride=new TaxOverrideDef(); // O: Allows the TaxDate =or other values) to be overridden for tax calculation. Situational only. //getTaxRequest.BusinessIdentificationNo=""; // O: Specified VAT ID of customer for international/VAT calculations and reporting. // Begin Address Section // Add the origin and destination addresses referred to by the // "setOriginCode" and "setDestinationCode" properties above. Address origin = new Address(); origin.AddressCode = "Origin"; origin.Line1 = "Avalara"; origin.Line2 = "100 Ravine Lane NE"; origin.Line3 = "Suite 220"; origin.City = "Bainbridge Island"; origin.Region = "WA"; origin.PostalCode = "98110"; origin.Country = "USA"; Address destination = new Address(); destination.AddressCode = "Dest"; destination.Line1 = "7462 Kearny Street"; destination.City = "Commerce City"; destination.Region = "CO"; destination.PostalCode = "80022"; destination.Country = "USA"; Address[] addresses = { origin, destination }; // // Alternate: Latitude / Longitude addressing // // // Address origin = new BaseAddress=; // origin.AddressCode="Origin"; // origin.Latitude="47.6253"; // origin.Longitude="-122.515114"; // // Address destination = new BaseAddress=; // destination.AddressCode="Destination"; // destination.Latitude="39.833597"; // destination.Longitude="-104.917220"; // Address[] addresses = {origin, destination}; // End Address Section getTaxRequest.Addresses = addresses; // Add invoice lines Line line1 = new Line(); // New instance of a line line1.LineNo = "101"; // R: string - line Number of invoice - must be unique. line1.ItemCode = "Item001"; // R: string - SKU or short name of Item line1.Qty = 1; // R: decimal - The number of items -- Qty of product sold. Does not function as a mulitplier for Amount line1.Amount = 1000; // R: decimal - the "NET" amount -- Amount should be the 'extended' or 'net' amount line1.CustomerUsageType = ""; // O: string - AKA Entity Use Code - Typically A - L =G = Reseller) line1.Description = "ITEM1"; // O: string - Description or category of item sold. line1.TaxCode = ""; // O: string - Pass standard, custom or Pro-Tax code // Can be NULL to default to tangible personal property =P0000000) line1.OriginCode = "Origin"; // R: Value representing the Origin Address line1.DestinationCode = "Dest"; // R: Value representing the Destination Address //Line 2 - Shipping/Freight line - See property descriptions above Line line2 = new Line(); // New instance of a line line2.LineNo = "102"; // R: string - SKU or short name of Item line2.ItemCode = "Shipping"; // R: string - SKU or short name of Item line2.Description = "Shipping- Freight Charges"; // O: string - Description or category of item sold. line2.Qty = 1; // R: decimal - The number of items -- Qty of product sold. Does not function as a mulitplier for Amount line2.Amount = 10; // R: decimal - the "NET" amount -- Amount should be the 'extended' or 'net' amount line2.TaxCode = "FR"; // O: string - Pass standard, custom or Pro-Tax code FR020100 line2.OriginCode = "Origin"; // R: Value representing the Origin Address line2.DestinationCode = "Dest"; // R: Value representing the Destination Address Line[] lines = { line1, line2 }; getTaxRequest.Lines = lines; // Sets array of lines return getTaxRequest; }
public static ValidateResult Validate(Address addr, string AcctNum, string LicKey, string CompanyCode, string webaddr) { //Convert input address data to query string string querystring = ""; if (addr.Line1 != null) { querystring = querystring + "Line1=" + addr.Line1.Replace(" ", "+"); } if (addr.Line2 != null) { querystring = querystring + "&Line2=" + addr.Line2.Replace(" ", "+"); } if (addr.Line3 != null) { querystring = querystring + "&Line3=" + addr.Line3.Replace(" ", "+"); } if (addr.City != null) { querystring = querystring + "&City=" + addr.City.Replace(" ", "+"); } if (addr.Region != null) { querystring = querystring + "&Region=" + addr.Region.Replace(" ", "+"); } if (addr.PostalCode != null) { querystring = querystring + "&PostalCode=" + addr.PostalCode.Replace(" ", "+"); } if (addr.Country != null) { querystring = querystring + "&Country=" + addr.Country.Replace(" ", "+"); } //Call the service Uri address = new Uri(webaddr + "address/validate.xml?" + querystring); HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(AcctNum + ":" + LicKey))); request.Method = "GET"; ValidateResult result = new ValidateResult(); try { WebResponse response = request.GetResponse(); XmlSerializer r = new XmlSerializer(result.GetType()); result = (ValidateResult)r.Deserialize(response.GetResponseStream()); addr = result.Address; //If the address was validated, take the validated address. } catch (Exception ex) { Console.WriteLine(ex.Message + " on address object"); } Console.WriteLine(result.ResultCode.ToString()); return result; }