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,
            }]

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

    Random posts

    Home
    Search
    Bookmark