> ## 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.

# Polar

> 学习如何将Polar与ShipThing集成。

## 获取API密钥

创建Polar账户后，您需要获取API密钥。您可以前往仪表板的[API页面](https://polar.sh/)获取。在`设置`下，滚动到`开发人员`，然后单击`新建令牌`。输入令牌的名称，设置`过期持续时间`，然后选择希望令牌具有的`范围`。为简单起见，您可以选择所有范围。

### 添加环境变量

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

```env .env.local theme={"system"}
POLAR_ACCESS_TOKEN=""
POLAR_WEBHOOK_SECRET=""
POLAR_ENV="" // 如果使用沙盒环境请设置为'sandbox'，否则使用'production'或省略此参数
```

## 应用内购买

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

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

### 创建结账会话

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

* 客户端

向`/api/polar/checkout`端点发送创建会话的请求。

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

* 服务端

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

## Webhook

### 创建 Webhook

要配置新的 Webhook，请前往 Polar 控制台的 Webhooks 页面。点击“添加端点”按钮，并至少选择以下事件：

对于订阅：

* `subscription.created`
* `subscription.updated`
* `subscription.canceled`

对于一次性支付：

* `order.created`

### Webhook 处理器

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

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