# SDK 快速開始 (/guides/getting-started)





SDK 快速開始 [#sdk-快速開始]

本指南將幫助您在幾分鐘內開始使用 Recur SDK（版本 0.4.4+）。

安裝 [#安裝]

<Tabs items="['NPM', 'CDN']">
  <Tab value="NPM">
    ```bash
    npm install recur-tw
    # 或
    yarn add recur-tw
    # 或
    pnpm add recur-tw
    ```
  </Tab>

  <Tab value="CDN">
    ```html
    <script src="https://unpkg.com/recur-tw@latest/dist/recur.umd.js"></script>
    ```
  </Tab>
</Tabs>

基本使用 [#基本使用]

1\. 初始化 SDK [#1-初始化-sdk]

使用 Publishable Key 初始化 SDK：

<Tabs items="['Vanilla JS', 'React']">
  <Tab value="Vanilla JS">
    ```javascript
    // 使用 CDN 載入後，RecurCheckout 會自動掛載到 window
    const recur = RecurCheckout.init({
      publishableKey: 'pk_test_xxx', // 您的 Publishable Key
    });
    ```
  </Tab>

  <Tab value="React">
    ```typescript
    import { RecurCheckout } from 'recur-tw';

    const recur = RecurCheckout.init({
      publishableKey: 'pk_test_xxx', // 您的 Publishable Key
    });
    ```
  </Tab>
</Tabs>

2\. 開啟結帳視窗 [#2-開啟結帳視窗]

<Callout type="info">
  **提示**：`customerEmail` 和 `customerName` 都是選填。如果未預填，用戶會在結帳頁面輸入（Email 在結帳時為必填，用於寄送收據）。
</Callout>

```javascript
// Modal 模式結帳
await recur.checkout({
  productId: 'prod_xxx',            // 產品 ID（或使用 productSlug）
  customerEmail: 'user@example.com', // 選填：預填客戶 Email
  customerName: '王小明',            // 選填：預填客戶姓名
  externalId: 'user_123',           // 選填：您系統中的用戶 ID
  mode: 'modal',                     // 'modal' 或 'iframe'
  onSuccess: (result) => {
    console.log('Checkout session 建立成功:', result);
  },
  onPaymentComplete: (result) => {
    console.log('付款完成:', result);
    alert(`訂閱成功！ID: ${result.id}`);
  },
  onError: (error) => {
    console.error('錯誤:', error.message);
  },
  onClose: () => {
    console.log('視窗已關閉');
  },
});
```

3\. Iframe 嵌入模式 [#3-iframe-嵌入模式]

將付款表單嵌入到您的頁面中：

```javascript
await recur.checkout({
  productId: 'prod_xxx',             // 產品 ID（或使用 productSlug）
  customerEmail: 'user@example.com', // 選填：預填 Email
  customerName: '王小明',             // 選填：預填姓名
  mode: 'iframe',
  container: '#payment-container',   // CSS 選擇器或 DOM 元素
  onPaymentComplete: (result) => {
    console.log('付款完成:', result);
  },
});
```

```html
<div id="payment-container"></div>
```

參數說明 [#參數說明]

checkout() 參數 [#checkout-參數]

| 參數                  | 類型                    | 必填  | 說明                              |
| ------------------- | --------------------- | --- | ------------------------------- |
| `productId`         | string                | ✅\* | 產品 ID（與 productSlug 二擇一）        |
| `productSlug`       | string                | ✅\* | 產品 Slug（與 productId 二擇一）        |
| `customerEmail`     | string                | ❌   | 預填客戶 Email（結帳時必填）               |
| `customerName`      | string                | ❌   | 預填客戶姓名                          |
| `externalId`        | string                | ❌   | 外部客戶 ID（連結您系統的用戶）               |
| `mode`              | string                | ❌   | `'modal'`（預設）或 `'iframe'`       |
| `container`         | string \| HTMLElement | ❌   | iframe 模式的容器（mode='iframe' 時必填） |
| `onSuccess`         | function              | ❌   | Checkout session 建立成功時回調        |
| `onPaymentComplete` | function              | ❌   | 付款完成時回調                         |
| `onError`           | function              | ❌   | 錯誤時回調                           |
| `onClose`           | function              | ❌   | 視窗關閉時回調                         |

Hosted Checkout 模式 [#hosted-checkout-模式]

如果您希望將用戶導向 Recur 託管的結帳頁面：

```javascript
await recur.redirectToCheckout({
  productId: 'prod_xxx',
  successUrl: 'https://yoursite.com/success?session_id={CHECKOUT_SESSION_ID}',
  cancelUrl: 'https://yoursite.com/cancel',
  customerEmail: 'user@example.com',  // 選填
  externalId: 'user_123',             // 選填
});
```

取得產品列表 [#取得產品列表]

```javascript
// 取得所有產品
const { products } = await recur.fetchProducts();

// 或篩選特定類型
// const { products } = await recur.fetchProducts({ type: 'SUBSCRIPTION' });
// const { products } = await recur.fetchProducts({ type: 'ONE_TIME' });

products.forEach(product => {
  console.log(product.id);             // prod_xxx
  console.log(product.name);           // "Pro Plan"
  console.log(product.type);           // "SUBSCRIPTION" | "ONE_TIME"
  console.log(product.price);          // 299
  console.log(product.interval);       // "month" (訂閱型才有)
  console.log(product.interval_count); // 1 (訂閱型才有)
});
```

Web Component [#web-component]

最簡單的整合方式 - 不需要寫 JavaScript：

```html
<recur-checkout
  publishable-key="pk_test_xxx"
  product-id="prod_xxx"
  success-url="/success"
  cancel-url="/cancel"
  customer-email="user@example.com"
  button-style="gradient">
  立即訂閱
</recur-checkout>

<script src="https://unpkg.com/recur-tw@latest/dist/recur.umd.js"></script>
```

下一步 [#下一步]

* [API 參考](/api) - 查看完整的 API 文件
* [Hosted Checkout](/guides/checkout/hosted-checkout) - 託管結帳頁面
* [範例](/guides/examples) - 查看實際範例程式碼

常見問題 [#常見問題]

如何取得 Publishable Key？ [#如何取得-publishable-key]

請登入 [Recur 儀表板](https://app.recur.tw) → 設定 → 開發者 → API 金鑰。

customerEmail 和 customerName 是必填嗎？ [#customeremail-和-customername-是必填嗎]

`customerEmail` 和 `customerName` 在建立 checkout session 時都是**選填**的。如果未預填，用戶會在結帳頁面輸入。但 Email 在結帳時是必填的（用於寄送收據）。

支援哪些支付方式？ [#支援哪些支付方式]

目前支援透過 PAYUNi 的信用卡支付，未來將支援更多支付方式。
