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

# Chargebee

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

## 获取API密钥

创建Chargebee账户后，您需要获取API密钥。您可以前往仪表板的[API页面](https://www.chargebee.com/docs/2.0/api_keys.html)获取。在这里您会找到`Secret key`和`Publishable key`。集成需要使用`Secret key`。

### 添加环境变量

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

```env .env.local theme={"system"}
CHARGEBEE_API_KEY=
CHARGEBEE_SITE=
CREEM_API_KEY=""
```

## 应用内购买

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

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

### 创建结账会话

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

* 客户端

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

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

* 服务端

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

## Webhooks

### 创建Webhook

要配置新的Webhook，请转到Chargebee仪表板中的Webhooks页面。点击“添加端点”按钮，并至少选择以下事件：

* `Subscription Created`
* `Subscription Changed`
* `Subscription Cancelled`

### Webhook处理程序

Stripe的Webhook在`apps/api`应用中的`POST /webhooks/chargebee`路由中处理。此路由会构造事件，然后根据事件类型进行切换以确定如何处理该事件。
