### Install ZipTax Go SDK Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Use 'go get' to install the ZipTax Go SDK. This command fetches and installs the package and its dependencies. ```bash go get github.com/ziptax/ziptax-go ``` -------------------------------- ### Quick Start: Get Sales Tax by Address Source: https://github.com/ziptax/ziptax-go/blob/main/README.md A basic example demonstrating how to create a ZipTax client and retrieve sales tax information for a given address. Ensure you replace 'your-api-key-here' with your actual API key. ```go package main import ( "context" "fmt" "log" "github.com/ziptax/ziptax-go" ) func main() { // Create a new client with your API key client, err := ziptax.NewClient("your-api-key-here") if err != nil { log.Fatal(err) } // Get sales tax by address ctx := context.Background() response, err := client.GetSalesTaxByAddress(ctx, "200 Spectrum Center Drive, Irvine, CA 92618") if err != nil { log.Fatal(err) } // Print the results fmt.Printf("Address: %s\n", response.AddressDetail.NormalizedAddress) if len(response.TaxSummaries) > 0 { fmt.Printf("Total Tax Rate: %.4f%%\n", response.TaxSummaries[0].Rate*100) } } ``` -------------------------------- ### GoDoc Example for GetOrder Function Source: https://github.com/ziptax/ziptax-go/blob/main/CLAUDE.md Illustrates the GoDoc format for exported functions, including a one-line summary, detailed explanation, practical usage example, and error case information. This function retrieves order details from TaxCloud. ```go // GetOrder retrieves a specific order by its ID from TaxCloud. // This function requires TaxCloud credentials to be configured during client initialization. // // Example: // // ctx := context.Background() // order, err := client.GetOrder(ctx, "order-123") // if err != nil { // return fmt.Errorf("failed to get order: %w", err) // } // fmt.Printf("Order %s has %d line items\n", order.OrderID, len(order.LineItems)) func (c *Client) GetOrder(ctx context.Context, orderID string) (*models.OrderResponse, error) ``` -------------------------------- ### Set Request Timeout with Context Source: https://github.com/ziptax/ziptax-go/blob/main/README.md This example shows how to set a timeout for an API request using `context.WithTimeout`. Ensure `defer cancel()` is called to release resources. ```go // With timeout ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) deferr cancel() response, err := client.GetSalesTaxByAddress(ctx, address) ``` -------------------------------- ### Recommend Product Code (TIC) Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Get an AI-powered best-match recommendation for a Taxability Information Code (TIC) based on a product description. This may have slightly higher latency. ```go response, err := client.RecommendProductCode(ctx, "baked goods sold in plastic packaging") if err != nil { log.Fatal(err) } prediction := response.Predictions[0] if prediction.Status == "success" { fmt.Printf("Recommended TIC: %s (%s)\n", prediction.TicID, prediction.Label) fmt.Printf("Description: %s\n", prediction.TicDescription) } ``` -------------------------------- ### Cancel Request with Context Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Demonstrates how to cancel an API request using `context.WithCancel`. The cancellation can be triggered from a separate goroutine, as shown in the example. ```go // With cancellation ctx, cancel := context.WithCancel(context.Background()) deferr cancel() // Cancel from another goroutine go func() { time.Sleep(100 * time.Millisecond) cancel() }() response, err := client.GetSalesTaxByAddress(ctx, address) ``` -------------------------------- ### Get Account Metrics (Go) Source: https://context7.com/ziptax/ziptax-go/llms.txt Retrieves account metrics including API usage statistics, request limits, and account status. Useful for monitoring API consumption. ```go package main import ( "context" "fmt" "log" "os" "github.com/ziptax/ziptax-go" ) func main() { client, _ := ziptax.NewClient(os.Getenv("ZIPTAX_API_KEY")) ctx := context.Background() metrics, err := client.GetAccountMetrics(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Account Status: Active=%v\n", metrics.IsActive) fmt.Printf("Message: %s\n", metrics.Message) fmt.Printf("\nCore API Usage:\n") fmt.Printf(" Requests: %d / %d\n", metrics.CoreRequestCount, metrics.CoreRequestLimit) fmt.Printf(" Usage: %.2f%%\n", metrics.CoreUsagePercent) fmt.Printf("\nGeo API Usage:\n") fmt.Printf(" Enabled: %v\n", metrics.GeoEnabled) fmt.Printf(" Requests: %d / %d\n", metrics.GeoRequestCount, metrics.GeoRequestLimit) fmt.Printf(" Usage: %.2f%%\n", metrics.GeoUsagePercent) } ``` -------------------------------- ### Get Rates by Postal Code Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Fetch sales tax rates for a given postal code. The response includes details for each city within that postal code. ```go response, err := client.GetRatesByPostalCode(ctx, "92694") for _, result := range response.Results { fmt.Printf("City: %s, Total Tax Rate: %.4f%%\n", result.GeoCity, result.TaxSales*100) } ``` -------------------------------- ### Get Account Metrics Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Retrieve account usage metrics, including core usage percentage and geolocation usage percentage. This helps monitor API consumption. ```go metrics, err := client.GetAccountMetrics(ctx) fmt.Printf("Core Usage: %.2f%%\n", metrics.CoreUsagePercent) fmt.Printf("Geo Usage: %.2f%%\n", metrics.GeoUsagePercent) ``` -------------------------------- ### Get Account Metrics Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Retrieve account usage metrics, including core and geolocation usage percentages. ```APIDOC ## Get Account Metrics ```go metrics, err := client.GetAccountMetrics(ctx) fmt.Printf("Core Usage: %.2f%%\n", metrics.CoreUsagePercent) fmt.Printf("Geo Usage: %.2f%%\n", metrics.GeoUsagePercent) ``` ``` -------------------------------- ### Get Sales Tax by Address with Options Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Retrieve sales tax information for a specific address using optional parameters like historical data, country code, and output format. ```go response, err := client.GetSalesTaxByAddress( ctx, "200 Spectrum Center Drive, Irvine, CA 92618", ziptax.WithHistorical("202401"), ziptax.WithCountryCode("USA"), ziptax.WithFormat("json"), ) ``` -------------------------------- ### Internal HTTP Client Methods Source: https://github.com/ziptax/ziptax-go/blob/main/CHANGELOG.md Internal methods for making HTTP requests to the TaxCloud API, supporting POST, PATCH, and GET with options. ```go Post() Patch() GetWithOptions() ``` -------------------------------- ### Recommend Product Code using AI Source: https://context7.com/ziptax/ziptax-go/llms.txt Gets an AI-powered best-match product code (TIC) recommendation. This method returns a single recommendation with higher accuracy but slightly higher latency compared to searching. ```go package main import ( "context" "fmt" "log" "os" "github.com/ziptax/ziptax-go" ) func main() { client, _ := ziptax.NewClient(os.Getenv("ZIPTAX_API_KEY")) ctx := context.Background() // Get AI-powered TIC recommendation response, err := client.RecommendProductCode(ctx, "organic fair trade coffee beans") if err != nil { log.Fatal(err) } if len(response.Predictions) > 0 { prediction := response.Predictions[0] if prediction.Status == "success" { fmt.Printf("Recommended TIC: %s\n", prediction.TicID) fmt.Printf("Label: %s\n", prediction.Label) fmt.Printf("Natural Label: %s\n", prediction.NaturalLabel) fmt.Printf("TIC Description: %s\n", prediction.TicDescription) fmt.Printf("Product Description: %s\n", prediction.ProductDescription) } else if prediction.Error != nil { fmt.Printf("Prediction failed: %s\n", *prediction.Error) } } } ``` -------------------------------- ### Get Rates by Postal Code (Go) Source: https://context7.com/ziptax/ziptax-go/llms.txt Retrieves tax rates for a US postal code. Handles both 5-digit and 9-digit postal codes, normalizing the latter. ```go package main import ( "context" "fmt" "log" "os" "github.com/ziptax/ziptax-go" ) func main() { client, _ := ziptax.NewClient(os.Getenv("ZIPTAX_API_KEY")) ctx := context.Background() // Lookup by postal code response, err := client.GetRatesByPostalCode(ctx, "92618") if err != nil { log.Fatal(err) } fmt.Printf("Results for postal code %s:\n", response.Results[0].GeoPostalCode) for _, result := range response.Results { fmt.Printf("\n City: %s, %s %s\n", result.GeoCity, result.GeoState, result.GeoCounty) fmt.Printf(" Sales Tax: %.4f%%\n", result.TaxSales*100) fmt.Printf(" Use Tax: %.4f%%\n", result.TaxUse*100) fmt.Printf(" State Sales Tax: %.4f%%\n", result.StateSalesTax*100) fmt.Printf(" City Sales Tax: %.4f%%\n", result.CitySalesTax*100) fmt.Printf(" County Sales Tax: %.4f%%\n", result.CountySalesTax*100) fmt.Printf(" District Sales Tax: %.4f%%\n", result.DistrictSalesTax*100) fmt.Printf(" Origin/Destination: %s\n", result.OriginDestination) } // 9-digit postal codes are automatically normalized to 5-digit response2, err := client.GetRatesByPostalCode(ctx, "92618-1905") if err != nil { log.Fatal(err) } fmt.Printf("\nNormalized from 92618-1905: %s\n", response2.Results[0].GeoPostalCode) } ``` -------------------------------- ### Get Rates by Postal Code Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Fetch sales tax rates for a given postal code. The response includes tax rates for different cities within that postal code. ```APIDOC ## Get Rates by Postal Code ```go response, err := client.GetRatesByPostalCode(ctx, "92694") for _, result := range response.Results { fmt.Printf("City: %s, Total Tax Rate: %.4f%%\n", result.GeoCity, result.TaxSales*100) } ``` ``` -------------------------------- ### Get Sales Tax by GeoLocation (Go) Source: https://context7.com/ziptax/ziptax-go/llms.txt Retrieves sales and use tax rates using latitude and longitude coordinates. Supports optional historical date lookups. ```go package main import ( "context" "fmt" "log" "os" "github.com/ziptax/ziptax-go" ) func main() { client, _ := ziptax.NewClient(os.Getenv("ZIPTAX_API_KEY")) ctx := context.Background() // Lookup by coordinates (Irvine, CA) response, err := client.GetSalesTaxByGeoLocation(ctx, "33.65253", "-117.74794") if err != nil { log.Fatal(err) } fmt.Printf("Address: %s\n", response.AddressDetail.NormalizedAddress) fmt.Printf("Incorporated: %s\n", response.AddressDetail.Incorporated) if len(response.TaxSummaries) > 0 { fmt.Printf("Total Tax Rate: %.4f%%\n", response.TaxSummaries[0].Rate*100) } // With optional historical date historicalResponse, err := client.GetSalesTaxByGeoLocation( ctx, "33.65253", "-117.74794", ziptax.WithHistorical("202312"), ) if err != nil { log.Fatal(err) } fmt.Printf("Historical Rate (Dec 2023): %.4f%%\n", historicalResponse.TaxSummaries[0].Rate*100) } ``` -------------------------------- ### Get Sales Tax by Address Source: https://context7.com/ziptax/ziptax-go/llms.txt Retrieve sales and use tax rate details for a US or Canadian street address. Supports optional parameters for historical rates, country code, and output format. ```go package main import ( "context" "fmt" "log" "os" "github.com/ziptax/ziptax-go" ) func main() { client, _ := ziptax.NewClient(os.Getenv("ZIPTAX_API_KEY")) ctx := context.Background() // Basic address lookup response, err := client.GetSalesTaxByAddress(ctx, "200 Spectrum Center Drive, Irvine, CA 92618") if err != nil { log.Fatal(err) } fmt.Printf("Normalized Address: %s\n", response.AddressDetail.NormalizedAddress) fmt.Printf("Coordinates: (%.6f, %.6f)\n", response.AddressDetail.GeoLat, response.AddressDetail.GeoLng) fmt.Printf("Incorporated: %s\n", response.AddressDetail.Incorporated) // Print tax summaries for _, summary := range response.TaxSummaries { fmt.Printf("%s Tax Rate: %.4f%%\n", summary.SummaryName, summary.Rate*100) } // Print base rates by jurisdiction for _, rate := range response.BaseRates { fmt.Printf(" %s (%s): %.4f%%\n", rate.JurName, rate.JurType, rate.Rate*100) } // With optional parameters (historical rates, country code) historicalResponse, err := client.GetSalesTaxByAddress( ctx, "200 Spectrum Center Drive, Irvine, CA 92618", ziptax.WithHistorical("202401"), // YYYYMM format ziptax.WithCountryCode("USA"), // USA or CAN ziptax.WithFormat("json"), // json or xml ) if err != nil { log.Fatal(err) } fmt.Printf("Historical Rate (Jan 2024): %.4f%%\n", historicalResponse.TaxSummaries[0].Rate*100) } ``` -------------------------------- ### Initialize Client with TaxCloud Credentials Source: https://github.com/ziptax/ziptax-go/blob/main/CLAUDE.md Demonstrates how to initialize the ZipTax client with optional TaxCloud credentials for dual API support. TaxCloud features are only available if these credentials are provided. ```go // Optional TaxCloud credentials client := ziptax.NewClient( "ziptax-api-key", ziptax.WithTaxCloudConnectionID("connection-id"), ziptax.WithTaxCloudAPIKey("taxcloud-key"), ) ``` -------------------------------- ### Get Sales Tax by Geolocation Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Calculate sales tax based on latitude and longitude coordinates. ```APIDOC ## Get Sales Tax by Geolocation ```go response, err := client.GetSalesTaxByGeoLocation( ctx, "33.65253", // latitude "-117.74794", // longitude ) ``` ``` -------------------------------- ### Common Development Commands Source: https://github.com/ziptax/ziptax-go/blob/main/CLAUDE.md Provides a list of common Make commands for managing the Go project, including running tests, building, formatting code, and linting. ```bash # Run tests make test # Run tests with coverage make test-coverage # Build make build # Format code make fmt # Run linter make lint # Run all checks make check ``` -------------------------------- ### Build the SDK Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Build the Ziptax Go SDK using the `make build` command. This compiles the SDK for use in your projects. ```bash # Build the SDK make build ``` -------------------------------- ### Initialize ZipTax Client Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Demonstrates creating a ZipTax client with default settings or custom options like timeout, retries, and retry wait times. ```go client, err := ziptax.NewClient("your-api-key") ``` ```go client, err := ziptax.NewClient( "your-api-key", ziptax.WithTimeout(60*time.Second), ziptax.WithMaxRetries(5), ziptax.WithRetryWait(2*time.Second, 60*time.Second), ) ``` -------------------------------- ### Functional Options Pattern for Configuration Source: https://github.com/ziptax/ziptax-go/blob/main/CLAUDE.md Shows the implementation of the functional options pattern for configuring the client. This pattern allows for backward compatibility and flexible option composition. ```go type Option func(*Config) func WithTimeout(d time.Duration) Option { return func(c *Config) { c.Timeout = d } } ``` -------------------------------- ### Get Sales Tax by Geolocation Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Calculate sales tax based on latitude and longitude coordinates. This function is useful for location-based tax lookups. ```go response, err := client.GetSalesTaxByGeoLocation( ctx, "33.65253", // latitude "-117.74794", // longitude ) ``` -------------------------------- ### Format Code Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Format the project's Go code according to standard Go formatting conventions using the `make fmt` command. ```bash # Format code make fmt ``` -------------------------------- ### Run All Tests Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Execute all tests in the project using the `make test` command. This is a standard command for running the test suite. ```bash # Run all tests make test ``` -------------------------------- ### Enable TaxCloud Order Management Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Initialize the client with TaxCloud credentials to enable TaxCloud order features. Both ZipTax and TaxCloud credentials are required. ```go client, err := ziptax.NewClient( "your-ziptax-api-key", ziptax.WithTaxCloudConnectionID("your-taxcloud-connection-id"), ziptax.WithTaxCloudAPIKey("your-taxcloud-api-key"), ) ``` -------------------------------- ### Initialize ZipTax Client Source: https://context7.com/ziptax/ziptax-go/llms.txt Create a ZipTax client using your API key. Supports optional configurations for timeouts, retries, and TaxCloud credentials. ```go package main import ( "log" "net/http" "os" "time" "github.com/ziptax/ziptax-go" ) func main() { // Basic client with default settings client, err := ziptax.NewClient(os.Getenv("ZIPTAX_API_KEY")) if err != nil { log.Fatal(err) } // Client with custom configuration customClient, err := ziptax.NewClient( os.Getenv("ZIPTAX_API_KEY"), ziptax.WithTimeout(60*time.Second), ziptax.WithMaxRetries(5), ziptax.WithRetryWait(2*time.Second, 60*time.Second), ziptax.WithHTTPClient(&http.Client{Timeout: 60 * time.Second}), ziptax.WithUserAgent("my-app/1.0"), ) if err != nil { log.Fatal(err) } // Client with TaxCloud credentials for order management taxCloudClient, err := ziptax.NewClient( os.Getenv("ZIPTAX_API_KEY"), ziptax.WithTaxCloudConnectionID(os.Getenv("TAXCLOUD_CONNECTION_ID")), ziptax.WithTaxCloudAPIKey(os.Getenv("TAXCLOUD_API_KEY")), ) if err != nil { log.Fatal(err) } _ = client _ = customClient _ = taxCloudClient } ``` -------------------------------- ### Create Order Directly using Go Source: https://context7.com/ziptax/ziptax-go/llms.txt Creates a new order in TaxCloud for tax filing. This method requires TaxCloud credentials and pre-calculated tax amounts for each line item. Ensure TaxCloud credentials and connection ID are set as environment variables. ```go package main import ( "context" "fmt" "log" "os" "github.com/ziptax/ziptax-go" "github.com/ziptax/ziptax-go/models" ) func main() { client, _ := ziptax.NewClient( os.Getenv("ZIPTAX_API_KEY"), ziptax.WithTaxCloudConnectionID(os.Getenv("TAXCLOUD_CONNECTION_ID")), ziptax.WithTaxCloudAPIKey(os.Getenv("TAXCLOUD_API_KEY")), ) ctx := context.Background() orderReq := &models.CreateOrderRequest{ OrderID: "order-2024-001", CustomerID: "customer-456", TransactionDate: "2024-01-15T09:30:00Z", CompletedDate: "2024-01-15T14:00:00Z", Origin: models.TaxCloudAddress{ Line1: "323 Washington Ave N", City: "Minneapolis", State: "MN", Zip: "55401-2427", }, Destination: models.TaxCloudAddress{ Line1: "200 Spectrum Center Drive Suite 300", City: "Irvine", State: "CA", Zip: "92618", }, LineItems: []models.CartItemWithTax{ { Index: 0, ItemID: "SKU-001", Price: 29.99, Quantity: 2, Tax: models.Tax{ Amount: 4.65, Rate: 0.0775, }, }, { Index: 1, ItemID: "SKU-002", Price: 15.50, Quantity: 1, Tax: models.Tax{ Amount: 1.20, Rate: 0.0775, }, }, }, Currency: &models.Currency{}, } response, err := client.CreateOrder(ctx, orderReq) if err != nil { log.Fatal(err) } fmt.Printf("Order Created Successfully!\n") fmt.Printf(" Order ID: %s\n", response.OrderID) fmt.Printf(" Customer ID: %s\n", response.CustomerID) fmt.Printf(" Connection ID: %s\n", response.ConnectionID) fmt.Printf(" Transaction Date: %s\n", response.TransactionDate) fmt.Printf(" Completed Date: %s\n", response.CompletedDate) fmt.Printf(" Line Items: %d\n", len(response.LineItems)) for i, item := range response.LineItems { fmt.Printf(" [%d] %s: $%.2f x %.0f, Tax: $%.2f\n", i, item.ItemID, item.Price, item.Quantity, item.Tax.Amount) } } ``` -------------------------------- ### Run Linter Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Execute the project's linter to check for code quality issues using the `make lint` command. ```bash # Run linter make lint ``` -------------------------------- ### Configure ZipTax Client Options Source: https://github.com/ziptax/ziptax-go/blob/main/CHANGELOG.md The SDK supports the functional options pattern for client configuration, including options for logging and context support. ```go WithLogger() ``` -------------------------------- ### Initialize ZipTax and TaxCloud Clients Source: https://context7.com/ziptax/ziptax-go/llms.txt Initializes clients for ZipTax and TaxCloud. The TaxCloud client requires additional configuration for connection ID and API key. Ensure environment variables are set for API keys. ```go ziptaxClient, _ := ziptax.NewClient(os.Getenv("ZIPTAX_API_KEY")) taxCloudClient, _ := ziptax.NewClient( os.Getenv("ZIPTAX_API_KEY"), ziptax.WithTaxCloudConnectionID(os.Getenv("TAXCLOUD_CONNECTION_ID")), ziptax.WithTaxCloudAPIKey(os.Getenv("TAXCLOUD_API_KEY")), ) ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Generate a test coverage report by running `make test-coverage`. This command executes tests and provides insights into code coverage. ```bash # Run tests with coverage make test-coverage ``` -------------------------------- ### Get Sales Tax by Address Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Retrieve sales tax information for a given US address. Optional parameters allow for historical data, country code specification, and response format. ```APIDOC ## Get Sales Tax by Address ```go response, err := client.GetSalesTaxByAddress( ctx, "200 Spectrum Center Drive, Irvine, CA 92618", ) ``` With optional parameters: ```go response, err := client.GetSalesTaxByAddress( ctx, "200 Spectrum Center Drive, Irvine, CA 92618", ziptax.WithHistorical("202401"), ziptax.WithCountryCode("USA"), ziptax.WithFormat("json"), ) ``` ``` -------------------------------- ### Organize Imports Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Organize Go imports in the project using the `make imports` command. This ensures imports are correctly sorted and formatted. ```bash # Organize imports make imports ``` -------------------------------- ### Client Initialization Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Initialize the ZipTax client with your API key. Optional configurations for timeout, retries, and TaxCloud credentials can be provided. ```APIDOC ## Client Initialization Create a client with default settings (ZipTax API only): ```go client, err := ziptax.NewClient("your-api-key") ``` Or customize the client with options: ```go client, err := ziptax.NewClient( "your-api-key", ziptax.WithTimeout(60*time.Second), ziptax.WithMaxRetries(5), ziptax.WithRetryWait(2*time.Second, 60*time.Second), ) ``` **Enable TaxCloud Order Management (Optional):** To use TaxCloud order features, provide both TaxCloud credentials during initialization: ```go client, err := ziptax.NewClient( "your-ziptax-api-key", ziptax.WithTaxCloudConnectionID("your-taxcloud-connection-id"), ziptax.WithTaxCloudAPIKey("your-taxcloud-api-key"), ) ``` ``` -------------------------------- ### Run All Checks Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Perform all code quality checks, including formatting, linting, and tests, by running `make check`. ```bash # Run all checks make check ``` -------------------------------- ### Workflow Diagram Source: https://github.com/ziptax/ziptax-go/blob/main/CLAUDE.md Illustrates the development workflow from API research to documentation. ```text 1. API Research → 2. Spec Definition → 3. Model Creation → 4. Implementation → 5. Testing → 6. Documentation ``` -------------------------------- ### ZipTax Go SDK Initial Release Features Source: https://github.com/ziptax/ziptax-go/blob/main/CHANGELOG.md The initial release of the ZipTax Go SDK includes core functionalities for sales tax calculation and account metrics, with support for functional options and automatic retries. ```go GetSalesTaxByAddress GetSalesTaxByGeoLocation GetRatesByPostalCode GetAccountMetrics ``` -------------------------------- ### Run Tests with Verbose Output Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Run tests with verbose output enabled using `make test-verbose`. This command provides detailed information about test execution. ```bash # Run tests with verbose output make test-verbose ``` -------------------------------- ### Table-Driven Tests in Go Source: https://github.com/ziptax/ziptax-go/blob/main/CLAUDE.md Demonstrates the use of table-driven tests for validating multiple scenarios. This pattern is useful for testing functions with various inputs and expected outcomes. ```go func TestValidation(t *testing.T) { tests := []struct { name string input string wantErr bool }{ {"valid", "12345", false}, {"invalid", "abc", true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Test logic }) } } ``` -------------------------------- ### Perform Concurrent Requests Source: https://github.com/ziptax/ziptax-go/blob/main/README.md This snippet illustrates how to safely make concurrent requests to the `GetSalesTaxByAddress` method using goroutines and a `sync.WaitGroup` for synchronization. ```go var wg sync.WaitGroup addresses := []string{"address1", "address2", "address3"} for _, addr := range addresses { wg.Add(1) go func(address string) { defer wg.Done() resp, err := client.GetSalesTaxByAddress(ctx, address) // Handle response... }(addr) } wg.Wait() ``` -------------------------------- ### Create Order From Cart using Go Source: https://context7.com/ziptax/ziptax-go/llms.txt Creates a TaxCloud order from a previously calculated cart. Requires the cartId obtained from a TaxCloud CalculateCart response. Ensure TaxCloud credentials and connection ID are set as environment variables. ```go package main import ( "context" "fmt" "log" "os" "github.com/ziptax/ziptax-go" "github.com/ziptax/ziptax-go/models" ) func main() { client, _ := ziptax.NewClient( os.Getenv("ZIPTAX_API_KEY"), ziptax.WithTaxCloudConnectionID(os.Getenv("TAXCLOUD_CONNECTION_ID")), ziptax.WithTaxCloudAPIKey(os.Getenv("TAXCLOUD_API_KEY")), ) ctx := context.Background() // First, calculate a cart to get a cartId cartReq := &models.CalculateCartRequest{ Items: []models.CartItem{ { CustomerID: "customer-789", Currency: models.CartCurrency{CurrencyCode: "USD"}, Destination: models.CartAddress{Address: "200 Spectrum Center Dr, Irvine, CA 92618"}, Origin: models.CartAddress{Address: "323 Washington Ave N, Minneapolis, MN 55401"}, LineItems: []models.CartLineItem{ {ItemID: "product-A", Price: 49.99, Quantity: 1}, }, }, }, } cartResult, err := client.CalculateCart(ctx, cartReq) if err != nil { log.Fatal(err) } // Extract cartId from TaxCloud response tcCart := cartResult.(*models.TaxCloudCalculateCartResponse) cartID := tcCart.Items[0].CartID fmt.Printf("Calculated cart ID: %s\n", cartID) // Create order from the calculated cart orderReq := &models.CreateOrderFromCartRequest{ CartID: cartID, OrderID: "my-order-12345", } order, err := client.CreateOrderFromCart(ctx, orderReq) if err != nil { log.Fatal(err) } fmt.Printf("Order created: %s\n", order.OrderID) fmt.Printf("Connection ID: %s\n", order.ConnectionID) fmt.Printf("Line Items: %d\n", len(order.LineItems)) } ``` -------------------------------- ### Validate Product Query String Source: https://github.com/ziptax/ziptax-go/blob/main/CHANGELOG.md A helper function to validate that product query strings are not empty before making API calls. ```go ValidateProductQuery(query string) error ``` -------------------------------- ### Configure TaxCloud Client Options Source: https://github.com/ziptax/ziptax-go/blob/main/CHANGELOG.md Use functional options to configure the TaxCloud client, setting connection ID, API key, and custom base URL. ```go WithTaxCloudConnectionID(id string) WithTaxCloudAPIKey(key string) WithTaxCloudBaseURL(url string) ``` -------------------------------- ### Create Order from Cart (TaxCloud) Source: https://github.com/ziptax/ziptax-go/blob/main/README.md After calculating a cart with TaxCloud credentials, convert it into a finalized order. This requires the cartId returned from a previous CalculateCart call. ```go req := &models.CreateOrderFromCartRequest{ CartID: "ce4a1234-5678-90ab-cdef-1234567890ab", // from CalculateCart response OrderID: "my-order-1", // your internal order ID } order, err := client.CreateOrderFromCart(ctx, req) if err != nil { log.Fatal(err) } fmt.Printf("Order created: %s\n", order.OrderID) ``` -------------------------------- ### Create a New Order for Tax Filing (TaxCloud) Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Create a new order for tax filing using TaxCloud API. Ensure all required fields, including origin, destination, and line items with tax details, are provided. ```go orderReq := &models.CreateOrderRequest{ OrderID: "order-123", CustomerID: "customer-456", TransactionDate: "2024-01-15T09:30:00Z", CompletedDate: "2024-01-15T09:30:00Z", Origin: models.TaxCloudAddress{ Line1: "200 Spectrum Center Drive Suite 300", City: "Irvine", State: "CA", Zip: "92618", }, Destination: models.TaxCloudAddress{ Line1: "323 Washington Ave N", City: "Minneapolis", State: "MN", Zip: "55401-2427", }, LineItems: []models.CartItemWithTax{ { Index: 0, ItemID: "item-1", Price: 10.8, Quantity: 1.5, Tax: models.Tax{ Amount: 1.31, Rate: 0.0813, }, }, }, Currency: &models.Currency{}, } response, err := client.CreateOrder(ctx, orderReq) if err != nil { log.Fatal(err) } fmt.Printf("Order created: %s\n", response.OrderID) ``` -------------------------------- ### Handle Ziptax SDK Errors in Go Source: https://context7.com/ziptax/ziptax-go/llms.txt Demonstrates how to check for and handle specific error types like ValidationError and APIError, as well as sentinel errors such as ErrInvalidAPIKey and ErrRateLimitExceeded, using errors.As and errors.Is. ```go package main import ( "context" "errors" "fmt" "log" "os" "github.com/ziptax/ziptax-go" ) func main() { client, _ := ziptax.NewClient(os.Getenv("ZIPTAX_API_KEY")) ctx := context.Background() // Example: Handle validation errors _, err := client.GetSalesTaxByAddress(ctx, "") if err != nil { var validationErr *ziptax.ValidationError if errors.As(err, &validationErr) { fmt.Printf("Validation Error:\n") fmt.Printf(" Field: %s\n", validationErr.Field) fmt.Printf(" Value: %q\n", validationErr.Value) fmt.Printf(" Message: %s\n", validationErr.Message) } } // Example: Handle API errors invalidClient, _ := ziptax.NewClient("invalid-key") _, err = invalidClient.GetSalesTaxByAddress(ctx, "200 Spectrum Center Drive, Irvine, CA 92618") if err != nil { var apiErr *ziptax.APIError if errors.As(err, &apiErr) { fmt.Printf("\nAPI Error:\n") fmt.Printf(" Status Code: %d\n", apiErr.StatusCode) fmt.Printf(" Code: %d\n", apiErr.Code) fmt.Printf(" Name: %s\n", apiErr.Name) fmt.Printf(" Message: %s\n", apiErr.Message) } } // Example: Check for sentinel errors response, err := client.GetSalesTaxByAddress(ctx, "200 Spectrum Center Drive, Irvine, CA 92618") if err != nil { switch { case errors.Is(err, ziptax.ErrInvalidAPIKey): log.Fatal("Invalid API key - check your credentials") case errors.Is(err, ziptax.ErrRateLimitExceeded): log.Fatal("Rate limit exceeded - implement backoff") case errors.Is(err, ziptax.ErrTaxCloudNotConfigured): log.Fatal("TaxCloud credentials required for this operation") case errors.Is(err, ziptax.ErrTimeout): log.Fatal("Request timed out") case errors.Is(err, ziptax.ErrContextCanceled): log.Fatal("Context was canceled") default: log.Fatalf("Unexpected error: %v", err) } } fmt.Printf("\nSuccess: %s\n", response.AddressDetail.NormalizedAddress) } ``` -------------------------------- ### Error Handling and Validation Source: https://github.com/ziptax/ziptax-go/blob/main/CHANGELOG.md The SDK provides structured error types and input validation for addresses, coordinates, postal codes, and dates, along with context support for timeouts and cancellation. ```go APIError ValidationError ``` -------------------------------- ### Default UserAgent Update Source: https://github.com/ziptax/ziptax-go/blob/main/CHANGELOG.md The default UserAgent string is now dynamically generated using the `Version` constant, formatted as `"ziptax-go/" + Version`. ```go "ziptax-go/" + Version ``` -------------------------------- ### Recommend Product Code (TIC) Source: https://github.com/ziptax/ziptax-go/blob/main/CHANGELOG.md Utilize this method for AI-powered Taxability Information Code (TIC) recommendations. It posts to ZipTax /search/tic/recommend and provides a single best-match recommendation. Expect slightly higher latency due to AI processing. ```go RecommendProductCode(query string) (*ProductCodeRecommendation, error) ``` -------------------------------- ### CreateOrder API Source: https://context7.com/ziptax/ziptax-go/llms.txt Creates a new order in TaxCloud for tax filing. Requires TaxCloud credentials and pre-calculated tax amounts. ```APIDOC ## POST /orders ### Description Creates a new order in TaxCloud for tax filing. Requires TaxCloud credentials and pre-calculated tax amounts. ### Method POST ### Endpoint /orders ### Request Body - **OrderID** (string) - Required - A unique identifier for the order. - **CustomerID** (string) - Required - The customer's unique identifier. - **TransactionDate** (string) - Required - The date and time of the transaction (ISO 8601 format). - **CompletedDate** (string) - Required - The date and time the order was completed (ISO 8601 format). - **Origin** (object) - Required - The origin address for the order. - **Line1** (string) - Required - Street address. - **City** (string) - Required - City name. - **State** (string) - Required - State abbreviation. - **Zip** (string) - Required - ZIP code. - **Destination** (object) - Required - The destination address for the order. - **Line1** (string) - Required - Street address. - **City** (string) - Required - City name. - **State** (string) - Required - State abbreviation. - **Zip** (string) - Required - ZIP code. - **LineItems** (array) - Required - A list of items in the order. - **Index** (integer) - Required - The index of the line item. - **ItemID** (string) - Required - The item's unique identifier. - **Price** (number) - Required - The price of the item. - **Quantity** (integer) - Required - The quantity of the item. - **Tax** (object) - Required - Tax details for the item. - **Amount** (number) - Required - The calculated tax amount. - **Rate** (number) - Required - The tax rate applied. - **Currency** (object) - Optional - Currency details for the order. ### Request Example ```json { "OrderID": "order-2024-001", "CustomerID": "customer-456", "TransactionDate": "2024-01-15T09:30:00Z", "CompletedDate": "2024-01-15T14:00:00Z", "Origin": { "Line1": "323 Washington Ave N", "City": "Minneapolis", "State": "MN", "Zip": "55401-2427" }, "Destination": { "Line1": "200 Spectrum Center Drive Suite 300", "City": "Irvine", "State": "CA", "Zip": "92618" }, "LineItems": [ { "Index": 0, "ItemID": "SKU-001", "Price": 29.99, "Quantity": 2, "Tax": { "Amount": 4.65, "Rate": 0.0775 } }, { "Index": 1, "ItemID": "SKU-002", "Price": 15.50, "Quantity": 1, "Tax": { "Amount": 1.20, "Rate": 0.0775 } } ], "Currency": {} } ``` ### Response #### Success Response (200) - **OrderID** (string) - The unique identifier for the created order. - **CustomerID** (string) - The customer's unique identifier. - **ConnectionID** (string) - The TaxCloud connection ID. - **TransactionDate** (string) - The date and time of the transaction. - **CompletedDate** (string) - The date and time the order was completed. - **LineItems** (array) - A list of line items in the order. #### Response Example ```json { "OrderID": "order-2024-001", "CustomerID": "customer-456", "ConnectionID": "your-connection-id", "TransactionDate": "2024-01-15T09:30:00Z", "CompletedDate": "2024-01-15T14:00:00Z", "LineItems": [ { "Index": 0, "ItemID": "SKU-001", "Price": 29.99, "Quantity": 2, "Tax": { "Amount": 4.65, "Rate": 0.0775 } }, { "Index": 1, "ItemID": "SKU-002", "Price": 15.50, "Quantity": 1, "Tax": { "Amount": 1.20, "Rate": 0.0775 } } ] } ``` ``` -------------------------------- ### Perform Full Refund Source: https://github.com/ziptax/ziptax-go/blob/main/README.md Use this snippet to create a full refund for an entire order. An empty request body signifies a full refund. Note that an order can only be refunded once. ```go // Empty request for full order refund refundReq := &models.RefundTransactionRequest{} refunds, err := client.RefundOrder(ctx, "order-123", refundReq) if err != nil { log.Fatal(err) } fmt.Printf("Full order refund created\n") ``` -------------------------------- ### Build and Calculate Cart Request Source: https://context7.com/ziptax/ziptax-go/llms.txt Constructs a sales tax calculation request for a shopping cart, including items with prices, quantities, and taxability codes. The request format is consistent for both ZipTax and TaxCloud. ```go tic := int64(40030) // Example TIC for clothing cartReq := &models.CalculateCartRequest{ Items: []models.CartItem{ { CustomerID: "customer-453", Currency: models.CartCurrency{CurrencyCode: "USD"}, Destination: models.CartAddress{ Address: "200 Spectrum Center Dr, Irvine, CA 92618", }, Origin: models.CartAddress{ Address: "323 Washington Ave N, Minneapolis, MN 55401-2427", }, LineItems: []models.CartLineItem{ { ItemID: "item-1", Price: 29.99, Quantity: 2, TaxabilityCode: &tic, }, { ItemID: "item-2", Price: 15.50, Quantity: 1, }, }, }, }, } // Calculate with ZipTax ziptaxResult, err := ziptaxClient.CalculateCart(ctx, cartReq) if err != nil { log.Fatal(err) } // Calculate with TaxCloud taxCloudResult, err := taxCloudClient.CalculateCart(ctx, cartReq) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Calculate Cart Tax (Dual Routing) Source: https://github.com/ziptax/ziptax-go/blob/main/CHANGELOG.md Calculate taxes for a shopping cart. This method defaults to routing to ZipTax /calculate/cart but automatically routes to TaxCloud /tax/connections/{connectionId}/carts when TaxCloud credentials are configured. It uses the same input contract regardless of the backend. ```go CalculateCart(request *CalculateCartRequest) (CalculateCartResult, error) ``` -------------------------------- ### Retrieve Order Details with Go Source: https://context7.com/ziptax/ziptax-go/llms.txt Fetches an existing order from TaxCloud using its order ID. Requires API keys and connection ID to be set as environment variables. ```go package main import ( "context" "fmt" "log" "os" "github.com/ziptax/ziptax-go" ) func main() { client, _ := ziptax.NewClient( os.Getenv("ZIPTAX_API_KEY"), ziptax.WithTaxCloudConnectionID(os.Getenv("TAXCLOUD_CONNECTION_ID")), ziptax.WithTaxCloudAPIKey(os.Getenv("TAXCLOUD_API_KEY")), ) ctx := context.Background() order, err := client.GetOrder(ctx, "order-2024-001") if err != nil { log.Fatal(err) } fmt.Printf("Order Details:\n") fmt.Printf(" Order ID: %s\n", order.OrderID) fmt.Printf(" Customer ID: %s\n", order.CustomerID) fmt.Printf(" Transaction Date: %s\n", order.TransactionDate) fmt.Printf(" Completed Date: %s\n", order.CompletedDate) fmt.Printf(" Exclude From Filing: %v\n", order.ExcludeFromFiling) fmt.Printf(" Delivered By Seller: %v\n", order.DeliveredBySeller) fmt.Printf("\n Origin: %s, %s, %s %s\n", order.Origin.Line1, order.Origin.City, order.Origin.State, order.Origin.Zip) fmt.Printf(" Destination: %s, %s, %s %s\n", order.Destination.Line1, order.Destination.City, order.Destination.State, order.Destination.Zip) fmt.Printf("\n Line Items (%d):\n", len(order.LineItems)) for _, item := range order.LineItems { fmt.Printf(" - %s: Qty %.0f @ $%.2f, Tax: $%.2f (%.4f%%)\n", item.ItemID, item.Quantity, item.Price, item.Tax.Amount, item.Tax.Rate*100) } } ```