开发文档 SDKs Python Python 同步与异步服务端客户端:会话、支付、发票、余额、客户消息与 Funnel 决策。
API v1 更新于 2026年11月6日
本页内容
1 SDK_VERSION= "$(curl -fsS 'https://cdn.longplayai.com/sdk/longplay/stable?package=python')" &&2 python -m pip install "https://cdn.longplayai.com/downloads/python/tinkerlandai_longplay_sdk-$SDK_VERSION-py3-none-any.whl" &&3 python -m pip freeze > requirements.lock默认解析最新稳定版,安装后将精确依赖写入 requirements.lock。需要 Python 3.11+。从 longplayai.com 分发,不在 PyPI;发行包名 tinkerlandai-longplay-sdk,导入名 longplay。
相关:pip、uv 与 requirements.txt
同步客户端# 设置 LONGPLAY_SERVER_KEY、LONGPLAY_PROJECT_ID 与 LONGPLAY_API_URL(本页为 https://api.longplayai.com)。事件与 Feature 必须已在该 App 的 Sandbox 配置。
1 import os2 3 from longplay import Longplay 4 5 with Longplay (6 api_key=os.environ["LONGPLAY_SERVER_KEY" ], 7 project_id=os.environ["LONGPLAY_PROJECT_ID" ], 8 environment="sandbox" , 9 base_url=os.environ["LONGPLAY_API_URL" ], 10 ) as client: 11 result = client.get_or_create_customer (external_user_id="merchant-user-123" ) 12 customer_id = result["customer" ]["id" ] 13 14 holdings = client.read_holdings (customer_id=customer_id) 15 check = client.check_entitlement ( 16 customer_id=customer_id, 17 internal_feature_id=os.environ["LONGPLAY_FEATURE_ID" ], 18 quantity="1" , 19 ) 20 if check["check" ]["allowed" ]: 21 usage = client.track_usage ( 22 customer_id=customer_id, 23 event_name="image_generated" , 24 quantity="1.25" , 25 properties={"quality" : "hd" }, 26 idempotency_key="merchant-event-123" , 27 ) 28 for receipt in usage["receipts" ]: 29 print (receipt["accepted" ], receipt.get ("reason" )) 权益检查只观察是否可用,不扣减;用量上报是独立的写操作。HTTP 成功不代表扣减成功:逐条检查 receipts 的 accepted 与 reason。
异步客户端# 1 import os2 3 from longplay import AsyncLongplay 4 5 6 async def read_customer_holdings (external_user_id: str):7 async with AsyncLongplay ( 8 api_key=os.environ["LONGPLAY_SERVER_KEY" ], 9 project_id=os.environ["LONGPLAY_PROJECT_ID" ], 10 environment="sandbox" , 11 base_url=os.environ["LONGPLAY_API_URL" ], 12 ) as client: 13 result = await client.get_or_create_customer (external_user_id=external_user_id) 14 return await client.read_holdings (customer_id=result["customer" ]["id" ]) 长期运行的服务请复用一个客户端,在关闭时调用 close()(同步)或 await aclose()(异步)。两个客户端都接受 timeout 秒数(默认 10,最大 120),以及用于测试或自定义网络的 HTTPX transport=。不使用环境代理、cookie,也不跟随重定向。
参数均为关键字参数;返回的 TypedDict 保留接口 JSON 中的原始字段名(如 `customerId`)。 方法 输入与行为 权限 get_or_create_customerexternal_user_id 或 email;可选 name、attributes、fingerprint。已有记录不会被修改。customers:writeget_customercustomer_id 与 external_user_id 二选一。customers:readlist_customers筛选条件与显式 offset/limit;返回 customers、hasMore、total。 customers:readupdate_customer保留的 request_id、一个查找条件与部分更新:name、email、attributes、remove_attributes、add_tags、remove_tags。 customers:writeread_holdingscustomer_id,可选 entity_id。entitlements:readcheck_entitlementcustomer_id、internal_feature_id;正数十进制字符串 quantity,可选 properties/entity_id。entitlements:readtrack_usagecustomer_id、保留的 idempotency_key,event_name 与 internal_feature_id 二选一;十进制字符串 quantity,可选 properties/entity_id。credits:consumesend_message保留的 request_id、customer_id、带 channel 的 message、expires_at,可选 connection_id。 messaging:writeread_messagemessage_id;读取派发状态和已验证回执。messaging:write
参数均为关键字参数;返回的 TypedDict 保留接口 JSON 中的原始字段名(如 `customerId`)。
get_or_create_customer
输入与行为 external_user_id 或 email;可选 name、attributes、fingerprint。已有记录不会被修改。
权限 customers:writeget_customer
输入与行为 customer_id 与 external_user_id 二选一。
权限 customers:readlist_customers
输入与行为 筛选条件与显式 offset/limit;返回 customers、hasMore、total。
权限 customers:readupdate_customer
输入与行为 保留的 request_id、一个查找条件与部分更新:name、email、attributes、remove_attributes、add_tags、remove_tags。
权限 customers:writeread_holdings
输入与行为 customer_id,可选 entity_id。
权限 entitlements:readcheck_entitlement
输入与行为 customer_id、internal_feature_id;正数十进制字符串 quantity,可选 properties/entity_id。
权限 entitlements:readtrack_usage
输入与行为 customer_id、保留的 idempotency_key,event_name 与 internal_feature_id 二选一;十进制字符串 quantity,可选 properties/entity_id。
权限 credits:consumesend_message
输入与行为 保留的 request_id、customer_id、带 channel 的 message、expires_at,可选 connection_id。
权限 messaging:writeread_message
输入与行为 message_id;读取派发状态和已验证回执。
权限 messaging:write省略的字段保持省略,None 不等于省略。数量使用十进制字符串,不使用浮点数。从 longplay.models 导入生成的 TypedDict。
错误与恢复# 1 from longplay import LongplayError 2 3 try :4 holdings = client.read_holdings (customer_id=customer_id) 5 except LongplayError as error:6 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 与取消都不代表已回滚。
会话与完整能力# Python SDK 提供当前 Server Key/混合凭据操作的方法,包括会话、支付、优惠、发票、余额管理与客户消息;保留操作仍返回 501,其他未支持分支以接口页为准。Funnel 决策通过 SDK 的 Funnel 客户端调用。可用方法见下表,完整支持矩阵还包含保留入口。
按领域划分的方法 领域 方法 客户消息与设备 send_message, read_messageCustomer、访客与会话 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_purchaseAI 定价 read_ai_pricingCLI 与 CI resolve_content, get_code_reference_config, submit_code_references
按领域划分的方法
客户消息与设备
方法 send_message, read_messageCustomer、访客与会话
方法 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_purchaseAI 定价
方法 read_ai_pricingCLI 与 CI
方法 resolve_content, get_code_reference_config, submit_code_references后端验证当前用户并解析对应 Customer 后,用具有 sessions:create 权限的 Server Key 调用会话方法。将包含 customerId、sessionId、accessToken、refreshToken、expiresAt 和 refreshExpiresAt 的完整会话交给同一用户的前端,并传入 identify(session);前端 SDK 负责后续刷新。
1 from longplay import Longplay 2 from longplay.models import CreateSessionResponse 3 4 5 def issue_customer_session (client: Longplay , customer_id: str) -> CreateSessionResponse :6 # Resolve customer_id from your authenticated user on the backend. 7 # Return the complete session to the same user's browser or app. 8 return client.create_session (request={"customerId" : customer_id}) 相关:支持矩阵 · 全部接口 · 请求约定