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
Decode the base64 encoded JSON object that was given from the form into a Hash For a card transaction “dateCreated”=>“2025-08-15 10:10:32”, “cardBatchId”=>“4656307”, “status”=>“APPROVED”, “type”=>“purchase”, “amount”=>“10.97”, “currency”=>“CAD”, “avsResponse”=>“X”, “cvvResponse”=>“”, “approvalCode”=>“T5E3ST”, “cardToken”=>“gv5J-lJAQNqVjZ_HkXyisQ”, “cardNumber”=>“4242424242”, “cardHolderName”=>“Test User”, “customerCode”=>“CST1022”, “invoiceNumber”=>“#30”, “warning”=>“”.
- #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.
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_token ⇒ Object
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_color ⇒ Object
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 |
#currency ⇒ Object
Returns the value of attribute currency.
9 10 11 |
# File 'app/models/effective/helcim_api.rb', line 9 def currency @currency end |
#environment ⇒ Object
All required
6 7 8 |
# File 'app/models/effective/helcim_api.rb', line 6 def environment @environment end |
#fee_saver ⇒ Object
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_response ⇒ Object
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_token ⇒ Object
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_timeout ⇒ Object
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
#assign_order_charges!(order, payment) ⇒ Object
Adds the order.surcharge if this is a fee saver order
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
# File 'app/models/effective/helcim_api.rb', line 199 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
230 231 232 233 234 235 236 237 238 239 240 |
# File 'app/models/effective/helcim_api.rb', line 230 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
Decode the base64 encoded JSON object that was given from the form into a Hash For a card transaction “dateCreated”=>“2025-08-15 10:10:32”, “cardBatchId”=>“4656307”, “status”=>“APPROVED”, “type”=>“purchase”, “amount”=>“10.97”, “currency”=>“CAD”, “avsResponse”=>“X”, “cvvResponse”=>“”, “approvalCode”=>“T5E3ST”, “cardToken”=>“gv5J-lJAQNqVjZ_HkXyisQ”, “cardNumber”=>“4242424242”, “cardHolderName”=>“Test User”, “customerCode”=>“CST1022”, “invoiceNumber”=>“#30”, “warning”=>“”
For an ACH transaction “batchId”=>“168333, ”dateCreated“=>”2025-10-10 11:48:47“, ”statusAuth“=>”APPROVED“, ”statusClearing“=>”OPENED“, ”type“=>”WITHDRAWAL“, ”amount“=>”1.05“, ”currency“=>”CAD“, ”approvalCode“=>”1232435435“, ”bankAccountNumber“=>”4333434“, ”bankToken“=>”3748uzocio7348“, ”invoiceNumber“=>”#26-1760118464“, ”customerCode“=>”CST0000“
150 151 152 153 154 155 156 157 158 159 160 161 162 |
# File 'app/models/effective/helcim_api.rb', line 150 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
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
# File 'app/models/effective/helcim_api.rb', line 242 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
33 34 35 |
# File 'app/models/effective/helcim_api.rb', line 33 def get_ach_transaction(id) get("/ach/transactions/#{id}").try(:dig, 'transaction') end |
#get_card_transaction(id) ⇒ Object
29 30 31 |
# File 'app/models/effective/helcim_api.rb', line 29 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
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
# File 'app/models/effective/helcim_api.rb', line 174 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
25 26 27 |
# File 'app/models/effective/helcim_api.rb', line 25 def health_check get('/connection-test') end |
#initialize_request(order) ⇒ Object
Make the Preload Request devdocs.helcim.com/reference/checkout-init
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 111 112 113 114 |
# File 'app/models/effective/helcim_api.rb', line 39 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.transaction_id(short: true) }, customerRequest: { contactName: order.billing_name, businessName: order.organization.to_s.presence, }.compact, }.compact params[:invoiceRequest][:lineItems] = order.order_items.map do |item| { description: scrub(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
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
# File 'app/models/effective/helcim_api.rb', line 267 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
164 165 166 167 168 169 170 171 |
# File 'app/models/effective/helcim_api.rb', line 164 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
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 324 |
# File 'app/models/effective/helcim_api.rb', line 289 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
215 216 217 218 219 220 221 222 223 224 225 226 227 |
# File 'app/models/effective/helcim_api.rb', line 215 def verify_payment!(order, payment) # Validate order ids if payment['invoiceNumber'].present? && !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 |