taiwan_payments 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +24 -0
  3. data/LICENSE.txt +21 -0
  4. data/README.ja.md +293 -0
  5. data/README.md +291 -0
  6. data/README.zh-TW.md +293 -0
  7. data/docs/ecpay-invoices.md +202 -0
  8. data/docs/ecpay-payments.md +191 -0
  9. data/docs/glossary/concepts.ja.md +33 -0
  10. data/docs/glossary/concepts.md +34 -0
  11. data/docs/glossary/ecpay-invoice.ja.md +113 -0
  12. data/docs/glossary/ecpay-invoice.md +114 -0
  13. data/docs/glossary/ecpay-payment.ja.md +64 -0
  14. data/docs/glossary/ecpay-payment.md +65 -0
  15. data/docs/rails.md +184 -0
  16. data/docs/sandbox-setup.md +104 -0
  17. data/docs/taiwan-payments-101.ja.md +138 -0
  18. data/docs/taiwan-payments-101.md +138 -0
  19. data/docs/taiwan-payments-101.zh-TW.md +138 -0
  20. data/docs/testing.md +140 -0
  21. data/docs/webhooks.md +113 -0
  22. data/exe/taiwan_payments +6 -0
  23. data/lib/generators/taiwan_payments/install/install_generator.rb +41 -0
  24. data/lib/generators/taiwan_payments/install/templates/ecpay_controller.rb.tt +26 -0
  25. data/lib/generators/taiwan_payments/install/templates/initializer.rb.tt +38 -0
  26. data/lib/taiwan_payments/cli.rb +271 -0
  27. data/lib/taiwan_payments/configuration.rb +86 -0
  28. data/lib/taiwan_payments/credentials.rb +27 -0
  29. data/lib/taiwan_payments/decimal.rb +36 -0
  30. data/lib/taiwan_payments/ecpay/aes_cipher.rb +36 -0
  31. data/lib/taiwan_payments/ecpay/check_mac_value.rb +63 -0
  32. data/lib/taiwan_payments/ecpay/checkout.rb +154 -0
  33. data/lib/taiwan_payments/ecpay/invoice_client.rb +253 -0
  34. data/lib/taiwan_payments/ecpay/invoice_mapper.rb +222 -0
  35. data/lib/taiwan_payments/ecpay/payment_client.rb +188 -0
  36. data/lib/taiwan_payments/ecpay/payment_methods.rb +40 -0
  37. data/lib/taiwan_payments/ecpay/payment_notification.rb +127 -0
  38. data/lib/taiwan_payments/ecpay/response_body.rb +30 -0
  39. data/lib/taiwan_payments/ecpay/trade_info.rb +68 -0
  40. data/lib/taiwan_payments/ecpay.rb +19 -0
  41. data/lib/taiwan_payments/environment.rb +22 -0
  42. data/lib/taiwan_payments/error_codes/ecpay_invoice.yml +80 -0
  43. data/lib/taiwan_payments/error_codes/ecpay_payment.yml +59 -0
  44. data/lib/taiwan_payments/error_codes.rb +23 -0
  45. data/lib/taiwan_payments/errors.rb +71 -0
  46. data/lib/taiwan_payments/form_helper.rb +21 -0
  47. data/lib/taiwan_payments/glossary/concepts.yml +122 -0
  48. data/lib/taiwan_payments/glossary/ecpay_invoice.yml +523 -0
  49. data/lib/taiwan_payments/glossary/ecpay_payment.yml +278 -0
  50. data/lib/taiwan_payments/glossary.rb +106 -0
  51. data/lib/taiwan_payments/hosted_form.rb +46 -0
  52. data/lib/taiwan_payments/http_client.rb +62 -0
  53. data/lib/taiwan_payments/instrumentation.rb +42 -0
  54. data/lib/taiwan_payments/invoice.rb +235 -0
  55. data/lib/taiwan_payments/money.rb +32 -0
  56. data/lib/taiwan_payments/php_compat.rb +39 -0
  57. data/lib/taiwan_payments/railtie.rb +23 -0
  58. data/lib/taiwan_payments/redactor.rb +29 -0
  59. data/lib/taiwan_payments/taipei_time.rb +42 -0
  60. data/lib/taiwan_payments/tax_id.rb +26 -0
  61. data/lib/taiwan_payments/testing.rb +152 -0
  62. data/lib/taiwan_payments/validation.rb +56 -0
  63. data/lib/taiwan_payments/version.rb +5 -0
  64. data/lib/taiwan_payments/webhooks.rb +54 -0
  65. data/lib/taiwan_payments.rb +67 -0
  66. metadata +118 -0
