# 客户与会话

创建与更新 Customer，签发 Customer Token，处理访客与登录后认领。

[网页版本](https://www.longplayai.com/zh-hans/docs/guides/customers)

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

## 创建或查找 Customer

用你系统里已验证的用户 ID 作为 `externalUserId`。同一个 ID 再次调用会返回同一个 Customer（`created: false`），已有资料不会被覆盖。

**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>

## 更新 Customer

只发送要修改的字段。每次更新生成一个 `requestId` 并保存；重试时使用同一个值，不会重复修改。

**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>

## 让浏览器直接调用

- 后端验证用户登录后，调用 `createCustomerSession`，把完整会话凭证对返回给该用户。
- 浏览器调用 `identify(session)`，SDK 使用 Access Token 请求业务接口，并使用 Refresh Token 自动换证。
- 退出或切换账号时，浏览器调用 `reset()`，后端调用 `revokeCustomerSessions`。

**后端: 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);
}
```

**浏览器: 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();
}
```

- 在 Console 的 接入 → 网站来源 中登记你的网站地址。
- 签发 Token 的 Key 需要 `sessions:create`。Token 只会带上该 Key 中的这些权限：`entitlements:read`、`credits:read`、`billing:read`、`billing:write`、`offers:resolve`、`funnels:run`、`features:read`、`events:write`、`content:read`。
- SDK 在 Access Token 即将到期时合并并发刷新，不会重放已发送的业务写请求。以 `expiresAt` 和 `refreshExpiresAt` 为准；两者受原会话和签发 Key 的有效期约束。刷新被明确拒绝后，重新验证用户登录再签发。

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

## 支持未登录用户

为访客生成 guestToken 并保存在 HttpOnly cookie 中，通过 `resumeGuestSession` 换取完整会话凭证对，传给浏览器的 `identify(session)`。用户登录后调用 `claimGuestCustomer` 绑定到其账号，再签发普通 Customer 会话。

**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 };
}
```

- 访客 Token 可以读取独立内容、运行 Funnel、读取 Feature 和上报事件：它只带签发 Key 中的 `funnels:run`、`features:read`、`events:write`、`content:read`。检查权益、购买和兑换优惠需要用户先登录。
- 签发访客 Token 的 Key 需要 `sessions:create`，以及上面四个权限中的至少一个。
- 访客会话以返回的 expiresAt 为准，且不晚于 guestToken 的到期时间（`guestExpiresAt`）。

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

## 相关接口

- **Customer、访客与会话 (10)**:  [createCustomer](https://www.longplayai.com/zh-hans/docs/api/create-customer.md); [getCustomer](https://www.longplayai.com/zh-hans/docs/api/get-customer.md); [listCustomers](https://www.longplayai.com/zh-hans/docs/api/list-customers.md); [updateCustomer](https://www.longplayai.com/zh-hans/docs/api/update-customer.md); [createSession](https://www.longplayai.com/zh-hans/docs/api/create-session.md); [refreshSession](https://www.longplayai.com/zh-hans/docs/api/refresh-session.md); [revokeSessions](https://www.longplayai.com/zh-hans/docs/api/revoke-sessions.md); [createGuestCustomer](https://www.longplayai.com/zh-hans/docs/api/create-guest-customer.md); [resumeGuestSession](https://www.longplayai.com/zh-hans/docs/api/resume-guest-session.md); [claimGuestCustomer](https://www.longplayai.com/zh-hans/docs/api/claim-guest-customer.md)

- [路径、凭据与权限见全部接口](https://www.longplayai.com/zh-hans/docs/api/operations.md#identity)
