# Quickstart

Install the SDK, create a Customer, check access and report usage.

Last updated: 2026-11-06

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

<a id="before"></a>

## Before you begin

- Select an App for integration checks in the production Console (console.longplayai.com) and create a Sandbox Server Key with `customers:write`, `entitlements:read` and `credits:consume`. Sandbox data also belongs to production.
- A metered Feature created under Features in Console; copy its ID.
- A configured free default Product that includes the Feature, under Commerce → Catalog → Products in Console. New Customers receive it automatically.

**.env.local**

```bash
LONGPLAY_API_URL=https://api.longplayai.com
LONGPLAY_SERVER_KEY=<SERVER_KEY>
LONGPLAY_PROJECT_ID=<APP_UUID>
LONGPLAY_FEATURE_ID=<FEATURE_UUID>
```

Keep configuration in an ignored backend environment file. Give the free Product enough allowance for at least one check and consumption; never expose the Server Key in browser-public variables.

- [Create a Server Key](https://www.longplayai.com/docs/guides/server-auth.md)

<a id="install"></a>

## Install the SDK

**TypeScript: npm**

```bash
npm install --save-exact @tinkerlandai/longplay-sdk@latest
```

**Python: pip**

```bash
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
```

**Go: go**

```bash
SDK_VERSION="$(curl -fsS 'https://cdn.longplayai.com/sdk/longplay/stable?package=go')" &&
go get longplayai.com/sdk/go@v"$SDK_VERSION"
```

<a id="run"></a>

## Create a Customer, check access, report usage

Save the program below in your backend project and run it.

**TypeScript: quickstart.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: quickstart.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)
}
```

**terminal**

```bash
node --env-file=.env.local --experimental-strip-types quickstart.ts
```

The command requires Node.js 22.6+. For Python/Go, load the same environment variables using your project's environment loader, then run python quickstart.py / go run . Use authenticated user IDs in the real application.

<a id="result"></a>

## Check the result

Success prints `recorded: true`. Running it again returns the same Customer and records another usage.

Also check the Customer ID, App/Sandbox response scope, check.allowed and usage receipt. The example generates a new usage ID on every run; persist and reuse the original idempotency key when recovering the same business action instead of rerunning it as a new debit.

**Troubleshooting**

| Symptom | Fix |
| --- | --- |
| `blocked: insufficient_balance` | The Customer has no available balance for this Feature. Check the default Product's configuration, that it includes the Feature, and that it was assigned to this Customer. Default Products are not reassigned when an existing Customer signs in again. |
| 401 `UNAUTHENTICATED` | The Key is incomplete, expired or revoked. |
| 403 `FORBIDDEN` | The Key lacks a scope listed above. |
| 403 `SCOPE_MISMATCH` | `LONGPLAY_PROJECT_ID` or `environment` does not match the Key's App and environment. |
| An error before any request is sent | The SDK validates input locally: for example, when `LONGPLAY_FEATURE_ID` is not a UUID, TypeScript throws a validation error (ZodError) and Python and Go raise a local `INVALID_REQUEST` with no HTTP status. |

<a id="next"></a>

## Next steps

- [Call Longplay from the browser](https://www.longplayai.com/docs/guides/customers.md#sessions)
- [Payments, subscriptions and billing](https://www.longplayai.com/docs/guides/commerce.md)
- [Notifications and webhooks](https://www.longplayai.com/docs/guides/notifications.md)
