Class: Effective::HelcimApi

Inherits:
Object
  • Object
show all
Defined in:
app/models/effective/helcim_api.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(environment: nil) ⇒ HelcimApi

Returns a new instance of HelcimApi.



16
17
18
19
20
21
22
23
# File 'app/models/effective/helcim_api.rb', line 16

def initialize(environment: nil)
  self.environment = EffectiveOrders.helcim.fetch(:environment)
  self.api_token = EffectiveOrders.helcim.fetch(:api_token)
  self.partner_token = EffectiveOrders.helcim.fetch(:partner_token)
  self.currency = EffectiveOrders.helcim.fetch(:currency)
  self.brand_color = EffectiveOrders.helcim.fetch(:brand_color)
  self.fee_saver = EffectiveOrders.helcim.fetch(:fee_saver)
end

Instance Attribute Details

#api_tokenObject

Returns the value of attribute api_token.



7
8
9
# File 'app/models/effective/helcim_api.rb', line 7

def api_token
  @api_token
end

#brand_colorObject

Returns the value of attribute brand_color.



10
11
12
# File 'app/models/effective/helcim_api.rb', line 10

def brand_color
  @brand_color
end

#currencyObject

Returns the value of attribute currency.



9
10
11
# File 'app/models/effective/helcim_api.rb', line 9

def currency
  @currency
end

#environmentObject

All required



6
7
8
# File 'app/models/effective/helcim_api.rb', line 6

def environment
  @environment
end

#fee_saverObject

Returns the value of attribute fee_saver.



11
12
13
# File 'app/models/effective/helcim_api.rb', line 11

def fee_saver
  @fee_saver
end

#last_responseObject

Returns the value of attribute last_response.



14
15
16
# File 'app/models/effective/helcim_api.rb', line 14

def last_response
  @last_response
end

#partner_tokenObject

Returns the value of attribute partner_token.



8
9
10
# File 'app/models/effective/helcim_api.rb', line 8

def partner_token
  @partner_token
end

#read_timeoutObject

Returns the value of attribute read_timeout.



13
14
15
# File 'app/models/effective/helcim_api.rb', line 13

def read_timeout
  @read_timeout
end

Instance Method Details

#card_info(payment) ⇒ Object

Takes a payment_intent and returns the card info we can store



165
166
167
168
169
170
171
172
173
# File 'app/models/effective/helcim_api.rb', line 165

def card_info(payment)
  # Return the authorization params merged with the card info
  last4 = payment['cardNumber'].to_s.last(4)
  card = payment['cardType'].to_s.downcase

  active_card = "**** **** **** #{last4} #{card}" if last4.present?

  { 'active_card' => active_card, 'card' => card }.compact
end

#decode_payment_payload(payload) ⇒ Object

Decode the base64 encoded JSON object that was given from the form into a Hash



113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'app/models/effective/helcim_api.rb', line 113

def decode_payment_payload(payload)
  return if payload.blank?

  raise('expected a string') unless payload.kind_of?(String)

  payment = (JSON.parse(Base64.decode64(payload)) rescue nil)
  raise('expected payment to be a Hash') unless payment.kind_of?(Hash)

  payment = payment.dig('data', 'data')
  raise('expected payment data') unless payment.kind_of?(Hash)
  raise('expected payment data with a transactionId') unless payment['transactionId'].present?

  payment
end

#get(endpoint, params: nil) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'app/models/effective/helcim_api.rb', line 175

def get(endpoint, params: nil)
  query = ('?' + params.compact.map { |k, v| "$#{k}=#{v}" }.join('&')) if params.present?

  uri = URI.parse(api_url + endpoint + query.to_s)

  http = Net::HTTP.new(uri.host, uri.port)
  http.read_timeout = (read_timeout || 30)
  http.use_ssl = true

  self.last_response = nil

  result = with_retries do
    puts "[GET] #{uri}" if Rails.env.development?

    response = http.get(uri, headers)
    raise Exception.new("#{response.code} #{response.body}") unless response.code == '200'

    response
  end

  self.last_response = result

  JSON.parse(result.body)
end

#get_transaction(id) ⇒ Object



29
30
31
# File 'app/models/effective/helcim_api.rb', line 29

def get_transaction(id)
  get("/card-transactions/#{id}")
end

#health_checkObject



25
26
27
# File 'app/models/effective/helcim_api.rb', line 25

def health_check
  get('/connection-test')
end

#initialize_request(order) ⇒ Object



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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'app/models/effective/helcim_api.rb', line 35

