> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kelviq.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> Documentation for the Kelviq Python SDK

## Overview

The Kelviq Python SDK provides a convenient way to interact with the Kelviq REST APIs from your Python application. The SDK supports both synchronous and asynchronous operations.

## Installation

To install the Kelviq SDK in your environment, run the following command:

```shell theme={null}
pip install kelviq-sdk
```

## Prerequisites

Before you can initialize the client and use the SDK methods, you need a **Server API Key**.

You can obtain this key from the Kelviq application:

1. Navigate to Settings.
2. Go to the [API keys](https://app.kelviq.com/settings/api-keys) section.
3. Copy the **Server API Key**.

> [!WARNING]
>
> **Security Warning:** The Server API Key should never be exposed in client-side code. Use it only in your backend services. For client-side applications, use the Client API Key with the [React SDK](https://docs.kelviq.com/frontend-integration/react-sdk.md) or [JavaScript SDK](https://docs.kelviq.com/frontend-integration/js-sdk.md).

Once copied, add this key to your environment variables (recommended for security):

```python theme={null}
import os

# Example of setting it in your code (environment variables recommended)
ACCESS_TOKEN = os.environ.get("KELVIQ_SERVER_API_KEY")
```

## Configuring the Client

The SDK supports both synchronous and asynchronous clients. The primary difference lies in how you create the client instance. Once created, both client types can invoke the same methods to communicate with the Kelviq application.

#### How to Create a Synchronous Client

Use the synchronous client for traditional, blocking I/O operations.

```python theme={null}
from kelviq_sdk import Kelviq

client = Kelviq.create_sync_client(access_token=ACCESS_TOKEN)
```

#### How to Create an Asynchronous Client

Use the asynchronous client for non-blocking I/O operations, suitable for applications using `asyncio`.

```python theme={null}
from kelviq_sdk import Kelviq

async_client = Kelviq.create_async_client(access_token=ACCESS_TOKEN)
```

## Caching and offline resilience

Entitlement caching is enabled by default for both synchronous and asynchronous clients. The SDK keeps a per-process in-memory cache with a 60-second freshness window. Reads use a fresh memory entry first, then an optional distributed cache, and then the Entitlement API.

If the API is unreachable or returns a server error, the SDK returns the last known cached entitlement response when one exists. If the customer or feature has never been cached, the original request error is raised.

```python theme={null}
client = Kelviq.create_sync_client(
    access_token=ACCESS_TOKEN,
    enable_cache=True,  # default: True
    cache_ttl=60.0,     # default: 60 seconds
)
```

Set `enable_cache=False` to disable caching.

To drop a customer's cached entitlements before the window expires, for example in a `subscription.paused`, `subscription.resumed`, or `subscription.cancelled` webhook handler:

```python theme={null}
client.entitlements.invalidate_cache(customerId=customer_id)
```

### Share the cache across workers

The in-memory cache and offline reporting queue belong to one process and disappear when it restarts. Use the optional Redis store when multiple workers, processes, or containers need one shared, durable cache and queue.

```shell theme={null}
pip install "kelviq-sdk[redis]"
```

```python theme={null}
from kelviq_sdk import Kelviq, RedisStore

store = RedisStore(
    url="redis://localhost:6379/0",
    prefix="kelviq:production",
)

client = Kelviq.create_sync_client(
    access_token=ACCESS_TOKEN,
    cache_store=store,
)
```

For an asynchronous client, use `AsyncRedisStore`. Use the same prefix for every worker that should share state.

### Replay queued usage

When a usage or event report fails because of a network problem, the SDK queues it and retries automatically on the next report call. You can also flush the queue explicitly:

```python theme={null}
remaining = client.reporting.flush()
# Async: remaining = await async_client.reporting.flush()
```

`remaining` is the number of reports still queued. Without Redis, the queue exists only in the current process.

See [When the Entitlement API is unavailable](https://docs.kelviq.com/product-catalog/entitlements.md#when-the-entitlement-api-is-unavailable) for access-control fallback guidance.

#### Enum Helpers

The SDK provides `ChargePeriod` and `CancellationType` enum classes to prevent typos when passing required string parameters:

```python theme={null}
from kelviq_sdk import ChargePeriod, CancellationType

# Use enums instead of raw strings
ChargePeriod.MONTHLY       # "MONTHLY"
CancellationType.IMMEDIATE # "IMMEDIATE"
```

## Supported Functionalities

The SDK currently supports the following operations:

1. [Customers](https://docs.kelviq.com/backend-integration/python-sdk.md#customers)

2. [Checkout](https://docs.kelviq.com/backend-integration/python-sdk.md#checkout)

3. [Entitlements](https://docs.kelviq.com/backend-integration/python-sdk.md#entitlements)

4. [Reporting](https://docs.kelviq.com/backend-integration/python-sdk.md#reporting)

5. [Subscriptions](https://docs.kelviq.com/backend-integration/python-sdk.md#subscriptions)

6. [Charges](https://docs.kelviq.com/backend-integration/python-sdk.md#charges)

7. [License](https://docs.kelviq.com/backend-integration/python-sdk.md#license)

8. [Portal](https://docs.kelviq.com/backend-integration/python-sdk.md#portal)

9. [Refunds](https://docs.kelviq.com/backend-integration/python-sdk.md#refunds)

10. [Payment Methods](https://docs.kelviq.com/backend-integration/python-sdk.md#payment-methods)

11. [Transactions](https://docs.kelviq.com/backend-integration/python-sdk.md#transactions)

***

## Customers

The `customers` module allows you to manage customer records within Kelviq. You can access these operations via the `customers` attribute on an initialized `Kelviq` client instance.

All methods are available in both synchronous and asynchronous versions, depending on how the `Kelviq` client was instantiated.

***

### Creates a new customer

**Synchronous**:

```python theme={null}
new_customer = client.customers.create(
    customerId="unique-customer-id-123",
    email="new.customer@example.com",
    name="John Doe",
    metadata={"source": "sdk_import", "priority": "high"}
)
print(f"Customer Created: ID = {new_customer.id}, Customer Client ID = {new_customer.customerId}")
```

**Asynchronous**:

```python theme={null}
new_customer = await async_client.customers.create(
    customerId="unique-customer-id-456",
    email="another.new.customer@example.com",
    name="Jane Roe"
)
print(f"Customer Created (Async): ID = {new_customer.id}, Customer Client ID = {new_customer.customerId}")
```

> [accordion] Response
>
> ```json theme={null}
> {
>   "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
>   "customerId": "unique-customer-id-123",
>   "name": "John Doe",
>   "email": "new.customer@example.com",
>   "details": {},
>   "metadata": {
>     "source": "sdk_import",
>     "priority": "high"
>   },
>   "createdOn": "2025-06-04T06:03:30.195790Z",
>   "modifiedOn": "2025-06-04T06:03:30.195831Z"
> }
> ```

**Required Parameters:**

* `customerId` (str): A unique identifier for the customer that you define. This ID will be used to reference the customer in subsequent API calls.
* `email` (str): The email address of the customer. Must be a valid email format.

**Optional Parameters:**

* `name` (str): The name of the customer.
* `metadata` (Dict\[str, str]): A dictionary of custom key-value pairs to store additional information about the customer.

**Returns:**
An instance of `CustomerResponse` (Pydantic model), representing the newly created customer record. Key attributes include:

* `id` (str): The server-generated unique UUID for the customer record.
* `customerId` (str): The client-provided customer identifier.
* `name` (str): The customer's name.
* `email` (str): The customer's email.
* `details` (\[Dict\[str, Any]]): Any server-added details about the customer (typically read-only).
* `metadata` (\[Dict\[str, str]]): The metadata associated with the customer.
* `createdOn` (string) : ISO 8601 timestamp of when the customer was created.
* `modifiedOn` (string) : ISO 8601 timestamp of when the customer was last modified.

### Updates an existing customer

This operation performs a partial update (PATCH), so you only need to provide the fields you want to change.

**Synchronous**:

```python theme={null}
    updated_customer = client.customers.update(
        customerId="unique-customer-id-123",
        name="Johnathan Doe",
        metadata={"source": "sdk_import", "priority": "very_high", "status": "active"}
    )
    print(f"Customer Updated: {updated_customer.name}")
```

**Asynchronous**:

```python theme={null}
    updated_customer = await async_client.customers.update(
        customerId="unique-customer-id-456",
        email="jane.roe.updated@example.com"
    )
    print(f"Customer Updated (Async): {updated_customer.email}")
```

> [accordion] Response
>
> ```json theme={null}
> {
>   "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
>   "customerId": "unique-customer-id-123",
>   "name": "Johnathan Doe",
>   "email": "new.customer@example.com",
>   "details": {},
>   "metadata": {
>     "source": "sdk_import",
>     "priority": "high",
>     "status": "active"
>   },
>   "createdOn": "2025-06-04T06:03:30.195790Z",
>   "modifiedOn": "2025-06-04T06:03:30.195831Z"
> }
> ```

**Parameters:**

**Required Parameters:**

* `customerId` (str): A unique identifier for the customer that you define. This ID will be used to reference the customer in subsequent API calls.

**Optional Parameters:**

* `email` (str): The email address of the customer. Must be a valid email format.
* `name` (str): The name of the customer.
* `metadata` (Dict\[str, str]): A dictionary of custom key-value pairs to store additional information about the customer.

**Returns:**
An instance of `CustomerResponse` (Pydantic model), representing the **updated** customer record. Key attributes include:

* `id` (str): The server-generated unique UUID for the customer record.
* `customerId` (str): The client-provided customer identifier.
* `name` (str): The customer's name.
* `email` (str): The customer's email.
* `details` (\[Dict\[str, Any]]): Any server-added details about the customer (typically read-only).
* `metadata` (\[Dict\[str, Any]]): The metadata associated with the customer.
* `createdOn` (string) : ISO 8601 timestamp of when the customer was created.
* `modifiedOn` (string) : ISO 8601 timestamp of when the customer was last modified.

***

## Checkout

The checkout module provides functionalities for creating and managing checkout sessions. You can access these operations via the checkout attribute on an initialized Kelviq client instance.

`create_session(...)`
This operation creates a new checkout session for a customer, allowing them to proceed with a purchase or subscription.

**Synchronous**:

```python theme={null}
response = client.checkout.create_session(
    planIdentifier="plan-pro-monthly",
    chargePeriod="MONTHLY",
    customerId="cust_789",  # Recommended, otherwise it will create a new customer
    successUrl="https://kelviq.com/checkout/success",
    trialPeriod=14,
)
print(f"Checkout Session URL: {response.checkoutUrl}")
```

**Asynchronous**:

```python theme={null}
response = await async_client.checkout.create_session(
    planIdentifier="plan-pro-monthly",
    chargePeriod="MONTHLY",
    customerId="cust_789",
    successUrl="https://kelviq.com/checkout/success",
    offeringId="96d3a293-34ac-48a5-b73d-976b15781afd",
    pricingTableId="6db2717a-4e43-4ae1-a293-6c0a775f6264",
    ruleId="f2ebc23f-3f79-4cf4-b17e-fe8e30a42ab2",
    features=[{'identifier':"seats", 'quantity': 5}],
    ipAddress="103.154.35.20",
)
print(f"Checkout Session URL: {response.checkoutUrl}")

```

> [accordion] Response
>
> ```json theme={null}
>  {
>       "checkoutUrl": "https://kelviq.com/checkout/cs_eeCGdGayc5oTMdGNV5XocfRk6o87K0vlwwCuKeiE7BLU9/",
>       "checkoutSessionId": "cs_eeCGdGayc5oTMdGNV5XocfRk6o87K0vlwwCuKeiE7BLU9"
>   }
> ```

**Required Parameters:**

* `planIdentifier` (str): The identifier of the specific plan the customer is checking out with. planIdentifier is mandatory.

* `successUrl` (str): The URL to which the user will be redirected after a successful checkout.

* `chargePeriod` (str | ChargePeriod): Required. The billing cycle for the subscription. You can use the `ChargePeriod` enum (e.g., `ChargePeriod.MONTHLY`) or a raw string. Must be one of:

  * `"ONE_TIME"` / `ChargePeriod.ONE_TIME`

  * `"MONTHLY"` / `ChargePeriod.MONTHLY`

  * `"YEARLY"` / `ChargePeriod.YEARLY`

  * `"WEEKLY"` / `ChargePeriod.WEEKLY`

  * `"DAILY"` / `ChargePeriod.DAILY`

  * `"TWENTY_EIGHT_DAYS"` / `ChargePeriod.TWENTY_EIGHT_DAYS`

  * `"THREE_MONTHS"` / `ChargePeriod.THREE_MONTHS`

  * `"SIX_MONTHS"` / `ChargePeriod.SIX_MONTHS`

**Optional Parameters:**

* `offeringId` (str): The ID (uuid) of the offering the customer is checking out with.

* `pricingTableId` (str): The id (uuid) of the pricingTable being used for this checkout. (Considered only if `offeringId` is not provided)

* `ruleId` (str): The id (uuid) of the pricing rule being applied. (Considered only if `offeringId` is not provided)

* `customerId` (str): The ID of the customer initiating the checkout. If you omit it, Kelviq creates a new customer.

* `features` (List\[Dict\[str, Union\[str, int]]]): Optional. A list of dictionaries, where each dictionary represents a feature and its desired quantity. Each dictionary **must** have two keys:
  * `"identifier"` (str): The unique identifier for the feature.
  * `"quantity"` (int): The desired quantity for this feature.
    * Example: `[{"identifier": "seats", "quantity": 10}, {"identifier": "api-calls-tier1", "quantity": 5000}]`

* `ipAddress` (str): The IP Address of the customer, used for location based pricing.

* `trialPeriod` (int): Number of trial days to apply. Must be greater than or equal to `1` and overrides the selected plan's configured trial period.

* `currencyCode` (str): The currency code for the checkout session (e.g. `"USD"`). Required when `customAmount` is provided.

* `customAmount` (float): A custom amount to charge for this checkout session. When provided, `taxBehavior` and `currencyCode` are also required.

* `taxBehavior` (str): Specifies how taxes are applied to the `customAmount`. Required when `customAmount` is provided. Must be one of:
  * `"INCLUSIVE"` — Tax is included in the custom amount.
  * `"EXCLUSIVE"` — Tax is added on top of the custom amount.

* `discountsEnabled` (bool): Whether the discount/coupon code field is shown on the checkout page. Defaults to `True`.

* `lockEmail` (bool): When `True`, the email field is pre-filled and locked so the customer cannot change it. Defaults to `False`.

* `defaultBillingCountry` (str): ISO 3166-1 alpha-2 country code (e.g. `"US"`, `"GB"`) used to pre-fill the billing address country on the checkout page.

* `metadata` (dict): Arbitrary key-value pairs to attach to the checkout session. The keys are preserved exactly as supplied and the object is returned unchanged on the `checkout.completed` webhook's `metadata` field. Example: `{"order_ref": "ABC-123", "source": "pricing_page"}`.

**Returns**:

An instance of CreateCheckoutSessionResponse (Pydantic model), which includes:

* `checkoutSessionId` (str): The unique ID for the created checkout session.

* `checkoutUrl` (str): The URL that the customer should be redirected to in order to complete the payment and activate the subscription/purchase.

***

## Entitlements

The entitlements module allows you to check and retrieve customer entitlements for various features. These operations target a specific edge API endpoint ( `https://edge.api.kelviq.com` by default) and use the GET HTTP method with query parameters.

### Checks if a specific customer has access to a particular feature.

This method directly returns a boolean indicating access status.

**Synchronous**:

```python theme={null}
has_feature_access = client.entitlements.has_access(
    customerId="cust_123",
    featureId="premium-reporting"
)
```

**Asynchronous**:

```python theme={null}
has_feature_access = await async_client.entitlements.has_access(
    customerId="cust_456",
    featureId="advanced-analytics"
)
```

> [accordion] Response
>
> ```shell theme={null}
>  True
> ```

**Required Parameters**:

* `customerId` (str): The unique identifier for the customer.

* `featureId` (str): The unique identifier for the feature whose access is being checked.

**Returns**:

* `bool`: True if the customer has access to the specified feature (considering feature type, limits, etc.), False otherwise or if the feature is not found in their entitlements.

### Retrieves the detailed entitlement information for a specific feature for a given customer.

**Synchronous**:

```python theme={null}
entitlement_response = client.entitlements.get_entitlement(
    customerId="cust_123",
    featureId="premium-reporting"
)
```

**Asynchronous**:

```python theme={null}
entitlement_response = await async_client.entitlements.get_entitlement(
    customerId="cust_456",
    featureId="advanced-analytics"
)
```

> [accordion] Response
>
> ```python theme={null}
> Entitlement(
>     featureId="advanced-analytics",
>     featureType="METER",
>     hasAccess=True,
>     hardLimit=False,
>     usageLimit=3,
>     currentUsage=0,
>     remaining=3,
>     items=[
>         EntitlementDetail(featureId="advanced-analytics", featureType="METER", hasAccess=True, resetAt="2025-05-22 08:27:45", hardLimit=False, usageLimit=3, currentUsage=0, remaining=3)
>     ]
> )
> ```

**Required Parameters**:

* `customerId` (str): The unique identifier for the customer.

* `featureId` (str): The unique identifier for the feature whose access is being checked.

**Returns**:

An `Entitlement` model (Pydantic), or `None` if the feature is not found. If the customer has multiple subscriptions, there can be multiple raw entries for the same featureId. The SDK aggregates these into a single model and keeps the raw entries accessible via the `items` attribute.

The aggregated `Entitlement` model includes:

* `featureId` (str): The feature ID.

* `featureType` (str): The type of the feature — `"METER"`, `"BOOLEAN"`, or `"CUSTOMIZABLE"`.

* `hasAccess` (bool): For **METER** features, computed as `remaining is None or remaining > 0`. For **BOOLEAN** and **CUSTOMIZABLE** features, `True` if any raw entry grants access.

* `hardLimit` (Optional\[bool]): For **METER**, `True` if any entry has a hard limit. For **BOOLEAN**, always `False`.

* `usageLimit` (Optional\[int]): For **METER**, summed across all items. For **CUSTOMIZABLE**, taken from the first item. For **BOOLEAN**, always `None`.

* `currentUsage` (Optional\[int]): For **METER**, summed across all items. For **CUSTOMIZABLE**, taken from the first item. For **BOOLEAN**, always `0`.

* `remaining` (Optional\[int]): For **METER**, computed as `usageLimit - currentUsage`. For **CUSTOMIZABLE**, taken from the first item. For **BOOLEAN**, always `None`.

* `items` (List\[EntitlementDetail]): The raw entitlement entries from the API. Each item retains its own `resetAt` value, since reset dates can differ across subscriptions.

### Retrieves all aggregated entitlements for a given customer.

**Synchronous**:

```python theme={null}
entitlements = client.entitlements.get_entitlements(
    customerId="cust_123"
)
# Access by feature ID
if "premium-reporting" in entitlements:
    ent = entitlements["premium-reporting"]
    print(f"hasAccess={ent.hasAccess}, items={len(ent.items)}")
```

**Asynchronous**:

```python theme={null}
entitlements = await async_client.entitlements.get_entitlements(
    customerId="cust_456"
)
for feature_id, ent in entitlements.items():
    print(f"{feature_id}: hasAccess={ent.hasAccess}, items={len(ent.items)}")
```

**Required Parameters**:

* `customerId` (str): The unique identifier for the customer.

**Returns**:

A `Dict[str, Entitlement]` keyed by `featureId`, where each value is an aggregated `Entitlement` model with an `.items` list containing the raw entries. See `get_entitlement` above for the full model structure.

### Retrieves the raw entitlement response for a specific feature (no aggregation).

**Synchronous**:

```python theme={null}
raw_response = client.entitlements.get_raw_entitlement(
    customerId="cust_123",
    featureId="premium-reporting"
)
print(f"Customer: {raw_response.customerId}")
for detail in raw_response.entitlements:
    print(f"  {detail.featureId}: {detail.hasAccess}")
```

**Asynchronous**:

```python theme={null}
raw_response = await async_client.entitlements.get_raw_entitlement(
    customerId="cust_456",
    featureId="advanced-analytics"
)
```

**Required Parameters**:

* `customerId` (str): The unique identifier for the customer.

* `featureId` (str): The unique identifier for the feature.

**Returns**:

An instance of `CheckEntitlementsResponse` (Pydantic model) containing the raw API response without aggregation:

* `customerId` (str): The customer's ID.

* `entitlements` (List\[EntitlementDetail]): The raw list of entitlement entries.

### Retrieves all raw entitlements for a given customer (no aggregation).

**Synchronous**:

```python theme={null}
raw_response = client.entitlements.get_raw_entitlements(
    customerId="cust_123"
)
```

**Asynchronous**:

```python theme={null}
raw_response = await async_client.entitlements.get_raw_entitlements(
    customerId="cust_456"
)
```

> [accordion] Response
>
> ```json theme={null}
>  {
>       "customerId": "cust_456",
>       "entitlements": [
>           {
>               "featureId": "advanced-analytics",
>               "featureType": "METER",
>               "hasAccess": true,
>               "resetAt": "2025-05-22 08:27:45",
>               "hardLimit": false,
>               "usageLimit": 3,
>               "currentUsage": 0,
>               "remaining": 3
>           }
>       ]
>   }
> ```

**Required Parameters**:

* `customerId` (str): The unique identifier for the customer.

**Returns**:

An instance of `CheckEntitlementsResponse` (Pydantic model) containing the raw API response without aggregation:

* `customerId` (str): The customer's ID.

* `entitlements` (List\[EntitlementDetail]): The raw list of entitlement entries. Each `EntitlementDetail` has fields like:

  * `featureId`: str

  * `hasAccess`: bool

  * `featureType`: str

  * `resetAt`: str

  * `hardLimit`: Optional\[bool]

  * `usageLimit`: Optional\[int]

  * `currentUsage`: Optional\[int]

  * `remaining`: Optional\[int]

***

## Reporting

### Reporting pre-aggregated usages for customer

This endpoint is used for reporting the pre-aggregated feature usage from your application (client-level) to the Kelviq application. It allows you to update the usage count for a specific feature associated with a customer.

**Synchronous**:

```python theme={null}
# Assuming 'client' is your synchronous Kelviq client
response = client.reporting.report_usage(
    value=150,
    customerId="customer_001",
    featureId="seats",
    behaviour="SET" # Or 'DELTA'
)
```

**Asynchronous**:

```python theme={null}
# Assuming 'async_client' is your asynchronous Kelviq client
response = await async_client.reporting.report_usage(
    value=75,
    customerId="customer_001",
    featureId="seats",
    behaviour="DELTA"
)
```

> [accordion] Response
>
> ```json theme={null}
>  {
>       "value": 150,
>       "customerId": "customer_001",
>       "featureId": "seats",
>       "behaviour": "SET",
>       "orgId": "1",
>       "eventName": "aggregated.usage",
>       "idempotencyKey": "597ee95063c744ed9bcc9b1cf5676a8a",
>       "timestamp": "2025-05-22 08:27:45.430732"
>   }
> ```

**Required Parameters**:

* `value` (int): The usage value being reported.

* `customerId` (str): The unique identifier for the customer associated with this usage.

* `featureId` (str): The unique identifier for the feature for which usage is being reported.

* `behaviour` parameter dictates how the usage is updated:

  * `SET`: This will replace the current usage value for the feature with the new `value` provided.

  * `DELTA`: This will increment the existing usage value for the feature by the amount specified in the `value` parameter

**Returns**:

An instance of ReportUsageResponse (Pydantic model), which includes:

* `value` (int): The usage value that was recorded.

* `customerId` (str): The customer ID associated with the usage.

* `featureId` (str): The feature Identifier for which usage was recorded.

* `behaviour` (str): The behaviour type ("SET" or "DELTA") that was processed.

* `orgId` (str): The organization ID associated with this record, as determined by the server.

* `eventName` (str): An internal event name generated by the server for this usage report (e.g., "aggregated.usage").

* `idempotencyKey` (str): A unique idempotency key generated by the server for this specific usage report instance.

* `timestamp` (str): The server-generated UTC timestamp (str format) indicating when the usage report was processed.

## Subscriptions

The subscriptions module allows you to list, retrieve, create, preview updates, update, and cancel customer subscriptions. You can access these operations via the `subscriptions` attribute on an initialized Kelviq client instance.

### List subscriptions

Retrieves a paginated list of subscriptions for a customer.

**Synchronous:**

```python theme={null}
page = client.subscriptions.list(
    customerId="cust_789",
    page=1,
    page_size=20,
)

for subscription in page.results:
    print(subscription.id, subscription.status)
```

**Asynchronous:**

```python theme={null}
page = await async_client.subscriptions.list(
    customerId="cust_789",
    page=1,
    page_size=20,
)

for subscription in page.results:
    print(subscription.id, subscription.status)
```

> [accordion] Response
>
> ```json theme={null}
> {
>   "count": 1,
>   "next": null,
>   "previous": null,
>   "results": [
>     {
>       "id": "09d706ca-58f3-4fb2-818f-5b8623d67e6e",
>       "startDate": "2025-07-28",
>       "endDate": null,
>       "status": "active",
>       "trialDaysRemaining": 0,
>       "customerId": "cust_789",
>       "billingType": "SUBSCRIPTION",
>       "files": [],
>       "links": [],
>       "license": []
>     }
>   ]
> }
> ```

**Required Parameters:**

* `customerId` (str): The client-defined identifier of the customer whose subscriptions will be returned.

**Optional Parameters:**

* `page` (int): Page number to retrieve.
* `page_size` (int): Number of subscriptions to return per page.
* `modifiedOnAfter` (str): Only return subscriptions modified on or after this ISO 8601 timestamp.
* `modifiedOnBefore` (str): Only return subscriptions modified on or before this ISO 8601 timestamp.

**Returns:**

A `PaginatedSubscriptionResponse` containing `count`, `next`, `previous`, and a `results` list of `SubscriptionData` models.

### Retrieve a subscription

Retrieves one subscription using its Kelviq subscription ID.

**Synchronous:**

```python theme={null}
subscription = client.subscriptions.retrieve(
    subscriptionId="09d706ca-58f3-4fb2-818f-5b8623d67e6e",
)

print(subscription.id, subscription.status)
for file in subscription.files:
    print(file.name, file.downloadUrl)
for link in subscription.links:
    print(link.name, link.url)
for license in subscription.license:
    print(license.licenseKey, license.activationLimit)
```

**Asynchronous:**

```python theme={null}
subscription = await async_client.subscriptions.retrieve(
    subscriptionId="09d706ca-58f3-4fb2-818f-5b8623d67e6e",
)

print(subscription.id, subscription.status)
```

> [accordion] Response
>
> ```json theme={null}
> {
>   "id": "09d706ca-58f3-4fb2-818f-5b8623d67e6e",
>   "externalSubscriptionId": "sub_1RpoZoSBstCzyocS7iPmith3",
>   "startDate": "2025-07-28",
>   "endDate": null,
>   "billingPeriodStartTime": "2025-07-28T10:46:34Z",
>   "billingPeriodEndTime": "2025-08-28T10:46:34Z",
>   "amount": "261.00",
>   "recurrence": "month",
>   "currency": "usd",
>   "status": "active",
>   "trialDaysRemaining": 0,
>   "customerId": "cust_789",
>   "billingType": "SUBSCRIPTION",
>   "recurrenceUnit": 1,
>   "recurrenceType": "MONTH",
>   "files": [],
>   "links": [],
>   "license": []
> }
> ```

**Required Parameters:**

* `subscriptionId` (str): The Kelviq UUID of the subscription.

**Returns:**

A `SubscriptionData` model. A missing subscription raises `NotFoundError`.

### Create a subscription

Creates a subscription directly for a customer without requiring a checkout session.

**Synchronous:**

```python theme={null}
from kelviq_sdk import ChargePeriod

subscription = client.subscriptions.create(
    planIdentifier="plan-pro-monthly",
    chargePeriod=ChargePeriod.MONTHLY,
    customerId="cust_789",
    successUrl="https://example.com/subscription/success",
    features=[{"identifier": "seats", "quantity": 5}],
    ipAddress="103.154.35.20",
)

print(subscription.id, subscription.status)
```

**Asynchronous:**

```python theme={null}
subscription = await async_client.subscriptions.create(
    planIdentifier="plan-pro-monthly",
    chargePeriod="MONTHLY",
    customerId="cust_789",
    successUrl="https://example.com/subscription/success",
    features=[{"identifier": "seats", "quantity": 5}],
    ipAddress="103.154.35.20",
)

print(subscription.id, subscription.status)
```

**Required Parameters:**

* `planIdentifier` (str): Identifier of the plan to subscribe to.
* `chargePeriod` (str | ChargePeriod): Billing period such as `MONTHLY`, `YEARLY`, `WEEKLY`, `DAILY`, or `TWENTY_EIGHT_DAYS`.
* `customerId` (str): Client-defined identifier of the customer.

**Optional Parameters:**

* `successUrl` (str): URL to redirect to after successful subscription creation.
* `features` (List\[Dict\[str, Any]]): Feature identifiers and requested quantities.
* `ipAddress` (str): Customer IP address used for location-based pricing.

**Returns:**

A `CreateSubscriptionResponse` model containing the created subscription, including its plan files, links, and issued licenses when available.

### Updates an existing subscription to a new plan

**Synchronous**:

```python theme={null}
from kelviq_sdk import ProrationBehavior

try:
    response = client.subscriptions.update(
        subscriptionId="78058918-9746-4280-9b9b-1bd5115eec6e",
        planIdentifier="premium-plan",
        chargePeriod="MONTHLY",
        prorationBehavior=ProrationBehavior.PRORATE_NEXT_INVOICE,
    )
    print(response.subscriptionId)
except Exception as e:
    print(f"Error updating subscription: {e}")
```

**Asynchronous**:

```python theme={null}
# Assuming 'async_client' is your asynchronous Kelviq client
try:
    response = await async_client.subscriptions.update(
        subscriptionId="78058918-9746-4280-9b9b-1bd5115eec6e",
        planIdentifier="new_plan_enterprise",
        chargePeriod="YEARLY",
        prorationBehavior=ProrationBehavior.PRORATE_NEXT_INVOICE,
        offeringId="offer_abc",
        pricingTableId="pw_def",
        ruleId="rule_ghi",
        ipAddress="103.154.35.20",
        features=[{'identifier': "seats", 'quantity': 10}],
        trialEnd="2027-12-31 23:59:59",  # or "now" to end the trial immediately
        paymentBehavior="activate_on_payment",
    )
    print(response.subscriptionId)
except Exception as e:
    print(f"Error updating subscription: {e}")
```

> [accordion] Response
>
> ```json theme={null}
>  {
>     "subscriptionId": "dffaf07e-4517-47db-ba3a-59a05aa2d465"
>  }
> ```

**Required Parameters**:

* `subscriptionId` (str): Required. The unique identifier of the subscription to be updated.
* `planIdentifier` (str): Required. The identifier of the new plan.
* `chargePeriod` (str | ChargePeriod): Required. The new charging period for the subscription. You can use the `ChargePeriod` enum (e.g., `ChargePeriod.MONTHLY`) or a raw string. Must be one of:
  * `"ONE_TIME"` / `ChargePeriod.ONE_TIME`
  * `"MONTHLY"` / `ChargePeriod.MONTHLY`
  * `"YEARLY"` / `ChargePeriod.YEARLY`
  * `"WEEKLY"` / `ChargePeriod.WEEKLY`
  * `"DAILY"` / `ChargePeriod.DAILY`
  * `"TWENTY_EIGHT_DAYS"` / `ChargePeriod.TWENTY_EIGHT_DAYS`
  * `"THREE_MONTHS"` / `ChargePeriod.THREE_MONTHS`
  * `"SIX_MONTHS"` / `ChargePeriod.SIX_MONTHS`

**Optional Parameters:**

* `offeringId` (str): Optional. The ID of the new offering, if applicable.
* `pricingTableId` (str): Optional. The ID of the new pricingTable, if applicable.
* `ruleId` (str): Optional. The ID of the new pricing rule, if applicable.
* `ipAddress` (str): The IP Address of the customer, used for location based pricing.
* `features` (\[List\[Dict\[str, Any]]]): Optional. A list of dictionaries, where each dictionary represents a feature and its desired quantity to update for the subscription. Each dictionary **must** have two keys:
  * `"identifier"` (str): The unique identifier for the feature.
  * `"quantity"` (int): The desired quantity for this feature.
    * Example: `[{'identifier': 'seats', 'quantity': 10}, {'identifier': 'projects', 'quantity': 5}]`
* `trialEnd` (str): Optional. Controls the trial period for the updated subscription. Accepts either:
  * The literal string `"now"` to end any active trial immediately.
  * An ISO 8601 datetime string (e.g. `"2027-12-31 23:59:59"`) to set a new trial end date. The datetime must be in the future. Naive datetimes are interpreted as UTC.
  * If omitted, the existing trial behavior on the subscription is preserved.
* `paymentBehavior` (`Literal["activate_on_payment"]`): Optional. Set to `"activate_on_payment"` to keep the current subscription active while payment is pending. The new plan and features are applied only after payment succeeds. If the pending update expires, the current subscription remains unchanged. Omit this field to use the default immediate-update behavior.
* `prorationBehavior` (`ProrationBehavior`): Controls how a mid-period change is billed. Use `ProrationBehavior.IMMEDIATE_CHARGE`, `ProrationBehavior.PRORATE_NEXT_INVOICE`, or `ProrationBehavior.NO_PRORATION`. When omitted, the organization's default is used.

**Returns**:

An instance of `UpdateSubscriptionResponse`, which includes:

* `subscriptionId` (str): UUID of the updated subscription.

### Preview a subscription update

Calculates the financial effect of an update without changing the subscription, creating an invoice, or charging the customer.

**Synchronous:**

```python theme={null}
from kelviq_sdk import ProrationBehavior

preview = client.subscriptions.preview_update(
    subscriptionId="78058918-9746-4280-9b9b-1bd5115eec6e",
    planIdentifier="premium-plan",
    chargePeriod="YEARLY",
    prorationBehavior=ProrationBehavior.PRORATE_NEXT_INVOICE,
    features=[{"identifier": "seats", "quantity": 10}],
)

print(preview.recurringAmount, preview.amountChargedImmediately)
print(preview.nextInvoice.lineItems if preview.nextInvoice else [])
```

**Asynchronous:**

```python theme={null}
preview = await async_client.subscriptions.preview_update(
    subscriptionId="78058918-9746-4280-9b9b-1bd5115eec6e",
    planIdentifier="premium-plan",
    chargePeriod="YEARLY",
    prorationBehavior=ProrationBehavior.NO_PRORATION,
)
```

Required parameters are `subscriptionId`, `planIdentifier`, and `chargePeriod`. Optional parameters are `prorationBehavior`, `features`, `ipAddress`, and `trialEnd`.

**Returns:** A `SubscriptionUpdatePreviewResponse` Pydantic model with recurring and immediate amounts in major and minor units, plus an optional next invoice and its line items.

### Cancel an active subscription for a customer.

**Synchronous**:

```python theme={null}
# Assuming 'client' is your synchronous Kelviq client
try:
    response = client.subscriptions.cancel(
        subscriptionId="78058918-9746-4280-9b9b-1bd5115eec6e",
        cancellationType="CURRENT_PERIOD_ENDS" # Or "IMMEDIATE", "SPECIFIC_DATE"
        # cancellationDate="2025-12-31" # Required if cancellationType is "SPECIFIC_DATE"
    )
    print(response.message)
except Exception as e:
    print(f"Error cancelling subscription: {e}")
```

**Asynchronous**:

```python theme={null}
# Assuming 'async_client' is your asynchronous Kelviq client
try:
    response = await async_client.subscriptions.cancel(
        subscriptionId="78058918-9746-4280-9b9b-1bd5115eec6e",
        cancellationType="IMMEDIATE"
    )
    print(response.message)
except Exception as e:
    print(f"Error cancelling subscription: {e}")
```

> [accordion] Response
>
> ```json theme={null}
>  {
>     "message": "Subscription cancellation processed successfully."
>  }
> ```

**Required Parameters**:

* `subscriptionId` (str): The unique identifier of the subscription to be cancelled.

* `cancellationType` (str | CancellationType): The type of cancellation to perform. You can use the `CancellationType` enum (e.g., `CancellationType.CURRENT_PERIOD_ENDS`) or a raw string. Must be one of:

  * `"IMMEDIATE"` / `CancellationType.IMMEDIATE`: The subscription is cancelled immediately.
  * `"CURRENT_PERIOD_ENDS"` / `CancellationType.CURRENT_PERIOD_ENDS`: The subscription will remain active until the end of the current billing period and then cancel.
  * `"SPECIFIC_DATE"` / `CancellationType.SPECIFIC_DATE`: The subscription will be cancelled on the specified `cancellationDate`.

* `cancellationDate` (str): The specific date for cancellation if `cancellationType` is `"SPECIFIC_DATE"`. Must be in `YYYY-MM-DD` format. This parameter is **required** if `cancellationType` is `"SPECIFIC_DATE"`.

**Returns**:

An instance of `CancelSubscriptionResponse`, which includes:

* `message` (str): A confirmation message indicating the result of the cancellation request.

***

## Charges

The synchronous and asynchronous `charges` clients immediately charge a customer's saved payment method for a one-time plan. Use sandbox mode when testing this operation.

**Synchronous:**

```python theme={null}
charge = client.charges.create(
    planIdentifier="lifetime-access",
    chargePeriod="ONE_TIME",
    customerId="cust_789",
    currencyCode="USD",
    customAmount=49.99,
    taxBehavior="INCLUSIVE",
    features=[{"identifier": "seats", "quantity": 5}],
)

print(charge.id, charge.status, charge.amount)
```

**Asynchronous:**

```python theme={null}
charge = await async_client.charges.create(
    planIdentifier="lifetime-access",
    chargePeriod="ONE_TIME",
    customerId="cust_789",
    currencyCode="USD",
    customAmount=49.99,
    taxBehavior="EXCLUSIVE",
)
```

`planIdentifier`, `chargePeriod="ONE_TIME"`, and `customerId` are required. `customAmount` must be positive and requires `currencyCode`. `taxBehavior` accepts `INCLUSIVE` or `EXCLUSIVE` and defaults to `EXCLUSIVE` on the API. Optional fields also include `features` and `ipAddress`.

**Returns:** A `CreateChargeResponse` Pydantic model containing the charge record, amount, currency, status, product, plan, features, and customer details.

***

## Refunds

The synchronous and asynchronous `refunds` clients let you list, create, and retrieve refunds for orders owned by your organization.

### List refunds

**Synchronous:**

```python theme={null}
page = client.refunds.list(
    status="SUCCEEDED",
    start_date="2026-07-01",
    page=1,
    page_size=10,
)
```

**Asynchronous:**

```python theme={null}
page = await async_client.refunds.list(status="SUCCEEDED", page=1, page_size=10)
```

> [accordion] Response
>
> ```json theme={null}
> {
>   "count": 1,
>   "next": null,
>   "previous": null,
>   "results": [
>     {
>       "id": "7c2f3a91-2d4e-4a8b-9b1c-6f0a2e5d9c11",
>       "reason": "REQUESTED_BY_CUSTOMER",
>       "amountUnits": 2500,
>       "amount": 25,
>       "internalNote": "Customer requested a partial refund.",
>       "failureReason": null,
>       "status": "SUCCEEDED",
>       "order": { "id": "ORD-20260715123000-A1B2C" }
>     }
>   ]
> }
> ```

**Optional Parameters:**

* `search` : Search by refund ID, order ID, customer name, email, or ID.
* `status` : Filter by refund status. One of `"PENDING"`, `"PROCESSING"`, `"SUCCEEDED"`, `"FAILED"`, `"CANCELED"`.
* `start_date` : Include refunds created on or after this date. Accepts a date (`YYYY-MM-DD`, treated as a UTC calendar day) or an ISO 8601 datetime with an offset (`2026-07-01T00:00:00+05:30`) for an exact instant.
* `end_date` : Include refunds created on or before this date. A date (`YYYY-MM-DD`) is inclusive of the whole UTC day; a datetime is an exclusive upper bound, so pass the next local midnight (`2026-07-02T00:00:00+05:30`) to get exactly one local day.
* `page` : Page number to return.
* `page_size` : Number of results per page. Defaults to 10, maximum 100.

**Returns:** A `RefundListResponse` Pydantic model with `count`, `next`, `previous`, and `results: List[RefundResponse]`.

### Create a refund

**Synchronous:**

```python theme={null}
refund = client.refunds.create(
    orderId="ORD-20260715123000-A1B2C",
    amountUnits=2500,
    reason="REQUESTED_BY_CUSTOMER",
    internalNote="Customer requested a partial refund.",
)
```

**Asynchronous:**

```python theme={null}
refund = await async_client.refunds.create(
    orderId="ORD-20260715123000-A1B2C",
    amountUnits=2500,
)
```

> [accordion] Response
>
> ```json theme={null}
> {
>   "id": "7c2f3a91-2d4e-4a8b-9b1c-6f0a2e5d9c11",
>   "reason": "REQUESTED_BY_CUSTOMER",
>   "amountUnits": 2500,
>   "amount": 25,
>   "internalNote": "Customer requested a partial refund.",
>   "failureReason": null,
>   "status": "SUCCEEDED",
>   "order": { "id": "ORD-20260715123000-A1B2C" }
> }
> ```

**Required Parameters:**

* `orderId` : The ID of an order owned by your organization.

**Optional Parameters:**

* `amountUnits` : Amount to refund in the currency's minor unit (e.g. cents for USD). Takes precedence over `amount` when both are provided.
* `amount` : Amount to refund in the currency's major unit (e.g. dollars for USD). Used only when `amountUnits` is omitted.
* `reason` : One of `"DUPLICATE"`, `"FRAUDULENT"`, `"REQUESTED_BY_CUSTOMER"`, `"OTHER"`. Defaults to `"REQUESTED_BY_CUSTOMER"`.
* `internalNote` : An internal note associated with the refund.

Omit both `amountUnits` and `amount` to refund the order's entire remaining refundable balance. The amount must be positive and cannot exceed the order's remaining refundable balance — the SDK raises `InvalidRequestError` if `orderId` is missing, and the API rejects invalid amounts.

**Returns:** A `RefundResponse` Pydantic model with `id`, `reason`, `amountUnits`, `amount`, `internalNote`, `failureReason`, `status`, and the complete serialized `order`.

### Retrieve a refund

**Synchronous:**

```python theme={null}
refund = client.refunds.retrieve("7c2f3a91-2d4e-4a8b-9b1c-6f0a2e5d9c11")
```

**Asynchronous:**

```python theme={null}
refund = await async_client.refunds.retrieve("7c2f3a91-2d4e-4a8b-9b1c-6f0a2e5d9c11")
```

**Required Parameters:**

* `refundId` : The UUID of the refund.

**Returns:** A `RefundResponse` Pydantic model, as above.

***

## Payment Methods

The synchronous and asynchronous `payment_methods` clients list saved payment methods for your organization.

### List payment methods

**Synchronous:**

```python theme={null}
page = client.payment_methods.list(customer_id="geo-jacob", page_size=10)
```

**Asynchronous:**

```python theme={null}
page = await async_client.payment_methods.list(customer_email="geojacob@example.com")
```

> [accordion] Response
>
> ```json theme={null}
> {
>   "count": 1,
>   "next": null,
>   "previous": null,
>   "results": [
>     {
>       "id": 482,
>       "customer": {
>         "customerId": "geo-jacob",
>         "name": "Geo Jacob",
>         "email": "geojacob@example.com",
>         "billingAddress": { "country": "US" }
>       },
>       "methodType": "card",
>       "methodData": {
>         "brand": "visa",
>         "last4": "4242",
>         "expMonth": 12,
>         "expYear": 2029,
>         "funding": "credit",
>         "country": "US"
>       },
>       "isDefault": true,
>       "status": "succeeded",
>       "createdOn": "2026-04-02T06:12:04.123456Z",
>       "modifiedOn": "2026-04-02T06:12:04.123456Z"
>     }
>   ]
> }
> ```

**Optional Parameters:**

* `customer_id` : Filter to payment methods belonging to the customer with this client-provided `customerId`.
* `customer_email` : Filter to payment methods belonging to the customer with this email address.
* `page` : Page number to return.
* `page_size` : Number of results per page. Defaults to 10, maximum 100.

Only payment methods with status `"succeeded"` are included in results.

**Returns:** A `PaymentMethodListResponse` Pydantic model with `count`, `next`, `previous`, and `results: List[PaymentMethodResponse]`. Each `methodData` dict is payment-provider-specific; for `card` it includes `brand`, `last4`, `expMonth`, `expYear`, `funding`, and `country`.

***

## Transactions

The synchronous and asynchronous `transactions` clients list financial transactions for your organization, ordered newest first.

### List transactions

**Synchronous:**

```python theme={null}
page = client.transactions.list(
    status="success",
    start_date="2026-07-01",
    page=1,
    page_size=25,
)

print(page.results[0].amountTotal, page.results[0].morFeeBreakdown)
```

**Asynchronous:**

```python theme={null}
page = await async_client.transactions.list(status="success")
```

> [accordion] Response
>
> ```json theme={null}
> {
>   "count": 1,
>   "next": null,
>   "previous": null,
>   "results": [
>     {
>       "id": "5b274952-0e54-48f6-aec6-e8a3f202b12e",
>       "order": { "id": "ORD-20260715123000-A1B2C" },
>       "createdOn": "2026-07-28T10:30:00Z",
>       "currency": "USD",
>       "currencySymbol": "$",
>       "amountTotal": 100,
>       "morFee": 4,
>       "morFeeBreakdown": [
>         { "name": "fixed_fee", "percentage": null, "valueUnits": 40, "currency": "USD" },
>         { "name": "base_fee", "percentage": "2.9", "valueUnits": 290, "currency": "USD" },
>         { "name": "subscription_fee", "percentage": "0.7", "valueUnits": 70, "currency": "USD" }
>       ],
>       "collectedTax": 0,
>       "netPayout": 96,
>       "status": "success",
>       "transactionType": "CHARGE",
>       "paymentMethodType": "card",
>       "availableOn": "2026-08-04",
>       "isSettled": false,
>       "paymentMethodName": "visa",
>       "last4": "4242"
>     }
>   ]
> }
> ```

**Optional Parameters:**

* `search` : Search by payment-provider IDs, customer name, email or ID, product name, or payment method type.
* `status` : Filter by transaction status. One of `"success"`, `"failure"`, `"pending"`.
* `start_date` : Include transactions created on or after this date. Accepts a date (`YYYY-MM-DD`, treated as a UTC calendar day) or an ISO 8601 datetime with an offset (`2026-07-01T00:00:00+05:30`) for an exact instant.
* `end_date` : Include transactions created on or before this date. A date (`YYYY-MM-DD`) is inclusive of the whole UTC day; a datetime is an exclusive upper bound, so pass the next local midnight (`2026-07-02T00:00:00+05:30`) to get exactly one local day.
* `page` : Page number to return.
* `page_size` : Number of results per page. Defaults to 10, maximum 100.

**Returns:** A `TransactionListResponse` Pydantic model with `count`, `next`, `previous`, and `results: List[TransactionResponse]`. Each transaction includes an itemized `morFeeBreakdown` (Merchant of Record fee components) when applicable — empty when no such fee applies.

***

## License

The `license` module allows you to activate, deactivate, and validate software licenses. You can access these operations via the `license` attribute on an initialized `Kelviq` client instance.

All methods are available in both synchronous and asynchronous versions, depending on how the `Kelviq` client was instantiated.

***

### Activate a license key

Creates a new license instance for a given license key, optionally associating it with a customer.

**Synchronous**:

```python theme={null}
response = client.license.activate(
    licenseKey="LIC-XXXX-YYYY-ZZZZ",
    customerId="cust_789",
    instanceName="My MacBook Pro",
    metadata={"os": "macOS", "arch": "arm64"}
)
print(f"Instance ID: {response.instanceId}")
print(f"License key: {response.license.licenseKey}")
```

**Asynchronous**:

```python theme={null}
response = await async_client.license.activate(
    licenseKey="LIC-XXXX-YYYY-ZZZZ",
    customerId="cust_789",
    instanceName="My MacBook Pro",
)
print(f"Instance ID: {response.instanceId}")
```

> [accordion] Response
>
> ```json theme={null}
> {
>   "instanceId": "8f3e2b1a-5c6d-4e9f-8a0b-1c2d3e4f5g6h",
>   "activatedAt": "2026-01-27T10:33:00Z",
>   "expiresOn": "2027-01-27T10:33:00Z",
>   "license": {
>     "id": "7be7a5b6-7a0e-4178-a085-8ef48f0649ab",
>     "licenseKey": "LIC-A8D5F89E-B46B-472C-9BED-66EE2545B85E",
>     "activatedOn": "2026-01-22T03:26:56Z",
>     "expiresOn": "2026-01-23T03:26:56Z",
>     "activationUsage": 1,
>     "activationLimit": 4,
>     "enabled": true,
>     "customer": {
>       "customerId": "cfa95cf8c8d24e8b9d3d2d1ada98a94d",
>       "name": "Geo",
>       "email": "geo@kelviq.com"
>     },
>     "plan": {
>       "identifier": "pro-yearly",
>       "name": "Pro Yearly",
>       "description": "Pro plan billed yearly",
>       "product": {
>         "id": "d970ab2d-834f-4c52-8742-2e6ed7e8a31f",
>         "identifier": "kelviq-engine",
>         "name": "Kelviq Engine",
>         "taxCode": "software",
>         "createdOn": "2025-01-01T00:00:00Z",
>         "modifiedOn": "2025-06-01T00:00:00Z"
>       },
>       "version": 1,
>       "isLatest": true
>     },
>     "subscription": {
>       "id": "09d706ca-58f3-4fb2-818f-5b8623d67e6e",
>       "recurrence": "1 month",
>       "billingPeriodStartTime": "2026-01-22T03:26:56Z",
>       "billingPeriodEndTime": "2026-02-22T03:26:56Z",
>       "startDate": "2026-01-22",
>       "endDate": null,
>       "status": "active",
>       "amount": "49.00",
>       "currency": "usd",
>       "trialDaysRemaining": 0,
>       "billingType": "SUBSCRIPTION",
>       "recurrenceUnit": 1,
>       "recurrenceType": "MONTH"
>     }
>   }
> }
> ```

**Required Parameters:**

* `licenseKey` (str): The license key string to activate.

**Optional Parameters:**

* `customerId` (str): The ID of the customer this instance is associated with.
* `instanceName` (str): A human-readable name for this instance (e.g. device name).
* `metadata` (Dict\[str, Any]): A dictionary of custom key-value pairs to attach to the instance.

**Returns:**

An instance of `LicenseActivateResponse` (Pydantic model), which includes:

* `instanceId` (str): The unique ID of the newly created license instance.
* `activatedAt` (str): ISO 8601 timestamp of when the instance was activated.
* `expiresOn` (Optional\[str]): ISO 8601 timestamp of when the instance expires, if applicable.
* `license` (`LicenseDetails`): The full license object. Key fields:
  * `id` (str): Server-generated UUID for the license.
  * `licenseKey` (str): The license key string.
  * `activatedOn` (Optional\[str]): ISO 8601 timestamp of when the license was first activated.
  * `expiresOn` (Optional\[str]): ISO 8601 timestamp of when the license expires.
  * `activationUsage` (int): Number of currently active instances.
  * `activationLimit` (int): Maximum number of allowed concurrent activations.
  * `enabled` (bool): Whether the license is active.
  * `customer` (Optional\[object]): The associated customer, if any. Fields: `customerId`, `name`, `email`.
  * `plan` (Optional\[object]): The plan associated with this license, if any. Fields: `identifier`, `name`, `description`, `version`, `isLatest`, and `product` (object with `id`, `identifier`, `name`, `taxCode`, `createdOn`, `modifiedOn`).
  * `subscription` (Optional\[object]): Subscription details, if any. Fields: `id`, `recurrence`, `billingPeriodStartTime`, `billingPeriodEndTime`, `startDate`, `endDate`, `status`, `amount`, `currency`, `trialDaysRemaining`, `billingType`, `recurrenceUnit`, `recurrenceType`.

***

### Deactivate a license instance

Deactivates a specific license instance by its instance ID.

**Synchronous**:

```python theme={null}
try:
    response = client.license.deactivate(
        licenseKey="LIC-XXXX-YYYY-ZZZZ",
        instanceId="8f3e2b1a-5c6d-4e9f-8a0b-1c2d3e4f5a6b"
    )
    print(response.message)
except Exception as e:
    print(f"Error deactivating license: {e}")
```

**Asynchronous**:

```python theme={null}
try:
    response = await async_client.license.deactivate(
        licenseKey="LIC-XXXX-YYYY-ZZZZ",
        instanceId="8f3e2b1a-5c6d-4e9f-8a0b-1c2d3e4f5a6b"
    )
    print(response.message)
except Exception as e:
    print(f"Error deactivating license: {e}")
```

> [accordion] Response
>
> ```json theme={null}
> {
>   "message": "License instance deactivated successfully.",
>   "deactivatedAt": "2026-01-27T10:35:00Z"
> }
> ```

**Required Parameters:**

* `licenseKey` (str): The license key string.
* `instanceId` (str): The unique ID of the instance to deactivate.

**Returns:**

An instance of `LicenseDeactivateResponse` (Pydantic model), which includes:

* `message` (str): Confirmation message.
* `deactivatedAt` (str): ISO 8601 timestamp of when the instance was deactivated.

***

### Validate a license key

Checks whether a license key (and optionally a specific instance) is valid.

**Synchronous**:

```python theme={null}
response = client.license.validate(
    licenseKey="LIC-XXXX-YYYY-ZZZZ",
    instanceId="8f3e2b1a-5c6d-4e9f-8a0b-1c2d3e4f5a6b"  # optional
)

if response.valid:
    print(f"License is valid: {response.code}")
else:
    print(f"License invalid: {response.detail}")
```

**Asynchronous**:

```python theme={null}
response = await async_client.license.validate(
    licenseKey="LIC-XXXX-YYYY-ZZZZ"
)
print(f"Valid: {response.valid}, Code: {response.code}")
```

> [accordion] Response
>
> ```json theme={null}
> {
>   "valid": true,
>   "code": "VALID",
>   "detail": "Instance ID valid for this license.",
>   "metadata": {
>     "os": "macOS",
>     "arch": "arm64"
>   },
>   "license": {
>     "id": "7be7a5b6-7a0e-4178-a085-8ef48f0649ab",
>     "licenseKey": "LIC-A8D5F89E-B46B-472C-9BED-66EE2545B85E",
>     "activatedOn": "2026-01-22T03:26:56Z",
>     "expiresOn": "2026-01-23T03:26:56Z",
>     "activationUsage": 1,
>     "activationLimit": 4,
>     "enabled": true,
>     "customer": {
>       "customerId": "cfa95cf8c8d24e8b9d3d2d1ada98a94d",
>       "name": "Geo",
>       "email": "geo@kelviq.com"
>     },
>     "plan": {
>       "identifier": "pro-yearly",
>       "name": "Pro Yearly",
>       "product": {
>         "id": "d970ab2d-834f-4c52-8742-2e6ed7e8a31f",
>         "identifier": "kelviq-engine",
>         "name": "Kelviq Engine",
>         "taxCode": "software"
>       }
>     },
>     "subscription": {
>       "id": "09d706ca-58f3-4fb2-818f-5b8623d67e6e",
>       "recurrence": "1 month",
>       "billingPeriodStartTime": "2026-01-22T03:26:56Z",
>       "billingPeriodEndTime": "2026-02-22T03:26:56Z",
>       "startDate": "2026-01-22",
>       "endDate": null,
>       "status": "active",
>       "amount": "49.00",
>       "currency": "usd",
>       "trialDaysRemaining": 0,
>       "billingType": "SUBSCRIPTION",
>       "recurrenceUnit": 1,
>       "recurrenceType": "MONTH"
>     }
>   }
> }
> ```

**Required Parameters:**

* `licenseKey` (str): The license key string to validate.

**Optional Parameters:**

* `instanceId` (str): If provided, also validates that this specific instance is active for the given license key.

**Returns:**

An instance of `LicenseValidateResponse` (Pydantic model), which includes:

* `valid` (bool): Whether the license (and instance, if provided) is valid.
* `code` (str): A short status code (e.g. `"VALID"`, `"INVALID"`, `"EXPIRED"`).
* `detail` (str): A human-readable description of the validation result.
* `metadata` (Optional\[Dict\[str, Any]]): Any metadata attached to the instance, if applicable.
* `license` (Optional\[`LicenseDetails`]): The full license object (same structure as in `activate`), or `None` if not found.

***

## Portal

The portal module allows you to create authenticated customer portal sessions. Once a session is created, you can redirect your customer directly to their self-serve customer portal without requiring them to log in manually. You can access these operations via the `portal` attribute on an initialized `Kelviq` client instance.

All methods are available in both synchronous and asynchronous versions, depending on how the `Kelviq` client was instantiated.

### Creates a new customer portal session

`create_session(...)`
This operation creates a new portal session for a customer. Combine the returned `customerPortalUrl` and `token` into a signed link (`{customerPortalUrl}?token={token}`) and redirect the customer there.

**Synchronous**:

```python theme={null}
session = client.portal.create_session(
    customerId="cust_789",
)
# Build the signed portal link — customerPortalUrl alone does not
# authenticate; the token must be appended as a query parameter.
portal_link = f"{session.customerPortalUrl}?token={session.token}"
print(f"Portal URL: {portal_link}")
```

**Asynchronous**:

```python theme={null}
session = await async_client.portal.create_session(
    customerId="cust_789",
)
portal_link = f"{session.customerPortalUrl}?token={session.token}"
print(f"Portal URL: {portal_link}")
```

> [accordion] Response
>
> ```json theme={null}
> {
>     "token": "cpt-4f7c5dc4-da9f-447b-d447-6266dc35ed6d:23fca530-adeb-4685-b3d5-9928c6d38275",
>     "email": "customer@example.com",
>     "customerPortalUrl": "https://www.kelviq.com/portal/aphelo/"
> }
> ```

**Required Parameters:**

* `customerId` (str): The unique identifier of the customer for whom the portal session is being created.

**Returns:**

An instance of `CreatePortalSessionResponse` (Pydantic model), which includes:

* `token` (str): The session token that authenticates the customer portal session.
* `email` (str): The email address of the customer.
* `customerPortalUrl` (str): The customer's billing portal base URL. **This URL alone does not authenticate the session** — append the `token` as a query parameter (`{customerPortalUrl}?token={token}`) to produce the signed link you share with the customer. The token expires, so create a fresh session per visit.

### Deep-linking to add a payment method

You can send a customer directly to the **add payment method** form and have them redirected back to your application when they're done. Append these query parameters to the signed portal link, targeting the `billing` page:

| Parameter | Required | Description |
| - | - | - |
| `intent` | Yes | Set to `add_payment_method` to auto-open the add payment method form. |
| `returnUrl` | No | URL-encoded `https` URL of your application. After the payment method is saved, the customer is redirected here with `?kelviq_setup=success` appended. `http` is only allowed for `localhost` during development. |
| `customerId` | No | Opens the form for this specific customer account. If omitted, the customer's first account is used. |

```python theme={null}
from urllib.parse import quote

session = client.portal.create_session(
    customerId="cust_789",
)

return_url = quote("https://your-app.com/billing/done", safe="")
add_payment_method_link = (
    f"{session.customerPortalUrl}billing"
    f"?token={session.token}"
    f"&intent=add_payment_method"
    f"&customerId=cust_789"
    f"&returnUrl={return_url}"
)
```

After the customer saves their payment method, the portal redirects them to `https://your-app.com/billing/done?kelviq_setup=success`.

***

## Webhooks

Kelviq can send real-time webhook notifications to your server when events occur in your account — for example, when a subscription is created or an invoice is paid.

### Verifying webhook signatures

Every webhook request includes three headers that you must use to verify the request is genuinely from Kelviq:

| Header | Description |
| - | - |
| `webhook-id` | Unique identifier for the event |
| `webhook-timestamp` | Unix timestamp of when the event was sent |
| `webhook-signature` | HMAC-SHA256 signature, prefixed with `v1,` |

Use the `validate_event` helper to verify the signature and parse the event in one step. It raises `WebhookVerificationError` if the signature is invalid.

```python theme={null}
from flask import Flask, request
from kelviq_sdk import validate_event, WebhookVerificationError

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    try:
        event = validate_event(
            payload=request.data,
            headers=request.headers,
            secret='<YOUR_WEBHOOK_SECRET>',
        )

        # Process the event
        print('Event type:', event.get('type'))

        return "", 202
    except WebhookVerificationError as e:
        return "", 403
```

> [!WARNING]
>
> Always pass the **raw** request body (e.g. `request.data` in Flask) to `validate_event`. Parsing the body as JSON before verification will break the signature check.

### Webhook event types

See [Webhook event types](https://docs.kelviq.com/guides/webhooks.md#event-types) for the complete list of supported events and their descriptions.

### Best practices

* **Return quickly** — respond with a `2xx` status before doing any heavy processing. Kelviq waits 10 seconds for a response. It retries up to 3 times at 60-second intervals on a timeout, connection failure, `5xx` or `429`; other non-`2xx` responses are not retried.
* **Use idempotency** — use the `webhook-id` header (or the event `id` field) to detect and skip duplicate deliveries.
* **Validate every request** — always verify the signature before trusting the payload.

***

## Using the Sandbox Environment

The SDK can connect to the Kelviq sandbox environment, which is perfect for **testing and development**. All operations performed in the sandbox are isolated and will not affect your live production data.

To use the sandbox, simply pass the argument `environment="sandbox"` when creating the client.

### How to Create a Synchronous Client (Sandbox)

```python theme={null}
from kelviq_sdk import Kelviq

# Note the 'environment' parameter
client = Kelviq.create_sync_client(
    access_token=ACCESS_TOKEN,
    environment="sandbox"
)
```

### Reading the environment from `KELVIQ_ENV`

`environment_from_env()` turns the `KELVIQ_ENV` convention shared with the Kelviq CLI and MCP server into the `environment` argument: `"sandbox"` when the variable is unset or empty, `"production"` or `"sandbox"` when it is set to one of those, and a `ValueError` naming any other value.

```python theme={null}
import os
from kelviq_sdk import Kelviq, environment_from_env

client = Kelviq.create_sync_client(
    access_token=os.environ["KELVIQ_SERVER_API_KEY"],
    environment=environment_from_env(),  # reads KELVIQ_ENV: sandbox when unset
)
```

`environment="production"` and `environment="prod"` mean the same thing.

> [!NOTE]
>
> The sandbox environment is completely separate from production. You will need to use a different set of API keys, and any data created (customers, subscriptions, etc.) will only exist in the sandbox.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.