Add EveryPay payments

* Refactor BankLink into Payments::BankLink, add Payments::EveryPay
* Write tests for existing invoice views
* Write basic tests for Payments module
This commit is contained in:
Maciej Szlosarczyk 2018-04-11 11:55:52 +03:00
parent f7c2b25a66
commit c5591b4828
No known key found for this signature in database
GPG key ID: 41D62D42D3B0D765
32 changed files with 818 additions and 31 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View file

@ -0,0 +1,8 @@
class Registrar
module Payments
class CallbacksController < BaseController
def new
end
end
end
end

View file

@ -0,0 +1,29 @@
class Registrar
module Payments
class EveryPayController < BaseController
load_resource class: Invoice
skip_authorization_check only: [:new, :update]
skip_before_action :verify_authenticity_token, only: :update
def new
set_invoice
@every_pay = EveryPayPayment.new(@invoice)
end
def create
set_invoice
end
def update
set_invoice
render 'complete'
end
private
def set_invoice
@invoice = Invoice.find(params[:invoice_id])
end
end
end
end

View file

@ -4,27 +4,35 @@ class Registrar
skip_authorization_check # actually anyone can pay, no problems at all
skip_before_action :authenticate_user!, :check_ip_restriction, only: [:back]
before_action :check_bank
# before_action :check_bank
# to handle existing model we should
# get invoice_id and then get number
# build BankTransaction without connection with right reference number
# do not connect transaction and invoice
# TODO: Refactor to :new
def pay
invoice = Invoice.find(params[:invoice_id])
@bank_link = BankLink::Request.new(params[:bank], invoice, self)
@bank_link.make_transaction
opts = {
return_url: self.registrar_return_payment_with_url(params[:bank], invoice_id: invoice.id),
response_url: self.registrar_return_payment_with_url(params[:bank])
}
@payment = ::Payments.create_with_type(params[:bank], invoice, opts)
@payment.create_transaction
end
# connect invoice and transaction
# both back and IPN
# TODO: Refactor to be restful
def back
@bank_link = BankLink::Response.new(params[:bank], params)
if @bank_link.valid? && @bank_link.ok?
@bank_link.complete_payment
invoice = Invoice.find(params[:invoice_id])
opts = { response: params }
@payment = ::Payments.create_with_type(params[:bank], invoice, opts)
if @payment.valid_response? && @payment.settled_payment?
@payment.complete_transaction
if @bank_link.invoice.binded?
if invoice.binded?
flash[:notice] = t(:pending_applied)
else
flash[:alert] = t(:something_wrong)
@ -32,14 +40,14 @@ class Registrar
else
flash[:alert] = t(:something_wrong)
end
redirect_to registrar_invoice_path(@bank_link.invoice)
redirect_to registrar_invoice_path(invoice)
end
private
def banks
ENV['payments_banks'].split(",").map(&:strip)
end
# def banks
# ENV['payments_banks'].split(",").map(&:strip)
# end
def check_bank
raise StandardError.new("Not Implemented bank") unless banks.include?(params[:bank])

View file

@ -94,13 +94,13 @@ class BankLink
def complete_payment
if valid?
transaction = BankTransaction.find_by(description: params["VK_MSG"])
transaction.sum = BigDecimal.new(params["VK_AMOUNT"].to_s)
transaction = BankTransaction.find_by(description: params["VK_MSG"])
transaction.sum = BigDecimal.new(params["VK_AMOUNT"].to_s)
transaction.bank_reference = params['VK_T_NO']
transaction.buyer_bank_code = params["VK_SND_ID"]
transaction.buyer_iban = params["VK_SND_ACC"]
transaction.buyer_name = params["VK_SND_NAME"]
transaction.paid_at = Time.parse(params["VK_T_DATETIME"])
transaction.buyer_iban = params["VK_SND_ACC"]
transaction.buyer_name = params["VK_SND_NAME"]
transaction.paid_at = Time.parse(params["VK_T_DATETIME"])
transaction.save!
transaction.autobind_invoice

15
app/models/payments.rb Normal file
View file

