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

# 应用接入快速开始

> 5 分钟完成 Profy 应用接入：创建应用、OAuth 授权、上报事件、完成扣费。

# 快速开始

本指南带你从零完成一个 Profy 应用的接入：创建应用 → 用户授权 → 上报计费事件。

## 前置条件

* 已注册 Profy 账号并通过创作者认证
* Node.js >= 18（用于运行示例）

## 第一步：创建应用

1. 进入 [Profy Studio](https://app.profy.cn/studio/works?tab=app)
2. 点击「创建应用」，输入应用名称
3. 创建成功后，记录 **App ID** 和 **App Secret**

<Warning>
  App Secret 仅在创建时完整展示。请妥善保管，不要提交到代码仓库。
</Warning>

## 第二步：配置回调地址

在应用管理页面 → 开发配置 → 回调地址，添加你的回调 URL。

* 生产环境必须使用 HTTPS
* 本地开发可使用 `http://localhost`

```
http://localhost:5180/callback
```

## 第三步：安装 SDK

<CodeGroup>
  ```bash npm theme={null}
  npm install @profy-ai/sdk
  ```

  ```bash bun theme={null}
  bun add @profy-ai/sdk
  ```

  ```bash Python theme={null}
  pip install profy-sdk
  # 含可选的 SQLAlchemy 自动建表支持：
  pip install profy-sdk[sqlalchemy]
  ```
</CodeGroup>

## 第四步：发起 OAuth 授权

将用户重定向到 Profy 授权页面：

```
https://app.profy.cn/oauth/authorize?client_id={APP_ID}&redirect_uri={CALLBACK_URL}&scope=events:write&response_type=code
```

| 参数              | 说明                        |
| --------------- | ------------------------- |
| `client_id`     | 你的 App ID                 |
| `redirect_uri`  | 与后台配置一致的回调地址              |
| `scope`         | 请求的权限，当前支持 `events:write` |
| `response_type` | 固定为 `code`                |

用户同意授权后，Profy 会将用户重定向到你的回调地址，并附带授权码：

```
http://localhost:5180/callback?code=abc123...
```

## 第五步：用授权码换取 Token

在你的后端服务中，使用 SDK 将授权码换成 Access Token：

```typescript theme={null}
import { ProfyApp } from "@profy-ai/sdk";

const profy = new ProfyApp({
  clientId: process.env.PROFY_APP_ID,
  clientSecret: process.env.PROFY_APP_SECRET,
});

// 用户授权后，回调地址收到 code
const token = await profy.exchangeCode(code, "http://localhost:5180/callback");

// token 包含：
// - accessToken:  JWT 格式，1 小时有效
// - refreshToken: 90 天有效，支持自动续期
// - expiresAt:    过期时间戳（毫秒）
```

<Warning>
  **永远不要在前端直接调用 `exchangeCode`。** App Secret 必须保存在后端，授权码交换只能在服务端完成。
</Warning>

## 第六步：上报计费事件

当用户在你的应用中触发了付费操作，调用 SDK 上报事件：

```typescript theme={null}
const result = await profy.reportEvent("generate_report", {
  token,
  metadata: { source: "web", userId: "user-123" },
});
```

SDK 会自动处理 Token 刷新——如果 Access Token 过期，会先用 Refresh Token 续期再重试。

## 完整示例

```typescript theme={null}
import { Hono } from "hono";
import { ProfyApp, type TokenData } from "@profy-ai/sdk";

const profy = new ProfyApp({
  clientId: process.env.PROFY_APP_ID!,
  clientSecret: process.env.PROFY_APP_SECRET!,
});

let tokenStore: TokenData | null = null;

const app = new Hono();

// 处理 OAuth 回调
app.post("/api/exchange", async (c) => {
  const { code } = await c.req.json();
  tokenStore = await profy.exchangeCode(code, "http://localhost:5180/callback");
  return c.json({ ok: true });
});

// 上报计费事件
app.post("/api/report", async (c) => {
  if (!tokenStore) return c.json({ error: "Not authenticated" }, 401);
  const result = await profy.reportEvent("generate_report", { token: tokenStore });
  return c.json(result);
});

export default app;
```

## 脚手架模板

我们提供了一个完整的前后端脚手架项目，包含 Vite 前端 + Hono 后端，开箱即用：

→ [profy-app-template](https://github.com/user/profy-app-template)

```bash theme={null}
git clone https://github.com/user/profy-app-template.git
cd profy-app-template
cp .env.example .env  # 填入 App ID 和 App Secret
npm install && npm run dev
```

## 流程图

```mermaid theme={null}
sequenceDiagram
    participant U as 用户
    participant A as 你的应用
    participant P as Profy

    U->>A: 点击「用 Profy 登录」
    A->>P: 重定向到 /oauth/authorize
    P->>U: 展示授权页面
    U->>P: 同意授权
    P->>A: 回调 ?code=xxx
    A->>P: POST /oauth/token（换取 Token）
    P-->>A: access_token + refresh_token
    U->>A: 触发付费操作
    A->>P: POST /openapi/v1/events（上报事件）
    P-->>A: 扣费成功
```

## 下一步

<CardGroup cols={3}>
  <Card title="SDK 完整指南" icon="book" href="/zh/documentation/sdk-guide">
    双语言 SDK 详细用法 + Token 持久化（Contrib）
  </Card>

  <Card title="API 参考" icon="code" href="/zh/api/post-token">
    查看完整的 OAuth 端点和 Events API 文档
  </Card>

  <Card title="计费事件配置" icon="credit-card" href="/zh/documentation/finance">
    了解如何在 Studio 中配置事件定价
  </Card>
</CardGroup>
