Class: APIHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/ecpay_payment/helper.rb

Constant Summary collapse

@@conf_xml =
Nokogiri::XML(File.open(conf))

Instance Method Summary collapse

Constructor Details

#initializeAPIHelper

Returns a new instance of APIHelper.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/ecpay_payment/helper.rb', line 14

def initialize
    active_merc_info = @@conf_xml.xpath('/Conf/MercProfile').text
    @op_mode = @@conf_xml.xpath('/Conf/OperatingMode').text
    @contractor_stat = @@conf_xml.xpath('/Conf/IsProjectContractor').text
    merc_info = @@conf_xml.xpath("/Conf/MerchantInfo/MInfo[@name=\"#{active_merc_info}\"]")
    @ignore_payment = []
    @@conf_xml.xpath('/Conf/IgnorePayment//Method').each {|t| @ignore_payment.push(t.text)}
    if merc_info != []
        @merc_id = merc_info[0].xpath('./MerchantID').text.freeze
        @hkey = merc_info[0].xpath('./HashKey').text.freeze
        @hiv = merc_info[0].xpath('./HashIV').text.freeze

    else
        raise "Specified merchant setting name (#{active_merc_info}) not found."
    end
end

Instance Method Details

#encode_special_param!(params, target_arr) ⇒ Object



79
80
81
82
83
84
85
86
87
88
# File 'lib/ecpay_payment/helper.rb', line 79

def encode_special_param!(params, target_arr)
    if params.is_a?(Hash)
        target_arr.each do |n|
            if params.keys.include?(n)
                val = self.urlencode_dot_net(params[n])
                params[n] = val
            end
        end
    end
end

#gen_aes_encrypt(params) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/ecpay_payment/helper.rb', line 117

def gen_aes_encrypt(params)
    if params.is_a?(Hash)
        # raise exception if param contains HashKey, HashIV
        sec = ['HashKey', 'HashIV']
        sec.each do |pa|
            if params.keys.include?(pa)
                raise "Parameters shouldn't contain #{pa}"
            end
        end
        cipher = OpenSSL::Cipher.new('AES-128-CBC')
        cipher.encrypt
        cipher.padding = 16
        cipher.key = @hkey
        cipher.iv = @hiv
        text = params['PaymentToken'].to_s
        encrypted = cipher.update(text) + cipher.final
        encrypted_base64 = Base64.encode64(encrypted)
        return self.urlencode_dot_net(encrypted_base64)
    else
        raise "Data recieved is not a Hash."
    end
end

#gen_chk_mac_value(params, mode: 1) ⇒ Object



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
115
# File 'lib/ecpay_payment/helper.rb', line 90

def gen_chk_mac_value(params, mode: 1)
    if params.is_a?(Hash)
        # raise exception if param contains CheckMacValue, HashKey, HashIV
        sec = ['CheckMacValue', 'HashKey', 'HashIV']
        sec.each do |pa|
            if params.keys.include?(pa)
                raise "Parameters shouldn't contain #{pa}"
            end
        end

        raw = params.sort_by{|key,val|key.downcase}.map!{|key,val| "#{key}=#{val}"}.join('&')
        raw = self.urlencode_dot_net(["HashKey=#{@hkey}", raw, "HashIV=#{@hiv}"].join("&"), case_tr: 'DOWN')
        p raw
        case mode
        when 0
        chksum = Digest::MD5.hexdigest(raw)
        when 1
        chksum = Digest::SHA256.hexdigest(raw)
        else
            raise "Unexpected hash mode."
        end
        return chksum.upcase!
    else
        raise "Data recieved is not a Hash."
    end
end

#gen_html_post_form(act:, id:, parameters:, input_typ: 'hidden', submit: true) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/ecpay_payment/helper.rb', line 168

def gen_html_post_form(act:, id:, parameters:, input_typ:'hidden', submit: true)
    f = Nokogiri::HTML::Builder.new do |doc|
        doc.form(method: 'post', action: act, id: id) {
            parameters.map{|key,val|
            doc.input(type: input_typ, name: key, id: key, value: val)
            }
            if submit == true
                doc.script(type: 'text/javascript').text("document.getElementById(\"#{id}\").submit();")
            end
        }
    end
    return f.to_html
end

#get_curr_unixtimeObject



43
44
45
# File 'lib/ecpay_payment/helper.rb', line 43

def get_curr_unixtime()
    return Time.now.to_i
end

#get_ignore_payObject



39
40
41
# File 'lib/ecpay_payment/helper.rb', line 39

def get_ignore_pay()
    return @ignore_payment
end

#get_mercidObject



31
32
33
# File 'lib/ecpay_payment/helper.rb', line 31

def get_mercid()
    return @merc_id
end

#get_op_modeObject



35
36
37
# File 'lib/ecpay_payment/helper.rb', line 35

def get_op_mode()
    return @op_mode
end

#http_request(method:, url:, payload:) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/ecpay_payment/helper.rb', line 140

def http_request(method:, url:, payload:)

    target_url = URI.parse(url)

    case method
    when 'GET'
      target_url.query = URI.encode_www_form(payload)
      res = Net::HTTP.get_response(target_url)
    when 'POST'
      res = Net::HTTP.post_form(target_url, payload)
    else
      raise ArgumentError, "Only GET & POST method are avaliable."
    end
    return res.body
    # if res == Net::HTTPOK
    #     return res
    # else
    #     raise "#{res.message}, #{res}"
    # end

    # when Net::HTTPClientError, Net::HTTPInternalServerError
    #   raise Net::HTTPError.new(http_response.message, http_response)
    # else
    #   raise Net::HTTPError.new("Unexpected HTTP response.", http_response)
    # end
end

#is_contractor?Boolean

Returns:

  • (Boolean)


47
48
49
50
51
52
53
54
55
# File 'lib/ecpay_payment/helper.rb', line 47

def is_contractor?()
    if @contractor_stat == 'N'
        return false
    elsif @contractor_stat == 'Y'
        return true
    else
        raise "Unknown [IsProjectContractor] configuration."
    end
end

#urlencode_dot_net(raw_data, case_tr: 'DOWN') ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/ecpay_payment/helper.rb', line 57

def urlencode_dot_net(raw_data, case_tr:'DOWN')
    if raw_data.is_a?(String)
        encoded_data = CGI.escape(raw_data)
        case case_tr
        when 'KEEP'
            # Do nothing
        when 'UP'
            encoded_data.upcase!
        when 'DOWN'
            encoded_data.downcase!
        end
        # Process encoding difference between .NET & CGI
        encoded_data.gsub!('%21', '!')
        encoded_data.gsub!('%2a', '*')
        encoded_data.gsub!('%28', '(')
        encoded_data.gsub!('%29', ')')
        return encoded_data
    else
        raise "Data recieved is not a string."
    end
end

#valid_chkmac_string?(str) ⇒ Boolean

Returns:

  • (Boolean)


183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/ecpay_payment/helper.rb', line 183

def valid_chkmac_string?(str)
    rtn_hash = {}
    rtn_list = str.split('&')
    rtn_list.each do |e|
        param = e.split('=')
        rtn_hash[param[0]] = param[1]
    end
    chkmac = rtn_hash['CheckMacValue']
    rtn_hash.delete('CheckMacValue')
    if chkmac.length == 64
        val = gen_chk_mac_value(rtn_hash)
    elsif chkmac.length == 32
        val = gen_chk_mac_value(rtn_hash, mode: 0)
    end
    if chkmac == val
        return true
    else
        return false
    end

end