Created
October 24, 2014 18:31
-
-
Save siong1987/97b5d8f083675f5641de to your computer and use it in GitHub Desktop.
Stripe MRR Calculation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I did a
puts invoice.lines.data
right before the error and this is the output