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

# サブスクリプション統合ガイド

> このガイドは、Dodo Paymentsのサブスクリプション製品をウェブサイトに統合するのに役立ちます。

## 前提条件

Dodo Payments APIを統合するには、次のものが必要です：

* Dodo Paymentsのマーチャントアカウント
* ダッシュボードからのAPI認証情報（APIキーとWebhookシークレットキー）

前提条件に関する詳細なガイドについては、この[セクション](/developer-resources/integration-guide#dashboard-setup)を確認してください。

## API統合

### チェックアウトセッション

Checkout Sessionsを使用して、セキュリティで保護されたホスト型チェックアウトでサブスクリプション商品を販売します。サブスクリプション商品を `product_cart` に渡し、返された `checkout_url` に顧客をリダイレクトしてください。

<Tip>
  **Mixed Checkout**: サブスクリプション商品を単発商品と同じチェックアウトセッションで組み合わせることができます。これにより、サブスクリプションに設定料金を追加したり、SaaSとハードウェアバンドルをまとめて提供したりするユースケースが可能になります。例については [Checkout Sessions guide](/developer-resources/checkout-session) を参照してください。
</Tip>

<Tabs>
  <Tab title="Node.js SDK">
    ```javascript theme={null}
    import DodoPayments from 'dodopayments';

    const client = new DodoPayments({
      bearerToken: process.env.DODO_PAYMENTS_API_KEY,
      environment: 'test_mode', // defaults to 'live_mode'
    });

    async function main() {
      const session = await client.checkoutSessions.create({
        product_cart: [
          { product_id: 'prod_subscription_monthly', quantity: 1 }
        ],
        // Optional: configure trials for subscription products
        subscription_data: { trial_period_days: 14 },
        customer: {
          email: 'subscriber@example.com',
          name: 'Jane Doe',
        },
        return_url: 'https://example.com/success',
      });

      console.log(session.checkout_url);
    }

    main();
    ```
  </Tab>

  <Tab title="Python SDK">
    ```python theme={null}
    import os
    from dodopayments import DodoPayments

    client = DodoPayments(
        bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"),
        environment="test_mode",  # defaults to "live_mode"
    )

    session = client.checkout_sessions.create(
        product_cart=[
            {"product_id": "prod_subscription_monthly", "quantity": 1}
        ],
        subscription_data={"trial_period_days": 14},  # optional
        customer={
            "email": "subscriber@example.com",
            "name": "Jane Doe",
        },
        return_url="https://example.com/success",
    )

    print(session.checkout_url)
    ```
  </Tab>

  <Tab title="REST API">
    ```javascript theme={null}
    const response = await fetch('https://test.dodopayments.com/checkouts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.DODO_PAYMENTS_API_KEY}`
      },
      body: JSON.stringify({
        product_cart: [
          { product_id: 'prod_subscription_monthly', quantity: 1 }
        ],
        subscription_data: { trial_period_days: 14 }, // optional
        customer: {
          email: 'subscriber@example.com',
          name: 'Jane Doe'
        },
        return_url: 'https://example.com/success'
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const session = await response.json();
    console.log(session.checkout_url);
    ```
  </Tab>
</Tabs>

### APIレスポンス

以下はレスポンスの例です：

```json theme={null}
{
  "session_id": "cks_Gi6KGJ2zFJo9rq9Ukifwa",
  "checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa"
}
```

顧客を `checkout_url` にリダイレクトします。

### Webhook

サブスクリプションを統合する際、サブスクリプションライフサイクルを追跡するためのWebhookを受信します。これらのWebhookは、サブスクリプションの状態や支払いシナリオを効果的に管理するのに役立ちます。

Webhookエンドポイントを設定するには、[詳細な統合ガイド](/developer-resources/integration-guide#implementing-webhooks)に従ってください。

#### サブスクリプションイベントタイプ

以下のWebhookイベントは、サブスクリプションの状態変更を追跡します：

1. **`subscription.active`** - サブスクリプションが正常に有効化されました。
2. **`subscription.updated`** - サブスクリプションオブジェクトが更新されました（任意のフィールドが変更されたときに発火します）。
3. **`subscription.on_hold`** - 更新失敗によりサブスクリプションが保留されました。
4. **`subscription.failed`** - マンダート作成中にサブスクリプションの作成が失敗しました。
5. **`subscription.renewed`** - 次回請求期間に向けてサブスクリプションが更新されました。

信頼性の高いサブスクリプションライフサイクル管理のために、これらのサブスクリプションイベントを追跡することをお勧めします。

<Tip>
  `subscription.updated` を使用して、サブスクリプションの変更をリアルタイムで通知し、APIをポーリングせずにアプリケーション状態を同期させます。
</Tip>

#### 支払いシナリオ

**成功した支払いフロー**

支払いが成功した場合、次のWebhookを受信します：

1. `subscription.active` - サブスクリプションの有効化を示します
2. `payment.succeeded` - 初回支払いを確認します:
   * 即時請求（トライアル0日）の場合：2〜10分以内に発生します
   * トライアル期間がある場合：その終了時に発生します
3. `subscription.renewed` - 支払いが差し引かれて次の請求サイクルに更新されたことを示します（基本的に、サブスクリプション商品で支払いが差し引かれるたびに `subscription.renewed` のウェブフックが `payment.succeeded` と共に届きます）。

**支払い失敗シナリオ**

1. サブスクリプション失敗

* `subscription.failed` - マンダート作成に失敗したためサブスクリプションの作成が失敗しました。
* `payment.failed` - 支払いが失敗したことを示します。

2. サブスクリプション保留

* `subscription.on_hold` - 更新支払いまたはプラン変更時の課金失敗によりサブスクリプションが保留されます。
* サブスクリプションが保留になると、支払い方法が更新されるまで自動更新されません。

<Info>**ベストプラクティス**: 実装を簡素化するため、サブスクリプションのライフサイクル管理には主にサブスクリプションイベントの追跡を推奨します。</Info>

### サブスクリプションが保留中の処理

サブスクリプションが `on_hold` 状態になると、再有効化するために支払い方法を更新する必要があります。このセクションでは、サブスクリプションが保留になるタイミングと対処方法を説明します。

#### サブスクリプションが保留中になるとき

サブスクリプションは次の理由で保留中になります：

* **更新支払いが失敗した場合**：自動更新の請求が資金不足、カードの期限切れ、または銀行の拒否により失敗します
* **プラン変更の請求が失敗した場合**：プランのアップグレード/ダウングレード中の即時請求が失敗します
* **支払い方法の承認が失敗した場合**：支払い方法が定期的な請求に対して承認できません

<Warning>
  `on_hold` 状態のサブスクリプションは自動的に更新されません。再有効化するには支払い方法を更新してください。
</Warning>

#### 保留中のサブスクリプションの再アクティブ化

`on_hold` 状態のサブスクリプションを再有効化するには Update Payment Method API を使用します。これにより自動的に以下が行われます:

1. 残額分の請求を作成
2. その請求に対して請求書を生成
3. 新しい支払い方法で支払いを処理
4. 支払いが成功すると、サブスクリプションを `active` 状態に再有効化

<Steps>
  <Step title="Handle subscription.on_hold webhook">
    `subscription.on_hold` ウェブフックを受け取ったら、アプリケーションの状態を更新し、顧客に通知します:

    ```javascript theme={null}
    // Webhook handler
    app.post('/webhooks/dodo', async (req, res) => {
      const event = req.body;
      
      if (event.type === 'subscription.on_hold') {
        const subscription = event.data;
        
        // Update subscription status in your database
        await updateSubscriptionStatus(subscription.subscription_id, 'on_hold');
        
        // Notify customer to update payment method
        await sendEmailToCustomer(subscription.customer_id, {
          subject: 'Payment Required - Subscription On Hold',
          message: 'Your subscription is on hold. Please update your payment method to continue service.'
        });
      }
      
      res.json({ received: true });
    });
    ```
  </Step>

  <Step title="Update payment method">
    顧客が支払い方法を更新する準備ができたら、Update Payment Method API を呼び出します:

    <CodeGroup>
      ```javascript Node.js theme={null}
      // Update with new payment method
      const response = await client.subscriptions.updatePaymentMethod(subscriptionId, {
        type: 'new',
        return_url: 'https://example.com/return'
      });

      // For on_hold subscriptions, a charge is automatically created
      if (response.payment_id) {
        console.log('Charge created for remaining dues:', response.payment_id);
        // Redirect customer to response.payment_link to complete payment
      }
      ```

      ```python Python theme={null}
      # Update with new payment method
      response = client.subscriptions.update_payment_method(
          subscription_id=subscription_id,
          type="new",
          return_url="https://example.com/return"
      )

      # For on_hold subscriptions, a charge is automatically created
      if response.payment_id:
          print("Charge created for remaining dues:", response.payment_id)
          # Redirect customer to response.payment_link to complete payment
      ```
    </CodeGroup>

    <Info>
      顧客が保存済みの支払い方法を持っている場合は、既存の支払い方法IDを使用することもできます:

      ```javascript theme={null}
      await client.subscriptions.updatePaymentMethod(subscriptionId, {
        type: 'existing',
        payment_method_id: 'pm_abc123'
      });
      ```
    </Info>
  </Step>

  <Step title="Monitor webhook events">
    支払い方法を更新したら、次のウェブフックイベントを監視してください:

    1. **`payment.succeeded`** - 残額請求が成功しました
    2. **`subscription.active`** - サブスクリプションが再有効化されました

    ```javascript theme={null}
    if (event.type === 'payment.succeeded') {
      const payment = event.data;
      
      // Check if this payment is for an on_hold subscription
      if (payment.subscription_id) {
        // Wait for subscription.active webhook to confirm reactivation
      }
    }

    if (event.type === 'subscription.active') {
      const subscription = event.data;
      
      // Update subscription status in your database
      await updateSubscriptionStatus(subscription.subscription_id, 'active');
      
      // Restore customer access
      await restoreCustomerAccess(subscription.customer_id);
      
      // Notify customer of successful reactivation
      await sendEmailToCustomer(subscription.customer_id, {
        subject: 'Subscription Reactivated',
        message: 'Your subscription has been reactivated successfully.'
      });
    }
    ```
  </Step>
</Steps>

### サンプルサブスクリプションイベントペイロード

***

| プロパティ         | タイプ    | 必須 | 説明                                            |
| ------------- | ------ | -- | --------------------------------------------- |
| `business_id` | string | はい | 事業の一意の識別子                                     |
| `timestamp`   | string | はい | イベントが発生したタイムスタンプ（配信時刻とは異なる場合があります）            |
| `type`        | string | はい | イベントの種類。 [Event Types](#event-types) を参照      |
| `data`        | object | はい | メインのデータペイロード。 [Data Object](#data-object) を参照 |

## サブスクリプションプランの変更

プラン変更APIエンドポイントを使用して、サブスクリプションプランをアップグレードまたはダウングレードできます。これにより、サブスクリプションの製品、数量を変更し、按分を処理できます。

<Card title="Change Plan API Reference" icon="arrows-rotate" href="/api-reference/subscriptions/change-plan">
  サブスクリプションプランの変更に関する詳細は、Change Plan API ドキュメントをご参照ください。
</Card>

### 按分オプション

サブスクリプションプランを変更する際、即時請求の処理方法について2つのオプションがあります：

#### 1. `prorated_immediately`

* 現在の請求サイクルの残り時間に基づいて按分金額を計算します
* 旧プランと新プランの差額のみを顧客に請求します
* トライアル期間中でも即座に新プランへ切り替え、すぐに顧客に課金します

#### 2. `full_immediately`

* 新プランのサブスクリプション料金を全額請求します
* 前のプランの残り時間やクレジットを無視します
* 請求サイクルをリセットしたい場合や、按分に関係なく全額を請求したい場合に便利です

#### 3. `difference_immediately`

* アップグレード時には、顧客に対して2つのプラン金額の差額が即時課金されます。
* 例えば、現在のプランが30ドルで顧客が80ドルにアップグレードした場合、\$50が即時に課金されます。
* ダウングレード時には、現在のプランの未使用分が内部クレジットとして加算され、今後のサブスクリプション更新に自動的に適用されます。
* 例えば、現在のプランが50ドルで顧客が20ドルプランに切り替えた場合、残りの\$30がクレジットとして加算され、次回請求サイクルに使用されます。

### 挙動

* このAPIを呼び出すと、Dodo Paymentsは選択した按分オプションに基づいて即座に課金を開始します
* プラン変更がダウングレードで `prorated_immediately` を使用した場合、クレジットが自動的に計算され、サブスクリプションのクレジット残高に追加されます。このクレジットは当該サブスクリプション専用で、同じサブスクリプションの今後の定期支払いに対してのみ差し引かれます。
* `full_immediately` オプションはクレジット計算をスキップし、新しいプランの金額を全額請求します

<Tip>
  **按分オプションは慎重に選択してください**: 未使用時間を考慮した公平な請求には `prorated_immediately` を使用し、現在の請求サイクルに関係なく新しいプラン金額を全額請求したい場合は `full_immediately` を使用してください。
</Tip>

### 請求処理

* プラン変更時に開始される即時請求は通常、2分以内に処理が完了します
* この即時請求が何らかの理由で失敗した場合、サブスクリプションは問題が解決されるまで自動的に保留中になります

## オンデマンドサブスクリプション

<Info>
  オンデマンドサブスクリプションでは、固定スケジュールだけでなく柔軟に顧客に課金できます。この機能はすべてのアカウントで利用可能です。
</Info>

**オンデマンドサブスクリプションを作成するには：**

オンデマンドサブスクリプションを作成するには、[POST /subscriptions](/api-reference/subscriptions/post-subscriptions) APIエンドポイントを使用し、リクエストボディに `on_demand` フィールドを含めてください。これにより即時課金なしで支払い方法を認可したり、カスタムの初期価格を設定したりできます。

**オンデマンドサブスクリプションに請求するには：**

その後の請求については、[POST /subscriptions/{subscription_id}/charge](/api-reference/subscriptions/create-charge) エンドポイントを使用し、その取引で顧客に請求する金額を指定します。

<Note>
  リクエスト/レスポンス例、安全なリトライポリシー、ウェブフックの処理などを含む完全なステップバイステップガイドについては、<a href="/developer-resources/ondemand-subscriptions">On-Demand Subscriptions Guide</a>を参照してください。
</Note>

## 関連APIリファレンス

API reference for creating subscription products and managing subscription lifecycle
API reference for upgrading, downgrading, or changing subscription plans with proration options
API reference for updating payment methods and reactivating on-hold subscriptions
API reference for updating subscription details and configuration

**オンデマンドサブスクリプションを請求するには：**

その後の請求については、[POST /subscriptions/{subscription_id}/charge](/api-reference/subscriptions/create-charge) エンドポイントを使用し、その取引の顧客に請求する金額を指定します。

<Note>
  要求/応答の例、安全な再試行ポリシー、Webhook ハンドリングを含む完全な段階的なガイドについては、<a href="/developer-resources/ondemand-subscriptions">オンデマンドサブスクリプションガイド</a>を参照してください。
</Note>

## 関連する API リファレンス

<CardGroup cols={2}>
  <Card title="Create Subscription" icon="code" href="/api-reference/subscriptions/post-subscriptions">
    サブスクリプション製品の作成およびサブスクリプションライフサイクルの管理に関する API リファレンス
  </Card>

  <Card title="Change Subscription Plan" icon="arrows-rotate" href="/api-reference/subscriptions/change-plan">
    プロレートオプションを使用したサブスクリプションプランのアップグレード、ダウングレード、または変更に関する API リファレンス
  </Card>

  <Card title="Update Payment Method" icon="credit-card" href="/api-reference/subscriptions/update-payment-method">
    支払い方法の更新および保留中のサブスクリプションの再有効化に関する API リファレンス
  </Card>

  <Card title="Patch Subscription" icon="pen" href="/api-reference/subscriptions/patch-subscriptions">
    サブスクリプション詳細および設定の更新に関する API リファレンス
  </Card>
</CardGroup>
