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

# SDKs

> 客户端库和框架集成

## SDKs 和库

Waffo Pancake 提供 TypeScript 和 Next.js 官方 SDK，以及直接 API 访问。

### 选择你的集成方式

<CardGroup cols={3}>
  <Card title="Next.js SDK" icon="react">
    **最快** — 开箱即用的组件、Hooks 和 Server Actions。内置收银台 UI、Webhook 路由和买家自助服务。

    `npm install @waffo/pancake-nextjs`
  </Card>

  <Card title="TypeScript SDK" icon="code">
    **灵活** — 完整 API 覆盖，自动签名、类型化响应和 Webhook 验证。适用于任何 Node.js 框架。

    `npm install @waffo/pancake-ts`
  </Card>

  <Card title="直接 API" icon="terminal">
    **完全控制** — REST 端点用于写操作，GraphQL 用于读操作。自行实现签名和验证。任何语言。
  </Card>
</CardGroup>

<Tip>
  **Next.js 项目**：从 `@waffo/pancake-nextjs` 开始 — 它封装了 `@waffo/pancake-ts` 并添加了 React 组件和 Server Actions。如需高级用例，可随时降级到 TypeScript SDK 或原始 API。
</Tip>

***

## TypeScript SDK

<Card title="@waffo/pancake-ts" icon="npm" href="https://www.npmjs.com/package/@waffo/pancake-ts">
  npm 上的官方 TypeScript SDK
</Card>

### 安装

```bash theme={"system"}
npm install @waffo/pancake-ts
```

### 特性

* 零运行时依赖，ESM + CJS，Node >= 20
* 自动请求签名和确定性幂等键
* 完整的 TypeScript 类型定义（15 个枚举，40+ 接口）
* 内置公钥的 Webhook 签名验证（测试/生产）

### 快速开始

```typescript theme={"system"}
import { WaffoPancake } from "@waffo/pancake-ts";

const client = new WaffoPancake({
  merchantId: process.env.WAFFO_MERCHANT_ID!,
  privateKey: process.env.WAFFO_PRIVATE_KEY!,
});

// 创建商店
const { store } = await client.stores.create({ name: "My Store" });

// 创建一次性商品
const { product } = await client.onetimeProducts.create({
  storeId: store.id,
  name: "E-Book: TypeScript Handbook",
  prices: {
    USD: { amount: "29.00", taxIncluded: false, taxCategory: "digital_goods" },
  },
});

// 创建收银台会话
const session = await client.checkout.createSession({
  productId: product.id,
  currency: "USD",
});
// => 将消费者重定向到 session.checkoutUrl
```

### 配置

| 参数           | 类型             | 必填 | 说明                               |
| ------------ | -------------- | -- | -------------------------------- |
| `merchantId` | `string`       | 是  | 您的商户 ID                          |
| `privateKey` | `string`       | 是  | RSA 私钥（PEM、base64 或原始格式 — 自动标准化） |
| `baseUrl`    | `string`       | 否  | API 基础 URL（默认：生产环境）              |
| `fetch`      | `typeof fetch` | 否  | 自定义 fetch 实现                     |

### 可用资源

| 命名空间                               | 方法                                                 | 说明             |
| ---------------------------------- | -------------------------------------------------- | -------------- |
| `client.stores`                    | `create()` `update()` `delete()`                   | 商店管理           |
| `client.onetimeProducts`           | `create()` `update()` `publish()` `updateStatus()` | 一次性商品 CRUD     |
| `client.subscriptionProducts`      | `create()` `update()` `publish()` `updateStatus()` | 订阅商品 CRUD      |
| `client.subscriptionProductGroups` | `create()` `update()` `delete()` `publish()`       | 商品分组（共享试用）     |
| `client.orders`                    | `cancelSubscription()`                             | 订单管理           |
| `client.checkout`                  | `createSession()`                                  | 创建收银台会话        |
| `client.graphql`                   | `query<T>()`                                       | 类型化 GraphQL 查询 |
| `client.auth`                      | `issueSessionToken()`                              | 为收银台签发买家会话令牌   |
| `client.webhooks`                  | `verify()`                                         | Webhook 签名验证   |

### 收银台模式

SDK 支持两种收银台模式，取决于你是否知道买家身份：

| 模式      | 方法                                | 买家身份 | 表单  | 使用场景      |
| ------- | --------------------------------- | ---- | --- | --------- |
| **认证式** | `checkout.authenticated.create()` | 商户提供 | 预填写 | 有用户账号的站点  |
| **匿名**  | `checkout.anonymous.create()`     | 不提供  | 空白  | 模板商店、分享链接 |