@@ -0,0 +1,271 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+ require "tmpdir"
5
+ require_relative "../taiwan_payments"
6
+ require_relative "glossary"
7
+
8
+ module TaiwanPayments
9
+ # The `taiwan_payments` command: small tools for the moments when an
10
+ # integration misbehaves and you need to see what the vendor sees, plus a
11
+ # way to try ECPay's test environment before writing any code.
12
+ class CLI
13
+ USAGE = <<~TEXT
14
+ Usage: taiwan_payments COMMAND [options]
15
+
16
+ Look things up
17
+ glossary TERM Explain a vendor field or a Taiwanese payment term
18
+ (try: glossary 載具, glossary RelateNumber)
19
+ tax-id NUMBER Check a company tax ID (統一編號)
20
+
21
+ Debug ECPay
22
+ ecpay mac PARAMS Compute a CheckMacValue, or verify the one in PARAMS.
23
+ PARAMS is a form body, a JSON object, or - for stdin.
24
+ --raw takes values as typed instead of URL-decoding them.
25
+ ecpay decrypt DATA Decrypt the Data of an e-invoice request or response.
26
+ DATA is the Base64 text, the whole JSON body, or -.
27
+
28
+ Try ECPay's test environment
29
+ ecpay checkout Write a checkout page for a test payment
30
+ [--amount N] [--order-no NO] [--item NAME] [--method METHOD]
31
+ [--return-url URL] [--output PATH] [--open]
32
+ ecpay query ORDER_NO Ask ECPay for the state of an order
33
+ ecpay invoice Issue a test invoice
34
+ [--amount N] [--order-no NO] [--item NAME] [--email EMAIL]
35
+
36
+ Common options
37
+ --zh Show messages in Chinese where available
38
+ --ja Show messages in Japanese where available
39
+ --production Use the production environment (needs your own keys)
40
+ -h, --help Show this help
41
+ -v, --version Show the version
42
+
43
+ Keys come from the environment, and default to ECPay's public test merchants:
44
+ payments ECPAY_MERCHANT_ID ECPAY_HASH_KEY ECPAY_HASH_IV
45
+ invoices ECPAY_INVOICE_MERCHANT_ID ECPAY_INVOICE_HASH_KEY ECPAY_INVOICE_HASH_IV
46
+ TEXT
47
+
48
+ # Published by ECPay for its stage environment.
49
+ TEST_CARD = "4311-9522-2222-2222, any future expiry, security code 222, SMS code 1234"
50
+ OPENERS = {/darwin/ => %w[open], /linux|bsd/ => %w[xdg-open], /mswin|mingw|cygwin/ => ["cmd", "/c", "start", ""]}.freeze
51
+
52
+ class UsageError < StandardError; end
53
+
54
+ # @param opener [#call] receives a file path to show in a browser
55
+ def initialize(argv, out: $stdout, err: $stderr, stdin: $stdin, env: ENV, opener: nil)
56
+ @argv = argv.dup
57
+ @out = out
58
+ @err = err
59
+ @stdin = stdin
60
+ @env = env
61
+ @opener = opener || method(:open_in_browser)
62
+ @production = false
63
+ end
64
+
65
+ # @return [Integer] process exit status
66
+ def run
67
+ previous_locale = TaiwanPayments.locale
68
+ extract_global_options!
69
+ dispatch(@argv.shift)
70
+ rescue UsageError, OptionParser::ParseError => error
71
+ @err.puts "#{error.message}\n\n#{USAGE}"
72
+ 2
73
+ rescue TaiwanPayments::Error => error
74
+ @err.puts "Error: #{error.message}"
75
+ 1
76
+ ensure
77
+ TaiwanPayments.locale = previous_locale
78
+ end
79
+
80
+ private
81
+
82
+ def extract_global_options!
83
+ TaiwanPayments.locale = :zh_tw if @argv.delete("--zh")
84
+ TaiwanPayments.locale = :ja if @argv.delete("--ja")
85
+ @production = !@argv.delete("--production").nil?
86
+ end
87
+
88
+ def dispatch(command)
89
+ case command
90
+ when nil, "help", "-h", "--help" then say(USAGE)
91
+ when "version", "-v", "--version" then say(VERSION)
92
+ when "glossary" then glossary
93
+ when "tax-id" then tax_id
94
+ when "ecpay" then ecpay(@argv.shift)
95
+ else raise UsageError, "unknown command: #{command}"
96
+ end
97
+ end
98
+
99
+ def ecpay(command)
100
+ case command
101
+ when "mac" then ecpay_mac
102
+ when "decrypt" then ecpay_decrypt
103
+ when "checkout" then ecpay_checkout
104
+ when "query" then ecpay_query
105
+ when "invoice" then ecpay_invoice
106
+ else raise UsageError, "unknown ecpay command: #{command.inspect}"
107
+ end
108
+ end
109
+
110
+ def say(text)
111
+ @out.puts text
112
+ 0
113
+ end
114
+
115
+ def argument!(name)
116
+ @argv.shift || raise(UsageError, "missing #{name}")
117
+ end
118
+
119
+ # "-" reads standard input, so secrets and long payloads can be piped in
120
+ # and stay out of shell history.
121
+ def text_argument!(name)
122
+ value = argument!(name)
123
+ (value == "-") ? @stdin.read.to_s.strip : value
124
+ end
125
+
126
+ def glossary
127
+ query = argument!("TERM")
128
+ matches = Glossary.search(query)
129
+ return fail_with("No glossary entry matches #{query.inspect}.") if matches.empty?
130
+
131
+ locale = TaiwanPayments.locale
132
+ matches.each do |entry|
133
+ @out.puts "#{entry.term} #{entry.zh} [#{Glossary::TABLES.fetch(entry.table).heading(locale)}]"
134
+ @out.puts " #{entry.meaning(locale)}"
135
+ @out.puts " #{(locale == :ja) ? "この gem では" : "In this gem"}: #{entry.gem.delete("`")}"
136
+ @out.puts
137
+ end
138
+ 0
139
+ end
140
+
141
+ def tax_id
142
+ number = argument!("NUMBER")
143
+ return say("#{number} is a valid tax ID (統一編號).") if TaxId.valid?(number)
144
+
145
+ fail_with("#{number} is not a valid tax ID (統一編號): it must be 8 digits with a correct checksum.")
146
+ end
147
+
148
+ def ecpay_mac
149
+ raw = false
150
+ OptionParser.new { |options| options.on("--raw") { raw = true } }.parse!(@argv)
151
+ text = text_argument!("PARAMS")
152
+ client = payment_client
153
+ # ECPay signs a query response as one piece of text. A value in it may
154
+ # contain "&", so it is checked whole before being split into fields.
155
+ keys = {hash_key: client.credentials.hash_key, hash_iv: client.credentials.hash_iv}
156
+ return say("CheckMacValue is valid.") if raw && ECPay::CheckMacValue.valid_body?(text, **keys)
157
+
158
+ params = parse_params(text, raw)
159
+ given = params.delete(ECPay::CheckMacValue::FIELD)
160
+ expected = client.check_mac_value(params)
161
+ return say(expected) if given.nil?
162
+ return say("CheckMacValue is valid.") if expected.casecmp?(given)
163
+
164
+ fail_with("CheckMacValue does NOT match.\n given: #{given}\n expected: #{expected}\n" \
165
+ "Check the keys, and try --raw if the values were copied already decoded.")
166
+ end
167
+
168
+ # Form bodies arrive URL-encoded, while values copied from a log or a
169
+ # query response are usually already decoded; --raw keeps them as typed.
170
+ def parse_params(text, raw)
171
+ return json_object(text, "PARAMS").transform_values(&:to_s) if text.start_with?("{")
172
+
173
+ raw ? ECPay::ResponseBody.parse(text) : PhpCompat.parse_query(text)
174
+ end
175
+
176
+ def ecpay_decrypt
177
+ text = text_argument!("DATA")
178
+ data = text.start_with?("{") ? json_object(text, "DATA")["Data"] : text
179
+ credentials = invoice_client.credentials
180
+ say(JSON.pretty_generate(ECPay::AesCipher.decrypt(data, hash_key: credentials.hash_key, hash_iv: credentials.hash_iv)))
181
+ end
182
+
183
+ def json_object(text, name)
184
+ JSON.parse(text)
185
+ rescue JSON::ParserError
186
+ raise UsageError, "#{name} looks like JSON but could not be parsed"
187
+ end
188
+
189
+ def ecpay_checkout
190
+ options = {amount: 100, order_no: "TWP#{Time.now.to_i}", item: "Test item", method: "all",
191
+ return_url: "https://example.com/webhooks/ecpay", output: nil, open: false}
192
+ OptionParser.new do |parser|
193
+ parser.on("--amount N", Integer) { |value| options[:amount] = value }
194
+ parser.on("--order-no NO") { |value| options[:order_no] = value }
195
+ parser.on("--item NAME") { |value| options[:item] = value }
196
+ parser.on("--method METHOD") { |value| options[:method] = value }
197
+ parser.on("--return-url URL") { |value| options[:return_url] = value }
198
+ parser.on("--output PATH") { |value| options[:output] = value }
199
+ parser.on("--open") { options[:open] = true }
200
+ end.parse!(@argv)
201
+
202
+ form = payment_client.checkout(order_no: options[:order_no], amount: options[:amount], description: options[:item],
203
+ items: [options[:item]], return_url: options[:return_url], payment_method: options[:method].to_sym)
204
+ path = options[:output] || File.join(Dir.tmpdir, "taiwan_payments_checkout_#{options[:order_no]}.html")
205
+ File.write(path, "<!doctype html>\n<meta charset=\"utf-8\">\n<title>ECPay checkout #{options[:order_no]}</title>\n#{form.to_html}")
206
+
207
+ @out.puts "Order #{options[:order_no]} for NT$#{options[:amount]}: checkout page written to #{path}"
208
+ @out.puts "Test card: #{TEST_CARD}" unless @production
209
+ @out.puts "Afterwards: taiwan_payments ecpay query #{options[:order_no]}"
210
+ @opener.call(path) if options[:open]
211
+ 0
212
+ end
213
+
214
+ def ecpay_query
215
+ order_no = argument!("ORDER_NO")
216
+ trade = payment_client.query(order_no: order_no)
217
+ return fail_with("ECPay has no trade for #{order_no}. The customer may never have reached the payment page.") if trade.nil?
218
+
219
+ say("#{trade.order_no}: #{trade.status} (TradeStatus #{trade.status_code}), NT$#{trade.amount}, " \
220
+ "ECPay trade no #{trade.trade_no}, paid at #{trade.paid_at || "-"}")
221
+ end
222
+
223
+ def ecpay_invoice
224
+ options = {amount: 100, order_no: "TWP#{Time.now.to_i}", email: "test@example.com", item: "Test item"}
225
+ OptionParser.new do |parser|
226
+ parser.on("--amount N", Integer) { |value| options[:amount] = value }
227
+ parser.on("--order-no NO") { |value| options[:order_no] = value }
228
+ parser.on("--email EMAIL") { |value| options[:email] = value }
229
+ parser.on("--item NAME") { |value| options[:item] = value }
230
+ end.parse!(@argv)
231
+
232
+ invoice = Invoice.new(order_no: options[:order_no], buyer: {email: options[:email]},
233
+ items: [{name: options[:item], unit_price: options[:amount]}])
234
+ result = invoice_client.issue(invoice)
235
+ say("Issued invoice #{result.invoice_no} (random number #{result.random_number}) for NT$#{invoice.total}, " \
236
+ "order #{options[:order_no]}, at #{result.issued_at}")
237
+ end
238
+
239
+ def fail_with(message)
240
+ @err.puts message
241
+ 1
242
+ end
243
+
244
+ def payment_client
245
+ build_client(ECPay::PaymentClient, "ECPAY")
246
+ end
247
+
248
+ def invoice_client
249
+ build_client(ECPay::InvoiceClient, "ECPAY_INVOICE")
250
+ end
251
+
252
+ def build_client(client_class, prefix)
253
+ keys = {merchant_id: @env["#{prefix}_MERCHANT_ID"], hash_key: @env["#{prefix}_HASH_KEY"], hash_iv: @env["#{prefix}_HASH_IV"]}
254
+ return client_class.new(**keys, env: @production ? :production : :sandbox) if keys.values.any?
255
+ return client_class.sandbox unless @production
256
+
257
+ # The public test keys are useless against production, and silently
258
+ # falling back to them would look like a signature bug.
259
+ raise ConfigurationError.new("--production needs #{prefix}_MERCHANT_ID, #{prefix}_HASH_KEY and #{prefix}_HASH_IV in the environment",
260
+ zh: "使用 --production 時必須設定環境變數 #{prefix}_MERCHANT_ID、#{prefix}_HASH_KEY、#{prefix}_HASH_IV",
261
+ ja: "--production を使うには、環境変数 #{prefix}_MERCHANT_ID、#{prefix}_HASH_KEY、#{prefix}_HASH_IV の設定が必要です")
262
+ end
263
+
264
+ def open_in_browser(path)
265
+ command = OPENERS.find { |platform, _| platform.match?(RUBY_PLATFORM) }&.last
266
+ return if command && system(*command, path)
267
+
268
+ @err.puts "Could not open a browser. Open this file yourself: #{path}"
269
+ end
270
+ end
271
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ # Optional process-wide setup, for apps with one merchant per product:
5
+ #
6
+ # TaiwanPayments.configure do |config|
7
+ # config.env = :production
8
+ # config.ecpay_payments = {merchant_id: "...", hash_key: "...", hash_iv: "..."}
9
+ # config.ecpay_invoices = :sandbox # ECPay's public test merchant
10
+ # end
11
+ # TaiwanPayments.ecpay_payments.checkout(...)
12
+ #
13
+ # Nothing in the gem reads this implicitly. Apps with several merchants
14
+ # build their own clients and never need it.
15
+ class Configuration
16
+ CLIENTS = {ecpay_payments: ECPay::PaymentClient, ecpay_invoices: ECPay::InvoiceClient}.freeze
17
+
18
+ # @return [Symbol, String, nil] :sandbox or :production, for every client
19
+ # that does not name its own
20
+ attr_accessor :env
21
+ # @return [Hash, Symbol, nil] credentials (merchant_id, hash_key, hash_iv
22
+ # and optionally env or platform_id), or :sandbox for the vendor's
23
+ # public test merchant
24
+ attr_accessor(*CLIENTS.keys)
25
+
26
+ # Clients are built on first use, not when configured, so that an app
27
+ # can boot (asset precompilation, CI) where the credentials are absent.
28
+ def build(name)
29
+ client_class = CLIENTS.fetch(name)
30
+ settings = public_send(name)
31
+ return client_class.sandbox if settings.to_s == "sandbox"
32
+
33
+ settings = settings.to_h.transform_keys(&:to_sym)
34
+ if settings.empty?
35
+ raise ConfigurationError.new("TaiwanPayments.#{name} is not configured; set config.#{name} inside TaiwanPayments.configure",
36
+ zh: "TaiwanPayments.#{name} 尚未設定,請在 TaiwanPayments.configure 中設定 config.#{name}",
37
+ ja: "TaiwanPayments.#{name} が設定されていません。TaiwanPayments.configure の中で config.#{name} を設定してください")
38
+ end
39
+
40
+ client_class.new(env: env, **settings)
41
+ end
42
+ end
43
+
44
+ @configuration = Configuration.new
45
+ @clients = {}
46
+ @configuration_mutex = Mutex.new
47
+
48
+ class << self
49
+ # Yields the configuration for changes. Calling it again adjusts the
50
+ # existing settings and discards clients built from the old ones.
51
+ #
52
+ # @yieldparam config [Configuration]
53
+ def configure
54
+ @configuration_mutex.synchronize do
55
+ updated = @configuration.dup
56
+ yield updated
57
+ @configuration = updated
58
+ @clients = {}
59
+ end
60
+ nil
61
+ end
62
+
63
+ # @return [ECPay::PaymentClient] the client described by `config.ecpay_payments`
64
+ # @raise [ConfigurationError] when it has not been configured
65
+ def ecpay_payments = configured_client(:ecpay_payments)
66
+
67
+ # @return [ECPay::InvoiceClient] the client described by `config.ecpay_invoices`
68
+ # @raise [ConfigurationError] when it has not been configured
69
+ def ecpay_invoices = configured_client(:ecpay_invoices)
70
+
71
+ # Forgets everything set through {configure}. Meant for test suites.
72
+ def reset_configuration!
73
+ @configuration_mutex.synchronize do
74
+ @configuration = Configuration.new
75
+ @clients = {}
76
+ end
77
+ nil
78
+ end
79
+
80
+ private
81
+
82
+ def configured_client(name)
83
+ @configuration_mutex.synchronize { @clients[name] ||= @configuration.build(name) }
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ Credentials = Data.define(:merchant_id, :hash_key, :hash_iv) do
5
+ def initialize(merchant_id:, hash_key:, hash_iv:)
6
+ super(
7
+ merchant_id: Credentials.required(merchant_id, "merchant_id"),
8
+ hash_key: Credentials.required(hash_key, "hash_key"),
9
+ hash_iv: Credentials.required(hash_iv, "hash_iv")
10
+ )
11
+ end
12
+
13
+ # Keys must never reach logs or error trackers, and #inspect is how
14
+ # objects end up in both.
15
+ def inspect
16
+ "#<TaiwanPayments::Credentials merchant_id=#{merchant_id.inspect} hash_key=[REDACTED] hash_iv=[REDACTED]>"
17
+ end
18
+ alias_method :to_s, :inspect
19
+
20
+ def self.required(value, name)
21
+ string = value.to_s.strip
22
+ raise ConfigurationError.new("#{name} is required", zh: "#{name} 為必填", ja: "#{name} は必須です") if string.empty?
23
+
24
+ string.freeze
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ # Exact decimal arithmetic for invoice lines. Binary floats would turn
5
+ # 34.9 x 3 into 104.69999999999999, and the vendors reject an invoice whose
6
+ # lines do not add up to its total.
7
+ module Decimal
8
+ module_function
9
+
10
+ # @return [Rational] the value as the decimal number it was written as
11
+ def parse(value, field)
12
+ rational =
13
+ case value
14
+ when Integer, Rational then value.to_r
15
+ when Float then (Rational(value.to_s) if value.finite?)
16
+ when String then Rational(value, exception: false)
17
+ when Numeric then (value.to_r if value.finite?)
18
+ end
19
+ return rational if rational
20
+
21
+ Validation.fail!(field, "#{field} must be a number (got #{value.inspect})", "#{field} 必須是數字(收到 #{value.inspect})",
22
+ "#{field} は数値である必要があります(受け取った値: #{value.inspect})")
23
+ end
24
+
25
+ # @return [Integer, Float] a JSON-friendly number; the vendors accept at
26
+ # most seven decimal places
27
+ def to_number(rational)
28
+ (rational.denominator == 1) ? rational.numerator : rational.round(7).to_f
29
+ end
30
+
31
+ # Taiwan invoices round half up (四捨五入), not to even.
32
+ def round(rational)
33
+ rational.round(half: :up)
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ module ECPay
5
+ # Encrypts the `Data` member of ECPay's JSON APIs (e-invoice):
6
+ # JSON -> URL-encode -> AES-128-CBC/PKCS7 -> Base64.
7
+ # Reference: https://developers.ecpay.com.tw/22160/
8
+ module AesCipher
9
+ ALGORITHM = "aes-128-cbc"
10
+ KEY_BYTES = 16
11
+
12
+ module_function
13
+
14
+ def encrypt(data, hash_key:, hash_iv:)
15
+ cipher = OpenSSL::Cipher.new(ALGORITHM).encrypt
16
+ cipher.key = hash_key
17
+ cipher.iv = hash_iv
18
+ [cipher.update(PhpCompat.urlencode(JSON.generate(data))) + cipher.final].pack("m0")
19
+ end
20
+
21
+ # @return [Hash] the decoded JSON object
22
+ # @raise [DecryptionError] wrong keys, or a body that is not ECPay ciphertext
23
+ def decrypt(ciphertext, hash_key:, hash_iv:)
24
+ cipher = OpenSSL::Cipher.new(ALGORITHM).decrypt
25
+ cipher.key = hash_key
26
+ cipher.iv = hash_iv
27
+ plaintext = cipher.update(ciphertext.to_s.unpack1("m")) + cipher.final
28
+ JSON.parse(PhpCompat.urldecode(plaintext))
29
+ rescue OpenSSL::Cipher::CipherError, JSON::ParserError, ArgumentError => error
30
+ raise DecryptionError.new("could not decrypt ECPay data (#{error.class}); check hash_key and hash_iv",
31
+ zh: "無法解密綠界資料(#{error.class}),請確認 hash_key 與 hash_iv",
32
+ ja: "ECPay のデータを復号できませんでした(#{error.class})。hash_key と hash_iv を確認してください")
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ module ECPay
5
+ # The signature on every ECPay payment request, response and webhook.
6
+ # Reference: https://developers.ecpay.com.tw/?p=2902
7
+ module CheckMacValue
8
+ FIELD = "CheckMacValue"
9
+
10
+ # ECPay's servers encode with .NET's HttpUtility.UrlEncode, which leaves
11
+ # these four characters bare. PHP-style encoding escapes them, so they
12
+ # are restored to make both sides hash the same string.
13
+ DOTNET_LITERALS = {"%21" => "!", "%2a" => "*", "%28" => "(", "%29" => ")"}.freeze
14
+
15
+ module_function
16
+
17
+ # @param params [Hash] every field being sent or received; a CheckMacValue
18
+ # entry is ignored so a received payload can be passed in whole
19
+ # @return [String] 64 uppercase hex characters
20
+ def generate(params, hash_key:, hash_iv:)
21
+ # ECPay's reference implementations sort with strcasecmp. Plain byte
22
+ # order would place lowercase fields such as "card4no" after every
23
+ # capitalised one and produce a different signature.
24
+ pairs = params
25
+ .map { |key, value| [key.to_s, value.to_s] }
26
+ .reject { |key, _| key == FIELD }
27
+ .sort_by { |key, _| key.downcase }
28
+ .map { |key, value| "#{key}=#{value}" }
29
+
30
+ sign(pairs.join("&"), hash_key: hash_key, hash_iv: hash_iv)
31
+ end
32
+
33
+ # @param query [String] already-ordered "A=1&B=2" pairs, values unescaped
34
+ def sign(query, hash_key:, hash_iv:)
35
+ payload = "HashKey=#{hash_key}&#{query}&HashIV=#{hash_iv}"
36
+ encoded = PhpCompat.urlencode(payload).downcase.gsub(/%(?:21|2a|28|29)/, DOTNET_LITERALS)
37
+ Digest::SHA256.hexdigest(encoded).upcase
38
+ end
39
+
40
+ def valid?(params, hash_key:, hash_iv:)
41
+ given = params.find { |key, _| key.to_s == FIELD }&.last
42
+ matches?(generate(params, hash_key: hash_key, hash_iv: hash_iv), given)
43
+ end
44
+
45
+ # Verifies a raw `k=v&...&CheckMacValue=X` response body without parsing
46
+ # it first. ECPay does not escape response values, so a value containing
47
+ # "&" cannot be split back into fields reliably, but the body is already
48
+ # in signing order and can be hashed as it stands.
49
+ def valid_body?(body, hash_key:, hash_iv:)
50
+ signed, separator, given = body.to_s.strip.rpartition("&#{FIELD}=")
51
+ return false if separator.empty?
52
+
53
+ matches?(sign(signed, hash_key: hash_key, hash_iv: hash_iv), given)
54
+ end
55
+
56
+ # Constant-time so a forged webhook cannot learn the signature byte by byte.
57
+ def matches?(expected, given)
58
+ given = given.to_s
59
+ !given.empty? && OpenSSL.secure_compare(expected, given.upcase)
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ module ECPay
5
+ # Builds the AioCheckOut/V5 parameters for one order.
6
+ # Reference: https://developers.ecpay.com.tw/?p=2862
7
+ class Checkout
8
+ PATH = "/Cashier/AioCheckOut/V5"
9
+ TRADE_DATE_FORMAT = "%Y/%m/%d %H:%M:%S"
10
+ LANGUAGES = {"en" => "ENG", "ko" => "KOR", "ja" => "JPN", "zh_cn" => "CHI", "zh_tw" => "CHT"}.freeze
11
+ ITEM_NAME_BYTES = 400
12
+ DESCRIPTION_BYTES = 200
13
+ URL_OPTIONS = {
14
+ order_result_url: "OrderResultURL", client_back_url: "ClientBackURL", payment_info_url: "PaymentInfoURL",
15
+ client_redirect_url: "ClientRedirectURL", item_url: "ItemURL"
16
+ }.freeze
17
+
18
+ # @param order_no [String] your unique order number, 1-20 letters/digits (MerchantTradeNo)
19
+ # @param amount [Integer] whole TWD (TotalAmount)
20
+ # @param description [String] shown on the payment page (TradeDesc)
21
+ # @param items [Array<String>, String] item names shown on the payment page (ItemName)
22
+ # @param return_url [String] server-to-server webhook for the payment result (ReturnURL)
23
+ # @param payment_method [Symbol] :all or one of PaymentMethods::VENDOR_NAMES (ChoosePayment)
24
+ # @param sub_method [String, nil] vendor code narrowing the method, e.g. "TAISHIN" (ChooseSubPayment)
25
+ # @param ignore_methods [Array<Symbol>] methods hidden when payment_method is :all (IgnorePayment)
26
+ # @param order_result_url [String, nil] browser is POSTed here with the result (OrderResultURL)
27
+ # @param client_back_url [String, nil] "back to shop" link on ECPay's page (ClientBackURL)
28
+ # @param payment_info_url [String, nil] webhook for ATM/CVS/barcode payment codes (PaymentInfoURL)
29
+ # @param client_redirect_url [String, nil] browser is POSTed here with the payment code (ClientRedirectURL)
30
+ # @param language [Symbol, String, nil] :en, :ja, :ko, :zh_cn; default is Traditional Chinese (Language)
31
+ # @param extra_paid_info [Boolean] ask for card digits, bank codes etc. in the webhook (NeedExtraPaidInfo)
32
+ # @param custom_fields [Array<String>] up to four 50-character values echoed back to you (CustomField1-4)
33
+ # @param atm_expire_days [Integer, nil] 1-60 days to pay an ATM transfer (ExpireDate)
34
+ # @param store_expire [Integer, nil] minutes for :cvs, days for :barcode (StoreExpireDate)
35
+ # @param store_descriptions [Array<String>] up to four lines printed at the kiosk (Desc_1-4)
36
+ # @param installments [Array<Integer>, nil] offered instalment terms, e.g. [3, 6, 12] (CreditInstallment)
37
+ # @param redeem [Boolean] allow paying with card reward points (Redeem)
38
+ # @param union_pay [Integer, nil] 0 customer chooses, 1 UnionPay only, 2 hide UnionPay (UnionPay)
39
+ # @param extra [Hash] raw vendor parameters for anything not modelled here, e.g. periodic billing
40
+ # @param trade_date [Time] order creation time (MerchantTradeDate)
41
+ def initialize(order_no:, amount:, description:, items:, return_url:, payment_method: :all, sub_method: nil,
42
+ ignore_methods: [], order_result_url: nil, client_back_url: nil, payment_info_url: nil,
43
+ client_redirect_url: nil, item_url: nil, remark: nil, store_id: nil, language: nil,
44
+ extra_paid_info: false, custom_fields: [], atm_expire_days: nil, store_expire: nil,
45
+ store_descriptions: [], installments: nil, redeem: false, union_pay: nil, extra: {}, trade_date: Time.now)
46
+ @order_no = Validation.format!(order_no, /\A[A-Za-z0-9]{1,20}\z/, :order_no, "MerchantTradeNo",
47
+ "must be 1-20 letters or digits", "必須為 1 至 20 碼英數字", "1〜20 文字の英数字である必要があります")
48
+ @amount = Money.twd!(amount, :amount, "TotalAmount")
49
+ @description = Validation.present!(description, :description, "TradeDesc")
50
+ @items = Array(items).map(&:to_s)
51
+ Validation.present!(@items.join, :items, "ItemName")
52
+ @return_url = Validation.http_url!(return_url, :return_url, "ReturnURL")
53
+ @payment_method = PaymentMethods.to_vendor(payment_method, :payment_method)
54
+ @sub_method = sub_method
55
+ @ignore_methods = Array(ignore_methods).map { |method| PaymentMethods.to_vendor(method, :ignore_methods) }
56
+ @urls = {order_result_url:, client_back_url:, payment_info_url:, client_redirect_url:, item_url:}.compact
57
+ @urls.each { |name, url| Validation.http_url!(url, name, URL_OPTIONS.fetch(name)) }
58
+ reject_shared_result_url!
59
+ @remark = remark
60
+ @store_id = store_id
61
+ @language = vendor_language(language)
62
+ @extra_paid_info = extra_paid_info
63
+ @custom_fields = limited_list(custom_fields, :custom_fields, "CustomField", 50)
64
+ @atm_expire_days = atm_expire_days
65
+ @store_expire = store_expire
66
+ @store_descriptions = limited_list(store_descriptions, :store_descriptions, "Desc_", 20)
67
+ @installments = Array(installments)
68
+ @redeem = redeem
69
+ @union_pay = union_pay
70
+ @extra = extra
71
+ @trade_date = trade_date
72
+ end
73
+
74
+ # @return [Hash{String => String}] unsigned vendor parameters, without MerchantID
75
+ def to_vendor_params
76
+ params = {
77
+ "MerchantTradeNo" => @order_no,
78
+ "MerchantTradeDate" => TaipeiTime.format(@trade_date, TRADE_DATE_FORMAT),
79
+ "PaymentType" => "aio",
80
+ "TotalAmount" => @amount,
81
+ "TradeDesc" => fit(@description, DESCRIPTION_BYTES),
82
+ "ItemName" => fit(@items.join("#"), ITEM_NAME_BYTES),
83
+ "ReturnURL" => @return_url,
84
+ "ChoosePayment" => @payment_method,
85
+ "EncryptType" => 1
86
+ }
87
+ params.merge!(optional_params, numbered("CustomField", @custom_fields), numbered("Desc_", @store_descriptions), @extra)
88
+ params.to_h { |name, value| [name.to_s, value.to_s] }
89
+ end
90
+
91
+ private
92
+
93
+ def optional_params
94
+ {
95
+ "ChooseSubPayment" => @sub_method,
96
+ "IgnorePayment" => (@ignore_methods.join("#") unless @ignore_methods.empty?),
97
+ "Remark" => @remark,
98
+ "StoreID" => @store_id,
99
+ "Language" => @language,
100
+ "NeedExtraPaidInfo" => ("Y" if @extra_paid_info),
101
+ "ExpireDate" => @atm_expire_days,
102
+ "StoreExpireDate" => @store_expire,
103
+ "CreditInstallment" => (@installments.join(",") unless @installments.empty?),
104
+ "Redeem" => ("Y" if @redeem),
105
+ "UnionPay" => @union_pay
106
+ }.merge(@urls.transform_keys { |name| URL_OPTIONS.fetch(name) }).compact
107
+ end
108
+
109
+ def numbered(prefix, values)
110
+ values.each_with_index.to_h { |value, index| ["#{prefix}#{index + 1}", value] }.reject { |_, value| value.to_s.empty? }
111
+ end
112
+
113
+ def limited_list(values, field, vendor_prefix, max_length)
114
+ list = Array(values)
115
+ if list.size > 4
116
+ Validation.fail!(field, "#{field} accepts at most 4 values (#{vendor_prefix}1-4)", "#{field} 最多 4 個值(#{vendor_prefix}1-4)",
117
+ "#{field} に指定できる値は 4 つまでです(#{vendor_prefix}1-4)")
118
+ end
119
+ list.each_with_index { |value, index| Validation.max_length!(value, max_length, field, "#{vendor_prefix}#{index + 1}") }
120
+ end
121
+
122
+ # ECPay sends the same result fields to both URLs. If they were one
123
+ # endpoint, an order would be processed twice and the browser would be
124
+ # shown the plain-text webhook acknowledgement.
125
+ def reject_shared_result_url!
126
+ return unless @urls[:order_result_url] == @return_url
127
+
128
+ Validation.fail!(:order_result_url, "order_result_url (OrderResultURL) must differ from return_url (ReturnURL)",
129
+ "order_result_url (OrderResultURL) 不可與 return_url (ReturnURL) 相同",
130
+ "order_result_url (OrderResultURL) には return_url (ReturnURL) と異なる URL を指定してください")
131
+ end
132
+
133
+ def vendor_language(language)
134
+ return nil if language.nil?
135
+
136
+ text = language.to_s
137
+ code = LANGUAGES[text.downcase.tr("-", "_")] || LANGUAGES.values.find { |vendor| vendor.casecmp?(text) }
138
+ code || Validation.one_of!(language, LANGUAGES.keys.map(&:to_sym), :language, "Language")
139
+ end
140
+
141
+ # ECPay truncates over-long text after the signature has been computed,
142
+ # which corrupts the last character and makes the checksum fail, losing
143
+ # the order. Both fields are display-only, so they are shortened here,
144
+ # on a character boundary, before signing. The limit is applied in bytes
145
+ # because the vendor docs do not say which unit they count and bytes is
146
+ # the safe reading for Chinese text.
147
+ def fit(text, max_bytes)
148
+ return text if text.bytesize <= max_bytes
149
+
150
+ text.byteslice(0, max_bytes).scrub("")
151
+ end
152
+ end
153
+ end
154
+ end