Skip to content
Sales Tax API Client for Go
Go Makefile
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
example Print example fields and values rather than just values Sep 10, 2019
test Allow setting a custom `*http.Client` Sep 4, 2019
.editorconfig Set up initial project Aug 22, 2019
.gitignore
.travis.yml Configure Travis CI Sep 13, 2019
Categories.go
Client.go Add godoc comments to all exported types/methods Sep 13, 2019
CreateCustomer.go Add godoc comments to all exported types/methods Sep 13, 2019
CreateOrder.go Add godoc comments to all exported types/methods Sep 13, 2019
CreateRefund.go Add godoc comments to all exported types/methods Sep 13, 2019
DeleteCustomer.go Add godoc comments to all exported types/methods Sep 13, 2019
DeleteOrder.go
DeleteRefund.go Add godoc comments to all exported types/methods Sep 13, 2019
Error.go Add godoc comments to all exported types/methods Sep 13, 2019
LICENSE
ListCustomers.go
ListOrders.go Add godoc comments to all exported types/methods Sep 13, 2019
ListRefunds.go Add godoc comments to all exported types/methods Sep 13, 2019
NexusRegions.go Add godoc comments to all exported types/methods Sep 13, 2019
README.md Fix release badge on README Sep 13, 2019
RatesForLocation.go Add godoc comments to all exported types/methods Sep 13, 2019
ShowCustomer.go Add godoc comments to all exported types/methods Sep 13, 2019
ShowOrder.go Add godoc comments to all exported types/methods Sep 13, 2019
ShowRefund.go Add godoc comments to all exported types/methods Sep 13, 2019
SummaryRates.go
TaxForOrder.go Add godoc comments to all exported types/methods Sep 13, 2019
TaxForOrder_types.go Add godoc comments to all exported types/methods Sep 13, 2019
UpdateCustomer.go Add godoc comments to all exported types/methods Sep 13, 2019
UpdateOrder.go Add godoc comments to all exported types/methods Sep 13, 2019
UpdateRefund.go Add godoc comments to all exported types/methods Sep 13, 2019
Validate.go Add godoc comments to all exported types/methods Sep 13, 2019
ValidateAddress.go
doc_test.go Add GoDoc examples for each method Sep 13, 2019
go.mod
go.sum
makefile Add commands to makefile for convenience Sep 3, 2019
request.go Build out client and support for necessary HTTP verbs Aug 22, 2019
request_helpers.go

README.md

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

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

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")

Usage

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,
	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 SmartCalcs 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
You can’t perform that action at this time.