# Billing の実装テスト

Billing 実装をテストして、本番環境での使用を確認する方法をご紹介します。

Test how your Billing integration handles subscription renewals, trials, payment failures, and webhook notifications before processing live payments. Choose the tests that apply to your integration and run them in a [sandbox](https://docs.stripe.com/sandboxes.md). For general testing guidance, see [Testing](https://docs.stripe.com/testing.md).

## Testing scenarios 

Review the following scenarios and run the tests that apply to your integration.

> #### Accounts v2 availability
> 
> The customer sign-up test in the following table refers to both `Customer` objects from the v1 API and customer-configured `Account` objects from the [Accounts v2 API](https://docs.stripe.com/accounts-v2/use-accounts-as-customers.md). The Accounts v2 API is generally available for Connect users and in public preview for other Stripe users.

| Scenario | What to verify | How to test |
| --- | --- | --- |
| **顧客の登録** | Your sign-up flow collects the required customer information and stores a customer-configured `Account` or `Customer` object in Stripe. | Complete your integration’s sign-up flow in a sandbox. In the Dashboard, confirm you’re viewing that sandbox, then go to **Customers** and find the customer record. |
| **請求書作成** | *Invoices* (Invoices are statements of amounts owed by a customer. They track the status of payments from draft through paid or otherwise finalized. Subscriptions automatically generate invoices, or you can manually create a one-off invoice) are generated and payment is collected as expected, either by automatically charging a payment method or sending an invoice to the customer. | [Simulate renewals and billing cycles](https://docs.stripe.com/billing/testing.md#simulate-subscriptions). |
| **サブスクリプションの管理** | The subscription in Stripe reflects any changes made through the *customer portal* (The customer portal is a secure, Stripe-hosted page that lets your customers manage their subscriptions and billing details). | With your [customer portal configured](https://docs.stripe.com/customer-management/configure-portal.md), create a sandbox subscription, open the customer portal as the test customer, and update the subscription. In the Dashboard, confirm you’re viewing that sandbox, then go to **Subscriptions** and verify the change. |
| **トライアル** | The subscription starts in `trialing` status, generates a zero-value trial invoice, and transitions to the expected status when the trial ends. | [Test subscription trial periods](https://docs.stripe.com/billing/testing.md#trials). |
| **支払いの失敗** | Your integration detects failed payments and handles retries and customer notifications according to your configuration. | [Test payment failures](https://docs.stripe.com/billing/testing.md#payment-failures). |

To identify the webhook events to monitor during these tests, see [Subscription events](https://docs.stripe.com/billing/subscriptions/webhooks.md#events).

## Subscription lifecycle tests

### Test renewals and changes over time 

Use test clocks to advance simulated time in a sandbox and see how your subscriptions and invoices change. For example, test how your integration handles a payment failure at an annual renewal without waiting a year.

You can run simulations in the Dashboard without writing code, or use the API. Use simulations to:

- 請求サイクルの途中でのアップグレードやプラン変更をテストします。
- Test how [customer balances](https://docs.stripe.com/billing/customer/balance.md) and [one-off invoice items](https://docs.stripe.com/billing/invoices/subscription.md#adding-upcoming-invoice-items) affect upcoming invoices.
- 実装で Billing のライフサイクルに関する Webhook が正しく処理されることを確認します。
- アプリでトライアルが適切に処理されることを検証します。
- 複数のフェーズからなるサブスクスケジュールを作成してテストします。

#### サブスクをシミュレート

ダッシュボードでサブスクをシミュレートするには、以下の手順に従います。API を使用してテストクロックを作成、管理する方法については、[テストクロックの高度な使用方法](https://docs.stripe.com/billing/testing/test-clocks/api-advanced-usage.md)を参照してください。

1. [ダッシュボード](https://dashboard.stripe.com)でサンドボックスを作成します。

2. [サブスク](https://dashboard.stripe.com/test/subscriptions)ページで、テストするサブスクをクリックします。

3. バナーの**シミュレーションを実行**をクリックします。

   The Dashboard might disable **Run simulation** if the subscription’s customer:

   - [スケジュールされたサブスク](https://docs.stripe.com/billing/subscriptions/subscription-schedules.md)を含め、サブスクが 4 件以上ある。
   - 見積もり、請求書、またはその他の関連オブジェクトが 25 件を超える複雑なプロファイルです。

4. In the modal, set the date and time to simulate, then click **Advance time**.

   You can advance the clock by any increment, up to two subscription intervals at a time from the initial frozen time. For example, for a monthly subscription, you can advance up to 2 months at a time. When the simulation completes, the banner displays the current simulation time.

#### シミュレーションを表示および削除する

ダッシュボードの**サブスク** > [シミュレーション](https://dashboard.stripe.com/test/billing/subscriptions/simulations)で、シミュレーションを確認できます。

シミュレーションを削除するには、**シミュレーションを終了**をクリックします。これにより、顧客やサブスクを含む、関連するすべてのオブジェクトがサンドボックスから削除されます。本番環境には影響しません。

### サブスクリプションのトライアル期間をテストする

To test a 7-day free trial that collects payment information up front, use test clocks:

1. 新しいシミュレーションを作成し、`frozen_time` を January 1 に設定します。

2. 顧客を追加して支払い方法を含めます。ここでは、4242424242424242 の[テストカード](https://docs.stripe.com/testing.md#cards)を使用します。

3. サブスクリプションを作成して、7 日間の無料トライアル期間を追加します。

   #### ダッシュボード

   ダッシュボードから既存のサブスクリプションにトライアル期間を追加するには、以下を行います。

   1. 変更するサブスクリプションを探します。
   2. **アクション**をクリックします。
   3. **サブスクリプションを更新**をクリックします。
   4. Click **Add free trial** and enter seven in **Free trial days**.
   5. **サブスクリプションを更新**をクリックします。

   #### API

   Create the subscription with `trial_end` set to 7 days after the simulation’s `frozen_time`, replacing the value in this example:

   #### Accounts v2

   ```curl
   curl https://api.stripe.com/v1/subscriptions \
     -u "<<YOUR_SECRET_KEY>>:" \
     -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
     -d "items[0][price]={{PRICE_ID}}" \
     -d trial_end=1610403705
   ```

   #### Customers v1

   ```curl
   curl https://api.stripe.com/v1/subscriptions \
     -u "<<YOUR_SECRET_KEY>>:" \
     -d "customer={{CUSTOMER_ID}}" \
     -d "items[0][price]={{PRICE_ID}}" \
     -d trial_end=1610403705
   ```

   **Expected result:** The subscription has a `trialing` status and generates a zero-value invoice for the free trial.

4. Advance the date to January 5 to test the [customer.subscription.trial_will_end](https://docs.stripe.com/api/events/types.md#event_types-customer.subscription.trial_will_end) event notification with the default 3 day notification window. If you’ve configured a different notification window, advance to that point instead. You can use this webhook event to inform your customers that the trial ends soon.

5. Advance the date to January 8 to end the trial. Advance simulated time as needed for invoice finalization and payment collection.

   **Expected result:** With a successful payment, the subscription becomes `active` and the invoice is paid. The subscription’s configured price determines the invoice amount.

6. サイクルを 1 つ (月次サブスクリプションの場合は 2 月 8 日まで) 進めて、サブスクリプションが更新されることを確認します。

#### Test trial periods without test clocks 

To test trial periods without waiting for a full trial:

1. Create a subscription with a [trial_end](https://docs.stripe.com/api/subscriptions/create.md#create_subscription-trial_end) value a few minutes in the future using the Subscriptions API. If you use Checkout, set [subscription_data.trial_end](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-subscription_data-trial_end) to at least 2 days in the future.
2. Let the trial end, then verify the subscription and invoice statuses expected for your configured payment flow.

Use [test clocks](https://docs.stripe.com/billing/testing.md#test-clocks) for controlled testing of `customer.subscription.trial_will_end` notification timing. Short trials can end before background notification processing observes them.

The default notification window is 3 days before the trial ends.

### サブスクリプションの Webhook 通知をテストする

Subscriptions integrations rely on *webhooks* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests). You set up a webhook endpoint on your server and specify which event notifications to listen for. Stripe sends notifications for events such as a subscription upgrades or cancellations. [Verify webhook signatures](https://docs.stripe.com/webhooks.md#verify-events) to confirm that events came from Stripe.

Whether you represent customers with Accounts v2 or [Customer objects](https://docs.stripe.com/api/customers.md), listen for `customer.subscription.*` events to track subscription activity.

Use these two methods to test your integration:

- **Test the subscription flow**: Create actual sandbox subscriptions, perform [subscription lifecycle](https://docs.stripe.com/billing/subscriptions/overview.md#subscription-lifecycle) actions such as upgrades or cancellations, and verify the received events and your application’s behavior.
- **Test individual handlers**: Set up the [Stripe CLI](https://docs.stripe.com/stripe-cli.md) and link it to your Stripe account to trigger synthetic event notifications, or trigger them through the [Dashboard](https://dashboard.stripe.com/test/account/webhooks). These events contain test data that doesn’t correspond to real subscription resources, so they don’t validate the complete subscription lifecycle.

Use the Stripe CLI to receive event notifications on your server without network tunnels or firewalls. Don’t rely on receiving events in a particular order.

For subscription event types and handling guidance, see [Subscription events](https://docs.stripe.com/billing/subscriptions/webhooks.md#events).

## Payment tests

### 支払いの失敗をテストする

Use [test cards](https://docs.stripe.com/testing.md#cards) to trigger payment failures for subscriptions and invoices.

A failed initial payment can leave a newly created subscription in an `incomplete` status. To test a payment failure after a trial instead:

1. Set 4000000000000341 as the customer’s default payment method.
2. Create a subscription with a short trial to defer the payment attempt until the trial ends.
3. Let the trial end and wait for the invoice to finalize and payment collection to be attempted.

In this test, the payment attempt fails and your integration receives `invoice.payment_failed`. Verify the invoice and subscription statuses, then check that your integration follows your configured retry and customer-notification behavior.

To test a payment failure at a quarterly or annual renewal without waiting for the billing period to pass, use test clocks to advance simulated time in a sandbox. See [advanced test clock scenarios](https://docs.stripe.com/billing/testing/test-clocks/api-advanced-usage.md#use-cases).

### 3D セキュアを必要とする支払いをテストする

To test authentication for subscriptions and invoices:

1. Use the 4000002760003184 card to trigger 3D Secure.
2. Authenticate or fail the payment attempt in the 3D Secure dialog that opens.

Check the result for each outcome:

- **Successful authentication**: The invoice is paid. If the invoice belongs to a subscription in an `incomplete` status, the subscription becomes `active`.
- **Unsuccessful authentication**: The invoice remains `open`.

For more authentication scenarios, see [3D Secure test cards](https://docs.stripe.com/testing.md#three-ds-cards).

### Test bank transfer payments for invoices 

銀行振込による請求書の手動支払いをテストする手順は、以下のとおりです。

1. サンドボックスで請求書を作成し、回収方法を `send_invoice` に設定した後、`payment_settings[payment_method_types]` 配列を `[customer_balance]` に設定します。
2. ダッシュボードで請求書を見つけ、**送信**をクリックします。

Stripe allocates your customer a unique virtual bank account number, which you can retrieve through the [funding instructions API](https://docs.stripe.com/payments/customer-balance/funding-instructions.md#create-funding-instructions). The virtual banking details also appear on the hosted invoice page and the PDF.

### Test the default payment method for invoices and subscriptions 

特定の[テストカード ID](https://docs.stripe.com/testing.md?testing-method=payment-methods#cards)を使用して、サブスクリプションとインボイスに使用されるデフォルトの決済手段をシミュレーションします。

Attach the payment method to the customer before setting it as the `default_payment_method`. For example, to use `pm_card_visa` as a test Visa payment method:

1. [Attach the test payment method](https://docs.stripe.com/api/payment_methods/attach.md) `pm_card_visa` to the customer associated with the subscription or invoice.
2. Create the subscription or invoice with the attached payment method’s ID as its `default_payment_method`.

The subscription or invoice uses this payment method for payment collection.

## 顧客の納税者番号確認をテストする

これらの魔法の納税者番号を使用して、テスト環境で特定の確認条件をトリガーします。納税者番号のタイプは、オーストラリア事業者登録番号 (ABN)、EU VAT 番号、またはイギリスの付加価値税 (GB VAT) 番号である必要があります。

| 番号 | タイプ |
| --- | --- |
| `000000000` | 本人確認成功 |
| `111111111` | 本人確認に失敗 |
| `222222222` | 確認は無期限に保留中のままになります |

## Automate your tests 

You can set up [automated testing](https://docs.stripe.com/automated-testing.md) for your integration. Use separate sandboxes for local development and continuous integration (CI) so automated tests don’t affect your products, prices, customers, webhook endpoints, settings, or test data.

For testing:

- サンドボックス内のサブスクリプション関連データについては、[データ保持ポリシー](https://support.stripe.com/questions/test-mode-subscription-data-retention)が適用されることに注意してください。
- テスト間で[クーポン](https://docs.stripe.com/api/coupons.md)や[プロモーションコード](https://docs.stripe.com/api/promotion_codes.md)などのリソースを再利用しないでください。
- [stripe-mock](https://github.com/stripe/stripe-mock) HTTP サーバーを使用します。これは、Stripe API を使用し API の動作をよく反映します。

## See also

- [サンドボックス](https://docs.stripe.com/sandboxes.md)
- [複数のアカウント](https://docs.stripe.com/get-started/account/multiple-accounts.md)
