Class: Pay::PaddleBilling::Charge

Inherits:
Object
  • Object
show all
Defined in:
lib/pay/lemon_squeezy/charge.rb,
lib/pay/paddle_billing/charge.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pay_charge) ⇒ Charge

Returns a new instance of Charge.



8
9
10
# File 'lib/pay/lemon_squeezy/charge.rb', line 8

def initialize(pay_charge)
  @pay_charge = pay_charge
end

Instance Attribute Details

#pay_chargeObject (readonly)

Returns the value of attribute pay_charge.



4
5
6
# File 'lib/pay/lemon_squeezy/charge.rb', line 4

def pay_charge
  @pay_charge
end

Class Method Details

.sync(charge_id, object: nil, try: 0, retries: 1) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/pay/lemon_squeezy/charge.rb', line 12

def self.sync(charge_id, object: nil, try: 0, retries: 1)
  # Skip loading the latest charge details from the API if we already have it
  object ||= ::Paddle::Transaction.retrieve(id: charge_id)

  # Ignore transactions that aren't completed
  return unless object.status == "completed"

  # Ignore charges without a Customer
  return if object.customer_id.blank?

  pay_customer = Pay::Customer.find_by(processor: :paddle_billing, processor_id: object.customer_id)
  return unless pay_customer

  # Ignore transactions that are payment method changes
  # But update the customer's payment method
  if object.origin == "subscription_payment_method_change"
    Pay::PaddleBilling::PaymentMethod.sync(pay_customer: pay_customer, attributes: object.payments.first)
    return
  end

  attrs = {
    amount: object.details.totals.grand_total,
    created_at: object.created_at,
    currency: object.currency_code,
    metadata: object.details.line_items&.first&.id,
    subscription: pay_customer.subscriptions.find_by(processor_id: object.subscription_id)
  }

  if object.payment
    case object.payment.method_details.type.downcase
    when "card"
      attrs[:payment_method_type] = "card"
      attrs[:brand] = details.card.type
      attrs[:exp_month] = details.card.expiry_month
      attrs[:exp_year] = details.card.expiry_year
      attrs[:last4] = details.card.last4
    when "paypal"
      attrs[:payment_method_type] = "paypal"
    end

    # Update customer's payment method
    Pay::PaddleBilling::PaymentMethod.sync(pay_customer: pay_customer, attributes: object.payments.first)
  end

  # Update or create the charge
  if (pay_charge = pay_customer.charges.find_by(processor_id: object.id))
    pay_charge.with_lock do
      pay_charge.update!(attrs)
    end
    pay_charge
  else
    pay_customer.charges.create!(attrs.merge(processor_id: object.id))
  end
end