Skip to content

Instantly share code, notes, and snippets.

@iloveitaly
Created January 31, 2018 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iloveitaly/e56a9487dfa85e08bdf63bfcfcd68dad to your computer and use it in GitHub Desktop.
Save iloveitaly/e56a9487dfa85e08bdf63bfcfcd68dad to your computer and use it in GitHub Desktop.
Example of using Stripe Subscriptions to manage simplistic usage based billing
# Mike Bianco <mike@suitesync.io>
# Description: Example of using Stripe Subscriptions to manage simplistic usage based billing
# Link: https://gist.github.com/iloveitaly/e56a9487dfa85e08bdf63bfcfcd68dad
require 'stripe'
Stripe.api_key = ENV['STRIPE_KEY']
plan = (Stripe::Plan.retrieve('example-usage-plan') rescue nil)
if !plan
plan = Stripe::Plan.create(
id: 'example-usage-plan',
name: 'Example Usage Based Billing Plan',
amount: 10_00,
interval: 'month',
currency: 'usd',
)
end
# create customer and attach a payment option
customer = Stripe::Customer.create
customer.sources.create(source: 'tok_visa')
# create the initial subscription with a quantity of 2
subscription = customer.subscriptions.create(
quantity: 2,
plan: plan.id
)
# wait a minute, a day, week, etc until the user requests a plan change
sleep(60)
# update the quantity on the plan. Stripe manages proration easily
subscription.quantity = 3
subscription.save
# take a look at the customer in Stripe to visually see how the subscriptions are created
puts "Customer: #{customer.id}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment