Pythonを用いたVertex Tax RESTful API連携ステップバイステップガイド

By JoeVu, at: 2024年9月29日12:00

Estimated Reading Time: __READING_TIME__ minutes

Step-by-Step Guide to Integrating with Vertex Tax RESTful API using Python
Step-by-Step Guide to Integrating with Vertex Tax RESTful API using Python

 

1. はじめに

 

以前のブログ投稿でVertexCloud 間接税についてご紹介したように、このブログ投稿では、Python を使用してVertex の Tax RESTful API と統合する手順を詳しく説明します。このチュートリアルを完了すると、Vertex のサービスを使用して、税金の計算とトランザクションのプログラムによる処理を行うことができるようになります。

 

バージョン1 は非推奨となったため、現在サポートされているバージョン2に焦点を当てます。

 

2. 前提条件

 

統合プロセスに入る前に、以下の準備が整っていることを確認してください。

 

  • Python(バージョン 3.6 以上)
     
  • Vertex Tax API の認証情報:APIキーを生成してサービスにアクセスするには、有効な Vertex アカウントが必要です。API アクセスを申し込む
     
  • Python ライブラリ:このガイドでは、HTTP 呼び出しを行うための requests と、API 応答を処理するための json を使用します - pip install requests
     
  • RESTful API の基本的な理解:RESTful API とのやり取り(GET、POST、PUT リクエストによる)に関する知識があれば、このガイドをより簡単に理解できます。

 

3. Python 環境の設定

 

まず、新しいプロジェクトフォルダを作成し、依存関係を整理するために仮想環境を設定します。方法は次のとおりです。

 

プロジェクトディレクトリの作成

 

mkdir vertex-tax-api
cd vertex-tax-api

 

仮想環境の設定

 

python3 -m venv vertex-env
source vertex-env/bin/activate

# MacOS/Linux の場合
# または vertex-env\Scripts\activate
# Windows の場合

 

必要な依存関係のインストール

 

pip install requests


これで、Vertex Tax API と統合するためのコードの記述を開始する準備ができました。

 

4. Vertex Tax API(バージョン 2)との認証

 

API 呼び出しを行う前に、OAuth 2.0 を使用して Vertex のシステムで認証する必要があります。認証プロセスでは、client_idclient_secret、およびgrant_typeclient_credentialsに設定)を認証エンドポイントに送信してトークンを取得する必要があります。


認証リクエストの例

 

Python を使用して認証し、Vertex の API(バージョン 2)からアクセストークンを取得する方法を次に示します。

 

import requests

# 認証トークンを取得する URL
auth_url = 'https://auth.vertexsmb.com/identity/connect/token'

# クライアント認証情報
client_id = 'your_client_id'
client_secret = 'your_client_secret'

# トークンリクエストのデータ
data = {
    'grant_type': 'client_credentials',
    'client_id': client_id,
    'client_secret': client_secret,
}

# ヘッダー
headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
}

# トークンを取得するためのリクエストを送信
response = requests.post(auth_url, data=data, headers=headers)

if response.status_code == 200:
    token = response.json().get('access_token')
    print(f"Access Token: {token}")
else:
    print("Authentication failed:", response.text)

 


正常に認証されると、API はアクセストークンを返します。他の API エンドポイントへのリクエストを行う際には、このトークンをAuthorizationヘッダーに含める必要があります。

 

5. 税金計算リクエストの実行(バージョン 2)

 

アクセストークンを取得したら、税金計算リクエストの実行に進みます。以下は税金計算リクエストのペイロードの例で、販売メッセージタイプ、トランザクションタイプ、通貨、顧客情報、明細項目、割引などを含んでいます。

 

税金計算リクエストの例

 

# 税金計算の URL(バージョン 2)
api_url = 'https://calcconnect.vertexsmb.com/vertex-ws/v2/supplies'

# アクセストークンを含むヘッダーを設定
headers = {
    'Authorization': f'Bearer {token}',
    'Content-Type': 'application/json',
}

# 税金計算のサンプルペイロード
payload = {
    "saleMessageType": "QUOTATION",
    "transactionType": "SALE",
    "transactionId": "998822",
    "originalCurrency": {
        "isoCurrencyCodeAlpha": "USD"
    },
    "currency": {
        "isoCurrencyCodeAlpha": "USD"
    },
    "customer": {
        "administrativeDestination": {
            "city": "Joe Vu",
            "country": "US",
            "mainDivision": "MO",
            "postalCode": "65049",
            "streetAddress1": ""
        },
        "customerCode": {
            "classCode": "TAX",
            "value": "GUEST"
        },
        "destination": {
            "city": "Lake Ozark",
            "country": "US",
            "mainDivision": "MO",
            "postalCode": "65049",
            "streetAddress1": ""
        },
        "isTaxExempt": "false"
    },
    "documentDate": "2024-09-04",
    "documentNumber": "3065",
    "lineItems": [
        {
            "lineItemNumber": "0",
            "product": {
                "value": "Stuff:Concrete"
            },
            "quantity": {
                "unitOfMeasure": "UOM",
                "value": 13
            },
            "discount": {
                "discountType": "DiscountAmount",
                "discountValue": "-0"
            },
            "unitPrice": "212.343",
            "vendorSKU": None
        }
    ],
    "discount": {
        "discountType": "DiscountAmount",
        "discountValue": 0,
        "userDefinedDiscountCode": "string"
    }
}

