Skip to content
Longplay
Docs
Browse docs / Python

Python

Synchronous and asynchronous server clients for sessions, payments, invoices, balances, Customer messaging and Funnel decisions.

Markdown
API v1Updated

Install#

terminalShell
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

Resolve the latest stable release, then freeze exact dependencies in requirements.lock. Python 3.11+. Distributed from longplayai.com rather than PyPI; the distribution is tinkerlandai-longplay-sdk and the import is longplay.

Related: pip, uv and requirements.txt

Synchronous client#

Set LONGPLAY_SERVER_KEY, LONGPLAY_PROJECT_ID and LONGPLAY_API_URL (https://api.longplayai.com here). Events and Features must already be configured in that App's Sandbox.

usage.pyPython
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"))

An entitlement check only observes access; usage is a separate write. HTTP success does not mean a debit was accepted: inspect each receipt's accepted and reason.

Asynchronous client#

holdings.pyPython
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"])

Reuse one client in a long-running service and close it on shutdown with close() (sync) or await aclose() (async). Both accept timeout in seconds (default 10, maximum 120) and an HTTPX transport= for tests or custom networking. Ambient proxies and cookies are not used and redirects are not followed.

Methods#

All arguments are keyword-only; returned TypedDicts keep wire keys such as `customerId`.
MethodInputs and behaviorScope
get_or_create_customerexternal_user_id or email; optional name, attributes, fingerprint. Existing records are not patched.customers:write
get_customerExactly one of customer_id or external_user_id.customers:read
list_customersFilters with explicit offset/limit; returns customers, hasMore, total.customers:read
update_customerA retained request_id, one lookup and a partial patch: name, email, attributes, remove_attributes, add_tags, remove_tags.customers:write
read_holdingscustomer_id, optional entity_id.entitlements:read
check_entitlementcustomer_id, internal_feature_id; positive decimal-string quantity, optional properties/entity_id.entitlements:read
track_usagecustomer_id, a retained idempotency_key, exactly one of event_name or internal_feature_id; decimal-string quantity, optional properties/entity_id.credits:consume
send_messageA retained request_id, customer_id, channel-tagged message, expires_at and optional connection_id.messaging:write
read_messagemessage_id; read dispatch state and verified receipts.messaging:write

All arguments are keyword-only; returned TypedDicts keep wire keys such as `customerId`.

  • get_or_create_customer

    Inputs and behavior
    external_user_id or email; optional name, attributes, fingerprint. Existing records are not patched.
    Scope
    customers:write
  • get_customer

    Inputs and behavior
    Exactly one of customer_id or external_user_id.
    Scope
    customers:read
  • list_customers

    Inputs and behavior
    Filters with explicit offset/limit; returns customers, hasMore, total.
    Scope
    customers:read
  • update_customer

    Inputs and behavior
    A retained request_id, one lookup and a partial patch: name, email, attributes, remove_attributes, add_tags, remove_tags.
    Scope
    customers:write
  • read_holdings

    Inputs and behavior
    customer_id, optional entity_id.
    Scope
    entitlements:read
  • check_entitlement

    Inputs and behavior
    customer_id, internal_feature_id; positive decimal-string quantity, optional properties/entity_id.
    Scope
    entitlements:read
  • track_usage

    Inputs and behavior
    customer_id, a retained idempotency_key, exactly one of event_name or internal_feature_id; decimal-string quantity, optional properties/entity_id.
    Scope
    credits:consume
  • send_message

    Inputs and behavior
    A retained request_id, customer_id, channel-tagged message, expires_at and optional connection_id.
    Scope
    messaging:write
  • read_message

    Inputs and behavior
    message_id; read dispatch state and verified receipts.
    Scope
    messaging:write

Omitted fields stay omitted; None is not an alias for omission. Quantities are decimal strings, never floats. Import the generated TypedDicts from longplay.models.

Errors and recovery#

errors.pyPython
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 exposes code, status, request_id, retryable, recovery, and optional reason and retry_after_seconds; it never retains the Key or payload. There are no automatic retries: persist the idempotency_key or request_id before sending and replay the same value and input after an uncertain result. TIMEOUT, NETWORK_ERROR and cancellation do not mean rollback.

Sessions and full coverage#

The Python SDK provides methods for current Server-Key/mixed-credential operations, including sessions, payments, offers, invoices, balance management and Customer messaging. Reserved operations still return 501; check reference pages for other unsupported branches. Use the SDK's Funnel client for Funnel decisions. See available methods below and the full support matrix, which also includes reserved entries.

Methods by area
AreaMethods
Customer messaging and installationssend_message, read_message
Customers, Guests and Sessionsget_or_create_customer, get_customer, list_customers, update_customer, create_session, revoke_sessions, create_guest_customer, resume_guest_session, claim_guest_customer
Entitlements and product presentationcheck_entitlement, resolve_offering, resolve_paywall, read_holdings
Balances, usage and ledgerread_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
Seatsread_seats, manage_seat
Subscriptions and paymentssetup_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
Invoices, refunds and billinglist_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
Coupons, rewards and referralsgrant_offer, grant_model_benefit, read_model_benefit
Feature flags, evaluation and eventsget_features, evaluate_features, track_events
Native purchasesrestore_native_purchase
AI pricingread_ai_pricing
CLI and CIresolve_content, get_code_reference_config, submit_code_references

Methods by area

  • Customer messaging and installations

    Methods
    send_message, read_message
  • Customers, Guests and Sessions

    Methods
    get_or_create_customer, get_customer, list_customers, update_customer, create_session, revoke_sessions, create_guest_customer, resume_guest_session, claim_guest_customer
  • Entitlements and product presentation

    Methods
    check_entitlement, resolve_offering, resolve_paywall, read_holdings
  • Balances, usage and ledger

    Methods
    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
  • Seats

    Methods
    read_seats, manage_seat
  • Subscriptions and payments

    Methods
    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
  • Invoices, refunds and billing

    Methods
    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
  • Coupons, rewards and referrals

    Methods
    grant_offer, grant_model_benefit, read_model_benefit
  • Feature flags, evaluation and events

    Methods
    get_features, evaluate_features, track_events
  • Native purchases

    Methods
    restore_native_purchase
  • AI pricing

    Methods
    read_ai_pricing
  • CLI and CI

    Methods
    resolve_content, get_code_reference_config, submit_code_references

After authenticating the user and resolving their Customer on your backend, issue the session with a Server Key holding sessions:create. Return the complete session, including customerId, sessionId, accessToken, refreshToken, expiresAt and refreshExpiresAt, to that user's frontend and pass it to identify(session); the frontend SDK handles subsequent refreshes.

sessions.pyPython
from longplay import Longplayfrom 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})

Related: Support matrix·All operations·Request conventions