> For the complete documentation index, see [llms.txt](https://docs.getsphere.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.getsphere.com/features/integrations/api/tax-calculation.md).

# Tax Calculation

Details on our real-time tax calculation API as well as error codes and messages are provided below.

## Tax Calculation Endpoint

Returns the tax due on each line item for a given customer location, broken down by jurisdiction, plus a `sphere_tax_calculation_id` to store on the resulting payment or invoice.

### Authentication

Send your API key in the `X-API-KEY` header. Contact Sphere to obtain a key. See API.

### Prerequisites

| Requirement                                                                       | If missing                                  |
| --------------------------------------------------------------------------------- | ------------------------------------------- |
| Billing provider connected in Sphere, so your products appear in the Products tab | `product_id` values are not recognised      |
| A Product Tax Code on every product you send                                      | `400 invalid_product_tax_code`              |
| A registration in Sphere for the customer's region, with tax calculation enabled  | `200` with empty `tax_amounts` (no tax due) |

## Calculate tax

> Returns the tax due on each line item for a customer location, broken down by jurisdiction, plus a sphere\_tax\_calculation\_id to store on the resulting payment or invoice.\
> \
> Amounts are integers in the currency's minor unit: 10000 is 100.00 USD. Send either customer\_address, or pull\_customer\_address with customer\_id.\
> \
> Before calling, connect your billing provider so your products appear in Sphere, and give every product a product tax code.\
> \
> A 200 with empty tax\_amounts means no tax is due: you have no active registration for the location, the customer is exempt, the product is exempt, or the sale is reverse-charged. Set include\_taxability\_reason to see which.

```json
{"openapi":"3.1.0","info":{"title":"Sphere API","version":"1.0.0"},"servers":[{"url":"https://api.getsphere.com/v1"},{"url":"https://server.getsphere.com/tax_api/v1"}],"security":[{"apiKeyAuth":[]},{}],"components":{"securitySchemes":{"apiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-KEY"}},"schemas":{"TaxCalculationRequest":{"type":"object","properties":{"customer_id":{"type":["string","null"],"description":"Customer id in your billing system, for example cus_... for Stripe. Lets Sphere apply the customer's stored exemption.","maxLength":255},"customer_address":{"allOf":[{"$ref":"#/components/schemas/CustomerAddress"}],"description":"Where the customer is taxed. Send country, and for the US either postal_code or address1, city and state; a full street address gives the most accurate rate. For Canada, send postal_code or state."},"ship_from":{"allOf":[{"$ref":"#/components/schemas/CustomerAddress"}],"description":"Origin for physical goods. Defaults to your business address in Sphere."},"tax_id":{"type":["string","null"],"description":"Customer tax ID, such as an EU VAT number, for the customer address country. Supported countries are those listed for tax_ids.country. An ID that fails the format check is ignored and tax is calculated as for an unregistered customer.","maxLength":100},"tax_ids":{"type":"array","items":{"$ref":"#/components/schemas/CustomerTaxId"},"description":"Several tax IDs, for example a Canadian GST and Québec QST number. Combined with tax_id."},"transaction_id":{"type":["string","null"],"description":"Invoice or payment id in your billing system, if it already exists. Links this calculation to the transaction when Sphere syncs it.","maxLength":255},"original_transaction_id":{"type":["string","null"],"description":"Credit notes only: the id of the invoice this credit reverses. Reverses that invoice's stored tax instead of calculating fresh; omit it (or if the invoice is not found in Sphere) to calculate normally.","maxLength":255},"line_items":{"type":"array","items":{"$ref":"#/components/schemas/TaxCalculationLineItem"},"description":"At least one line."},"currency":{"type":"string","description":"ISO 4217 code, for example usd.","maxLength":3,"minLength":3},"include_taxability_reason":{"type":"boolean","default":false,"description":"Add a taxability_reason to each tax rate, and return zero-amount entries for untaxed lines so the reason is visible."},"include_tax_source":{"type":"boolean","default":false,"description":"Add tax_source to each line: whether it was taxed at the origin or the destination."},"pull_customer_address":{"type":"boolean","default":false,"description":"Use the address stored on the billing-system customer instead of customer_address. Requires customer_id. Stripe only."},"tax_exempt":{"type":["boolean","null"],"description":"Treat the customer as exempt (true) or taxable (false) for this request only. Omit to use the customer's stored exemption."}},"required":["currency","line_items"]},"CustomerAddress":{"type":"object","properties":{"address1":{"type":["string","null"],"description":"Street address.","maxLength":512},"address2":{"type":["string","null"],"description":"Apartment, suite or unit.","maxLength":512},"city":{"type":["string","null"],"description":"City or town."},"state":{"type":["string","null"],"description":"State or province code, for example CA or QC."},"postal_code":{"type":["string","null"],"description":"Postal or ZIP code."},"country":{"type":["string","null"],"description":"Two-letter country code, for example US."}}},"CustomerTaxId":{"type":"object","properties":{"value":{"type":"string","description":"The tax ID, such as an EU VAT number.","maxLength":100},"country":{"allOf":[{"$ref":"#/components/schemas/CountryEnum"}],"description":"Two-letter country code of the registration; case-insensitive. Defaults to the customer address country. Use ca for Québec QST numbers, ic for the Canary Islands and gr for Greece.","maxLength":2}},"required":["value"]},"CountryEnum":{"type":"string","enum":["ae","al","am","at","au","az","be","bg","bo","br","by","ca","ch","cl","co","cy","cz","de","dk","ec","ee","eg","es","fi","fr","gb","gr","hr","hu","ic","id","ie","il","in","is","it","jp","ke","kh","kr","kz","li","lt","lu","lv","ma","md","mt","mx","my","nl","no","nz","om","pe","ph","pl","pt","ro","rs","ru","sa","se","sg","si","sk","th","tr","tw","tz","ua","uy","uz","vn","za"]},"TaxCalculationLineItem":{"type":"object","properties":{"id":{"type":["string","null"],"description":"Your identifier for the line, echoed back in the response. Defaults to product_id. Make it unique per line.","maxLength":255},"amount":{"type":"integer","description":"Line total in the currency's minor unit: 10000 is 100.00."},"product_id":{"type":"string","description":"Product id in your billing system. Must have a product tax code in Sphere.","maxLength":255},"discount_amount":{"type":"integer","default":0,"description":"Discount on the line, in minor units. Subtracted from amount before tax is calculated."},"tax_inclusive":{"type":"boolean","default":false,"description":"Whether amount already includes tax. A tax pricing behavior set in Sphere on the product, region or account takes precedence. On a credit note that reverses an original line (API connections only), must match that line's tax-inclusive pricing as stored in Sphere, or the request is rejected. If a Sphere setting made the original tax-inclusive, send true."},"original_transaction_line_item_id":{"type":"string","description":"Credit notes only: the id of the line on original_transaction_id this line credits. When any line sets it, lines without it will be treated as new line items to be calculated.","maxLength":255},"ship_to":{"allOf":[{"$ref":"#/components/schemas/CustomerAddress"}],"description":"Destination for this line, for physical goods. Overrides customer_address."},"ship_from":{"allOf":[{"$ref":"#/components/schemas/CustomerAddress"}],"description":"Origin for this line, for physical goods. Overrides the request-level ship_from."}},"required":["amount","product_id"]},"TaxCalculationResponse":{"properties":{"message":{"description":"Human-readable status.","title":"Message","type":"string"},"data":{"$ref":"#/components/schemas/TaxCalculationData"}},"required":["message","data"],"title":"TaxCalculationResponse","type":"object"},"TaxCalculationData":{"properties":{"lines":{"description":"One per line item, in request order.","items":{"$ref":"#/components/schemas/TaxCalculationLine"},"title":"Lines","type":"array"},"sphere_tax_calculation_id":{"anyOf":[{"format":"uuid","type":"string"},{"type":"null"}],"default":null,"description":"Store on the resulting payment or invoice, for example in Stripe metadata, so Sphere can match the transaction to this calculation. Absent when you have no active registration for the location.","title":"Sphere Tax Calculation Id"}},"required":["lines"],"title":"TaxCalculationData","type":"object"},"TaxCalculationLine":{"properties":{"id":{"description":"The line id you sent, or its product_id.","title":"Id","type":"string"},"tax_amounts":{"description":"One entry per tax applied. Empty when no tax is due, unless include_taxability_reason is true.","items":{"$ref":"#/components/schemas/TaxAmount"},"title":"Tax Amounts","type":"array"},"calculation_id":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"description":"Internal reference for the line's calculation.","title":"Calculation Id"},"tax_source":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"description":"origin or destination. Present when include_tax_source is true.","title":"Tax Source"}},"required":["id","tax_amounts"],"title":"TaxCalculationLine","type":"object"},"TaxAmount":{"properties":{"amount":{"description":"Tax, in the currency's minor unit.","title":"Amount","type":"integer"},"taxable_amount":{"description":"Base the tax was calculated on, in minor units. 0 when the line is not taxable.","title":"Taxable Amount","type":"integer"},"tax_rate":{"$ref":"#/components/schemas/TaxRate"}},"required":["amount","taxable_amount","tax_rate"],"title":"TaxAmount","type":"object"},"TaxRate":{"properties":{"percentage":{"description":"Rate as a percentage: 6.0, not 0.06.","title":"Percentage","type":"number"},"inclusive":{"description":"Whether the tax is included in the amount.","title":"Inclusive","type":"boolean"},"display_name":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"Name to show the customer.","title":"Display Name"},"jurisdiction":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"The jurisdiction levying the tax, such as a state, county or city.","title":"Jurisdiction"},"country":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"Two-letter country code.","title":"Country"},"state":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"State or province code, where the tax is sub-national.","title":"State"},"tax_type":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"description":"One of sales_tax, vat, gst, hst, pst, qst, jct, igst, lease_tax or amusement_tax. Absent when the type can't be determined.","title":"Tax Type"},"taxability_reason":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"description":"Present when include_taxability_reason is true. For example standard_rated, product_exempt or reverse_charge.","title":"Taxability Reason"}},"required":["percentage","inclusive","display_name","jurisdiction","country","state"],"title":"TaxRate","type":"object"},"ApiError":{"properties":{"type":{"description":"Always api_error.","title":"Type","type":"string"},"code":{"description":"Machine-readable error code.","title":"Code","type":"string"},"message":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"description":"What went wrong.","title":"Message"}},"required":["type","code"],"title":"ApiError","type":"object"}}},"paths":{"/calculate_tax":{"post":{"operationId":"calculate_tax_create","description":"Returns the tax due on each line item for a customer location, broken down by jurisdiction, plus a sphere_tax_calculation_id to store on the resulting payment or invoice.\n\nAmounts are integers in the currency's minor unit: 10000 is 100.00 USD. Send either customer_address, or pull_customer_address with customer_id.\n\nBefore calling, connect your billing provider so your products appear in Sphere, and give every product a product tax code.\n\nA 200 with empty tax_amounts means no tax is due: you have no active registration for the location, the customer is exempt, the product is exempt, or the sale is reverse-charged. Set include_taxability_reason to see which.","summary":"Calculate tax","tags":["Tax calculation"],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaxCalculationRequest"}},"application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/TaxCalculationRequest"}},"multipart/form-data":{"schema":{"$ref":"#/components/schemas/TaxCalculationRequest"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaxCalculationResponse"}}},"description":""},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiError"}}},"description":"validation_errors: the body failed validation; message lists the fields. customer_tax_location_invalid: the address is incomplete or could not be located. invalid_product_tax_code: a product has no product tax code in Sphere. unsupported_feature: pull_customer_address is not available for your billing provider. customer_address_pull_failed: the customer's address could not be fetched from your billing provider."},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiError"}}},"description":"Missing or invalid API key."},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiError"}}},"description":"Unexpected error."}}}}}}
```

### Example

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://server.getsphere.com/tax_api/calculate_tax \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: YOUR_API_KEY" \
  -d '{
    "customer_id": "cus_RQx5PQDFSMH6Ku",
    "customer_address": {
      "address1": "Investors Boulevard",
      "city": "Myrtle Beach",
      "state": "SC",
      "postal_code": "29579",
      "country": "US"
    },
    "line_items": [
      { "id": "line_1", "amount": 10000, "product_id": "prod_RArEhwhXLfX5jF" }
    ],
    "currency": "usd"
  }'
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const res = await fetch('https://server.getsphere.com/tax_api/calculate_tax', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'X-API-KEY': process.env.SPHERE_API_KEY },
  body: JSON.stringify({
    customer_id: 'cus_RQx5PQDFSMH6Ku',
    customer_address: { address1: 'Investors Boulevard', city: 'Myrtle Beach', state: 'SC', postal_code: '29579', country: 'US' },
    line_items: [{ id: 'line_1', amount: 10000, product_id: 'prod_RArEhwhXLfX5jF' }],
    currency: 'usd',
  }),
});
const { data } = await res.json();
```

{% endtab %}

{% tab title="Python" %}

```python
import os, requests