@ -0,0 +1,15 @@
module Payments
PAYMENT_METHODS = ENV['payment_methods'].strip.split(', ').freeze
PAYMENT_BANKLINK_BANKS = ENV['payment_banklink_banks'].strip.split(', ').freeze
def self.create_with_type(type, invoice, opts = {})
fail ArgumentError unless PAYMENT_METHODS.include?(type)
if PAYMENT_BANKLINK_BANKS.include?(type)
BankLink.new(type, invoice, opts)
elsif type == 'every_pay'
# TODO: refactor to be variable
EveryPay.new(type, invoice, opts)
end
end
end

View file

@ -0,0 +1,108 @@
module Payments
class BankLink < Base
# TODO: Remove magic numbers, convert certain fields to proper constants
# TODO: Remove hashrockets
def form_fields
@fields ||= (hash = {}
hash["VK_SERVICE"] = "1012"
hash["VK_VERSION"] = "008"
hash["VK_SND_ID"] = seller_account
hash["VK_STAMP"] = invoice.number
hash["VK_AMOUNT"] = number_with_precision(invoice.sum_cache, :precision => 2, :separator => ".")
hash["VK_CURR"] = invoice.currency
hash["VK_REF"] = ""
hash["VK_MSG"] = invoice.order
hash["VK_RETURN"] = return_url
hash["VK_CANCEL"] = return_url
hash["VK_DATETIME"] = Time.now.strftime("%Y-%m-%dT%H:%M:%S%z")
hash["VK_MAC"] = calc_mac(hash)
hash["VK_ENCODING"] = "UTF-8"
hash["VK_LANG"] = "ENG"
hash)
end
def valid_response?
return false unless response
case response["VK_SERVICE"]
when "1111"
validate_success && validate_amount && validate_currency
when "1911"
validate_cancel
else
false
end
end
private
def validate_success
pars = %w(VK_SERVICE VK_VERSION VK_SND_ID VK_REC_ID VK_STAMP VK_T_NO VK_AMOUNT VK_CURR
VK_REC_ACC VK_REC_NAME VK_SND_ACC VK_SND_NAME VK_REF VK_MSG VK_T_DATETIME).freeze
@validate_success ||= (
data = pars.map{|e| prepend_size(response[e]) }.join
verify_mac(data, response["VK_MAC"])
)
end
def validate_cancel
pars = %w(VK_SERVICE VK_VERSION VK_SND_ID VK_REC_ID VK_STAMP VK_REF VK_MSG).freeze
@validate_cancel ||= (
data = pars.map{|e| prepend_size(response[e]) }.join
verify_mac(data, response["VK_MAC"])
)
end
def validate_amount
source = number_with_precision(BigDecimal.new(response["VK_AMOUNT"].to_s), precision: 2, separator: ".")
target = number_with_precision(invoice.sum_cache, precision: 2, separator: ".")
source == target
end
def validate_currency
invoice.currency == response["VK_CURR"]
end
def sign(data)
private_key = OpenSSL::PKey::RSA.new(File.read(seller_certificate))
signed_data = private_key.sign(OpenSSL::Digest::SHA1.new, data)
signed_data = Base64.encode64(signed_data).gsub(/\n|\r/, '')
signed_data
end
def verify_mac(data, mac)
bank_public_key = OpenSSL::X509::Certificate.new(File.read(bank_certificate)).public_key
bank_public_key.verify(OpenSSL::Digest::SHA1.new, Base64.decode64(mac), data)
end
def calc_mac(fields)
pars = %w(VK_SERVICE VK_VERSION VK_SND_ID VK_STAMP VK_AMOUNT VK_CURR VK_REF
VK_MSG VK_RETURN VK_CANCEL VK_DATETIME).freeze
data = pars.map{|e| prepend_size(fields[e]) }.join
sign(data)
end
def prepend_size(value)
value = (value || "").to_s.strip
string = ""
string << sprintf("%03i", value.size)
string << value
end
def seller_account
ENV["#{type}_seller_account"]
end
def seller_certificate
ENV["#{type}_seller_certificate"]
end
def bank_certificate
ENV["#{type}_bank_certificate"]
end
end
end

View file

