Module: Payola::InvoiceBehavior::ClassMethods

Defined in:
app/services/payola/invoice_behavior.rb

Instance Method Summary collapse

Instance Method Details

#create_sale(subscription, invoice) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
# File 'app/services/payola/invoice_behavior.rb', line 28

def create_sale(subscription, invoice)
  Payola::Sale.new do |s|
    s.email = subscription.email
    s.state = 'processing'
    s.owner = subscription
    s.product = subscription.plan
    s.stripe_token = 'invoice'
    s.amount = invoice.total
    s.currency = invoice.currency
  end
end

#create_sale_from_event(event) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'app/services/payola/invoice_behavior.rb', line 8

def create_sale_from_event(event)
  invoice = event.data.object

  return unless invoice.charge

  subscription = Payola::Subscription.find_by!(stripe_id: invoice.subscription)
  secret_key = Payola.secret_key_for_sale(subscription)

  stripe_sub = Stripe::Customer.retrieve(subscription.stripe_customer_id, secret_key).subscriptions.retrieve(invoice.subscription, secret_key)
  subscription.sync_with!(stripe_sub)

  sale = create_sale(subscription, invoice)

  charge = Stripe::Charge.retrieve(invoice.charge, secret_key)

  update_sale_with_charge(sale, charge, secret_key)

  return sale, charge
end

#update_sale_with_charge(sale, charge, secret_key) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/services/payola/invoice_behavior.rb', line 40

def update_sale_with_charge(sale, charge, secret_key)
  sale.stripe_id  = charge.id
  sale.card_type  = charge.source.brand
  sale.card_last4 = charge.source.last4

  if charge.respond_to?(:fee)
    sale.fee_amount = charge.fee
  elsif !charge.balance_transaction.nil?
    balance = Stripe::BalanceTransaction.retrieve(charge.balance_transaction, secret_key)
    sale.fee_amount = balance.fee
  end
end