-
-
Save bcackerman/8ee448e01012689abc22 to your computer and use it in GitHub Desktop.
Stripe Monthly Recurring Revenue (MRR) Calculator
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 & fixed for more subscription based Stripe account from: https://gist.github.com/jacobpatton/a68d228bf2414852d862 | |
# | |
# puts Stripe::Mrr.new(api_key: 'api_key').report | |
# | |
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 arr | |
mrr * 12 | |
end | |
def report | |
puts "MRR: $#{mrr / 100} \n ARR: $#{arr / 100}" | |
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['subscriptions'].first | |
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