# Entitlements, balances and usage

Check access, report usage, manage balances and Entities, and bill AI calls.

Last updated: 2026-11-06

[Web version](https://www.longplayai.com/docs/guides/entitlements)

<a id="check"></a>

## Check access and report usage

Call `checkEntitlement` before running a feature and `trackUsage` after it succeeds. Quantities are decimal strings.

**TypeScript: usage.ts**

```ts
import { createLongplayServer } from "@tinkerlandai/longplay-sdk/server";

const longplay = createLongplayServer({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
});
const featureId = process.env.LONGPLAY_FEATURE_ID!;

async function main() {
  // 1. Find or create the Customer for your signed-in user.
  const { customer } = await longplay.getOrCreateCustomer({ externalUserId: "user-42" });

  // 2. Check access before doing the work.
  const { check } = await longplay.checkEntitlement({
    customerId: customer.id,
    requirement: { internal_feature_id: featureId, quantity: "1", properties: {} },
  });
  if (!check.allowed) return console.log("blocked:", check.reason);

  // 3. Report usage after the work succeeds. Use your own event ID in production.
  const { receipts } = await longplay.trackUsage({
    customerId: customer.id,
    command: { internal_feature_id: featureId, quantity: "1", idempotencyKey: crypto.randomUUID() },
  });
  console.log("recorded:", receipts[0]?.accepted);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
```

**Python: usage.py**

```python
import os
import uuid

from longplay import Longplay

feature_id = os.environ["LONGPLAY_FEATURE_ID"]

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:
    # 1. Find or create the Customer for your signed-in user.
    customer_id = client.get_or_create_customer(external_user_id="user-42")["customer"]["id"]

    # 2. Check access before doing the work.
    check = client.check_entitlement(
        customer_id=customer_id, internal_feature_id=feature_id, quantity="1"
    )["check"]
    if not check["allowed"]:
        print("blocked:", check["reason"])
    else:
        # 3. Report usage after the work succeeds. Use your own event ID in production.
        usage = client.track_usage(
            customer_id=customer_id,
            internal_feature_id=feature_id,
            quantity="1",
            idempotency_key=str(uuid.uuid4()),
        )
        print("recorded:", usage["receipts"][0]["accepted"])
```

**Go: main.go**

```go
package main

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"log"
	"os"

	longplay "longplayai.com/sdk/go"
)

func main() {
	client, err := longplay.NewClient(longplay.Config{
		APIKey:      os.Getenv("LONGPLAY_SERVER_KEY"),
		ProjectID:   os.Getenv("LONGPLAY_PROJECT_ID"),
		Environment: longplay.Sandbox,
		BaseURL:     os.Getenv("LONGPLAY_API_URL"),
	})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()
	ctx := context.Background()
	featureID := os.Getenv("LONGPLAY_FEATURE_ID")

	// 1. Find or create the Customer for your signed-in user.
	customer, err := client.GetOrCreateCustomer(ctx, longplay.CreateCustomerParams{
		ExternalUserID: longplay.Ptr("user-42"),
	})
	if err != nil {
		log.Fatal(err)
	}

	// 2. Check access before doing the work.
	access, err := client.CheckEntitlement(ctx, longplay.CheckEntitlementParams{
		CustomerID: customer.Customer.ID,
		Requirement: longplay.CheckEntitlementParamsRequirement{
			InternalFeatureID: featureID,
			Quantity:          "1",
			Properties:        map[string]any{},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	if !access.Check.Allowed {
		log.Println("blocked")
		return
	}

	// 3. Report usage after the work succeeds. Use your own event ID in production.
	key := make([]byte, 16)
	if _, err := rand.Read(key); err != nil {
		log.Fatal(err)
	}
	usage, err := client.TrackUsage(ctx, longplay.TrackUsageParams{
		CustomerID: customer.Customer.ID,
		Command: longplay.TrackUsageParamsCommand{
			InternalFeatureID: longplay.Ptr(featureID),
			Quantity:          longplay.Ptr("1"),
			IdempotencyKey:    hex.EncodeToString(key),
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Println("recorded:", usage.Receipts[0].Accepted)
}
```

- Generate and save an `idempotencyKey` per usage; retrying an unknown result with the same key never bills twice.
- HTTP 200 does not mean usage was accepted: check each receipt's `accepted` and `reason`.

- [Product overview: usage-based billing](https://www.longplayai.com/usage-based-billing)

<a id="reserve"></a>

## Reserve, then confirm

For long-running work, reserve balance first, confirm the actual quantity when it finishes, or release it on failure.

**reserve.ts**

```ts
import { createLongplayServer } from "@tinkerlandai/longplay-sdk/server";

const longplay = createLongplayServer({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
});

const feature = process.env.LONGPLAY_FEATURE_ID!;

// Hold credits before long-running work; keys are persisted per job.
export async function runJob(customerId: string, jobId: string, estimate: string) {
  const { receipt } = await longplay.mutateBalance({
    customerId,
    command: {
      operation: "reserve",
      internal_feature_id: feature,
      quantity: estimate,
      properties: {},
      idempotencyKey: `${jobId}:reserve`,
      expiresInSeconds: 600,
    },
  });
  if (!receipt.accepted) return { started: false as const, reason: receipt.reason };
  return { started: true as const, reservationId: receipt.id };
}

export async function finishJob(customerId: string, jobId: string, reservationId: string, actual: string | null) {
  const command = actual
    ? { operation: "confirm" as const, operationId: reservationId, quantity: actual, idempotencyKey: `${jobId}:confirm` }
    : { operation: "release" as const, operationId: reservationId, idempotencyKey: `${jobId}:release` };
  const { receipt } = await longplay.mutateBalance({ customerId, command });
  return receipt;
}
```

<a id="balances"></a>

## Read balances and the ledger

**balances.ts**

```ts
import { createLongplayServer } from "@tinkerlandai/longplay-sdk/server";

const longplay = createLongplayServer({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
});

export async function readBalances(customerId: string) {
  const { holdings } = await longplay.readHoldings({ customerId });
  const { ledger } = await longplay.readLedger({
    customerId,
    query: { type: null, from: null, to: null, after: null, limit: 20 },
  });
  return { holdings, ledger };
}
```

**Balance management**

| Task | Methods |
| --- | --- |
| Create or revoke balance grants | `manageBalanceGrant`, `listBalanceGrants` |
| Correct one balance | `adjustBalance`, `readBalanceSource` |
| Set usage | `setUsage`, `readUsage` |
| Report usage in bulk | `submitUsageBatch`, `readUsageBatch` |
| Statements and analytics | `readCreditStatement`, `readUsageAnalytics`, `readCreditAnalytics` |
| Meter per workspace or device | `manageUsageEntity` |
| Assign seats | `readSeats`, `manageSeat` |

<a id="ai"></a>

## Bill AI calls

Pass the middleware to the AI SDK's `wrapLanguageModel`; each call is billed by actual token usage.

**ai-billing.ts**

```ts
import {
  createAiUsageMiddleware,
  createConfiguredAiPricing,
  createLongplayServer,
  type AiUsageRecord,
} from "@tinkerlandai/longplay-sdk/server";

const longplay = createLongplayServer({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
});

// Your own durable store for usage records and frozen quotes.
declare function saveUsageRecord(record: AiUsageRecord): Promise<void>;

export async function billingMiddleware(customerId: string, callId: string) {
  const featureId = process.env.LONGPLAY_AI_FEATURE_ID!;
  const pricing = await createConfiguredAiPricing(longplay, {
    internal_feature_id: featureId,
    customerId,
  });
  return createAiUsageMiddleware({
    pricing,
    client: longplay,
    modelId: "openai/gpt-4o",
    reasoning: "output",
    context: () => ({ customerId, internal_feature_id: featureId, idempotencyKey: callId }),
    persist: saveUsageRecord,
  });
}
// Pass the result to wrapLanguageModel({ model, middleware }) from the AI SDK.
```

- Use a new `idempotencyKey` per model call and store records in `persist` to recover after failures.
- Write `modelId` as `provider/model`; your backend needs access to https://models.dev for model prices.

<a id="operations"></a>

## Related operations

- **Entitlements and product presentation (4)**:  [checkEntitlement](https://www.longplayai.com/docs/api/check-entitlement.md); [resolveOffering](https://www.longplayai.com/docs/api/resolve-offering.md); [resolvePaywall](https://www.longplayai.com/docs/api/resolve-paywall.md); [readHoldings](https://www.longplayai.com/docs/api/read-holdings.md)
- **Balances, usage and ledger (16)**:  [readBalanceSource](https://www.longplayai.com/docs/api/read-balance-source.md); [adjustBalance](https://www.longplayai.com/docs/api/adjust-balance.md); [readUsage](https://www.longplayai.com/docs/api/read-usage.md); [setUsage](https://www.longplayai.com/docs/api/set-usage.md); [manageBalanceGrant](https://www.longplayai.com/docs/api/manage-balance-grant.md); [listBalanceGrants](https://www.longplayai.com/docs/api/list-balance-grants.md); [manageUsageEntity](https://www.longplayai.com/docs/api/manage-usage-entity.md); [readUsageAnalytics](https://www.longplayai.com/docs/api/read-usage-analytics.md); [readCreditAnalytics](https://www.longplayai.com/docs/api/read-credit-analytics.md); [submitUsageBatch](https://www.longplayai.com/docs/api/submit-usage-batch.md); [readUsageBatch](https://www.longplayai.com/docs/api/read-usage-batch.md); [readLedger](https://www.longplayai.com/docs/api/read-ledger.md); [readCreditStatement](https://www.longplayai.com/docs/api/read-credit-statement.md); [quoteBalance](https://www.longplayai.com/docs/api/quote-balance.md); [trackUsage](https://www.longplayai.com/docs/api/track-usage.md); [mutateBalance](https://www.longplayai.com/docs/api/mutate-balance.md)
- **Seats (2)**:  [readSeats](https://www.longplayai.com/docs/api/read-seats.md); [manageSeat](https://www.longplayai.com/docs/api/manage-seat.md)
- **AI pricing (1)**:  [readAiPricing](https://www.longplayai.com/docs/api/read-ai-pricing.md)

- [Paths, credentials and scopes in All operations](https://www.longplayai.com/docs/api/operations.md#access)
