Class: Effective::HelcimApi
- Inherits:
-
Object
- Object
- Effective::HelcimApi
- Defined in:
- app/models/effective/helcim_api.rb
Instance Attribute Summary collapse
-
#api_token ⇒ Object
Returns the value of attribute api_token.
-
#brand_color ⇒ Object
Returns the value of attribute brand_color.
-
#currency ⇒ Object
Returns the value of attribute currency.
-
#environment ⇒ Object
All required.
-
#fee_saver ⇒ Object
Returns the value of attribute fee_saver.
-
#last_response ⇒ Object
Returns the value of attribute last_response.
-
#partner_token ⇒ Object
Returns the value of attribute partner_token.
-
#read_timeout ⇒ Object
Returns the value of attribute read_timeout.
Instance Method Summary collapse
-
#assign_order_charges!(order, payment) ⇒ Object
Adds the order.surcharge if this is a fee saver order.
-
#card_info(payment) ⇒ Object
Takes a payment_intent and returns the card info we can store.
-
#decode_payment_payload(payload) ⇒ Object
When the payment is aborted, the decoded payload is a string with the error “HelcimPay.js transaction aborted - "Transaction declined.
- #get(endpoint, params: nil) ⇒ Object
- #get_ach_transaction(id) ⇒ Object
- #get_card_transaction(id) ⇒ Object
-
#get_payment(order, payment_payload) ⇒ Object
Considers the insecure payment_payload, requests the real transaction from Helcim and verifies it vs the order.
- #health_check ⇒ Object
-
#initialize(environment: nil) ⇒ HelcimApi
constructor
A new instance of HelcimApi.
-
#initialize_request(order) ⇒ Object
Make the Preload Request devdocs.helcim.com/reference/checkout-init.
- #post(endpoint, params:) ⇒ Object
- #purchased?(payment) ⇒ Boolean
-
#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.
- #verify_payment!(order, payment) ⇒ Object
Constructor Details
#initialize(environment: nil) ⇒ HelcimApi
Returns a new instance of HelcimApi.
18 19 20 21 22 23 24 25 |
# File 'app/models/effective/helcim_api.rb', line 18 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_token ⇒ Object
Returns the value of attribute api_token.
9 10 11 |
# File 'app/models/effective/helcim_api.rb', line 9 def api_token @api_token end |
#brand_color ⇒ Object
Returns the value of attribute brand_color.
12 13 14 |
# File 'app/models/effective/helcim_api.rb', line 12 def brand_color @brand_color end |
#currency ⇒ Object
Returns the value of attribute currency.
11 12 13 |
# File 'app/models/effective/helcim_api.rb', line 11 def currency @currency end |
#environment ⇒ Object
All required
8 9 10 |
# File 'app/models/effective/helcim_api.rb', line 8 def environment @environment end |
#fee_saver ⇒ Object
Returns the value of attribute fee_saver.
13 14 15 |
# File 'app/models/effective/helcim_api.rb', line 13 def fee_saver @fee_saver end |
#last_response ⇒ Object
Returns the value of attribute last_response.
16 17 18 |
# File 'app/models/effective/helcim_api.rb', line 16 def last_response @last_response end |
#partner_token ⇒ Object
Returns the value of attribute partner_token.
10 11 12 |
# File 'app/models/effective/helcim_api.rb', line 10 def partner_token @partner_token end |
#read_timeout ⇒ Object
Returns the value of attribute read_timeout.
15 16 17 |
# File 'app/models/effective/helcim_api.rb', line 15 def read_timeout @read_timeout end |
Instance Method Details
#assign_order_charges!(order, payment) ⇒ Object
Adds the order.surcharge if this is a fee saver order
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 |
# File 'app/models/effective/helcim_api.rb', line 198 def assign_order_charges!(order, payment) raise('expected an order') unless order.kind_of?(Effective::Order) raise('expected a payment Hash') unless payment.kind_of?(Hash) return unless EffectiveOrders.fee_saver? # Validate amounts if purchased amount = payment['amount'].to_f amountAuthorized = order.total_to_f surcharge = ((amount - amountAuthorized) * 100.0).round(0) raise('expected surcharge to be a positive number') if surcharge < 0 order.update!(surcharge: surcharge) end |
#card_info(payment) ⇒ Object
Takes a payment_intent and returns the card info we can store
229 230 231 232 233 234 235 236 237 238 239 |
# File 'app/models/effective/helcim_api.rb', line 229 def card_info(payment) # Return the authorization params merged with the card info last4 = (payment['cardNumber'] || payment['bankAccountL4L4']).to_s.last(4) card = payment['cardType'].to_s.downcase card = 'ACH' if card.blank? && payment['bankAccountId'].present? active_card = "**** **** **** #{last4} #{card}".strip if last4.present? { 'active_card' => active_card, 'card' => card }.compact end |
#decode_payment_payload(payload) ⇒ Object
When the payment is aborted, the decoded payload is a string with the error “HelcimPay.js transaction aborted - "Transaction declined. DECLINED - Do Not Honor"
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
# File 'app/models/effective/helcim_api.rb', line 142 def decode_payment_payload(payload) return if payload.blank? raise('expected a string') unless payload.kind_of?(String) decoded = (Base64.decode64(payload) rescue nil) payment = (JSON.parse(decoded) rescue nil) if payment.blank? && decoded.to_s.downcase.include?('declined') return :declined end raise('expected payment to be a Hash') unless payment.kind_of?(Hash) || payment.blank? return payment if payment.blank? 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
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
# File 'app/models/effective/helcim_api.rb', line 241 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_ach_transaction(id) ⇒ Object
35 36 37 |
# File 'app/models/effective/helcim_api.rb', line 35 def get_ach_transaction(id) get("/ach/transactions/#{id}").try(:dig, 'transaction') end |
#get_card_transaction(id) ⇒ Object
31 32 33 |
# File 'app/models/effective/helcim_api.rb', line 31 def get_card_transaction(id) get("/card-transactions/#{id}") end |
#get_payment(order, payment_payload) ⇒ Object
Considers the insecure payment_payload, requests the real transaction from Helcim and verifies it vs the order
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
# File 'app/models/effective/helcim_api.rb', line 173 def get_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 = if payment_payload['cardBatchId'].present? && payment_payload['type'].to_s.downcase == 'purchase' get_card_transaction(transaction_id) elsif payment_payload['batchId'].present? && payment_payload['type'].to_s.downcase == 'withdrawal' get_ach_transaction(transaction_id) end raise("expected an existing card-transaction or ach-transaction payment with params #{payment_payload}") unless payment.kind_of?(Hash) unless (payment['transactionId'].to_s == payment_payload['transactionId'].to_s) || (payment['id'].to_s == payment_payload['transactionId'].to_s) raise('expected the payment and payment_payload to have the same transactionId') end # Normalize the card info and scrub out the card number payment = payment.merge(card_info(payment)).except('cardNumber') payment end |
#health_check ⇒ Object
27 28 29 |
# File 'app/models/effective/helcim_api.rb', line 27 def health_check get('/connection-test') end |
#initialize_request(order) ⇒ Object
Make the Preload Request devdocs.helcim.com/reference/checkout-init
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 |
# File 'app/models/effective/helcim_api.rb', line 41 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') }, customerRequest: { contactName: order.billing_name, businessName: order.organization.to_s.presence, }.compact }.compact 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
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
# File 'app/models/effective/helcim_api.rb', line 266 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
163 164 165 166 167 168 169 170 |
# File 'app/models/effective/helcim_api.rb', line 163 def purchased?(payment) raise('expected a payment Hash') unless payment.kind_of?(Hash) return true if (payment['status'] == 'APPROVED' && payment['type'] == 'purchase') # CC return true if (payment['bankAccountId'].present? && payment['responseMessage'].to_s.downcase == 'approved') # ACH false 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
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
# File 'app/models/effective/helcim_api.rb', line 288 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) ⇒ Object
214 215 216 217 218 219 220 221 222 223 224 225 226 |
# File 'app/models/effective/helcim_api.rb', line 214 def verify_payment!(order, payment) # Validate order ids if payment['invoiceNumber'].to_s.start_with?('#') && !payment['invoiceNumber'].start_with?('#' + 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 payment end |