SaaS / FaaSStripe

How to replace Subscription interval on Stripe Billings

When you have any web service with a subscription, we usually want to provide several interval plans like mont […]

広告ここから
広告ここまで

When you have any web service with a subscription, we usually want to provide several interval plans like monthly and annual.

If you using Stripe billing, we can change the subscription interval by the following code.

const changeSubscriptionInterval = async (subscriptionId: string, priceId: string) => {
  const stripe = new Stripe('KEY', {
    apiVersion: '2020-03-02'
  })
  const subscription = await stripe.subscriptions.retrieve(subscriptionId)
  if (subscription.quantity < 2) {

    const itemCount = subscription.items.data.reduce((prev, current) => {
      return prev + current.quantity
    }, 0)

    if (itemCount < 2) {
      await stripe.subscriptions.update(subscriptionId, {
        items: [{
          id: subscription.items.data[0].id,
          deleted: true,
        }, {
          price: priceId,
          quantity: 1,
        }]
      })
    }

  }
  /**
   * Should write another process to change interval
   * - 1. reduce current subscription item quantity
   * - 2. add new subscription or subscription item with same interval one
   */
...

Tips: use deleted attribute to remove subscription item in subscriptions.update

If you want to remove a subscription item from subscription, we can remove it by using stripe.subscriptionItems.del method.

But when the subscription’s item and quantity are only one, we can not use the method by the following error.

A subscription must have at least one active plan. To cancel a subscription, please use the cancel API endpoint on /v1/subscriptions.

When you want to change the interval, we have to remove the current subscription item and add a new subscription item. So if you cannot use subscriptionItems.del, we need to use subscriptions.update instead. And the method can use deleted attribute to remove the item.

      await stripe.subscriptions.update(subscriptionId, {
        items: [{
          id: subscription.items.data[0].id,
          deleted: true,
        }, {
          price: priceId,
          quantity: 1,
        }]

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts