Class: Pay::Asaas::Customer

Inherits:
Customer
  • Object
show all
Defined in:
lib/pay/asaas/customer.rb

Instance Method Summary collapse

Instance Method Details

#api_recordObject



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/pay/asaas/customer.rb', line 29

def api_record
  if processor_id?
    Pay::Asaas::Api::Customer.find(id: processor_id)
  else
    customer_response = Pay::Asaas::Api::Customer.create(params: api_record_attributes)
    update!(processor_id: customer_response["id"])
    customer_response
  end
rescue ApiClient::ApiError => e
  Rails.logger.error "[Pay] Error creating Asaas customer: #{e.message}"
  raise Pay::Asaas::Error, e.message
end

#api_record_attributesObject

Raises:

  • (StandardError)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/pay/asaas/customer.rb', line 11

def api_record_attributes
  document = if owner.respond_to?(:document)
    owner.document
  elsif owner.respond_to?(:cpf)
    owner.cpf
  elsif owner.respond_to?(:cnpj)
    owner.cnpj
  else
    raise StandardError, "The document attribute, and it's alternatives are not implemented for #{owner.class}"
  end

  raise StandardError, "The document attribute is required" if document.nil?

  document = document.gsub(/[^\d]/, "")

  { email: email, name: customer_name, cpfCnpj: document, externalReference: owner.id }
end

#charge(amount, options = {}) ⇒ Object

Charges only for pix right now



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/pay/asaas/customer.rb', line 48

def charge(amount, options = {})
  # Setup the customer's default payment method
  params = {
    billingType: "PIX",
    dueDate: Time.zone.today.to_s,
    value: amount / 100.0, # Asaas expects a float
  }.merge(options)
    .merge(customer: processor_id || api_record["id"]) # Merge last to not let override customer

  transaction = Pay::Asaas::Api::Payment.create(params: params)

  attrs = {
    amount: amount,
    payment_method_type: "pix",
  }

  attrs = attrs.merge(options[:attrs]) if options[:attrs]

  charge = charges.find_or_initialize_by(processor_id: transaction["id"])
  charge.update(attrs)
  charge
rescue ApiClient::ApiError => e
  Rails.logger.error "[Pay] Error creating Asaas charge: #{e.message}"
  raise Pay::Asaas::Error, e.message
end

#update_api_record(**attributes) ⇒ Object



42
43
44
45
# File 'lib/pay/asaas/customer.rb', line 42

def update_api_record(**attributes)
  api_record unless processor_id?
  Pay::Asaas::Api::Customer.update!(id: processor_id, params: api_record_attributes.merge(attributes))
end