#Stripe API / Subscription Schedule / Update end date / cancel Subscription / proration adjustment in Upcoming invoice / Ruby code exeample

# Docs

https://stripe.com/docs/billing/subscriptions/subscription-schedules
https://stripe.com/docs/billing/subscriptions/subscription-schedules/use-cases
https://stripe.com/docs/api/subscription_schedules/release
https://support.stripe.com/questions/create-update-and-schedule-subscriptions

# Code

```rb

require 'stripe'

Stripe::api_key = ENV['STRIPE_SECRET_KEY']

product1 = Stripe::Product.create(name: "Gold plan #{rand(9999999999)}")
plan1 = Stripe::Plan.create(interval: 'day', currency: 'jpy', amount: 5000, product: product1.id, usage_type: 'licensed')

tax_rate = Stripe::TaxRate.create(display_name: 'Tax Rate', percentage: 10.0, inclusive: false)
customer = Stripe::Customer.create
payment_method = Stripe::PaymentMethod.create(type: 'card', card: { number: '4242424242424242', exp_year: 2030, exp_month: 01})
customer_payment_method = Stripe::PaymentMethod.attach(payment_method.id, customer: customer.id)

def put_subscription_schedule(subscription_schedule, message)
  puts '-' * 100
  puts "Subscription Schedule"
  puts message
  puts '-' * 100
  puts subscription_schedule
  puts '-' * 100
  puts "https://dashboard.stripe.com/test/subscription_schedules/#{subscription_schedule.id}"
end

# https://stripe.com/docs/api/subscription_schedules/create
subscription_schedule = Stripe::SubscriptionSchedule.create(
  {
    customer: customer.id,
    start_date: Time.now.to_i + 5,
    default_settings: {
      default_payment_method: customer_payment_method.id,
    },
    phases: [
      {
        plans:
          [
            { plan: plan1.id, quantity: 1 },
          ],
        default_tax_rates: [tax_rate],
      },
    ],
  }
)
put_subscription_schedule(subscription_schedule, 'CREATED')

puts '-' * 100
puts "Wait until subscription schedule starts"
puts '-' * 100
until subscription_schedule.status == 'active' do
  subscription_schedule = Stripe::SubscriptionSchedule.retrieve(subscription_schedule.id)
  puts subscription_schedule.status
  sleep 2
end


def update_subscription_schedule(base_subscription_schedule, end_from_start_date: )
  Stripe::SubscriptionSchedule.update(
    base_subscription_schedule.id,
    {
      end_behavior: 'cancel',
      phases: [
        {
          plans:
            [
              {
                plan:     base_subscription_schedule.phases[0].plans[0].plan,
                quantity: base_subscription_schedule.phases[0].plans[0].quantity
              },
            ],
          default_tax_rates: [base_subscription_schedule.phases[0].default_tax_rates[0].id],
          start_date: base_subscription_schedule.phases[0].start_date,
          end_date: base_subscription_schedule.phases[0].start_date + end_from_start_date
        },
      ]
    }
  )
end


# STEP A
# Set subscrition canceled in one day, fit to plan natural cycle "day"
# It cancel Upcoming invoice 
# It does not create proration adjustment or Upcoming invoice
#  Because subscription schedule cycle is smart finishing.
#
# Happens events kinds are ...
#  subscription_schedule.updated
updated_subscription_schedule = update_subscription_schedule(subscription_schedule, end_from_start_date: 24*60*60)
put_subscription_schedule(updated_subscription_schedule, 'UPDATED')

# STEP B
# Set subscrition canceled in half a day.
# Not wait natural plan interval end.
# It makes proration adjustment half price of plan in Upcoming invoice.
#
#   Unused time on Gold plan xxxxxxxx after 02 Jan 2020 / 1 / -¥2,500
#
#   Subtotal -¥2,500
#   Tax Rate (10%) -¥250
#   Total -¥2,750
#   Applied balance ¥2,750
#   Amount due ¥0
#
# Happens events kinds are ...
#   subscription_schedule.updated
#   customer.subscription.updated
#   invoiceitem.created
updated_subscription_schedule = update_subscription_schedule(subscription_schedule, end_from_start_date: 12*60*60)
put_subscription_schedule(updated_subscription_schedule, 'UPDATED')

# STEP C
# Set subscription back natural full ony day.
# It makes Upcoming Invoice plice zero
#
#   Time on Gold plan xxxxxxxx after 02 Jan 2020 / 1 / ¥2,500
#   Unused time on Gold plan xxxxxxxx after 02 Jan 2020 / 1 / -¥2,500
#
#   Subtotal ¥0
#   Tax Rate (10%) ¥0
#   Total ¥0
#   Amount due ¥0
updated_subscription_schedule = update_subscription_schedule(subscription_schedule, end_from_start_date: 24*60*60)
put_subscription_schedule(updated_subscription_schedule, 'UPDATED')

# STEP D
#   Gold plan 5392253972 / 1 / ¥5,000 / ¥5,000
#   Unused time on Gold plan 5392253972 after 02 Jan 2020 / 1 / -¥2,500
#
#   Subtotal ¥2,500
#   Tax Rate (10%) ¥250
#   Total ¥2,750
#   Amount due ¥2,750
updated_subscription_schedule = update_subscription_schedule(subscription_schedule, end_from_start_date: 36*60*60)
put_subscription_schedule(updated_subscription_schedule, 'UPDATED')

```

# BEFORE UPDATE

No ends day

![image](https://user-images.githubusercontent.com/13635059/71647420-2b896880-2d3a-11ea-96fe-80bd5d62024b.png)

# STEP A

Ends was set

![image](https://user-images.githubusercontent.com/13635059/71647438-54a9f900-2d3a-11ea-8809-d4e27f9b8436.png)



# STEP B

Upcoming invoice occurs

![image](https://user-images.githubusercontent.com/13635059/71647445-6e4b4080-2d3a-11ea-9b55-b2cccb7200ea.png)


# STEP C

next Upcoming invoice occurs

![image](https://user-images.githubusercontent.com/13635059/71647457-84f19780-2d3a-11ea-82d2-ec96fbb43f1f.png)

# STEP D

![image](https://user-images.githubusercontent.com/13635059/71647468-bc604400-2d3a-11ea-9470-410ab279bda5.png)


# Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/2908








<!-- Update From Qiita API -->

# チャットメンバー募集


何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ





# Twitter


https://twitter.com/YumaInaura


<!-- Update From Qiita API -->