@ -0,0 +1,49 @@
module Payments
class Base
include ActionView::Helpers::NumberHelper
attr_reader :type,
:invoice,
:return_url,
:response_url,
:response
def initialize(type, invoice, opts = {})
@type = type
@invoice = invoice
@return_url = opts[:return_url]
@response_url = opts[:response_url]
@response = opts[:response]
end
def create_transaction
transaction = BankTransaction.where(description: invoice.order).first_or_initialize(
reference_no: invoice.reference_no,
currency: invoice.currency,
iban: invoice.seller_iban
)
transaction.save!
end
def complete_transaction
fail NotImplementedError
end
def settled_payment?
fail NotImplementedError
end
def form_fields
fail NotImplementedError
end
def form_url
ENV["#{type}_payment_url"]
end
def valid_response?
fail NotImplementedError
end
end
end

View file

@ -0,0 +1,111 @@
module Payments
class EveryPay < Base
# TODO: Move to setting or environment
USER = ENV['every_pay_api_user'].freeze
KEY = ENV['every_pay_api_key'].freeze
ACCOUNT_ID = ENV['every_pay_seller_account'].freeze
SUCCESSFUL_PAYMENT = %w(settled authorized).freeze
def form_fields
base_json = base_params
base_json.merge!("nonce": SecureRandom.hex(15))
hmac_fields = (base_json.keys + ["hmac_fields"]).sort.uniq!
# Not all requests require use of hmac_fields, add only when needed
base_json["hmac_fields"] = hmac_fields.join(",")
hmac_string = hmac_fields.map{|k, _v| "#{k}=#{base_json[k]}"}.join("&")
hmac = OpenSSL::HMAC.hexdigest("sha1", KEY, hmac_string)
base_json.merge!("hmac": hmac)
base_json
end
def valid_response?
return false unless response
valid_hmac? && valid_amount? && valid_account?
end
def settled_payment?
SUCCESSFUL_PAYMENT.include?(response[:payment_state])
end
def complete_transaction
if valid_response? && settled_payment?
transaction = BankTransaction.find_by(
reference_no: invoice.reference_no,
currency: invoice.currency,
iban: invoice.seller_iban
)
transaction.sum = response[:amount]
transaction.paid_at = DateTime.strptime(response[:timestamp],'%s')
transaction.buyer_name = response[:cc_holder_name]
transaction.save!
transaction.autobind_invoice
end
end
private
def base_params
{
api_username: USER,
account_id: ACCOUNT_ID,
timestamp: Time.now.to_i.to_s,
callback_url: response_url,
customer_url: return_url,
amount: invoice.sum_cache,
order_reference: SecureRandom.hex(15),
transaction_type: "charge",
hmac_fields: ""
}.with_indifferent_access
end
def valid_hmac?
hmac_fields = response[:hmac_fields].split(',')
hmac_hash = {}
hmac_fields.map do|field|
hmac_hash[field.to_sym] = response[field.to_sym]
end
hmac_string = hmac_hash.map {|k, _v|"#{k}=#{hmac_hash[k]}"}.join("&")
expected_hmac = OpenSSL::HMAC.hexdigest("sha1", KEY, hmac_string)
expected_hmac == response[:hmac]
end
def valid_amount?
invoice.sum_cache == BigDecimal.new(response[:amount])
end
def valid_account?
response[:account_id] == ACCOUNT_ID
end
def return_params
{"utf8"=>"",
"_method"=>"put",
"authenticity_token"=>"Eb0/tFG0zSJriUUmDykI8yU/ph3S19k0KyWI2/Vxd9srF46plVJf8z8vRrkbuziMP6I/68dM3o/+QwbrI6dvSw==",
"nonce"=>"2375e05dfd12db5af207b11742b70bda",
"timestamp"=>"1523887506",
"api_username"=>"ca8d6336dd750ddb",
"transaction_result"=>"completed",
"payment_reference"=>"95c98cd27f927e93ab7bcf7968ebff7fe4ca9314ab85b5cb15b2a6d59eb56940",
"payment_state"=>"settled",
"amount"=>"240.0",
"order_reference"=>"0c430ff649e1760313e4d98b5e90e6",
"account_id"=>"EUR3D1",
"cc_type"=>"master_card",
"cc_last_four_digits"=>"0487",
"cc_month"=>"10",
"cc_year"=>"2018",
"cc_holder_name"=>"John Doe",
"hmac_fields"=>"account_id,amount,api_username,cc_holder_name,cc_last_four_digits,cc_month,cc_type,cc_year,hmac_fields,nonce,order_reference,payment_reference,payment_state,timestamp,transaction_result",
"hmac"=>"4a2ed8729be9a0c35c27fe331d01c4df5d8707c1",
"controller"=>"registrar/payments/every_pay",
"action"=>"update",
"invoice_id"=>"1"}
end
end
end