r = requests.post(
    "https://server.getsphere.com/tax_api/calculate_tax",
    headers={"X-API-KEY": os.environ["SPHERE_API_KEY"]},
    json={
        "customer_id": "cus_RQx5PQDFSMH6Ku",
        "customer_address": {"address1": "Investors Boulevard", "city": "Myrtle Beach",
                             "state": "SC", "postal_code": "29579", "country": "US"},
        "line_items": [{"id": "line_1", "amount": 10000, "product_id": "prod_RArEhwhXLfX5jF"}],
        "currency": "usd",
    },
)
r.raise_for_status()
data = r.json()["data"]
```

{% endtab %}
{% endtabs %}

### Tax IDs and exemptions

| Situation                                 | Send                                | Result                                                                                                                                   |
| ----------------------------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Business customer with a VAT / GST number | `"tax_id": "DE123456789"`           | Where a reverse charge applies, `tax_amounts` is empty; with `include_taxability_reason: true`, `taxability_reason` is `reverse_charge`. |
| Customer holds an exemption               | `"tax_exempt": true`                | No tax for this request.                                                                                                                 |
| You need to know why a line has no tax    | `"include_taxability_reason": true` | Reason on each result, e.g. `product_exempt`, `reverse_charge`.                                                                          |

```json
{
  "customer_id": "cus_RQx5PQDFSMH6Ku",
  "tax_id": "DE123456789",
  "include_taxability_reason": true,
  "customer_address": { "city": "Berlin", "postal_code": "10115", "country": "DE" },
  "line_items": [{ "id": "line_1", "amount": 10000, "product_id": "prod_RArEhwhXLfX5jF" }],
  "currency": "eur"
}
```

{% hint style="info" %}
Reverse-charge treatment for business customers depends on your account configuration. Contact Sphere to enable it.
{% endhint %}

### Errors

All errors are `{"type": "api_error", "code": "…", "message": "…"}`.

| Status | `code`                          | Cause                                                           | Resolution                                                  |
| ------ | ------------------------------- | --------------------------------------------------------------- | ----------------------------------------------------------- |
| 401    | `unauthorized_access`           | Missing or invalid API key                                      | Check the `X-API-KEY` header and that the key is active     |
| 400    | `validation_errors`             | Malformed request                                               | `message` lists the failing fields                          |
| 400    | `customer_tax_location_invalid` | Address incomplete or unresolvable                              | Check `city`, `postal_code`, `country` (and `state` for US) |
| 400    | `invalid_product_tax_code`      | A `product_id` has no tax code in Sphere                        | Assign one in the Products tab                              |
| 400    | `unsupported_feature`           | `pull_customer_address` not available for your billing provider | Send `customer_address`                                     |
| 400    | `customer_address_pull_failed`  | Address could not be read from the billing provider             | Send `customer_address`                                     |
| 429    | `too_many_requests`             | Rate limit                                                      | Back off and retry                                          |
| 500    | `internal_server_error`         | Unexpected error                                                | Retry; contact support if it persists                       |
