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

# Lemonsqueezy

> 学习如何设置ShipThing与Lemonsqueezy的集成。

[Lemon Squeezy](https://www.lemonsqueezy.com/) 是一个用于运行SaaS业务的一体化平台。它处理支付、订阅、全球税务合规、欺诈预防、多货币等功能。以下是如何将默认支付处理器从Stripe切换到Lemon Squeezy的方法。

## 获取API密钥

创建Lemonsqueezy账户后，您需要获取API密钥。您可以通过访问仪表板中的[API页面](https://app.lemonsqueezy.com/settings/api)来获取。在这里您将找到`Secret key`和`Publishable key`。您需要`Secret key`来完成集成。

### 添加环境变量

要使用Lemonsqueezy集成，您需要在`.env.local`以及生产环境中定义以下环境变量：

```env .env.local theme={"system"}
LEMON_SQUEEZY_API_KEY=
LEMON_SQUEEZY_WEBHOOK_SECRET=
```

## 应用内购买

您可以通过导入`lemonsqueezy`对象在应用中的任何地方使用Lemonsqueezy：

```ts page.tsx theme={"system"}
import { lemonsqueezy } from '@repo/payments';
```

### 创建结账会话

我们需要创建一个结账会话来向用户收费，您只需要修改部分代码。它由两部分组成：

* 客户端

它发送请求到`/api/lemonsqueezy/checkout`端点来创建会话。

```tsx apps/web/[locale]/components/payment/price-form.tsx theme={"system"}
      const response = await fetch('/api/lemonsqueezy/checkout', { // 修改为`/api/lemonsqueezy/checkout`
        method: 'POST',
        body: JSON.stringify({
          priceId: item.priceId,
          interval: item.interval,
        }),
      });
```

* 服务端

在`apps/web/api/lemonsqueezy/checkout/route.ts`中实现业务逻辑

<Tip>
  Lemonsqueezy允许使用产品的[购买链接](https://docs.lemonsqueezy.com/guides/developer-guide/taking-payments#creating-checkouts-from-the-lemon-squeezy-dashboard)，而无需通过API创建结账会话。
</Tip>

## Webhook

### 创建Webhook

要配置新的Webhook，请前往Lemonsqueezy仪表板中的[Webhook页面](https://app.lemonsqueezy.com/settings/webhooks)。点击“添加端点”按钮，并至少选择以下事件：

对于订阅：

* `subscription_created`
* `subscription_updated`
* `subscription_cancelled`

对于一次性付款：

* `order_created`

您还需要输入一个签名密钥，您可以在终端中运行以下命令来获取：

```sh Terminal theme={"system"}
openssl rand -base64 32
```

### Webhook处理器

Stripe的Webhook由`apps/api`应用中的`POST /webhooks/lemonsqueezy`路由处理。该路由会构建事件，然后根据事件类型来决定如何处理该事件。

<Note>
  我们已为您实现了`Webhook`处理器的基本结构。您可以根据需要进行修改。
</Note>
