Skip to content

taxjar/taxjar-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

64 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TaxJar Sales Tax API for Go GitHub tag (latest SemVer) GoDoc Build Status

TaxJar

Official Go client for Sales Tax API v2. For the API documentation, please visit https://developers.taxjar.com/api/reference/.


Requirements
Installation
Authentication
Usage
Error Handling
Optional Configuration
Sandbox Environment
Testing


Requirements

Installation

go get -u github.com/taxjar/taxjar-go
// Then, import the package:
import "github.com/taxjar/taxjar-go"

Authentication

Generate a TaxJar API token. Enter the token when instantiating with NewClient. You may want to utilize an environment variable such as TAXJAR_API_KEY as seen below:

func NewClient(config ...Config) Config

// Instantiate client with your TaxJar API token:
client := taxjar.NewClient(taxjar.Config{
	APIKey: os.Getenv("TAXJAR_API_KEY"),
})
// or configure client after instantiating:
client := taxjar.NewClient()
client.APIKey = os.Getenv("TAXJAR_API_KEY")

You're now ready to use TaxJar! Check out our quickstart guide to get up and running quickly.

Usage

Categories - List all tax categories
TaxForOrder - Calculate sales tax for an order
ListOrders - List order transactions
ShowOrder - Show order transaction
CreateOrder - Create order transaction
UpdateOrder - Update order transaction
DeleteOrder - Delete order transaction
ListRefunds - List refund transactions
ShowRefund - Show refund transaction
CreateRefund - Create refund transaction
UpdateRefund - Update refund transaction
DeleteRefund - Delete refund transaction
ListCustomers - List customers
ShowCustomer - Show customer
CreateCustomer - Create customer
UpdateCustomer - Update customer
DeleteCustomer - Delete customer
RatesForLocation - List tax rates for a location (by zip/postal code)
NexusRegions - List nexus regions
ValidateAddress - Validate an address
Validate - Validate a VAT number
SummaryRates - Summarize tax rates for all regions


List all tax categories (API docs)

The TaxJar API provides product-level tax rules for a subset of product categories. These categories are to be used for products that are either exempt from sales tax in some jurisdictions or are taxed at reduced rates. You need not pass in a product tax code for sales tax calculations on product that is fully taxable. Simply leave that parameter out.

func (client *Config) Categories() (*CategoriesResponse, error)

res, _ := client.Categories()
fmt.Println(res.Categories) // CategoriesResponse.Categories

Calculate sales tax for an order (API docs)

Shows the sales tax that should be collected for a given order.

func (client *Config) TaxForOrder(params TaxForOrderParams) (*TaxForOrderResponse, error)

res, _ := client.TaxForOrder(taxjar.TaxForOrderParams{
	FromCountry: "US",
	FromZip:     "94025",
	FromState:   "CA",
	FromCity:    "Menlo Park",
	FromStreet:  "2825 Sand Hill Rd",
	ToCountry:   "US",
	ToZip:       "94303",
	ToState:     "CA",
	ToCity:      "Palo Alto",
	ToStreet:    "5230 Newell Road",
	Amount:      267.9,
	Shipping:    0,
	LineItems:   []taxjar.TaxLineItem{
		{
			ID:             "1",
			Quantity:       1,
			ProductTaxCode: "19005",
			UnitPrice:      535.8,
			Discount:       267.9,
		},
	},
})
fmt.Println(res.Tax) // TaxForOrderResponse.Tax
fmt.Println(res.Tax.AmountToCollect) // TaxForOrderResponse.Tax.AmountToCollect

List order transactions (API docs)

Lists existing order transactions created through the API.

func (client *Config) ListOrders(params ListOrdersParams) (*ListOrdersResponse, error)

res, _ := client.ListOrders(ListOrdersParams{
	FromTransactionDate: "2015/05/01",
	ToTransactionDate:   "2015/05/31",
})
fmt.Println(res.Orders) // ListOrdersResponse.Orders

Show order transaction (API docs)

Shows an existing order transaction created through the API.

func (client *Config) ShowOrder(transactionID string, params ...ShowOrderParams) (*ShowOrderResponse, error)

res, _ := client.ShowOrder("123")
fmt.Println(res.Order) // ShowOrderResponse.Order

Create order transaction (API docs)

Creates a new order transaction.

func (client *Config) CreateOrder(params CreateOrderParams) (*CreateOrderResponse, error)