<Warning>
  **当你知道买家身份时，请务必使用认证式收银台。** 认证式收银台将订单绑定到你提供的 `buyerIdentity` — 一个稳定的、商户控制的标识符。没有它：

  * **试用滥用**：买家可以通过更换邮箱地址无限领取免费试用
  * **订单断链**：不同邮箱被视为不同用户
  * **无自助服务**：买家无法在客户门户中管理订单
</Warning>

#### 认证式收银台（推荐）

```typescript theme={"system"}
const result = await client.checkout.authenticated.create({
  productId: "PROD_xxx",
  currency: "USD",
  buyerIdentity: "userIdInYourSystem",
});
// Redirect: res.redirect(result.checkoutUrl) or window.location.href = result.checkoutUrl
```

<Note>
  `buyerIdentity` 仅用于订单归属和试用追踪，不会渲染到收银台页面。如需预填收银台邮箱输入框，请显式传 `buyerEmail`。
</Note>

支持动态定价和试用控制：

```typescript theme={"system"}
const result = await client.checkout.authenticated.create({
  productId: "PROD_xxx",
  currency: "USD",
  buyerIdentity: "userIdInYourSystem",
  buyerEmail: "customer@example.com",
  priceSnapshot: { amount: "19.99", taxCategory: "digital_goods" },
  withTrial: true,
  billingDetail: { country: "US", isBusiness: false },
  successUrl: "https://example.com/thank-you",
});
```

#### 匿名收银台

```typescript theme={"system"}
const result = await client.checkout.anonymous.create({
  productId: "PROD_xxx",
  currency: "USD",
});
// Also supports priceSnapshot and withTrial
```

### Webhook 验证

```typescript theme={"system"}
import { verifyWebhook, WebhookEventType } from "@waffo/pancake-ts";

// Express（使用原始 body — 解析后的 JSON 会破坏签名验证）
app.post("/webhooks", express.raw({ type: "application/json" }), (req, res) => {
  try {
    const event = verifyWebhook(
      req.body.toString("utf-8"),
      req.headers["x-waffo-signature"] as string,
    );
    res.status(200).send("OK");

    switch (event.eventType) {
      case WebhookEventType.OrderCompleted:
        // 处理订单完成
        break;
      case WebhookEventType.SubscriptionActivated:
        // 处理订阅激活
        break;
    }
  } catch {
    res.status(401).send("Invalid signature");
  }
});

// Next.js App Router
export async function POST(request: Request) {
  const body = await request.text();
  const sig = request.headers.get("x-waffo-signature");
  try {
    const event = verifyWebhook(body, sig);
    // 处理事件 ...
    return new Response("OK");
  } catch {
    return new Response("Invalid signature", { status: 401 });
  }
}
```

### 错误处理

```typescript theme={"system"}
import { WaffoPancakeError } from "@waffo/pancake-ts";

try {
  await client.stores.create({ name: "" });
} catch (err) {
  if (err instanceof WaffoPancakeError) {
    console.log(err.status);  // 400
    console.log(err.errors);  // [{ message: "...", layer: "store" }, ...]
  }
}
```

***

## Next.js SDK

<Card title="@waffo/pancake-nextjs" icon="npm" href="https://www.npmjs.com/package/@waffo/pancake-nextjs">
  官方 Next.js SDK — 组件、Hooks 和 Server Actions
</Card>

### 安装

```bash theme={"system"}
npm install @waffo/pancake-nextjs
```

需要 `@waffo/pancake-ts` 作为 peer dependency。适用于 Next.js 14+ App Router。

### Client 导出

| 导出                           | 类型            | 说明                     |
| ---------------------------- | ------------- | ---------------------- |
| `CheckoutButton`             | 组件            | 三模式收银台按钮（链接 / 匿名 / 认证） |
| `WaffoPancakeProvider`       | 组件            | 买家自助服务上下文，自动管理令牌生命周期   |
| `useCheckout()`              | Hook          | 编程式收银台控制               |
| `useBuyer()`                 | Hook          | 买家自助服务操作（取消、退款、恢复、查询）  |
| `useBuyerOrders()`           | Hook          | 获取买家的订单                |
| `useBuyerPayments()`         | Hook          | 获取买家的支付记录              |
| `useBuyerRefundTickets()`    | Hook          | 获取买家的退款工单              |
| `useMerchantOrders()`        | Hook          | 商户后台订单                 |
| `useMerchantSales()`         | Hook          | 商户销售概览                 |
| `useMerchantSubscriptions()` | Hook          | 商户订阅概览                 |
| `Webhook`                    | Route Handler | 自动验证签名并分发事件            |

