Skip to main content

Official Python SDK for the TrueTrial API

Project description

TrueTrial Python SDK

Official Python client for the TrueTrial API. Manage trial periods, warranties, subscriptions, and compliance-first order lifecycle tracking.

Requirements

  • Python 3.10 or later
  • An active TrueTrial account with an API key

Installation

pip install truetrial

Or install from source:

pip install -e /path/to/sdks/python

Quick Start

Synchronous Usage

from truetrial import TrueTrialClient

client = TrueTrialClient(api_key="tt_live_your_key_here")

# List orders
orders = client.orders.list()

# Create an order
order = client.orders.create(
    external_order_id="EXT-12345",
    consumer_email="customer@example.com",
    product_type="physical",
    price_cents=4999,
    currency="USD",
)

# Get a specific order
order = client.orders.get("01JARW5X...")

# Close when done
client.close()

Use a context manager to handle cleanup automatically:

with TrueTrialClient(api_key="tt_live_your_key_here") as client:
    orders = client.orders.list(filters={"status": "delivered"})

Asynchronous Usage

import asyncio
from truetrial import AsyncTrueTrialClient

async def main():
    async with AsyncTrueTrialClient(api_key="tt_live_your_key_here") as client:
        orders = await client.orders.list()
        order = await client.orders.get("01JARW5X...")

asyncio.run(main())

API Reference

Client Initialization

TrueTrialClient(
    api_key="tt_live_...",                          # Required
    base_url="https://truetrial.test/api/v1",       # Optional, defaults shown
)

Orders

client.orders.list(filters={"status": "delivered"})
client.orders.create(
    external_order_id="EXT-123",
    consumer_email="user@example.com",
    product_type="physical",
    price_cents=2999,
)
client.orders.get("order_id")
client.orders.status("order_id")

Shipments

client.shipments.create(
    "order_id",
    carrier="ups",
    tracking_number="1Z999AA10123456784",
)
client.shipments.list("order_id")

Digital Delivery

client.digital_delivery.confirm(
    "order_id",
    delivered_at="2026-01-15T10:30:00Z",
)

Temporal Elements

Manage trials, evaluations, subscriptions, warranties, and guarantees:

client.temporal.get("order_id")
client.temporal.extend("order_id", days=7, reason="Customer request")
client.temporal.adjust("order_id", expires_at="2026-03-01T00:00:00Z")
client.temporal.claim("order_id", reason="Product defective", description="...")
client.temporal.resolve_claim("order_id", resolution="approved")

Cancellations

client.cancellations.create("order_id", reason="Changed mind")
client.cancellations.get("order_id")

Webhooks

client.webhooks.list()
client.webhooks.create(
    url="https://example.com/webhooks/truetrial",
    events=["order.delivered", "trial.expired"],
)
client.webhooks.delete("webhook_id")

System

health = client.system.carrier_health()

Enums

All API enum values are available as Python StrEnum classes for type safety:

from truetrial import (
    OrderStatus,
    TemporalType,
    TemporalStatus,
    ShipmentStatus,
    ProductType,
    Carrier,
    DurationUnit,
    DeliverySource,
    WebhookEvent,
)

# Use in comparisons
if order.status == OrderStatus.Delivered:
    print("Order has been delivered")

# Use when creating resources
client.shipments.create(
    "order_id",
    carrier=Carrier.Ups,
    tracking_number="1Z...",
)

Error Handling

All API errors are raised as typed exceptions:

from truetrial import (
    TrueTrialError,
    AuthenticationError,
    ValidationError,
    NotFoundError,
    RateLimitError,
    ServerError,
)

try:
    order = client.orders.get("nonexistent_id")
except NotFoundError as e:
    print(f"Not found: {e}")
    print(f"Status code: {e.status_code}")  # 404
except ValidationError as e:
    print(f"Validation failed: {e}")
    print(f"Field errors: {e.errors}")  # {"field": ["error message"]}
except AuthenticationError:
    print("Check your API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except ServerError:
    print("TrueTrial API is having issues")
except TrueTrialError as e:
    print(f"Unexpected API error: {e} (HTTP {e.status_code})")

Webhook Verification

Verify incoming webhook signatures using HMAC SHA-256:

from truetrial import verify_webhook, parse_webhook
from truetrial.webhook import WebhookVerificationError

# Verify only (returns True or raises WebhookVerificationError)
try:
    verify_webhook(
        payload=request.body,
        signature=request.headers["X-TrueTrial-Signature"],
        secret="whsec_your_webhook_secret",
        tolerance=300,  # Optional: reject webhooks older than 5 minutes
        timestamp=request.headers["X-TrueTrial-Timestamp"],
    )
except WebhookVerificationError as e:
    print(f"Invalid webhook: {e}")

# Verify and parse in one step
try:
    event = parse_webhook(
        payload=request.body,
        signature=request.headers["X-TrueTrial-Signature"],
        secret="whsec_your_webhook_secret",
        tolerance=300,
        timestamp=request.headers["X-TrueTrial-Timestamp"],
    )
    print(f"Received event: {event['event']}")
    print(f"Event data: {event['data']}")
except WebhookVerificationError:
    return "Invalid signature", 403

Flask Example

from flask import Flask, request, jsonify
from truetrial import parse_webhook
from truetrial.webhook import WebhookVerificationError

app = Flask(__name__)

@app.route("/webhooks/truetrial", methods=["POST"])
def handle_webhook():
    try:
        event = parse_webhook(
            payload=request.get_data(),
            signature=request.headers.get("X-TrueTrial-Signature", ""),
            secret="whsec_your_webhook_secret",
            tolerance=300,
            timestamp=request.headers.get("X-TrueTrial-Timestamp", "0"),
        )
    except WebhookVerificationError:
        return jsonify({"error": "Invalid signature"}), 403

    if event["event"] == "order.delivered":
        handle_delivery(event["data"])
    elif event["event"] == "trial.expired":
        handle_trial_expiry(event["data"])

    return jsonify({"received": True}), 200

Development

Install development dependencies:

pip install -e ".[dev]"

Run tests:

pytest

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

truetrial-1.0.1.tar.gz (11.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

truetrial-1.0.1-py3-none-any.whl (18.1 kB view details)

Uploaded Python 3

File details

Details for the file truetrial-1.0.1.tar.gz.

File metadata

  • Download URL: truetrial-1.0.1.tar.gz
  • Upload date:
  • Size: 11.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for truetrial-1.0.1.tar.gz
Algorithm Hash digest
SHA256 8a9bdad933f2b3d6240bfb537a6115e9ca6890ba44ffcf80466cdfeaa223d287
MD5 719fe60f6ad50f3b7cbffd0e18d8754e
BLAKE2b-256 c3759fc9d4820d7a5d59d3f2f453a9f3a27c3b6a4e2e356aaaefc08763e034f4

See more details on using hashes here.

File details

Details for the file truetrial-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: truetrial-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 18.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for truetrial-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 138eb6a9a727689d5e78b162798cc10ca270715d11c5c72bb9a72666e4314664
MD5 c8a0d5a86f9e4b65e121351e92182f6e
BLAKE2b-256 74b4070c3d29a327863d867ee78de3f2187217373a3d9709427bb16ae4d04e57

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page