# Python

同步与异步服务端客户端：会话、支付、发票、余额、客户消息与 Funnel 决策。

更新于 2026-11-06

[网页版本](https://www.longplayai.com/zh-hans/docs/sdk/python)

<a id="install"></a>

## 安装

**terminal**

```bash
SDK_VERSION="$(curl -fsS 'https://cdn.longplayai.com/sdk/longplay/stable?package=python')" &&
python -m pip install "https://cdn.longplayai.com/downloads/python/tinkerlandai_longplay_sdk-$SDK_VERSION-py3-none-any.whl" &&
python -m pip freeze > requirements.lock
```

默认解析最新稳定版，安装后将精确依赖写入 requirements.lock。需要 Python 3.11+。从 longplayai.com 分发，不在 PyPI；发行包名 `tinkerlandai-longplay-sdk`，导入名 `longplay`。

- [pip、uv 与 requirements.txt](https://www.longplayai.com/zh-hans/docs/install.md#python)

<a id="sync"></a>

## 同步客户端

设置 `LONGPLAY_SERVER_KEY`、`LONGPLAY_PROJECT_ID` 与 `LONGPLAY_API_URL`（本页为 https://api.longplayai.com）。事件与 Feature 必须已在该 App 的 Sandbox 配置。

**usage.py**

```python
import os

from longplay import Longplay

with Longplay(
    api_key=os.environ["LONGPLAY_SERVER_KEY"],
    project_id=os.environ["LONGPLAY_PROJECT_ID"],
    environment="sandbox",
    base_url=os.environ["LONGPLAY_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["LONGPLAY_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`。

<a id="async"></a>

## 异步客户端

**holdings.py**

```python
import os

from longplay import AsyncLongplay


async def read_customer_holdings(external_user_id: str):
    async with AsyncLongplay(
        api_key=os.environ["LONGPLAY_SERVER_KEY"],
        project_id=os.environ["LONGPLAY_PROJECT_ID"],
        environment="sandbox",
        base_url=os.environ["LONGPLAY_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，也不跟随重定向。

<a id="methods"></a>

## 方法

**参数均为关键字参数；返回的 TypedDict 保留接口 JSON 中的原始字段名（如 `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` |
| `send_message` | 保留的 `request_id`、`customer_id`、带 channel 的 `message`、`expires_at`，可选 `connection_id`。 | `messaging:write` |
| `read_message` | `message_id`；读取派发状态和已验证回执。 | `messaging:write` |

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

<a id="errors"></a>

## 错误与恢复

**errors.py**

```python
from longplay import LongplayError

try:
    holdings = client.read_holdings(customer_id=customer_id)
except LongplayError as error:
    print(error.code, error.status, error.request_id, error.retryable, error.recovery)
```

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

<a id="other-operations"></a>

## 会话与完整能力

Python SDK 提供当前 Server Key／混合凭据操作的方法，包括会话、支付、优惠、发票、余额管理与客户消息；保留操作仍返回 501，其他未支持分支以接口页为准。Funnel 决策通过 SDK 的 Funnel 客户端调用。可用方法见下表，完整支持矩阵还包含保留入口。

**按领域划分的方法**

| 领域 | 方法 |
| --- | --- |
| 客户消息与设备 | `send_message`, `read_message` |
| Customer、访客与会话 | `get_or_create_customer`, `get_customer`, `list_customers`, `update_customer`, `create_session`, `revoke_sessions`, `create_guest_customer`, `resume_guest_session`, `claim_guest_customer` |
| 权益与商品展示 | `check_entitlement`, `resolve_offering`, `resolve_paywall`, `read_holdings` |
| 余额、用量与账本 | `read_balance_source`, `adjust_balance`, `read_usage`, `set_usage`, `manage_balance_grant`, `list_balance_grants`, `manage_usage_entity`, `read_usage_analytics`, `read_credit_analytics`, `submit_usage_batch`, `read_usage_batch`, `read_ledger`, `read_credit_statement`, `quote_balance`, `track_usage`, `mutate_balance` |
| 席位 | `read_seats`, `manage_seat` |
| 订阅与支付 | `setup_payment`, `read_payment_setup`, `verify_subscriptions`, `preview_attach`, `attach`, `read_subscription_operation`, `preview_update`, `update`, `read_subscription_update`, `list_subscriptions`, `list_purchases`, `list_subscription_conflicts`, `retry_subscription_conflict`, `manage_subscription_trial`, `read_subscription_trial`, `preview_subscription_batch`, `confirm_subscription_batch`, `read_subscription_batch`, `abandon_subscription_batch`, `record_merchant_event` |
| 发票、退款与计费 | `list_invoice_templates`, `preview_invoice`, `create_invoice`, `manage_invoice`, `read_invoice_operation`, `list_invoices`, `get_invoice`, `preview_refund`, `refund`, `read_refund`, `manage_billing_limits`, `read_billing_invoice`, `prepare_billing_adjustment` |
| 优惠券、奖励与推荐 | `grant_offer`, `grant_model_benefit`, `read_model_benefit` |
| 功能开关、求值与事件 | `get_features`, `evaluate_features`, `track_events` |
| 原生购买 | `restore_native_purchase` |
| AI 定价 | `read_ai_pricing` |
| CLI 与 CI | `resolve_content`, `get_code_reference_config`, `submit_code_references` |

后端验证当前用户并解析对应 Customer 后，用具有 `sessions:create` 权限的 Server Key 调用会话方法。将包含 `customerId`、`sessionId`、`accessToken`、`refreshToken`、`expiresAt` 和 `refreshExpiresAt` 的完整会话交给同一用户的前端，并传入 `identify(session)`；前端 SDK 负责后续刷新。

**sessions.py**

```python
from longplay import Longplay
from longplay.models import CreateSessionResponse


def issue_customer_session(client: Longplay, customer_id: str) -> CreateSessionResponse:
    # Resolve customer_id from your authenticated user on the backend.
    # Return the complete session to the same user's browser or app.
    return client.create_session(request={"customerId": customer_id})
```

- [支持矩阵](https://www.longplayai.com/zh-hans/docs/guides/platforms.md)
- [全部接口](https://www.longplayai.com/zh-hans/docs/api/operations.md)
- [请求约定](https://www.longplayai.com/zh-hans/docs/api.md)
