2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Stripe BillingのテストクロックAPIを利用して、定期課金のシミュレーションをCLIから簡単に実行する

Posted at

Stripeには、定期課金の時間経過をシミュレートするための「テストクロック」機能が用意されています。

これを利用することで、「契約してから2週間目にプランをダウングレードした場合、次回の請求はどうなるか?」などの、時間経過が関わるテストが簡単にできるようになります。

テストクロックをGUIで操作する方法については、以下の記事がとてもわかりやすいです。

この記事では、できるだけ1つのコマンドで簡単にテストができるようにするJSスクリプトコードサンプルを紹介します。

コードでやるべきこと

テストクロックを使うには、少なくとも2つのコマンド・スクリプトが必要です。

1: テストクロック・顧客・サブスクリプションを作成するスクリプト

テストクロックを利用する場合、テストクロック作成後に、顧客を作成する必要があります。

そのため、以下のステップでAPIを呼び出すスクリプトが必要です。

  • テストクロックを作成する
  • テストクロックに関連付けした顧客データを作成する
  • サブスクリプションを作成する
  • 作成したリソースのIDを表示する
const clock = await stripe.testHelpers.testClocks.create({
  frozen_time: dayjs().unix(),
  name: 'From js script'
})
const customer = await stripe.customers.create({
  payment_method: 'pm_card_visa',
  invoice_settings: {default_payment_method: 'pm_card_visa'},
  test_clock: clock.id,
})
const subscription = await stripe.subscriptions.create({
  customer: customer.id,
  items: [{
    price: 'price_xxxx',
    quantity: 1
  }]
})
console.log([
  `Clock ID: ${clock.id}`,
  `Customer: ${customer.id}`,
  `Subscription: ${subscription.id}`
])

コマンドの引数や環境変数を利用して、サブスクリプションの料金IDを変更できるようにすると、より実用的になるでしょう。

2: 任意の時間にテストクロックを進めるスクリプト

もう1つ必要なものは、作成したテストクロックの時間を進めるスクリプトです。

ここでは、「対象のID」と「進めたい時間(UNIX TIME)」の2つを指定します。

await stripe.testHelpers.testClocks.advance('clock_xxxx', {
  frozen_time: dayjs().add(1, 'month').unix()
})

サンプルのように、dayjsなどの日付操作ライブラリを利用することで、「1ヶ月後」などの相対的な日付操作がやりやすくなります。

CLIツールにする場合

このようなテスト機能は、社内・チーム用のCLIツールにすると便利です。

oclifを利用する場合、以下のようにオプションを設定することで、より使いやすく、共有しやすくなります。

import {Command, Flags} from '@oclif/core';

export default class Hello extends Command {
  static flags = {
    clockId: Flags.string({
      char: 'c',
      description: 'Test Clock ID',
      required: true,
    }),
    fronzenTime: Flags.integer({
      char: 'f',
      description: 'UNIX Time',
      required: true,
    }),
  };

  async run(): Promise<void> {
    const {
      flags: {
        clockId,
        fronzenTime,
      },
    } = await this.parse(Hello);
    await stripe.testHelpers.testClocks.advance(clockId, {
      frozen_time: fronzenTime,
    });

    this.log('Complete!');
  };
};

[PR] Stripe開発者向け情報をQiitaにて配信中!

  • [Stripe Updates]:開発者向けStripeアップデート紹介・解説
  • ユースケース別のStripe製品や実装サンプルの紹介
  • Stripeと外部サービス・OSSとの連携方法やTipsの紹介
  • 初心者向けのチュートリアル(予定)

など、Stripeを利用してオンラインビジネスを始める方法について週に2〜3本ペースで更新中です。

-> Stripe Organizationsをフォローして最新情報をQiitaで受け取る

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?