View file

@ -0,0 +1,19 @@
.row
.col-md-12
%h4= "Credit card payment successful"
%hr
%dl.dl-horizontal
%dt= t(:invoice)
%dd= @invoice.reference_no
%dt= "Card Type"
%dd= params['cc_type'].humanize
%dt= "Card Holder"
%dd= params['cc_holder_name']
%dt= "Card Last four digits"
%dd= params['cc_last_four_digits']
%dt= "Valid thru"
%dd= "#{params['cc_month']}/#{params['cc_year']}"

View file

@ -0,0 +1,4 @@
= form_tag "https://igw-demo.every-pay.com/transactions/", method: :post do
- @every_pay.keys.each do |k, v|
= hidden_field_tag(k, @every_pay[k])
= submit_tag t("registrar.invoices.to_card_payment")

View file

@ -1,6 +1,7 @@
%h4= t(:pay_by_bank_link)
%h4= t('registrar.invoices.pay_invoice')
%hr
- ENV['payments_banks'].split(",").each do |meth|
- locals[:payment_channels].each do |meth|
- meth = meth.strip
= link_to registrar_payment_with_path(meth, invoice_id: params[:id]) do
= image_tag("#{meth}.png")

View file

@ -0,0 +1,7 @@
%h4= t('registrar.invoices.pay_by_credit_card')
- @every_pay = EveryPayPayment.new(@invoice).json
%hr
= form_tag "https://igw-demo.every-pay.com/transactions/", method: :post do
- @every_pay.keys.each do |k, v|
= hidden_field_tag(k, @every_pay[k])
= submit_tag t("registrar.invoices.to_card_payment")

View file

@ -17,4 +17,4 @@
- if !@invoice.cancelled? && !@invoice.binded?
.row.semifooter
.col-md-12.text-right= render 'registrar/invoices/partials/banklinks'
.col-md-6-offset-6.text-right= render 'registrar/invoices/partials/banklinks', locals: { payment_channels: Payments::PAYMENT_METHODS }

View file

@ -0,0 +1,19 @@
.row
.col-md-12
%h4= "Credit card payment successful"
%hr
%dl.dl-horizontal
%dt= t(:invoice)
%dd= @invoice.reference_no
%dt= "Card Type"
%dd= params['cc_type'].humanize
%dt= "Card Holder"
%dd= params['cc_holder_name']
%dt= "Card Last four digits"
%dd= params['cc_last_four_digits']
%dt= "Valid thru"
%dd= "#{params['cc_month']}/#{params['cc_year']}"

View file

@ -0,0 +1,4 @@
= form_tag "https://igw-demo.every-pay.com/transactions/", method: :post do
- @every_pay.keys.each do |k, v|
= hidden_field_tag(k, @every_pay[k])
= submit_tag t("registrar.invoices.to_card_payment")

View file

@ -1,11 +1,15 @@
.h3
= t('registrar.invoices.redirected_to_bank')
.payment-form
= form_tag @bank_link.url, method: :post do
- @bank_link.fields.each do |k, v|
= form_tag @payment.form_url, method: :post do
- @payment.form_fields.each do |k, v|
= hidden_field_tag k, v
= submit_tag "Mine maksma"
= submit_tag t('registrar.invoices.go_to_bank')
:javascript
function loadListener () {
$('.payment-form form').submit();
}
:coffeescript
load_listener = ->
$('.payment-form form').submit()
window.addEventListener 'load', load_listener
document.addEventListener('load', loadListener)