Skip to content

Instantly share code, notes, and snippets.

@siong1987
Created October 24, 2014 18:31
Show Gist options
  • Save siong1987/97b5d8f083675f5641de to your computer and use it in GitHub Desktop.
Save siong1987/97b5d8f083675f5641de to your computer and use it in GitHub Desktop.
Stripe MRR Calculation
require 'stripe'
require 'ostruct'
# modified from: https://gist.github.com/jacobpatton/a68d228bf2414852d862
#
# puts Stripe::Mrr.new(api_key: 'api_key').mrr
#
module Stripe
class Mrr
attr_reader :api_key
def initialize(args = {})
raise ArgumentError, ":api_key is a required argument" unless args[:api_key]
@api_key = args[:api_key]
Stripe.api_key = @api_key
@charges = []
@time = Time.now.to_i
end
def mrr
subscriptions.inject(0) do |sum, subscription|
amount, interval = subscription.amount, subscription.interval
amount = amount / 12 if interval == 'year'
sum + amount
end
end
def charges
fetch_charges if @charges.empty?
@charges
end
def subscriptions
charges.inject([]) do |collection, charge|
puts charge.id
next collection unless charge.paid
next collection if charge.invoice.nil?
puts charge.invoice
invoice = Stripe::Invoice.retrieve(charge.invoice)
subscription = invoice.lines.data.find {|l| l.type == 'subscription'}
if subscription.nil?
puts 'no subscription'
next collection
end
next collection unless subscription.period.end > @time
collection.concat([OpenStruct.new(amount: invoice.amount_due, interval: subscription.plan.interval)])
end
end
private
def fetch_charges(opts = {})
opts = {limit: 100}.merge!(opts)
collection = Stripe::Charge.all(opts)
@charges.concat(collection.data)
fetch_charges(starting_after: @charges.last.id) if collection.has_more
end
end
end
@bcackerman
Copy link

I did a puts invoice.lines.data right before the error and this is the output

#<Stripe::StripeObject:0x3fd8bec477ec> JSON: {
  "subscriptions": [
    {"id":"sub_4lBuQuiFO22JLs","object":"line_item","type":"subscription","livemode":true,"amount":4900,"currency":"usd","proration":false,"period":{"start":1415742863,"end":1418334863},"subscription":null,"quantity":1,"plan":{"id":"simple","interval":"month","name":"Simple","created":1390971289,"amount":4900,"currency":"usd","object":"plan","livemode":true,"interval_count":1,"metadata":{},"statement_description":null},"description":null,"metadata":{}}
  ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment