1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Stripeの無料トライアル終了後にサブスクリプションを自動キャンセルする方法

Posted at

はじめに

Stripeを使ってサービスの無料トライアルを提供し、トライアル期間終了後に自動でサブスクリプションをキャンセルしたい場合があります。
特に、ユーザーにクレジットカード情報を入力させずに開始して、期間終了後は自動的に解約するパターンです。

この記事ではNode.jsからStripeのAPIを直接利用して、トライアル終了時にサブスクリプションを自動キャンセルする方法を解説します✨
初心者向けにコード例、ハマりポイントのトラブルシューティングも載せてます!

🛠前提条件と準備

✅ Stripeアカウント
✅ プロダクトと価格(plan)を作成済み
✅ Node.jsの環境がある(npm initできる)
✅ StripeのAPIキー(テスト用)が用意できる

無料トライアル付きサブスクリプションを作成

事前に顧客 (customer) と価格 (price) を作成しておく。

const subscription = await stripe.subscriptions.create({
  customer: 'cus_XXXXXXXX',
  items: [{ price: 'price_YYYYYYYY' }],
  trial_period_days: 14
});

console.log(`Subscription created: ${subscription.id}, status: ${subscription.status}`);

これだけだと、トライアル後に勝手に有料化するから次の設定を追加するよ!

トライアル終了後に自動キャンセルさせる

2023年以降、trial_settings.end_behavior.missing_payment_method が登場。
これを使えば支払い方法が未登録なら終了と同時にキャンセルされる!

const subscription = await stripe.subscriptions.create({
  customer: 'cus_XXXXXXXX',
  items: [{ price: 'price_YYYYYYYY' }],
  trial_period_days: 14,
  trial_settings: {
    end_behavior: {
      missing_payment_method: 'cancel'  // または 'pause'
    }
  }
});

console.log(`Subscription created: ${subscription.id}, status: ${subscription.status}`);

🚨トラブルシューティング

🔷 trial_settingsが無効って言われる

→ APIバージョンが古い可能性あり。
 apiVersionを2023-08-16以降にするか、ダッシュボードでデフォルトを最新にする。

🔷 トライアル終了後にキャンセルされない

→ 支払い方法が既に登録されているとキャンセルされない。
 未登録の時だけ動く仕様なので注意!

🔷 トライアル終了通知を送りたい

→ customer.subscription.trial_will_end というWebhookイベントで3日前に通知できる。
 Stripeのダッシュボードでも自動通知メールが設定できるよ。

🌟おわりに

Stripeのトライアル終了後に自動でキャンセルするなら、
trial_settings.end_behavior.missing_payment_method: 'cancel'
をセットするのが一番スマートです!

おまけメモ

  • ユーザーが後で戻れるようにするならpauseもあり
  • トライアル終了前のリマインド通知は忘れずに
  • テスト環境でしっかり動作確認してから本番に
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?