res, _ := client.CreateOrder(taxjar.CreateOrderParams{
	TransactionID:   "123",
	TransactionDate: "2019/05/15",
	FromCountry:     "US",
	FromZip:         "94025",
	FromState:       "CA",
	FromCity:        "Menlo Park",
	FromStreet:      "2825 Sand Hill Rd",
	ToCountry:       "US",
	ToZip:           "94303",
	ToState:         "CA",
	ToCity:          "Palo Alto",
	ToStreet:        "5230 Newell Road",
	Amount:          267.9,
	Shipping:        0,
	SalesTax:        0,
	LineItems:       []taxjar.OrderLineItem{
		{
			ID:             "1",
			Quantity:       1,
			Description:    "Legal Services",
			ProductTaxCode: "19005",
			UnitPrice:      535.8,
			Discount:       267.9,
			SalesTax:       0,
		},
	},
})
fmt.Println(res.Order) // CreateOrderResponse.Order

Update order transaction (API docs)

Updates an existing order transaction created through the API.

func (client *Config) UpdateOrder(params UpdateOrderParams) (*UpdateOrderResponse, error)

res, _ := client.UpdateOrder(taxjar.UpdateOrderParams{
	TransactionID: "123",
	Amount:        283.6,
	Shipping:      5,
	SalesTax:      1.04,
	LineItems:     []taxjar.OrderLineItem{
		{
			ID:             "1",
			Quantity:       1,
			Description:    "Legal Services",
			ProductTaxCode: "19005",
			UnitPrice:      535.8,
			Discount:       267.9,
			SalesTax:       0,
		},
		{
			ID:          "2",
			Quantity:    2,
			Description: "Hoberman Switch Pitch",
			UnitPrice:   10.7,
			Discount:    10.7,
			SalesTax:    1.04,
		},
	},
})
fmt.Println(res.Order) // UpdateOrderResponse.Order

Delete order transaction (API docs)

Deletes an existing order transaction created through the API.

func (client *Config) DeleteOrder(transactionID string, params ...DeleteOrderParams) (*DeleteOrderResponse, error)

res, _ := client.DeleteOrder("123")
fmt.Println(res.Order) // DeleteOrderResponse.Order

List refund transactions (API docs)

Lists existing refund transactions created through the API.

func (client *Config) ListRefunds(params ListRefundsParams) (*ListRefundsResponse, error)

res, _ := client.ListRefunds(taxjar.ListRefundsParams{
	FromTransactionDate: "2015/05/01",
	ToTransactionDate:   "2015/05/31",
})
fmt.Println(res.Refunds) // ListRefundsResponse.Refunds

Show refund transaction (API docs)

Shows an existing refund transaction created through the API.

func (client *Config) ShowRefund(transactionID string, params ...ShowRefundParams) (*ShowRefundResponse, error)

res, _ := client.ShowRefund("321")
fmt.Println(res.Refund) // ShowRefundResponse.Refund

Create refund transaction (API docs)

Creates a new refund transaction.

func (client *Config) CreateRefund(params CreateRefundParams) (*CreateRefundResponse, error)

res, _ := client.CreateRefund(taxjar.CreateRefundParams{
	TransactionID:          "123-refund",
	TransactionReferenceID: "123",
	TransactionDate:        "2019/05/15",
	FromCountry:            "US",
	FromZip:                "94025",
	FromState:              "CA",
	FromCity:               "Menlo Park",
	FromStreet:             "2825 Sand Hill Rd",
	ToCountry:              "US",
	ToZip:                  "94303",
	ToState:                "CA",
	ToCity:                 "Palo Alto",
	ToStreet:               "5230 Newell Road",
	Amount:                 -5.35,
	Shipping:               -0,
	SalesTax:               -0.52,
	LineItems:              []taxjar.RefundLineItem{
		{
			ID:             "1",
			Quantity:       1,
			Description:    "Legal Services",
			ProductTaxCode: "19005",
			UnitPrice:      -0,
			Discount:       -0,
			SalesTax:       -0,
		},
		{
			ID:          "2",
			Quantity:    1,
			Description: "Hoberman Switch Pitch",
			UnitPrice:   -0,
			Discount:    -5.35,
			SalesTax:    -0.52,
		},
	},
})
fmt.Println(res.Refund) // CreateRefundResponse.Refund

Update refund transaction (API docs)

Updates an existing refund transaction created through the API.

func (client *Config) UpdateRefund(params UpdateRefundParams) (*UpdateRefundResponse, error)

