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 “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_payment(order, payment_payload) ⇒ Object
Considers the insecure payment_payload, requests the real transaction from Helcim and verifies it vs the order.
- #get_transaction(id) ⇒ Object
- #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
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
# File 'app/models/effective/helcim_api.rb', line 175 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
206 207 208 209 210 211 212 213 214 215 216 |
# File 'app/models/effective/helcim_api.rb', line 206 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 card = 'ACH' if card.blank? && payment['bankToken'].present? 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 “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”=>“”
129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
# File 'app/models/effective/helcim_api.rb', line 129 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
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 |
# File 'app/models/effective/helcim_api.rb', line 218 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_payment(order, payment_payload) ⇒ Object
Considers the insecure payment_payload, requests the real transaction from Helcim and verifies it vs the order
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
# File 'app/models/effective/helcim_api.rb', line 154 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 = 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 # Normalize the card info and scrub out the card number payment = payment.merge(card_info(payment)).except('cardNumber') payment 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_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
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.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: 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
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
# File 'app/models/effective/helcim_api.rb', line 243 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
144 145 146 147 148 149 150 151 |
# File 'app/models/effective/helcim_api.rb', line 144 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['bankToken'].present? && payment['type'] == 'WITHDRAWAL') # 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
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
# File 'app/models/effective/helcim_api.rb', line 265 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
191 192 193 194 195 196 197 198 199 200 201 202 203 |
# File 'app/models/effective/helcim_api.rb', line 191 def verify_payment!(order, payment) # Validate order ids unless payment['invoiceNumber'].to_s.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 |