# POST リクエストを行う
response = requests.post(api_url, json=payload, headers=headers)

if response.status_code == 200:
    tax_info = response.json()
    print("Tax Calculation Result:", tax_info)
else:
    print("Error in API call:", response.text)


この例では、詳細なトランザクションを Vertex API に送信しています。ペイロードには、トランザクションの種類、顧客の詳細、数量、価格、適用される割引を含む明細項目などの重要なフィールドが含まれています。

 

サンプルレスポンス

 

{
  "data": {
    "currency": {
      "isoCurrencyCodeAlpha": "USD",
      "isoCurrencyCodeNum": 0,
      "isoCurrencyName": "US Dollar"
    },
    "customer": {
      "administrativeDestination": {
        "city": "Joe Vu",
        "country": "US",
        "locationCode": "",
        "mainDivision": "MO",
        "postalCode": "65049",
        "streetAddress1": "",
        "taxAreaId": "260294565"
      },
      "customerCode": {
        "classCode": "TAX",
        "isBusinessIndicator": false,
        "value": "GUEST"
      },
      "destination": {
        "city": "Joe Vu",
        "country": "US",
        "locationCode": "",
        "mainDivision": "MO",
        "postalCode": "65049",
        "streetAddress1": "",
        "taxAreaId": "260294565"
      },
      "isTaxExempt": false,
      "taxRegistrations": []
    },
    "discount": {
      "userDefinedDiscountCode": "string"
    },
    "documentDate": "2024-09-04",
    "documentNumber": "998822",
    "lineItems": [
      {
        "customer": {
          "administrativeDestination": {
            "city": "Joe Vu",
            "country": "US",
            "locationCode": "",
            "mainDivision": "MO",
            "postalCode": "65049",
            "streetAddress1": "",
            "taxAreaId": "260294565"
          },
          "customerCode": {
            "classCode": "TAX",
            "isBusinessIndicator": false,
            "value": "GUEST"
          },
          "destination": {
            "city": "Lake Ozark",
            "country": "US",
            "locationCode": "",
            "mainDivision": "MO",
            "postalCode": "65049",
            "streetAddress1": "",
            "taxAreaId": "260294565"
          },
          "isTaxExempt": false,
          "taxRegistrations": []
        },
        "discount": {
          "userDefinedDiscountCode": "string"
        },
        "extendedPrice": 2760.459,
        "fairMarketValue": 2760.459,
        "lineItemNumber": 0,
        "locationCode": "",
        "product": {
          "value": "book 1"
        },
        "quantity": {
          "unitOfMeasure": "UOM",
          "value": 13
        },
        "taxIncludedIndicator": false,
        "taxes": [
          {
            "calculatedTax": 116.62,
            "calculationRuleId": {
              "salesTaxHolidayIndicator": false,
              "userDefined": false,
              "value": "v301028065"
            },
            "effectiveRate": 0.04225,
            "exempt": 0,
            "imposition": {
              "impositionId": "1",
              "jurisdictionId": "19873",
              "userDefined": false,
              "value": "Sales and Use Tax"
            },
            "impositionType": {
              "impositionTypeId": "v1",
              "userDefined": false,
              "value": "General Sales and Use Tax"
            },
            "inclusionRuleId": {
              "salesTaxHolidayIndicator": false,
              "userDefined": false,
              "value": "v315534188"
            },
            "isService": false,
            "jurisdiction": {
              "effectiveDate": "1900-01-01",
              "expirationDate": "9999-12-31",
              "jurisdictionId": "19873",
              "jurisdictionType": "STATE",
              "value": "MISSOURI"
            },
            "maxTaxIndicator": false,
            "nominalRate": 0.04225,
            "nonTaxable": 0,
            "notRegisteredIndicator": false,
            "situs": "DESTINATION",
            "taxCollectedFromParty": "BUYER",
            "taxResult": "TAXABLE",
            "taxStructure": "SINGLE_RATE",
            "taxType": "SALES",
            "taxable": 2760.46
          },
          {
            "calculatedTax": 41.41,
            "calculationRuleId": {
              "salesTaxHolidayIndicator": false,
              "userDefined": false,
              "value": "v309207820"
            },
            "effectiveRate": 0.015,
            "exempt": 0,
            "imposition": {
              "impositionId": "1",
              "jurisdictionId": "20023",
              "userDefined": false,
              "value": "Local Sales and Use Tax"
            },
            "impositionType": {
              "impositionTypeId": &
Tag list:
- Vertex
- Vertex API integration
- Vertex tax integration
- Vertex API how to
- Vertex Cloud API
- VertexCloud
- Vertex Tax API
- how to integrate with Vertex Cloud API

Related

Python Outsourcing

Read more
Python Flask

Read more

Subscribe

Subscribe to our newsletter and never miss out lastest news.