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.0.tar.gz (11.5 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.0-py3-none-any.whl (17.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: truetrial-1.0.0.tar.gz
  • Upload date:
  • Size: 11.5 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.0.tar.gz
Algorithm Hash digest
SHA256 ba545d78549ad9cb96c108e7eb3d09b80a986e2b19f748cb59ad155face6f81a
MD5 18a43560150d1c06ee902eaec2b410da
BLAKE2b-256 76a1dd24427ce58811318c4de3ff69e8ea867c793f9055524b2ec2a7e325e51e

See more details on using hashes here.

File details

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

File metadata

  • Download URL: truetrial-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 17.9 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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f3444df4f6d6f3f3be980422f7e8d16c4f482acb3b2851152b099760088c1baa
MD5 e3e58b22fc5da325c1a755377854cfc4
BLAKE2b-256 2a2028681582b7fa58e1c29c5460ff89a5ac51027139d38fcf6bc7925feaf75b

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