res, _ := client.UpdateRefund(taxjar.UpdateRefundParams{
	TransactionID:          "123-refund",
	TransactionReferenceID: "123",
	Amount:                 -10.35,
	Shipping:               -5,
})
fmt.Println(res.Refund) // UpdateRefundResponse.Refund

Delete refund transaction (API docs)

Deletes an existing refund transaction created through the API.

func (client *Config) DeleteRefund(transactionID string, params ...DeleteRefundParams) (*DeleteRefundResponse, error)

res, _ := client.DeleteRefund("123-refund")
fmt.Println(res.Refund) // DeleteRefundResponse.Refund

List customers (API docs)

Lists existing customers created through the API.

func (client *Config) ListCustomers() (*ListCustomersResponse, error)

res, _ := client.ListCustomers()
fmt.Println(res.Customers) // ListCustomersResponse.Customers

Show customer (API docs)

Shows an existing customer created through the API.

func (client *Config) ShowCustomer(customerID string) (*ShowCustomerResponse, error)

res, _ := client.ShowCustomer("123")
fmt.Println(res.Customer) // ShowCustomerResponse.Customer

Create customer (API docs)

Creates a new customer.

func (client *Config) CreateCustomer(params CreateCustomerParams) (*CreateCustomerResponse, error)

res, _ := client.CreateCustomer(taxjar.CreateCustomerParams{
	CustomerID:    "123",
	ExemptionType: "wholesale",
	Name:          "Initech",
	ExemptRegions: []taxjar.ExemptRegion{
		{
			Country: "US",
			State:   "TX",
		},
	},
	Country: "US",
	State:   "TX",
	Zip:     "78744",
	City:    "Austin",
	Street:  "4120 Freidrich Lane",
})
fmt.Println(res.Customer) // CreateCustomerResponse.Customer

Update customer (API docs)

Updates an existing customer created through the API.

func (client *Config) UpdateCustomer(params UpdateCustomerParams) (*UpdateCustomerResponse, error)

res, _ := client.UpdateCustomer(taxjar.UpdateCustomerParams{
	CustomerID:    "123",
	ExemptionType: "non_exempt",
	Name:          "Initech",
	ExemptRegions: []taxjar.ExemptRegion{
		{
			Country: "US",
			State:   "MA",
		},
		{
			Country: "US",
			State:   "TX",
		},
	},
})
fmt.Println(res.Customer) // UpdateCustomerResponse.Customer

Delete customer (API docs)

Deletes an existing customer created through the API.

func (client *Config) DeleteCustomer(customerID string) (*DeleteCustomerResponse, error)

res, _ := client.DeleteCustomer("123")
fmt.Println(res.Customer) // DeleteCustomerResponse.Customer

List tax rates for a location (by zip/postal code) (API docs)

Shows the sales tax rates for a given location.

Please note this method only returns the full combined rate for a given location. It does not support nexus determination, sourcing based on a ship from and ship to address, shipping taxability, product exemptions, customer exemptions, or sales tax holidays. We recommend using TaxForOrder to accurately calculate sales tax for an order.

func (client *Config) RatesForLocation(zip string, params ...RatesForLocationParams) (*RatesForLocationResponse, error)

res, _ := client.RatesForLocation("90002")
fmt.Println(res.Rate) // RatesForLocationResponse.Rate

List nexus regions (API docs)

Lists existing nexus locations for a TaxJar account.

func (client *Config) NexusRegions() (*NexusRegionsResponse, error)

res, _ := client.NexusRegions()
fmt.Println(res.Regions) // NexusRegionsResponse.Regions

Validate an address (API docs)

Validates a customer address and returns back a collection of address matches. Address validation requires a TaxJar Plus subscription.

func (client *Config) ValidateAddress(params ValidateAddressParams) (*ValidateAddressResponse, error)

res, _ := client.ValidateAddress(taxjar.ValidateAddressParams{
	Country: "US",
	State:   "AZ",
	Zip:     "85297",
	City:    "Gilbert",
	Street:  "3301 South Greenfield Rd",
})
fmt.Println(res.Addresses) // ValidateAddressResponse.Addresses

Validate a VAT number (API docs)

Validates an existing VAT identification number against VIES.

func (client *Config) Validate(params ValidateParams) (*ValidateResponse, error)

res, _ := client.Validate({
	VAT: "FR40303265045",
})
fmt.Println(res.Validation) // ValidateResponse.Validation

Summarize tax rates for all regions (API docs)

Retrieve minimum and average sales tax rates by region as a backup.

