跳到正文
Indiana
控制台
开发文档
章节目录 / Python

Python

同步与异步服务端客户端:Customer、持有、权益检查与用量上报。

API v1更新于

安装

terminalShell
python -m pip install "https://tinker.cash/downloads/python/tinkerlandai_indiana_sdk-0.6.1-py3-none-any.whl"

版本 0.6.1,需要 Python 3.11+。从 tinker.cash 分发,不在 PyPI;发行包名 tinkerlandai-indiana-sdk,导入名 indiana。

相关:pip、uv 与 requirements.txt

同步客户端

设置 INDIANA_API_KEY、INDIANA_PROJECT_ID 与 INDIANA_API_URL(生产为 https://api.tinker.cash)。事件与 Feature 必须已在该 App/环境配置。

usage.pyPython
import os from indiana import Indiana with Indiana(    api_key=os.environ["INDIANA_API_KEY"],    project_id=os.environ["INDIANA_PROJECT_ID"],    environment="sandbox",    base_url=os.environ["INDIANA_API_URL"],) as client:    result = client.get_or_create_customer(external_user_id="merchant-user-123")    customer_id = result["customer"]["id"]     holdings = client.read_holdings(customer_id=customer_id)    check = client.check_entitlement(        customer_id=customer_id,        internal_feature_id=os.environ["INDIANA_FEATURE_ID"],        quantity="1",    )    if check["check"]["allowed"]:        usage = client.track_usage(            customer_id=customer_id,            event_name="image_generated",            quantity="1.25",            properties={"quality": "hd"},            idempotency_key="merchant-event-123",        )        for receipt in usage["receipts"]:            print(receipt["accepted"], receipt.get("reason"))

权益检查只观察是否可用,不扣减;用量上报是独立的写操作。HTTP 成功不代表扣减成功:逐条检查 receipts 的 accepted 与 reason。

异步客户端

holdings.pyPython
import os from indiana import AsyncIndiana  async def read_customer_holdings(external_user_id: str):    async with AsyncIndiana(        api_key=os.environ["INDIANA_API_KEY"],        project_id=os.environ["INDIANA_PROJECT_ID"],        environment="sandbox",        base_url=os.environ["INDIANA_API_URL"],    ) as client:        result = await client.get_or_create_customer(external_user_id=external_user_id)        return await client.read_holdings(customer_id=result["customer"]["id"])

长期运行的服务请复用一个客户端,在关闭时调用 close()(同步)或 await aclose()(异步)。两个客户端都接受 timeout 秒数(默认 10,最大 120),以及用于测试或自定义网络的 HTTPX transport=。不使用环境代理、cookie,也不跟随重定向。

方法

参数均为关键字参数;返回的 TypedDict 保留线上字段名(如 `customerId`)。
方法输入与行为权限
get_or_create_customerexternal_user_id 或 email;可选 name、attributes、fingerprint。已有记录不会被修改。customers:write
get_customercustomer_id 与 external_user_id 二选一。customers:read
list_customers筛选条件与显式 offset/limit;返回 customers、hasMore、total。customers:read
update_customer保留的 request_id、一个查找条件与部分更新:name、email、attributes、remove_attributes、add_tags、remove_tags。customers:write
read_holdingscustomer_id,可选 entity_id。entitlements:read
check_entitlementcustomer_id、internal_feature_id;正数十进制字符串 quantity,可选 properties/entity_id。entitlements:read
track_usagecustomer_id、保留的 idempotency_key,event_name 与 internal_feature_id 二选一;十进制字符串 quantity,可选 properties/entity_id。credits:consume

参数均为关键字参数;返回的 TypedDict 保留线上字段名(如 `customerId`)。

  • get_or_create_customer

    输入与行为
    external_user_id 或 email;可选 name、attributes、fingerprint。已有记录不会被修改。
    权限
    customers:write
  • get_customer

    输入与行为
    customer_id 与 external_user_id 二选一。
    权限
    customers:read
  • list_customers

    输入与行为
    筛选条件与显式 offset/limit;返回 customers、hasMore、total。
    权限
    customers:read
  • update_customer

    输入与行为
    保留的 request_id、一个查找条件与部分更新:name、email、attributes、remove_attributes、add_tags、remove_tags。
    权限
    customers:write
  • read_holdings

    输入与行为
    customer_id,可选 entity_id。
    权限
    entitlements:read
  • check_entitlement

    输入与行为
    customer_id、internal_feature_id;正数十进制字符串 quantity,可选 properties/entity_id。
    权限
    entitlements:read
  • track_usage

    输入与行为
    customer_id、保留的 idempotency_key,event_name 与 internal_feature_id 二选一;十进制字符串 quantity,可选 properties/entity_id。
    权限
    credits:consume

省略的字段保持省略,None 不等于省略。数量使用十进制字符串,不使用浮点数。从 indiana.models 导入生成的 TypedDict。

错误与恢复

errors.pyPython
from indiana import IndianaError try:    holdings = client.read_holdings(customer_id=customer_id)except IndianaError as error:    print(error.code, error.status, error.request_id, error.retryable, error.recovery)

IndianaError 提供 code、status、request_id、retryable、recovery,以及可选的 reason 和 retry_after_seconds;不保存 Key 或请求内容。SDK 不自动重试:发送前持久保存 idempotency_key 或 request_id,结果不确定时用原值和原输入重放。TIMEOUT、NETWORK_ERROR 与取消都不代表已回滚。

调用其他操作

Python SDK 覆盖 Customer、持有、权益检查与用量上报七项操作。会话签发、支付、优惠、发票、余额管理与 Funnel 决策等其他服务端操作可以直接调用 HTTP API:使用同一把 Server Key、X-Indiana-Protocol: 0.6 与 JSON 请求体,按错误对象的 code 和 recovery 处理失败。

sessions.pyPython
import os import httpx # An operation outside the SDK: issue a Customer Token (sessions:create).response = httpx.post(    f"{os.environ['INDIANA_API_URL']}/api/v1/customer-sessions",    headers={        "Authorization": f"Bearer {os.environ['INDIANA_API_KEY']}",        "X-Indiana-Protocol": "0.6",    },    json={"customerId": "<CUSTOMER_UUID>"},    timeout=10,)body = response.json()if response.is_error:    raise RuntimeError(body["error"]["code"])customer_token = body["customerToken"]

相关:全部接口·请求约定