### Get App Access Token Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_content.md This example shows how to obtain an application access token using the SDK. It demonstrates the setup of the client and the request object for the `GetAppAccessToken` endpoint. ```APIDOC ## Get App Access Token ### Description This example demonstrates how to obtain an application access token using the Chanjet OpenAPI Python SDK. It covers the initialization of the `ChanjetClient` and the construction of a `GetAppAccessTokenRequest`. ### Method POST (implied by SDK usage) ### Endpoint /open/api/v2/app/accessToken ### Request Body - **app_ticket** (string) - Required - The ticket for the application. ### Request Example ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.get_app_access_token_request import GetAppAccessTokenRequest from chanjet_openapi_python_sdk.response.get_app_access_token_response import GetAppAccessTokenResponse from chanjet_openapi_python_sdk.content.get_app_access_token_content import GetAppAccessTokenContent client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' req = GetAppAccessTokenRequest() req.request_uri = '/open/api/v2/app/accessToken' req.content = GetAppAccessTokenContent('your_app_ticket') result = client.execute(req, GetAppAccessTokenResponse) ``` ### Response #### Success Response (200) - **access_token** (string) - The application access token. - **expires_in** (integer) - The expiration time of the token in seconds. #### Response Example ```json { "access_token": "your_access_token", "expires_in": 7200 } ``` ``` -------------------------------- ### Use Example: Get App Access Token Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/authentication-api.md Demonstrates how to use the ChanjetClient to obtain an application access token. Ensure your app_key, app_secret, and app_ticket are correctly configured. ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.get_app_access_token_request import GetAppAccessTokenRequest from chanjet_openapi_python_sdk.response.get_app_access_token_response import GetAppAccessTokenResponse from chanjet_openapi_python_sdk.content.get_app_access_token_content import GetAppAccessTokenContent client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' req = GetAppAccessTokenRequest() req.request_uri = '/open/api/v2/app/accessToken' req.content = GetAppAccessTokenContent('your_app_ticket') result = client.execute(req, GetAppAccessTokenResponse) if result.code == '200': print(f"应用凭证: {result.result.appAccessToken}") print(f"过期时间: {result.result.expireTime}") else: print(f"获取失败: {result.message}") ``` -------------------------------- ### Common Usage: Building a GET Request Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_request.md Example demonstrating how to construct a GET request using a specific request class like `QueryInventoryRequest`. ```APIDOC ## Common Usage: Building a GET Request ### Description This example shows how to instantiate and configure a `QueryInventoryRequest` for a GET operation, including setting the URI and query parameters. ### Request Example ```python from chanjet_openapi_python_sdk.request.tplus.query_inventory_request import QueryInventoryRequest req = QueryInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Query' req.add_query_param('page', 1) req.add_query_param('limit', 100) ``` ``` -------------------------------- ### Get Tenant Token API Usage Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/authentication-api.md Demonstrates how to use the ChanjetClient to obtain a tenant access token. Ensure you have your app_key and app_secret configured. ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.get_tenant_token_request import GetTenantTokenRequest from chanjet_openapi_python_sdk.response.get_tenant_token_response import GetTenantTokenResponse from chanjet_openapi_python_sdk.content.get_tenant_token_content import GetTenantTokenContent client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' req = GetTenantTokenRequest() req.request_uri = '/open/api/v2/auth/tenant/getToken' req.content = GetTenantTokenContent('tenant_id', 'app_name') result = client.execute(req, GetTenantTokenResponse) if result.result: print(f"访问令牌: {result.value.accessToken}") print(f"有效期: {result.value.expiresIn} 秒") print(f"企业 ID: {result.value.orgId}") else: print(f"获取失败: {result.error.msg}") ``` -------------------------------- ### Install Chanjet OpenAPI Python SDK from Source Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/QUICKSTART.md Install the SDK from its source code repository. This involves cloning the repository and then performing a local installation. ```bash git clone https://github.com/Chanjet/chanjet-openapi-python-sdk.git cd chanjet-openapi-python-sdk pip install -e . ``` -------------------------------- ### Build a GET Request Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_request.md Example of constructing a GET request using a concrete request class, setting the URI and query parameters. ```python from chanjet_openapi_python_sdk.request.tplus.query_inventory_request import QueryInventoryRequest req = QueryInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Query' req.add_query_param('page', 1) req.add_query_param('limit', 100) ``` -------------------------------- ### Create Sale Order Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_content.md This example demonstrates how to create a sale order with complex content, including nested objects and lists, using the SDK. It shows the setup for creating a sale order with details. ```APIDOC ## Create Sale Order ### Description This example demonstrates how to create a sale order with complex content, including nested objects and lists, using the Chanjet OpenAPI Python SDK. It shows the setup for creating a sale order with details and dynamic properties. ### Method POST (implied by SDK usage) ### Endpoint /tplus/api/v2/sale/order/Create ### Parameters #### Request Body - **voucher_date** (string) - Required - The date of the voucher. - **external_code** (string) - Required - The external code for the order. - **customer_code** (string) - Required - The code of the customer. - **address** (string) - Required - The shipping address. - **link_man** (string) - Required - The contact person. - **contact_phone** (string) - Required - The contact phone number. - **header_dynamic_property_keys** (list) - Optional - Keys for header dynamic properties. - **header_dynamic_property_values** (list) - Optional - Values for header dynamic properties. - **dto.SaleOrderDetails** (list of SaleOrderDetail) - Required - A list of sale order details. ### SaleOrderDetail Object - **inventory_code** (string) - Required - The code of the inventory item. - **unit_name** (string) - Required - The name of the unit. - **quantity** (float) - Required - The quantity of the item. - **orig_discount_price** (float) - Required - The original discount price. - **detail_dynamic_property_keys** (list) - Optional - Keys for detail dynamic properties. - **detail_dynamic_property_values** (list) - Optional - Values for detail dynamic properties. ### Request Example ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.create_sale_order_request import CreateSaleOrderRequest from chanjet_openapi_python_sdk.content.tplus.create_sale_order_content import CreateSaleOrderContent, SaleOrderDetail client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' req = CreateSaleOrderRequest() req.request_uri = '/tplus/api/v2/sale/order/Create' content = CreateSaleOrderContent( voucher_date='2024-01-15', external_code='EXT001', customer_code='CUST001', address='送货地址', link_man='联系人', contact_phone='13800138000', header_dynamic_property_keys=[], header_dynamic_property_values=[] ) # Add sale order details detail = SaleOrderDetail( inventory_code='INV001', unit_name='个', quantity=10.0, orig_discount_price=100.0, detail_dynamic_property_keys=[], detail_dynamic_property_values=[] ) content.dto.SaleOrderDetails.append(detail) req.content = content result = client.execute(req) ``` ### Response #### Success Response (200) - **code** (string) - The result code. - **message** (string) - The result message. - **data** (object) - The data returned by the API. #### Response Example ```json { "code": "0", "message": "Success", "data": { "voucher_code": "SALE001", "voucher_id": "12345" } } ``` ``` -------------------------------- ### Basic Usage Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_logger.md Demonstrates how to configure the logger and use the ChanjetClient for API requests. Logs at the INFO level will be visible. ```APIDOC ## Basic Usage ### Description This example shows how to initialize the logger to INFO level and then use the ChanjetClient to make an API call. INFO level logs will be outputted during the request execution. ### Example ```python import logging from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.utils.chanjet_logger import ChanjetLogger from chanjet_openapi_python_sdk.request.tplus.query_inventory_request import QueryInventoryRequest from chanjet_openapi_python_sdk.response.tplus.query_inventory_response import QueryInventoryResponse from chanjet_openapi_python_sdk.content.tplus.query_inventory_content import QueryInventoryContent # Configure logger to INFO level ChanjetLogger(logging.INFO) client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' req = QueryInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Query' req.content = QueryInventoryContent('INV001', 'CLASS001', False, True) # Executing the request will output INFO level logs result = client.execute(req, QueryInventoryResponse) ``` ``` -------------------------------- ### Get Tenant Token Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/QUICKSTART.md Example of how to obtain a tenant token for accessing specific tenant resources. ```APIDOC ## Get Tenant Token ### Description This example shows how to request a tenant token using your `app_key`, `app_secret`, `tenant_id`, and `app_name`. ### Method `client.execute(req, GetTenantTokenResponse)` ### Request Parameters - `req.request_uri`: `/open/api/v2/auth/tenant/getToken` - `req.content`: `GetTenantTokenContent` object with the following fields: - `tenant_id` (string): The ID of the tenant. - `app_name` (string): The name of the application. ### Request Example ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.get_tenant_token_request import GetTenantTokenRequest from chanjet_openapi_python_sdk.response.get_tenant_token_response import GetTenantTokenResponse from chanjet_openapi_python_sdk.content.get_tenant_token_content import GetTenantTokenContent client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' req = GetTenantTokenRequest() req.request_uri = '/open/api/v2/auth/tenant/getToken' req.content = GetTenantTokenContent( tenant_id='your_tenant_id', app_name='your_app_name' ) result = client.execute(req, GetTenantTokenResponse) if result.result: print(f"Access Token: {result.value.accessToken}") print(f"Expires In: {result.value.expiresIn} seconds") else: print(f"Error: {result.error.msg}") ``` ``` -------------------------------- ### Create Inventory Usage Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/tplus-inventory-api.md Demonstrates how to instantiate ChanjetClient, create a CreateInventoryRequest, populate it with CreateInventoryContent, and execute the request to create a new inventory item. ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.create_inventory_request import CreateInventoryRequest from chanjet_openapi_python_sdk.content.tplus.create_inventory_content import CreateInventoryContent client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' req = CreateInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Create' # 创建存货内容 content = CreateInventoryContent( code='INV001', name='产品名称', shorthand='JH', specification='规格', inventory_class_code='CLASS001', unit_code='UNIT001', unit_name='个', disabled='0', is_single_unit='1', is_purchase='1', is_sale='1' ) req.content = content # 执行请求 result = client.execute(req) print(result) ``` -------------------------------- ### Create Sales Order Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/QUICKSTART.md Example of how to create a sales order with details using the SDK. ```APIDOC ## Create Sales Order ### Description This example shows how to create a sales order, including header information and line item details. ### Method `client.execute(req)` ### Request Parameters - `req.request_uri`: `/tplus/api/v2/sale/order/Create` - `req.content`: `CreateSaleOrderContent` object with the following fields: - `voucher_date` (string): Date of the voucher. - `external_code` (string): External reference code. - `customer_code` (string): Customer code. - `address` (string): Delivery address. - `link_man` (string): Contact person. - `contact_phone` (string): Contact phone number. - `header_dynamic_property_keys` (list): Keys for header dynamic properties. - `header_dynamic_property_values` (list): Values for header dynamic properties. - `dto.SaleOrderDetails` (list of `SaleOrderDetail`): List of order line items. - `inventory_code` (string): Inventory code for the item. - `unit_name` (string): Unit of measure. - `quantity` (float): Quantity ordered. - `orig_discount_price` (float): Original discount price. - `detail_dynamic_property_keys` (list): Keys for detail dynamic properties. - `detail_dynamic_property_values` (list): Values for detail dynamic properties. ### Request Example ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.create_sale_order_request import CreateSaleOrderRequest from chanjet_openapi_python_sdk.content.tplus.create_sale_order_content import CreateSaleOrderContent, SaleOrderDetail client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' req = CreateSaleOrderRequest() req.request_uri = '/tplus/api/v2/sale/order/Create' # Create sales order content = CreateSaleOrderContent( voucher_date='2024-01-15', external_code='EXT001', customer_code='CUST001', address='Delivery Address', link_man='Contact Person', contact_phone='13800000000', header_dynamic_property_keys=[], header_dynamic_property_values=[] ) # Add order details detail = SaleOrderDetail( inventory_code='INV001', unit_name='pcs', quantity=10.0, orig_discount_price=100.0, detail_dynamic_property_keys=[], detail_dynamic_property_values=[] ) content.dto.SaleOrderDetails.append(detail) req.content = content # Execute request result = client.execute(req) print(result) ``` ``` -------------------------------- ### Query Inventory Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/QUICKSTART.md Example of how to query inventory information using the SDK. ```APIDOC ## Query Inventory ### Description This example demonstrates how to query inventory details by providing parameters such as inventory code, classification code, and status. ### Method `client.execute(req, QueryInventoryResponse)` ### Request Parameters - `req.request_uri`: `/tplus/api/v2/inventory/Query` - `req.content`: `QueryInventoryContent` object with the following fields: - `code` (string): Inventory code. - `inventory_class_code` (string): Inventory classification code. - `is_stop` (boolean): Whether to include stopped items. - `is_sale` (boolean): Whether to include saleable items. ### Request Example ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.query_inventory_request import QueryInventoryRequest from chanjet_openapi_python_sdk.response.tplus.query_inventory_response import QueryInventoryResponse from chanjet_openapi_python_sdk.content.tplus.query_inventory_content import QueryInventoryContent client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' # Create request req = QueryInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Query' req.content = QueryInventoryContent( code='INV001', inventory_class_code='C001', is_stop=False, is_sale=True ) # Execute request result = client.execute(req, QueryInventoryResponse) # Process result print(f"Code: {result.Code}") print(f"Name: {result.Name}") ``` ``` -------------------------------- ### Get Tenant Token Response Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_response.md Example of the GetTenantTokenResponse class, inheriting from ChanjetResponse, for handling tenant token API responses. ```APIDOC ### Get Tenant Token Response ```python from chanjet_openapi_python_sdk.chanjet_response import ChanjetResponse class GetTenantTokenResponse(ChanjetResponse): def __init__(self, data=None): # Whether successful self.result = '' # Response content self.value = self.Value() # Error information self.error = self.Error() if data: self.__dict__ = data class Error: def __init__(self): # Error code self.code = 0 # Error message self.msg = '' class Value: def __init__(self): # Access token self.accessToken = '' # Refresh token self.refreshToken = '' # Authorization scope self.scope = '' # Expiration time self.expiresIn = '' ``` ``` -------------------------------- ### Complete Example Application for Inventory Management Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/QUICKSTART.md A full Python application demonstrating how to initialize the Chanjet client, configure logging, and query inventory information using the SDK. Ensure environment variables like CHANJET_SERVER_URL, CHANJET_APP_KEY, CHANJET_APP_SECRET, and CHANJET_OPEN_TOKEN are set. ```python import logging import os from datetime import datetime from dotenv import load_dotenv from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.utils.chanjet_logger import ChanjetLogger from chanjet_openapi_python_sdk.request.tplus.query_inventory_request import QueryInventoryRequest from chanjet_openapi_python_sdk.response.tplus.query_inventory_response import QueryInventoryResponse from chanjet_openapi_python_sdk.content.tplus.query_inventory_content import QueryInventoryContent # 加载环境变量 load_dotenv() # 配置日志 ChanjetLogger(logging.INFO) logger = logging.getLogger(__name__) class InventoryManager: def __init__(self): self.client = ChanjetClient(os.getenv('CHANJET_SERVER_URL')) self.client.app_key = os.getenv('CHANJET_APP_KEY') self.client.app_secret = os.getenv('CHANJET_APP_SECRET') self.client.open_token = os.getenv('CHANJET_OPEN_TOKEN') def query_inventory(self, code, class_code): """查询存货信息""" try: req = QueryInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Query' req.content = QueryInventoryContent(code, class_code, False, True) result = self.client.execute(req, QueryInventoryResponse) logger.info(f"成功查询存货: {result.Code}") return result except Exception as e: logger.error(f"查询存货失败: {str(e)}") raise def main(): manager = InventoryManager() try: # 查询存货 result = manager.query_inventory('INV001', 'CLASS001') print(f"存货编码: {result.Code}") print(f"存货名称: {result.Name}") print(f"时间戳: {datetime.now().isoformat()}") except Exception as e: print(f"应用异常: {str(e)}") if __name__ == '__main__': main() ``` -------------------------------- ### Install Chanjet OpenAPI Python SDK using pip Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/QUICKSTART.md Install the SDK using pip. Ensure you have Python 3.8+ and requests==2.26.0. ```bash pip install chanjet-openapi-python-sdk ``` -------------------------------- ### Batch Create Partner Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/tplus-partner-api.md This section demonstrates how to use the Tplus API to create multiple partners in a batch. It includes a Python SDK example with necessary client setup and a function to create a single partner, which is then iterated over for batch creation. ```APIDOC ## Batch Create Partner ### Description This endpoint allows for the creation of multiple partner records in a single request. It utilizes the `CreatePartnerRequest` and `CreatePartnerContent` from the Tplus SDK to send partner data. ### Method POST ### Endpoint /tplus/api/v2/partner/Create ### Parameters #### Request Body - **code** (string) - Required - The unique code for the partner. - **name** (string) - Required - The full name of the partner. - **shorthand** (string) - Required - The shorthand name for the partner. - **partner_abb_name** (string) - Required - The abbreviated name of the partner. - **partner_type_code** (string) - Required - The code representing the partner's type (e.g., '0' for Customer, '1' for Supplier). - **partner_class_code** (string) - Required - The code representing the partner's class (e.g., 'VIP', 'REGULAR'). ### Request Example ```json { "code": "CUST001", "name": "北京客户有限公司", "shorthand": "BJKH", "abb_name": "北京客户", "type_code": "0", "class_code": "VIP" } ``` ### Response #### Success Response (200) - **result** (object) - Contains the result of the partner creation operation. #### Response Example ```json { "message": "Success", "code": "0", "data": { "partnerId": "some_partner_id" } } ``` ``` -------------------------------- ### Initialize ChanjetLogger Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/configuration.md Configure the ChanjetLogger at the start of your application. Sets the logging level to INFO. ```python import logging from chanjet_openapi_python_sdk.utils.chanjet_logger import ChanjetLogger # 在程序启动时配置日志 ChanjetLogger(logging.INFO) ``` -------------------------------- ### Query Inventory API Usage Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/tplus-inventory-api.md Demonstrates how to use the QueryInventoryRequest to fetch inventory details. Ensure you have your application credentials and open token configured. ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.query_inventory_request import QueryInventoryRequest from chanjet_openapi_python_sdk.response.tplus.query_inventory_response import QueryInventoryResponse from chanjet_openapi_python_sdk.content.tplus.query_inventory_content import QueryInventoryContent client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' # 创建请求 req = QueryInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Query' req.content = QueryInventoryContent('INV001', 'CLASS001', False, True) # 执行请求 result = client.execute(req, QueryInventoryResponse) # 访问响应数据 print(f"编码: {result.Code}") print(f"名称: {result.Name}") print(f"分类编码: {result.InventoryClass.Code}") print(f"分类名称: {result.InventoryClass.Name}") ``` -------------------------------- ### CustomContent Class Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_content.md An example demonstrating the basic structure for creating a custom content class by inheriting from ChanjetContent and defining required attributes in the initializer. ```python from chanjet_openapi_python_sdk.chanjet_content import ChanjetContent class CustomContent(ChanjetContent): def __init__(self, param1, param2): """ 初始化方法 :param param1: 参数1说明 :type param1: str :param param2: 参数2说明 :type param2: str """ self.field1 = param1 self.field2 = param2 ``` -------------------------------- ### Query Inventory Response Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_response.md Example of a specific response class, QueryInventoryResponse, inheriting from ChanjetResponse and mapping inventory-related fields. ```APIDOC ### Query Inventory Response ```python from chanjet_openapi_python_sdk.chanjet_response import ChanjetResponse class QueryInventoryResponse(ChanjetResponse): def __init__(self, data=None): # Inventory code self.Code = '' # Inventory name self.Name = '' # Inventory mnemonic code self.Shorthand = '' # Inventory classification self.InventoryClass = self.InventoryClassInfo() # Whether it is disabled self.Disabled = '' # Whether it is a sales attribute self.IsSale = '' if data: self.__dict__ = data class InventoryClassInfo: def __init__(self): # Inventory classification code self.Code = '' # Inventory classification name self.Name = '' def __str__(self): return str(self.__dict__) ``` ``` -------------------------------- ### Common Usage: Building a POST Request Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_request.md Example demonstrating how to construct a POST request using `CreateInventoryRequest` and setting the request body content. ```APIDOC ## Common Usage: Building a POST Request ### Description This example illustrates how to create a POST request using `CreateInventoryRequest`, including defining the request URI and populating the request body with `CreateInventoryContent`. ### Request Example ```python from chanjet_openapi_python_sdk.request.tplus.create_inventory_request import CreateInventoryRequest from chanjet_openapi_python_sdk.content.tplus.create_inventory_content import CreateInventoryContent req = CreateInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Create' content = CreateInventoryContent( code='INV001', name='产品名称', shorthand='JH', specification='规格', inventory_class_code='CLASS001', unit_code='UNIT001', unit_name='个', disabled='0', is_single_unit='1', is_purchase='1', is_sale='1' ) req.content = content ``` ``` -------------------------------- ### Custom Response Class Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_response.md An example demonstrating how to create a custom response class by inheriting from ChanjetResponse and defining properties. ```APIDOC ## Usage Pattern All response classes should inherit from `ChanjetResponse` and define corresponding attributes to map API returned data fields. **Basic Structure Example** ```python from chanjet_openapi_python_sdk.chanjet_response import ChanjetResponse class CustomResponse(ChanjetResponse): def __init__(self, data=None): # Define response attributes self.code = '' self.message = '' self.data = {} # If data is passed, bind it to the current instance if data: self.__dict__ = data def __str__(self): return str(self.__dict__) ``` ``` -------------------------------- ### Example: Creating a Sale Delivery Order Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/tplus-order-api.md Demonstrates how to instantiate the `ChanjetClient`, create a `CreateSaleDeliveryRequest`, populate it with `CreateSaleDeliveryContent` and `SaleDeliveryDetail` objects, and execute the request. Remember to replace placeholder credentials with your actual app key, app secret, and open token. ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.create_sale_delivery_request import CreateSaleDeliveryRequest from chanjet_openapi_python_sdk.content.tplus.create_sale_delivery_contect import CreateSaleDeliveryContent, SaleDeliveryDetail client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' req = CreateSaleDeliveryRequest() req.request_uri = '/tplus/api/v2/sale/delivery/Create' # 创建销货单主体 content = CreateSaleDeliveryContent( voucher_date='2024-01-15', external_code='DEL20240115001', customer_code='CUST001', invoice_type_code='INVOICE001', address='北京市朝阳区送货地址', link_man='李四', contact_phone='13800138001', header_dynamic_property_keys=[], header_dynamic_property_values=[] ) # 添加销货单明细 detail = SaleDeliveryDetail( inventory_code='INV001', unit_name='个', quantity=10.0, orig_price=100.0, orig_tax_amount=1100.0, detail_dynamic_property_keys=[], detail_dynamic_property_values=[] ) content.dto.SaleDeliveryDetails.append(detail) req.content = content # 执行请求 result = client.execute(req) print(result) ``` -------------------------------- ### Query Inventory using Chanjet SDK Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/QUICKSTART.md Example of querying inventory data by providing inventory codes and other filter criteria. Ensure client is initialized with credentials. ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.query_inventory_request import QueryInventoryRequest from chanjet_openapi_python_sdk.response.tplus.query_inventory_response import QueryInventoryResponse from chanjet_openapi_python_sdk.content.tplus.query_inventory_content import QueryInventoryContent client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' # 创建请求 req = QueryInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Query' req.content = QueryInventoryContent( code='INV001', # 存货编码 inventory_class_code='C001', # 分类编码 is_stop=False, # 不包括已停用 is_sale=True # 销售属性 ) # 执行请求 result = client.execute(req, QueryInventoryResponse) # 处理结果 print(f"编码: {result.Code}") print(f"名称: {result.Name}") ``` -------------------------------- ### Debug Mode Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_logger.md Illustrates how to set the logger to DEBUG mode for detailed logging output, useful for troubleshooting. ```APIDOC ## Debug Mode ### Description This example shows how to set the logger to DEBUG level. In this mode, all detailed logs, including request headers, bodies, and responses, will be outputted, which is highly beneficial for debugging purposes. ### Example ```python import logging from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.utils.chanjet_logger import ChanjetLogger # Set to DEBUG level for detailed log information ChanjetLogger(logging.DEBUG) client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' # All API calls will output detailed debug information ``` ``` -------------------------------- ### Custom Response Class Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_response.md Example of creating a custom response class that inherits from ChanjetResponse. It defines attributes for code, message, and data, and binds incoming data to these attributes. ```python from chanjet_openapi_python_sdk.chanjet_response import ChanjetResponse class CustomResponse(ChanjetResponse): def __init__(self, data=None): # 定义响应的属性 self.code = '' self.message = '' self.data = {} # 如果 data 被传入,将其绑定到当前实例 if data: self.__dict__ = data def __str__(self): return str(self.__dict__) ``` -------------------------------- ### Build a POST Request Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_request.md Example of constructing a POST request, including setting the request URI and request body content using a specific content class. ```python from chanjet_openapi_python_sdk.request.tplus.create_inventory_request import CreateInventoryRequest from chanjet_openapi_python_sdk.content.tplus.create_inventory_content import CreateInventoryContent req = CreateInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Create' content = CreateInventoryContent( code='INV001', name='产品名称', shorthand='JH', specification='规格', inventory_class_code='CLASS001', unit_code='UNIT001', unit_name='个', disabled='0', is_single_unit='1', is_purchase='1', is_sale='1' ) req.content = content ``` -------------------------------- ### Python SDK Example for Creating a Sale Order Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/tplus-order-api.md Demonstrates how to use the T+ Order Management API via the Python SDK to create a new sales order. Ensure you have initialized the ChanjetClient with your credentials and the correct request URI. ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.create_sale_order_request import CreateSaleOrderRequest from chanjet_openapi_python_sdk.content.tplus.create_sale_order_content import CreateSaleOrderContent, SaleOrderDetail client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' req = CreateSaleOrderRequest() req.request_uri = '/tplus/api/v2/sale/order/Create' # 创建销售订单主体 content = CreateSaleOrderContent( voucher_date='2024-01-15', external_code='EXT20240115001', customer_code='CUST001', address='北京市朝阳区送货地址', link_man='张三', contact_phone='13800138000', header_dynamic_property_keys=[], header_dynamic_property_values=[] ) # 添加销售订单明细 detail1 = SaleOrderDetail( inventory_code='INV001', unit_name='个', quantity=10.0, orig_discount_price=100.0, detail_dynamic_property_keys=[], detail_dynamic_property_values=[] ) detail2 = SaleOrderDetail( inventory_code='INV002', unit_name='箱', quantity=5.0, orig_discount_price=500.0, detail_dynamic_property_keys=[], detail_dynamic_property_values=[] ) content.dto.SaleOrderDetails.append(detail1) content.dto.SaleOrderDetails.append(detail2) req.content = content # 执行请求 result = client.execute(req) print(result) ``` -------------------------------- ### Full Error Handling Example for Inventory Query Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/errors.md This example shows how to safely query inventory using the Chanjet Python SDK and handle various potential exceptions, such as HTTP method errors, response serialization errors, timeouts, HTTP errors, network issues, JSON decoding errors, and other unexpected exceptions. It's recommended to use this pattern for all API calls. ```python import logging import json import requests from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.query_inventory_request import QueryInventoryRequest from chanjet_openapi_python_sdk.response.tplus.query_inventory_response import QueryInventoryResponse from chanjet_openapi_python_sdk.content.tplus.query_inventory_content import QueryInventoryContent from chanjet_openapi_python_sdk.exception.http_method_exception import HttpMethodException from chanjet_openapi_python_sdk.exception.serialize_response_exception import SerializeResponseException from chanjet_openapi_python_sdk.utils.chanjet_logger import ChanjetLogger # 配置日志 ChanjetLogger(logging.INFO) def query_inventory_safely(): client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' req = QueryInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Query' req.content = QueryInventoryContent('INV001', 'CLASS001', False, True) try: result = client.execute(req, QueryInventoryResponse) print(f"成功: {result}") return result except HttpMethodException as e: print(f"HTTP 方法错误: {e}") # 检查请求类是否正确实现了 get_http_method() except SerializeResponseException as e: print(f"响应类错误: {e}") # 检查响应类是否继承自 ChanjetResponse except requests.exceptions.Timeout as e: print(f"请求超时: {e}") # 可能需要增加超时时间或重试 except requests.exceptions.HTTPError as e: print(f"HTTP 错误: {e}") # 检查认证信息和请求参数 except requests.exceptions.RequestException as e: print(f"网络错误: {e}") # 检查网络连接 except json.JSONDecodeError as e: print(f"JSON 解析错误: {e}") # 检查服务器响应格式 except Exception as e: print(f"未知错误: {e}") # 记录日志并通知管理员 if __name__ == '__main__': query_inventory_safely() ``` -------------------------------- ### Batch Query Partner Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/tplus-partner-api.md This section provides a Python SDK example for querying multiple partners by their codes. It demonstrates how to set up the client, define partner codes to query, and process the responses to display partner details. ```APIDOC ## Batch Query Partner ### Description This endpoint allows for querying partner information based on a list of partner codes. It uses the `QueryPartnerRequest` and `QueryPartnerResponse` from the Tplus SDK to retrieve details for specified partners. ### Method POST ### Endpoint /tplus/api/v2/partner/Query ### Parameters #### Request Body - **code** (string) - Required - The unique code of the partner to query. ### Request Example ```json { "code": "CUST001" } ``` ### Response #### Success Response (200) - **Code** (string) - The partner's code. - **Name** (string) - The partner's name. - **PartnerType** (object) - Information about the partner's type. - **Name** (string) - The name of the partner type. - **PartnerClass** (object) - Information about the partner's class. - **Name** (string) - The name of the partner class. #### Response Example ```json { "Code": "CUST001", "Name": "北京客户有限公司", "PartnerType": { "Code": "0", "Name": "客户" }, "PartnerClass": { "Code": "VIP", "Name": "VIP 客户" } } ``` ``` -------------------------------- ### Create Sale Order with Nested Objects and Lists Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_content.md This example demonstrates creating a sale order, including nested details like sale order items. It requires app key, app secret, open token, and specific order details. ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.create_sale_order_request import CreateSaleOrderRequest from chanjet_openapi_python_sdk.content.tplus.create_sale_order_content import CreateSaleOrderContent, SaleOrderDetail client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' req = CreateSaleOrderRequest() req.request_uri = '/tplus/api/v2/sale/order/Create' content = CreateSaleOrderContent( voucher_date='2024-01-15', external_code='EXT001', customer_code='CUST001', address='送货地址', link_man='联系人', contact_phone='13800138000', header_dynamic_property_keys=[], header_dynamic_property_values=[] ) # 添加销售订单明细 detail = SaleOrderDetail( inventory_code='INV001', unit_name='个', quantity=10.0, orig_discount_price=100.0, detail_dynamic_property_keys=[], detail_dynamic_property_values=[] ) content.dto.SaleOrderDetails.append(detail) req.content = content result = client.execute(req) ``` -------------------------------- ### Tplus Inventory API Usage Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/tplus-inventory-api.md Demonstrates how to use the ChanjetClient to query current stock information using the QueryCurrentStockRequest. Ensure your client is initialized with valid credentials and the request object is populated correctly. ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.query_current_stock_request import QueryCurrentStockRequest from chanjet_openapi_python_sdk.response.tplus.query_current_stock_response import QueryCurrentStockResponse from chanjet_openapi_python_sdk.content.tplus.query_current_stock_content import QueryCurrentStockContent client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' req = QueryCurrentStockRequest() req.request_uri = '/tplus/api/v2/inventory/CurrentStock/Query' req.content = QueryCurrentStockContent('INV001', 'WAREHOUSE001', 'LOC001') result = client.execute(req, QueryCurrentStockResponse) print(result) ``` -------------------------------- ### Load ChanjetClient Configuration from .env File Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/configuration.md This example demonstrates how to load Chanjet API credentials from a `.env` file using the `python-dotenv` library. Ensure the `.env` file is added to your `.gitignore` to prevent accidental commits of sensitive information. ```python from dotenv import load_dotenv import os from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient # 加载 .env 文件 load_dotenv() client = ChanjetClient(os.getenv('CHANJET_SERVER_URL')) client.app_key = os.getenv('CHANJET_APP_KEY') client.app_secret = os.getenv('CHANJET_APP_SECRET') client.open_token = os.getenv('CHANJET_OPEN_TOKEN') ``` -------------------------------- ### ChanjetClient Logging Integration Example Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_logger.md Illustrates how ChanjetClient logs various details during request execution, such as URL, headers, parameters, and request body, depending on the configured logging level. ```python # Example of log calls within ChanjetClient logging.info(f'url: {self._server_url + req.request_uri}') logging.info(f'request-header: {str(self.get_request_headers())}') if http_method in ['get', 'delete']: logging.info(f'request-params: {str(req.get_query_params())}') else: logging.info(f'request-content: {str(req.content)}') ``` -------------------------------- ### Handle HttpMethodException Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/errors.md Example of how to catch and handle HttpMethodException when an unsupported HTTP method is used during a request. Ensure the ChanjetClient and HttpMethodException are imported. ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.exception.http_method_exception import HttpMethodException client = ChanjetClient('https://openapi.chanjet.com') try: # 某个请求的 get_http_method() 返回了不支持的方法 # 例如返回 'patch' 而不是 'post' result = client.execute(req) except HttpMethodException as e: print(f"HTTP 方法错误: {e}") # 处理错误 ``` -------------------------------- ### Executing a Request with a Response Class Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_response.md Example demonstrating how to execute a request using ChanjetClient and specify a response class (QueryInventoryResponse) for deserialization. The result is an instance of the specified response class. ```python from chanjet_openapi_python_sdk.chanjet_client import ChanjetClient from chanjet_openapi_python_sdk.request.tplus.query_inventory_request import QueryInventoryRequest from chanjet_openapi_python_sdk.response.tplus.query_inventory_response import QueryInventoryResponse from chanjet_openapi_python_sdk.content.tplus.query_inventory_content import QueryInventoryContent client = ChanjetClient('https://openapi.chanjet.com') client.app_key = 'your_app_key' client.app_secret = 'your_app_secret' client.open_token = 'your_open_token' req = QueryInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Query' req.content = QueryInventoryContent('INV001', 'CLASS001', False, True) # 返回 QueryInventoryResponse 实例 result = client.execute(req, QueryInventoryResponse) print(result.Code) # 访问响应属性 print(result.Name) ``` -------------------------------- ### Executing a Request Without a Response Class Source: https://github.com/chanjet/chanjet-openapi-python-sdk/blob/master/_autodocs/api-reference/chanjet_response.md Example showing how to execute a request without specifying a response class. In this case, the ChanjetClient returns the response as a dictionary. ```python req = QueryInventoryRequest() req.request_uri = '/tplus/api/v2/inventory/Query' req.content = QueryInventoryContent('INV001', 'CLASS001', False, True) # 返回字典 result = client.execute(req) print(result['Code']) # 访问字典键 print(result['Name']) ```