### Server 导出（`@waffo/pancake-nextjs/server`）

| 导出                                  | 说明                          |
| ----------------------------------- | --------------------------- |
| `createCheckoutAction(config)`      | Server Action：创建收银台会话       |
| `createBuyerTokenAction(config)`    | Server Action：签发买家会话令牌      |
| `createBuyerSessionAction(config)`  | Server Action：买家自助服务操作      |
| `createMerchantQueryAction(config)` | Server Action：商户 GraphQL 查询 |

### 快速示例

```typescript theme={"system"}
// app/lib/actions.ts
"use server";
import { createCheckoutAction, createBuyerTokenAction } from "@waffo/pancake-nextjs/server";

const config = {
  merchantId: process.env.WAFFO_MERCHANT_ID!,
  privateKey: process.env.WAFFO_PRIVATE_KEY!,
};

export const checkoutAction = createCheckoutAction(config);
export const issueBuyerToken = createBuyerTokenAction(config);
```

```tsx theme={"system"}
// app/components/BuyButton.tsx
"use client";
import { CheckoutButton } from "@waffo/pancake-nextjs";
import { checkoutAction } from "@/app/lib/actions";

export function BuyButton({ productId }: { productId: string }) {
  return (
    <CheckoutButton
      type="authenticated"
      action={checkoutAction}
      productId={productId}
      currency="USD"
      buyerIdentity={user.email}
    >
      Subscribe Now
    </CheckoutButton>
  );
}
```

### Webhook Route Handler

```typescript theme={"system"}
// app/api/webhooks/waffo/route.ts
import { Webhook } from "@waffo/pancake-nextjs";

export const POST = Webhook({
  onOrderCompleted: async (event) => {
    // Deliver digital goods
  },
  onSubscriptionActivated: async (event) => {
    // Provision access
  },
  onSubscriptionCanceled: async (event) => {
    // Revoke access
  },
});
```

<Card title="Next.js 指南" icon="code" href="/zh/integrate/nextjs">
  完整的 Next.js 集成分步指南。
</Card>

***

## 直接 API 访问

你也可以直接使用 REST 和 GraphQL API。API Key 认证由 SDK 自动处理，无需手动设置请求头。

```typescript theme={"system"}
// 创建商品
const { product } = await client.onetimeProducts.create({
  storeId: "your-store-uuid",
  name: "My Product",
  prices: {
    USD: { amount: "29.00", taxIncluded: false, taxCategory: "saas" },
  },
});

// 通过 GraphQL 查询数据
const data = await client.graphql.query<{ stores: Array<{ id: string; name: string; status: string }> }>(
  `{ stores { id name status } }`
);
```

***

## SDK 路线图

| 语言                       | 状态                                                                                   |
| ------------------------ | ------------------------------------------------------------------------------------ |
| **Node.js / TypeScript** | 已发布 — [`@waffo/pancake-ts`](https://www.npmjs.com/package/@waffo/pancake-ts)         |
| **Next.js**              | 已发布 — [`@waffo/pancake-nextjs`](https://www.npmjs.com/package/@waffo/pancake-nextjs) |
| **Python**               | 计划中                                                                                  |
| **Go**                   | 计划中                                                                                  |
| **PHP**                  | 计划中                                                                                  |

***

## 框架指南

<CardGroup cols={2}>
  <Card title="Next.js" icon="code" href="/zh/integrate/nextjs">
    使用 Next.js 和 Server Actions 构建。
  </Card>

  <Card title="收银台会话" icon="cart-shopping" href="/zh/guides/checkout-session">
    通过编程方式创建收银台流程。
  </Card>

  <Card title="订阅" icon="repeat" href="/zh/guides/subscriptions">
    实现周期性计费。
  </Card>

  <Card title="Webhooks" icon="webhook" href="/zh/integrate/webhooks">
    接收实时事件通知。
  </Card>
</CardGroup>

***

## API 参考

完整的端点文档：

<Card title="API 参考" icon="book" href="/zh/api-reference/introduction">
  完整的 REST 和 GraphQL API 文档。
</Card>
