Magento® 2 provides the calculation of the tax amount when creating an order. Magento firstly was developed for the USA, because sales tax rates can be different in different locations (county/city). The default Magento 2 functionality allows setting the tax rate by the following parameters: country, region (state/province), postcode. The administrator can set the tax rates in Stores -> Tax Zones, and Rates menu on admin panel. But as the USA has a lot of locations with different postcodes, it could be a bit challenging to output all necessary tax rates pegged to the postcode manually.

Now we’ll consider the way of how to do this.

How In Magento Set Tax Rate Programmatically

Let’s imagine the CSV-file of Magento tax class for shipping rates (more than 1000 rows) for Northern Carolina state that has the following format:


We’ll pay attention to a ZipCode field which contains the location postcode and Estimated Combined Rate presented in the decimal format.

$api_url = "….";//link to Magento 2 Store
$ch = curl_init();
$res = curl_exec($ch);
$result = json_decode($res,true);
  echo $result['message'];
$token = $result;//Getting the connection token 
$file = fopen('TAXRATES_ZIP5_NC201701.csv','rt');
$header = fgetcsv($file);
while($row = fgetcsv($file)){
   $taxArray = array(
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-type: application/json","Authorization: Bearer ".$token));
$res = curl_exec($ch);
echo $res."<br/>";   

This example describes the tax rate to percent value because the tax rates are set exactly in this format in Magento 2. As we needed to place the configuration of the tax rates only for Northern Carolina, it was not difficult to find the identifier of this state in Magento based online store. We created an entry in tax_calculation_rate table for each location by requesting _/V1/taxRates() API method and transmitting it the array in JSON format as a parameter.

If the file provided the data for locations in different states, we would better get the array of states using_/V1/directory/countries/US() API method which would return the array with information about the USA from Magento 2. This array would include state id – state code binding. First, we would get the state code, and then we would place the state id in the request for the appropriate state code from State column.


The main advantage of this method is that the script could have no clue about Magento, except the accesses to the admin panel, the website link, and API methods which it requests. That’s why this script can run on the host that is different from Magento’s host. We hope that our quick tip will help you to get along with Magento tax. If you have other questions related to Magento 2 Development please contact us.
5.00 / 5.0
Article rating (2 Reviews)
Do you find this article useful? Please, let us know your opinion and rate the post!
Not badGoodVery GoodGreatAwesome