def initialize_request(order)
  params = {
    amount: ('%.2f' % order.total_to_f),
    currency: currency,
    paymentType: 'purchase',   # purchase, preauth, verify
    paymentMethod: (fee_saver ? 'cc-ach' : 'cc'),
    hasConvenienceFee: (fee_saver ? 1 : 0),
    allowPartial: 0,
    taxAmount: ('%.2f' % order.tax_to_f if order.tax.to_i > 0),
    hideExistingPaymentDetails: 0,
    setAsDefaultPaymentMethod: 1,
    confirmationScreen: false,
    displayContactFields: 0,
    customStyling: {
      brandColor: (brand_color || '815AF0')
    },
    invoiceRequest: {
      invoiceNumber: '#' + order.to_param
    },
    customerRequest: {
      contactName: order.billing_name,
      businessName: order.organization.to_s.presence,
    }.compact,
  }.compact

  params[:invoiceRequest][:lineItems] = order.order_items.map do |item|
    {
      description: item.name,
      quantity: item.quantity,
      price: ('%.2f' % item.price_to_f),
      total: ('%.2f' % item.subtotal_to_f),
      taxAmount: ('%.2f' % item.tax_to_f),
    }
  end

  address = order.billing_address
  country = helcim_country(address&.country_code)

  if address.present? && country.to_s.length == 3
    params[:customerRequest][:billingAddress] = {
      name: order.billing_name,
      street1: address.address1,
      street2: address.address2,
      city: address.city,
      province: address.state_code,
      country: country,
      postalCode: address.postal_code,
      email: order.email,
    }
  end

  address = order.shipping_address
  country = helcim_country(address&.country_code)

  if address.present? && country.to_s.length == 3
    params[:customerRequest][:shippingAddress] = {
      name: order.billing_name,
      street1: address.address1,
      street2: address.address2,
      city: address.city,
      province: address.state_code,
      country: country,
      postalCode: address.postal_code,
      email: order.email,
    }
  end

  response = post('/helcim-pay/initialize', params: params)
  raise("expected response to be a Hash") unless response.kind_of?(Hash)

  token = response['checkoutToken']
  raise("expected response to include a checkoutToken") unless token.present?

  # Return the token to the front end form
  token
end

#post(endpoint, params:) ⇒ Object

Raises:

  • (Exception)


200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'app/models/effective/helcim_api.rb', line 200

def post(endpoint, params:)
  uri = URI.parse(api_url + endpoint)

  http = Net::HTTP.new(uri.host, uri.port)
  http.read_timeout = (read_timeout || 30)
  http.use_ssl = true

  self.last_response = nil

  puts "[POST] #{uri} #{params}" if Rails.env.development?

  response = http.post(uri.path, params.to_json, headers)
  raise Exception.new("#{response.code} #{response.body}") unless response.code == '200'

  self.last_response = response

  JSON.parse(response.body)
end

#purchased?(payment) ⇒ Boolean

Returns:

  • (Boolean)


128
129
130
131
# File 'app/models/effective/helcim_api.rb', line 128

def purchased?(payment)
  raise('expected a payment Hash') unless payment.kind_of?(Hash)
  (payment['status'] == 'APPROVED' && payment['type'] == 'purchase')
end

#set_logo!(path: nil) ⇒ Object

Effective::HelcimApi.new.set_logo! Put your file in the apps/tenant/app/assets/images/tenant/helcim-logo.png Run this once to set the logo

Raises:

  • (Exception)


222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'app/models/effective/helcim_api.rb', line 222

def set_logo!(path: nil)
  path ||= Rails.root.join("apps/#{Tenant.current}/app/assets/images/#{Tenant.current}/helcim-logo.png")
  raise("Expected #{path} to exist") unless File.exist?(path)

  url = URI.parse(api_url + '/branding/logo')
  boundary = "AaB03x"

  # Build multipart form data
  body = [
    "--#{boundary}",
    "Content-Disposition: form-data; name=\"logo\"; filename=\"#{File.basename(path)}\"",
    "Content-Type: image/#{File.extname(path).downcase.delete('.')}",
    "",
    File.binread(path),
    "--#{boundary}--"
  ].join("\r\n")

  # Set up HTTP request
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  
  # Create POST request
  request = Net::HTTP::Post.new(url.path)
  request.body = body

  request.initialize_http_header(headers.merge({
    'Content-Type' => "multipart/form-data; boundary=#{boundary}",
    'Content-Length' => request.body.length.to_s,
  }))

  # Send request
  response = http.request(request)
  raise Exception.new("#{response.code} #{response.body}") unless response.code == '200'

  JSON.parse(response.body)
end

#verify_payment(order, payment_payload) ⇒ Object

Considers the insecure payment_payload, requests the real transaction from Helcim and verifies it vs the order



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'app/models/effective/helcim_api.rb', line 134

def verify_payment(order, payment_payload)
  raise('expected a payment_payload Hash') unless payment_payload.kind_of?(Hash)

  transaction_id = payment_payload['transactionId']
  raise('expected a payment_payload with a transactionId') unless transaction_id.present?

  payment = get_transaction(transaction_id)
  raise('expected an existing card-transaction payment') unless payment.kind_of?(Hash)

  # Compare the payment (trusted truth) and the payment_payload (untrusted)
  if payment['transactionId'].to_s != payment_payload['transactionId'].to_s
    raise('expected the payment and payment_payload to have the same transactionId')
  end

  # Validate order ids
  if payment['invoiceNumber'].to_s != '#' + order.to_param
    raise("expected card-transaction invoiceNumber to be the same as the order to_param")
  end

  # Validate amounts if purchased
  if purchased?(payment) && (amount = payment['amount'].to_f) != (amountAuthorized = order.total_to_f)
    raise("expected card-transaction amount #{amount} to be the same as the amountAuthorized #{amountAuthorized} but it was not")
  end

  # Normalize the card info and scrub out the card number
  payment = payment.merge(card_info(payment)).except('cardNumber')

  payment
end