This method is useful for periodically pulling down rates to use if the TaxJar API is unavailable. However, it does not support nexus determination, sourcing based on a ship from and ship to address, shipping taxability, product exemptions, customer exemptions, or sales tax holidays. We recommend using TaxForOrder to accurately calculate sales tax for an order.

func (client *Config) SummaryRates() (*SummaryRatesResponse, error)

res, _ := client.SummaryRates()
fmt.Println(res.SummaryRates) // SummaryRatesResponse.SummaryRates

Error Handling

res, err := client.TaxForOrder(taxjar.TaxForOrderParams{
	FromCountry: "US",
	FromZip:     "94025",
	FromState:   "CA",
	FromCity:    "Menlo Park",
	FromStreet:  "2825 Sand Hill Rd",
	ToCountry:   "US",
	ToZip:       "94303",
	ToState:     "CA",
	ToCity:      "Palo Alto",
	ToStreet:    "5230 Newell Road",
	Amount:      267.9,
	Shipping:    0,
	LineItems:   []taxjar.TaxLineItem{
		{
			ID:             "1",
			Quantity:       1,
			ProductTaxCode: "19005",
			UnitPrice:      535.8,
			Discount:       267.9,
		},
	},
})
if err != nil {
  fmt.Println(err) // taxjar: 401 Unauthorized - Not Authorized for route 'POST /v2/taxes'
} else {
  fmt.Println(res.Tax)
}
// or extract more information by asserting to `*taxjar.Error`
if err := err.(*taxjar.Error); err != nil {
	fmt.Println(err.Status) // 401
	fmt.Println(err.Err) // Unauthorized
	fmt.Println(err.Detail) // Not authorized for route `POST /v2/taxes'
	fmt.Printf("%+v", errors.Wrap(err, "")) // Stack trace:
	// taxjar: 401 Unauthorized - Not Authorized for route 'POST /v2/taxes'
	//
	// main.main
	//         /Path/to/your/file.go:292
	// runtime.main
	//         /usr/local/go/src/runtime/proc.go:200
	// runtime.goexit
	//         /usr/local/go/src/runtime/asm_amd64.s:1337
} else {
	fmt.Println(res.Tax)
}

Optional Configuration

To add additional headers to each request, assign them to client.Headers. For example, to test specific error response codes, pass the custom X-TJ-Expected-Response header:

client.Headers = map[string]interface{}{
	"X-TJ-Expected-Response": 422,
}

If you'd like to customize the timeout for requests, pass a time value to client.Timeout.

client.Timeout = 45 * time.Second // taxjar.DefaultTimeout: 30 * time.Second

To set more detailed timeouts, you may also pass a custom transport to client.Transport.

client.Transport = &http.Transport{
	DialContext: (&net.Dialer{
		Timeout:   20 * Time.Second,
		KeepAlive: 20 * Time.Second,
	}).DialContext,
	TLSHandshakeTimeout:   20 * time.Second,
	ExpectContinueTimeout: 8 * time.Second,
	ResponseHeaderTimeout: 6 * time.Second,
}

/* taxjar.DefaultTransport:
&http.Transport{
	DialContext: (&net.Dialer{
		Timeout:   10 * Time.Second,
		KeepAlive: 10 * Time.Second,
	}).DialContext,
	TLSHandshakeTimeout:   10 * time.Second,
	ExpectContinueTimeout: 4 * time.Second,
	ResponseHeaderTimeout: 3 * time.Second,
}
*/

For even more customization, pass a custom *http.Client to client.HTTPClient.

client.HTTPClient = &http.Client{/* your configuration here */}

Sandbox Environment

You may also configure the client to use TaxJar's sandbox environment. The sandbox environment requires a TaxJar Plus subscription.

import "github.com/taxjar/taxjar-go"

// Instantiate client and set `APIURL`:
client := taxjar.NewClient(taxjar.Config{
	APIKey: os.Getenv("TAXJAR_SANDBOX_API_KEY"),
	APIURL: taxjar.SandboxAPIURL,
})

// or
client := taxjar.NewClient()
client.APIKey = os.Getenv("TAXJAR_SANDBOX_API_KEY")
client.APIURL = taxjar.SandboxAPIURL

Testing

make test

To validate API methods in the TaxJar sandbox environment, pass the following environment variables:

TAXJAR_API_URL="https://api.sandbox.taxjar.com" \
TAXJAR_API_KEY="9e0cd62a22f451701f29c3bde214" \
make test