Class: StripeEventProcessor

Inherits:
Object
  • Object
show all
Defined in:
app/controllers/concerns/stripe_event_processor.rb

Class Method Summary collapse

Class Method Details

.payment_intent_succeeded(object, event) ⇒ Object



2
3
4
5
6
7
8
9
10
11
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
# File 'app/controllers/concerns/stripe_event_processor.rb', line 2

def self.payment_intent_succeeded(object, event)
  id_key = event[:id]

  method_id = object[:payment_method]
  method = Stripe::PaymentMethod.retrieve(method_id)
  billing_details = method[:billing_details]

  user = if object[:metadata][:user_id].present?
           User.find(object[:metadata][:user_id])
         end

  customer = if user.present? && user.cid.present?
               begin
                 Stripe::Customer.retrieve(user.cid)
               rescue Stripe::InvalidRequestError
                 Stripe::Customer.create({ name: billing_details[:name], email: billing_details[:email],
                                           description: user.present? ? user.username : 'anonymous donor',
                                           metadata: { user_id: user&.id } },
                                         { idempotency_key: id_key })
               end
             else
               existing = Stripe::Customer.list({ email: billing_details[:email] })[:data]
               if existing.empty?
                 Stripe::Customer.create({ name: billing_details[:name], email: billing_details[:email],
                                           description: user.present? ? user.username : 'anonymous donor',
                                           metadata: { user_id: user&.id } },
                                         { idempotency_key: id_key })
               else
                 existing[0]
               end
             end

  if user.present? && user.cid != customer.id
    user.update(cid: customer.id)
  end

  cust_methods = Stripe::PaymentMethod.list({ customer: customer.id, type: 'card' })[:data]

  if method.customer.present?
    method.detach
  end

  if !cust_methods.empty? && cust_methods.any? { |pm| pm[:card][:fingerprint] == method[:card][:fingerprint] }
    "Already attached (#{method[:card][:fingerprint]})."
  elsif object[:setup_future_usage].present?
    method.attach({ customer: customer.id })
    'Attached.'
  else
    'Future not set up, unable to attach.'
  end
end