# Customers and sessions

Create and update Customers, issue Customer Tokens, and handle Guests and claims after login.

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

<a id="create"></a>

## Create or find a Customer

Use the verified user ID from your system as `externalUserId`. Calling again with the same ID returns the same Customer (`created: false`) and leaves its profile unchanged.

**TypeScript: customer.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" },
});

async function main() {
  const { customer, created } = await longplay.getOrCreateCustomer({
    externalUserId: "user-42",
  });
  console.log(customer.id, created);
}

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

**Python: customer.py**

```python
import os

from longplay import Longplay

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:
    result = client.get_or_create_customer(external_user_id="user-42")
    print(result["customer"]["id"], result["created"])
```

**Go: main.go**

```go
package main

import (
	"context"
	"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()

	result, err := client.GetOrCreateCustomer(context.Background(), longplay.CreateCustomerParams{
		ExternalUserID: longplay.Ptr("user-42"),
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Println(result.Customer.ID, result.Created)
}
```

<a id="update"></a>

## Update a Customer

Send only the fields to change. Generate and save a `requestId` per update; retrying with the same value never applies the change twice.

**TypeScript: customer.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 syncProfile(input: {
  verifiedUserId: string;
  requestId: string; // persisted before the first attempt
  plan: string;
}) {
  const { customer, changed } = await longplay.updateCustomer({
    lookup: { type: "externalUserId", value: input.verifiedUserId },
    requestId: input.requestId,
    patch: {
      attributes: { plan: input.plan },
      tagChanges: { add: ["beta"], remove: [] },
    },
  });
  return { customerId: customer.id, changed };
}
```

**Python: customer.py**

```python
import os

from longplay import Longplay

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:
    result = client.update_customer(
        request_id="<PERSISTED_REQUEST_UUID>",
        external_user_id="user-42",
        attributes={"plan": "pro"},
        add_tags=["beta"],
    )
    print(result["customer"]["id"], result["changed"], result["replayed"])
```

**Go: customer.go**

```go
package customers

import (
	"context"

	longplay "longplayai.com/sdk/go"
)

// SyncProfile reuses requestID (persisted before the first attempt) on every retry.
func SyncProfile(ctx context.Context, client *longplay.Client, verifiedUserID, requestID string) (bool, error) {
	result, err := client.UpdateCustomer(ctx, longplay.UpdateCustomerParams{
		Lookup:    longplay.LookupByExternalUserID(verifiedUserID),
		RequestID: requestID,
		Patch: longplay.UpdateCustomerParamsPatch{
			Attributes: longplay.Ptr(map[string]any{"plan": "pro"}),
			TagChanges: &longplay.UpdateCustomerParamsPatchTagChanges{Add: []string{"beta"}, Remove: []string{}},
		},
	})
	if err != nil {
		return false, err
	}
	return result.Changed, nil
}
```

<a id="sessions"></a>

## Call Longplay from the browser

- After your backend verifies the login, call `createCustomerSession` and return the complete session credential pair to that user.
- The browser calls `identify(session)`. The SDK uses the Access Token for business requests and the Refresh Token for automatic rotation.
- On sign-out or account switch, the browser calls `reset()` and your backend calls `revokeCustomerSessions`.

**Backend: server/session.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" },
});

// Call only after your own login check succeeds.
export async function issueCustomerSession(verifiedUserId: string) {
  const { customer } = await longplay.getOrCreateCustomer({
    externalUserId: verifiedUserId,
  });
  return longplay.createCustomerSession(customer.id);
}
```

**Browser: app/longplay.ts**

```ts
import { createLongplay, type CustomerSession } from "@tinkerlandai/longplay-sdk";

const longplay = createLongplay({
  baseUrl: "https://api.longplayai.com",
  scope: { projectId: "<APP_UUID>", environment: "sandbox" },
});

export async function signIn(session: CustomerSession) {
  longplay.identify(session);
  const { holdings } = await longplay.readHoldings();
  return holdings;
}

export function signOut() {
  longplay.reset();
}
```

- Register your website origin under Integrations → Website origins in Console.
- The issuing Key needs `sessions:create`. The token carries only these scopes, and only those the Key has: `entitlements:read`, `credits:read`, `billing:read`, `billing:write`, `offers:resolve`, `funnels:run`, `features:read`, `events:write`, `content:read`.
- The SDK shares concurrent refreshes before the Access Token expires and never replays an already-sent business write. Use `expiresAt` and `refreshExpiresAt`; both are bounded by the original session and issuing Key. After a definitive refresh refusal, verify the user's login again before issuing a new session.

<a id="guests"></a>

## Support signed-out users

Generate a guestToken for the visitor, keep it in an HttpOnly cookie and exchange it through `resumeGuestSession` for a complete credential pair. Pass that pair to the browser's `identify(session)`. After login, call `claimGuestCustomer` to bind the visitor to the account, then issue a regular Customer session.

**guest.ts**

```ts
import { createGuestToken, 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" },
});

// 1. First visit: create the guest token once and keep it in an HttpOnly cookie.
export async function startGuest(savedGuestToken?: string) {
  const guestToken = savedGuestToken ?? createGuestToken();
  await longplay.createGuestCustomer({ guestToken });
  const session = await longplay.resumeGuestSession({ guestToken });
  return { guestToken, session };
}

// 2. After your own login succeeds: bind the guest to the verified account.
export async function claimGuest(input: {
  guestToken: string;
  verifiedUserId: string;
  requestId: string;
}) {
  const { customer, switched } = await longplay.claimGuestCustomer({
    guestToken: input.guestToken,
    externalUserId: input.verifiedUserId,
    requestId: input.requestId,
  });
  const session = await longplay.createCustomerSession(customer.id);
  return { session, switched };
}
```

- A guest token can read standalone content, run Funnels, read Features and send events: it carries only the issuing Key's `content:read`, `funnels:run`, `features:read` and `events:write`. Checking access, buying and redeeming offers require the user to sign in first.
- The Key that issues guest tokens needs `sessions:create` plus at least one of those four scopes.
- Use the returned expiresAt for the Guest session; it cannot outlive the guestToken's expiry (`guestExpiresAt`).

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

## Related operations

- **Customers, Guests and Sessions (10)**:  [createCustomer](https://www.longplayai.com/docs/api/create-customer.md); [getCustomer](https://www.longplayai.com/docs/api/get-customer.md); [listCustomers](https://www.longplayai.com/docs/api/list-customers.md); [updateCustomer](https://www.longplayai.com/docs/api/update-customer.md); [createSession](https://www.longplayai.com/docs/api/create-session.md); [refreshSession](https://www.longplayai.com/docs/api/refresh-session.md); [revokeSessions](https://www.longplayai.com/docs/api/revoke-sessions.md); [createGuestCustomer](https://www.longplayai.com/docs/api/create-guest-customer.md); [resumeGuestSession](https://www.longplayai.com/docs/api/resume-guest-session.md); [claimGuestCustomer](https://www.longplayai.com/docs/api/claim-guest-customer.md)

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