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,253 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ module ECPay
5
+ # Client for ECPay's B2C e-invoice product (電子發票). It covers consumer
6
+ # invoices and invoices carrying a buyer tax ID, which is what an online
7
+ # shop issues.
8
+ #
9
+ # ECPay gives the e-invoice product its own merchant keys. The keys from
10
+ # the payment product will not work here.
11
+ #
12
+ # @example
13
+ # client = TaiwanPayments::ECPay::InvoiceClient.sandbox
14
+ # invoice = TaiwanPayments::Invoice.new(order_no: "ORD1001", buyer: {email: "buyer@example.com"},
15
+ # items: [{name: "Oolong tea", quantity: 2, unit_price: 500}])
16
+ # client.issue(invoice).invoice_no # => "AB12345678"
17
+ class InvoiceClient
18
+ PROVIDER = "ECPay"
19
+ HOSTS = {sandbox: "https://einvoice-stage.ecpay.com.tw", production: "https://einvoice.ecpay.com.tw"}.freeze
20
+ # ECPay's shared public test merchant for e-invoices.
21
+ SANDBOX_CREDENTIALS = {merchant_id: "2000132", hash_key: "ejCk326UnaZWKisg", hash_iv: "q9jcZX8Ib9LM8wYk"}.freeze
22
+ SUCCESS = %w[1].freeze
23
+ NOT_FOUND = "2"
24
+ # TriggerIssue reports success with its own pair of codes: issued now,
25
+ # or accepted and due after the delay set when it was scheduled.
26
+ TRIGGERED = %w[4000003 4000004].freeze
27
+ TRANSPORT_OK = "1"
28
+ SCHEDULE_DAYS = (1..15)
29
+
30
+ attr_reader :credentials, :env, :platform_id
31
+
32
+ # @param env [Symbol] :sandbox or :production. Required, so that going
33
+ # live is always a deliberate choice.
34
+ # @param platform_id [String, nil] only for platform merchants (特約合作平台商)
35
+ def initialize(merchant_id:, hash_key:, hash_iv:, env:, platform_id: nil, http: HttpClient.new)
36
+ @credentials = Credentials.new(merchant_id: merchant_id, hash_key: hash_key, hash_iv: hash_iv)
37
+ @env = Environment.normalize(env)
38
+ @platform_id = platform_id
39
+ @http = http
40
+ validate_key_sizes!
41
+ freeze
42
+ end
43
+
44
+ # A client for ECPay's shared public test merchant. Nothing to sign up for.
45
+ def self.sandbox(**options)
46
+ new(**SANDBOX_CREDENTIALS, env: :sandbox, **options)
47
+ end
48
+
49
+ # Issues an invoice immediately (開立發票).
50
+ #
51
+ # @param invoice [Invoice]
52
+ # @param extra [Hash] raw ECPay fields to add or override, for options
53
+ # this gem does not model (for example "InvType" => "08")
54
+ # @return [InvoiceResult]
55
+ # @raise [ValidationError] the invoice breaks an ECPay rule
56
+ # @raise [ApiError] ECPay refused it, for example a reused order number
57
+ def issue(invoice, extra: {})
58
+ data = succeed!(call("/B2CInvoice/Issue", InvoiceMapper.issue(invoice, extra: extra), "issue"))
59
+ InvoiceResult.new(invoice_no: data["InvoiceNo"], issued_at: TaipeiTime.parse(data["InvoiceDate"]),
60
+ random_number: data["RandomNumber"], raw: data.freeze)
61
+ end
62
+
63
+ # Hands an invoice to ECPay to issue later (延遲開立), for example when
64
+ # a return period ends or the goods ship.
65
+ #
66
+ # @param days [Integer, nil] issue automatically after this many days
67
+ # (1 to 15). nil holds the invoice until {#trigger} is called.
68
+ # @param reference [String] your handle for the pending invoice (Tsr)
69
+ # @param notify_url [String, nil] ECPay POSTs here once the invoice exists
70
+ # @return [ScheduledInvoice]
71
+ def schedule(invoice, days: nil, reference: invoice.order_no, notify_url: nil, extra: {})
72
+ params = InvoiceMapper.issue(invoice).merge(
73
+ "DelayFlag" => days.nil? ? "2" : "1",
74
+ "DelayDay" => days.nil? ? 0 : Validation.one_of!(days, SCHEDULE_DAYS, :days, "DelayDay"),
75
+ "Tsr" => Validation.max_length!(Validation.present!(reference, :reference, "Tsr"), 30, :reference, "Tsr").to_s,
76
+ "PayType" => "2",
77
+ "PayAct" => "ECPAY"
78
+ )
79
+ params["NotifyURL"] = Validation.http_url!(notify_url, :notify_url, "NotifyURL") if notify_url
80
+ data = succeed!(call("/B2CInvoice/DelayIssue", params.merge(extra.transform_keys(&:to_s)), "schedule"))
81
+ ScheduledInvoice.new(reference: data["OrderNumber"], raw: data.freeze)
82
+ end
83
+
84
+ # Releases an invoice held by {#schedule}. ECPay does not return the
85
+ # invoice number here; fetch it with {#find} or receive it at notify_url.
86
+ #
87
+ # @return [true]
88
+ def trigger(reference)
89
+ params = {"Tsr" => Validation.present!(reference, :reference, "Tsr").to_s, "PayType" => "2"}
90
+ succeed!(call("/B2CInvoice/TriggerIssue", params, "trigger"), ok: TRIGGERED)
91
+ true
92
+ end
93
+
94
+ # Voids an invoice (作廢發票). Only possible within the same two-month
95
+ # tax period; after that, issue an allowance instead.
96
+ #
97
+ # @param issued_on [Time, Date, String] the day the invoice was issued
98
+ # @param reason [String] up to 20 characters
99
+ # @return [true]
100
+ def void(invoice_no:, issued_on:, reason:)
101
+ params = {"InvoiceNo" => InvoiceMapper.invoice_no!(invoice_no), "InvoiceDate" => InvoiceMapper.invoice_date(issued_on),
102
+ "Reason" => InvoiceMapper.reason!(reason)}
103
+ succeed!(call("/B2CInvoice/Invalid", params, "void"))
104
+ true
105
+ end
106
+
107
+ # Issues a credit note (折讓) against an invoice, for a partial refund
108
+ # or a return after the tax period has closed.
109
+ #
110
+ # @param items [Array<Invoice::Item, Hash>] what is being credited
111
+ # @param email [String, nil] where ECPay sends the allowance notice
112
+ # @param phone [String, nil] ditto, by SMS
113
+ # @return [AllowanceResult]
114
+ def allowance(invoice_no:, issued_on:, items:, email: nil, phone: nil, buyer_name: nil, extra: {})
115
+ params = InvoiceMapper.allowance(invoice_no: invoice_no, issued_on: issued_on, items: items, email: email,
116
+ phone: phone, buyer_name: buyer_name, extra: extra)
117
+ data = succeed!(call("/B2CInvoice/Allowance", params, "allowance"))
118
+ AllowanceResult.new(allowance_no: data["IA_Allow_No"], invoice_no: data["IA_Invoice_No"],
119
+ issued_at: TaipeiTime.parse(data["IA_Date"]), remaining_amount: data["IA_Remain_Allowance_Amt"], raw: data.freeze)
120
+ end
121
+
122
+ # Voids a credit note (作廢折讓).
123
+ #
124
+ # @return [true]
125
+ def void_allowance(invoice_no:, allowance_no:, reason:)
126
+ params = {"InvoiceNo" => InvoiceMapper.invoice_no!(invoice_no),
127
+ "AllowanceNo" => Validation.present!(allowance_no, :allowance_no, "AllowanceNo").to_s,
128
+ "Reason" => InvoiceMapper.reason!(reason)}
129
+ succeed!(call("/B2CInvoice/AllowanceInvalid", params, "void_allowance"))
130
+ true
131
+ end
132
+
133
+ # Looks up an issued invoice, by your order number or by invoice number
134
+ # plus the day it was issued.
135
+ #
136
+ # @return [InvoiceRecord, nil] nil when ECPay has no such invoice
137
+ def find(order_no: nil, invoice_no: nil, issued_on: nil)
138
+ query =
139
+ if order_no
140
+ {"RelateNumber" => order_no.to_s}
141
+ elsif invoice_no && issued_on
142
+ {"InvoiceNo" => InvoiceMapper.invoice_no!(invoice_no), "InvoiceDate" => InvoiceMapper.invoice_date(issued_on)}
143
+ else
144
+ raise ArgumentError, "pass order_no:, or invoice_no: together with issued_on:"
145
+ end
146
+ data = call("/B2CInvoice/GetIssue", query, "find")
147
+ return nil if data["RtnCode"].to_s == NOT_FOUND
148
+
149
+ InvoiceMapper.record(succeed!(data))
150
+ end
151
+
152
+ # A link to ECPay's printable page for an invoice. ECPay only has one
153
+ # for invoices issued with print enabled; the link expires, so fetch it
154
+ # when the buyer asks instead of storing it.
155
+ #
156
+ # @return [String] URL
157
+ def print_url(invoice_no:, issued_on:, extra: {})
158
+ params = {"InvoiceNo" => InvoiceMapper.invoice_no!(invoice_no), "InvoiceDate" => InvoiceMapper.invoice_date(issued_on),
159
+ "PrintStyle" => 1, "IsShowingDetail" => 1}
160
+ succeed!(call("/B2CInvoice/InvoicePrint", params.merge(extra.transform_keys(&:to_s)), "print_url"))["InvoiceHtml"]
161
+ end
162
+
163
+ # Asks whether a donation code (捐贈碼) belongs to a registered charity.
164
+ # A malformed code is answered locally. ECPay's stage environment says
165
+ # yes to every well-formed code.
166
+ #
167
+ # @raise [ApiError] the Ministry of Finance lookup is unavailable
168
+ def donation_code_valid?(code)
169
+ return false unless Invoice::DONATION_CODE.match?(code.to_s)
170
+
171
+ succeed!(call("/B2CInvoice/CheckLoveCode", {"LoveCode" => code.to_s}, "check_donation_code"))["IsExist"] == "Y"
172
+ end
173
+
174
+ # Asks whether a mobile barcode carrier (手機條碼) is registered with the
175
+ # Ministry of Finance. A malformed barcode is answered locally. As with
176
+ # donation codes, the stage environment says yes to every well-formed one.
177
+ #
178
+ # @raise [ApiError] the Ministry of Finance lookup is unavailable
179
+ def mobile_barcode_valid?(number)
180
+ return false unless Invoice::Carrier::FORMATS.fetch(:mobile_barcode).match?(number.to_s)
181
+
182
+ succeed!(call("/B2CInvoice/CheckBarcode", {"BarCode" => number.to_s}, "check_mobile_barcode"))["IsExist"] == "Y"
183
+ end
184
+
185
+ def inspect
186
+ "#<#{self.class.name} merchant_id=#{credentials.merchant_id.inspect} env=#{env.inspect}>"
187
+ end
188
+
189
+ private
190
+
191
+ # AES-128 needs exactly 16 bytes for each. Checking at construction
192
+ # replaces an opaque OpenSSL error on the first request.
193
+ def validate_key_sizes!
194
+ {hash_key: credentials.hash_key, hash_iv: credentials.hash_iv}.each do |name, value|
195
+ next if value.bytesize == AesCipher::KEY_BYTES
196
+
197
+ raise ConfigurationError.new("#{name} must be #{AesCipher::KEY_BYTES} characters for ECPay e-invoices (got #{value.bytesize})",
198
+ zh: "綠界電子發票的 #{name} 必須為 #{AesCipher::KEY_BYTES} 個字元(目前 #{value.bytesize})",
199
+ ja: "ECPay 電子発票の #{name} は #{AesCipher::KEY_BYTES} 文字である必要があります(現在 #{value.bytesize} 文字)")
200
+ end
201
+ end
202
+
203
+ def keys
204
+ {hash_key: credentials.hash_key, hash_iv: credentials.hash_iv}
205
+ end
206
+
207
+ # @return [Hash] the decrypted `Data` of the response
208
+ def call(path, params, operation)
209
+ data = {"MerchantID" => credentials.merchant_id}.merge(params)
210
+ envelope = {"MerchantID" => credentials.merchant_id, "RqHeader" => {"Timestamp" => Time.now.to_i},
211
+ "Data" => AesCipher.encrypt(data, **keys)}
212
+ envelope = {"PlatformID" => platform_id.to_s}.merge(envelope) if platform_id
213
+
214
+ response = @http.post_json("#{HOSTS.fetch(env)}#{path}", envelope,
215
+ log: {provider: PROVIDER, operation: operation, params: data})
216
+ body = parse_envelope(response)
217
+ # TransCode covers the envelope: bad keys or a stale timestamp. ECPay
218
+ # sends these with HTTP 500 and no Data.
219
+ unless body["TransCode"].to_s == TRANSPORT_OK
220
+ raise api_error("T#{body["TransCode"]}", body["TransMsg"], body)
221
+ end
222
+
223
+ AesCipher.decrypt(body["Data"], **keys)
224
+ end
225
+
226
+ def parse_envelope(response)
227
+ body = JSON.parse(response.body)
228
+ return body if body.is_a?(Hash) && body.key?("TransCode")
229
+
230
+ raise unexpected_response(response)
231
+ rescue JSON::ParserError
232
+ raise unexpected_response(response)
233
+ end
234
+
235
+ def succeed!(data, ok: SUCCESS)
236
+ return data if ok.include?(data["RtnCode"].to_s)
237
+
238
+ raise api_error(data["RtnCode"], data["RtnMsg"], data)
239
+ end
240
+
241
+ def api_error(code, vendor_message, raw)
242
+ ApiError.new(code: code, provider: PROVIDER, vendor_message: vendor_message,
243
+ translation: ErrorCodes.translate(:ecpay_invoice, code), translation_ja: ErrorCodes.translate(:ecpay_invoice, code, :ja), raw: raw)
244
+ end
245
+
246
+ def unexpected_response(response)
247
+ HttpError.new("unexpected response from ECPay e-invoice (HTTP #{response.status})", status: response.status,
248
+ body: response.body, zh: "綠界電子發票回應格式不符預期(HTTP #{response.status})",
249
+ ja: "ECPay 電子発票から想定外のレスポンスが返されました(HTTP #{response.status})")
250
+ end
251
+ end
252
+ end
253
+ end
@@ -0,0 +1,222 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ module ECPay
5
+ # Translates between the provider-neutral invoice model and ECPay's B2C
6
+ # e-invoice fields. ECPay's own rules are checked here so that a mistake
7
+ # reads as a sentence instead of a numeric RtnCode from the API.
8
+ # Reference: https://developers.ecpay.com.tw/7896/
9
+ module InvoiceMapper
10
+ TAX_TYPES = {taxable: "1", zero_rated: "2", exempt: "3", mixed: "9"}.freeze
11
+ CARRIER_TYPES = {member: "1", citizen_certificate: "2", mobile_barcode: "3"}.freeze
12
+ CUSTOMS_CLEARANCE = {non_customs: "1", customs: "2"}.freeze
13
+ ZERO_TAX_RATE_REASONS = ("71".."79").to_a.freeze
14
+ INVOICE_NO = /\A[A-Z]{2}\d{8}\z/
15
+ # A B2C invoice has no tax ID; ECPay reports that as ten zeros.
16
+ NO_TAX_ID = /\A0*\z/
17
+
18
+ # vendor field => [our name for it, maximum characters]
19
+ LIMITS = {
20
+ "RelateNumber" => [:order_no, 50],
21
+ "CustomerID" => [:"buyer.customer_id", 20],
22
+ "CustomerName" => [:"buyer.name", 60],
23
+ "CustomerAddr" => [:"buyer.address", 100],
24
+ "CustomerPhone" => [:"buyer.phone", 20],
25
+ "CustomerEmail" => [:"buyer.email", 80],
26
+ "InvoiceRemark" => [:remark, 200]
27
+ }.freeze
28
+ ITEM_LIMITS = {
29
+ "ItemName" => [:"items.name", 500],
30
+ "ItemWord" => [:"items.unit", 6],
31
+ "ItemRemark" => [:"items.remark", 120]
32
+ }.freeze
33
+ REASON_LIMIT = 20
34
+
35
+ module_function
36
+
37
+ # @return [Hash] the `Data` payload for /B2CInvoice/Issue
38
+ def issue(invoice, extra: {})
39
+ validate!(invoice)
40
+ buyer = invoice.buyer
41
+ carrier = invoice.carrier
42
+ params = {
43
+ "RelateNumber" => invoice.order_no,
44
+ "CustomerID" => buyer.customer_id.to_s,
45
+ "CustomerIdentifier" => buyer.tax_id.to_s,
46
+ "CustomerName" => buyer.name.to_s,
47
+ "CustomerAddr" => buyer.address.to_s,
48
+ "CustomerPhone" => buyer.phone.to_s,
49
+ "CustomerEmail" => buyer.email.to_s,
50
+ "ClearanceMark" => CUSTOMS_CLEARANCE.fetch(invoice.customs_clearance, ""),
51
+ "Print" => flag(invoice.print?),
52
+ "Donation" => flag(invoice.donation?),
53
+ "LoveCode" => invoice.donation_code.to_s,
54
+ "CarrierType" => carrier ? CARRIER_TYPES.fetch(carrier.type) : "",
55
+ # The member carrier is keyed by the buyer's contact details, and
56
+ # ECPay rejects a number alongside it.
57
+ "CarrierNum" => (carrier && carrier.type != :member) ? carrier.number.to_s : "",
58
+ "TaxType" => TAX_TYPES.fetch(invoice.tax_type),
59
+ "SalesAmount" => invoice.total,
60
+ "InvoiceRemark" => invoice.remark.to_s,
61
+ "Items" => items(invoice.items, TAX_TYPES[invoice.tax_type], remark: true),
62
+ "InvType" => "07",
63
+ "vat" => "1"
64
+ }
65
+ params["ZeroTaxRateReason"] = invoice.zero_tax_rate_reason if invoice.zero_tax_rate_reason
66
+ check_limits!(params, LIMITS)
67
+ params.merge(extra.transform_keys(&:to_s))
68
+ end
69
+
70
+ # @return [Hash] the `Data` payload for /B2CInvoice/Allowance
71
+ def allowance(invoice_no:, issued_on:, items:, email: nil, phone: nil, buyer_name: nil, extra: {})
72
+ lines = (items.is_a?(Hash) ? [items] : Array(items)).map { |item| Invoice::Item.coerce(item) }
73
+ Validation.fail!(:items, "items must contain at least one item", "items 至少需要一個品項", "items には少なくとも 1 つの品目が必要です") if lines.empty?
74
+
75
+ {
76
+ "InvoiceNo" => invoice_no!(invoice_no),
77
+ "InvoiceDate" => invoice_date(issued_on),
78
+ "AllowanceNotify" => allowance_notify(email, phone),
79
+ "CustomerName" => buyer_name.to_s,
80
+ "NotifyMail" => email.to_s,
81
+ "NotifyPhone" => phone.to_s,
82
+ "AllowanceAmount" => Decimal.round(lines.sum(0r, &:amount)),
83
+ "Items" => items(lines, TAX_TYPES[:taxable], remark: false)
84
+ }.merge(extra.transform_keys(&:to_s))
85
+ end
86
+
87
+ # @return [InvoiceRecord] built from a /B2CInvoice/GetIssue response
88
+ def record(data)
89
+ tax_id = data["IIS_Identifier"].to_s
90
+ InvoiceRecord.new(
91
+ invoice_no: data["IIS_Number"],
92
+ order_no: data["IIS_Relate_Number"],
93
+ total: data["IIS_Sales_Amount"],
94
+ tax_amount: data["IIS_Tax_Amount"],
95
+ issued_at: TaipeiTime.parse(data["IIS_Create_Date"]),
96
+ random_number: data["IIS_Random_Number"],
97
+ buyer: Invoice::Buyer.new(name: data["IIS_Customer_Name"], email: data["IIS_Customer_Email"],
98
+ phone: data["IIS_Customer_Phone"], address: data["IIS_Customer_Addr"],
99
+ tax_id: NO_TAX_ID.match?(tax_id) ? nil : tax_id, customer_id: data["IIS_Customer_ID"]),
100
+ carrier_type: CARRIER_TYPES.key(data["IIS_Carrier_Type"].to_s),
101
+ carrier_number: blank_to_nil(data["IIS_Carrier_Num"]),
102
+ # ECPay reports "0" when the invoice was not donated.
103
+ donation_code: (data["IIS_Love_Code"].to_s == "0") ? nil : blank_to_nil(data["IIS_Love_Code"]),
104
+ voided: data["IIS_Invalid_Status"].to_s == "1",
105
+ uploaded: data["IIS_Upload_Status"].to_s == "1",
106
+ printed: data["IIS_Print_Flag"].to_s == "1",
107
+ remaining_allowance_amount: data["IIS_Remain_Allowance_Amt"],
108
+ raw: data.freeze
109
+ )
110
+ end
111
+
112
+ def invoice_no!(value)
113
+ Validation.format!(value, INVOICE_NO, :invoice_no, "InvoiceNo",
114
+ "must be 2 capital letters followed by 8 digits", "必須為 2 碼大寫英文加 8 碼數字",
115
+ "大文字の英字 2 文字に続けて数字 8 桁である必要があります").to_s
116
+ end
117
+
118
+ # ECPay looks an invoice up by number and the day it was issued.
119
+ def invoice_date(value)
120
+ TaipeiTime.date(Validation.present!(value, :issued_on, "InvoiceDate"))
121
+ end
122
+
123
+ def reason!(value)
124
+ Validation.present!(value, :reason, "Reason")
125
+ Validation.max_length!(value, REASON_LIMIT, :reason, "Reason").to_s
126
+ end
127
+
128
+ def flag(value) = value ? "1" : "0"
129
+
130
+ def blank_to_nil(value)
131
+ text = value.to_s
132
+ text.empty? ? nil : text
133
+ end
134
+
135
+ def items(lines, default_tax_type, remark:)
136
+ lines.each_with_index.map do |item, index|
137
+ line = {
138
+ "ItemSeq" => index + 1,
139
+ "ItemName" => item.name,
140
+ "ItemCount" => Decimal.to_number(item.quantity),
141
+ "ItemWord" => item.unit,
142
+ "ItemPrice" => Decimal.to_number(item.unit_price),
143
+ "ItemTaxType" => item.tax_type ? TAX_TYPES.fetch(item.tax_type) : default_tax_type,
144
+ "ItemAmount" => Decimal.to_number(item.amount)
145
+ }
146
+ line["ItemRemark"] = item.remark.to_s if remark
147
+ check_limits!(line, ITEM_LIMITS)
148
+ end
149
+ end
150
+
151
+ def allowance_notify(email, phone)
152
+ if email && phone then "A"
153
+ elsif email then "E"
154
+ elsif phone then "S"
155
+ else "N"
156
+ end
157
+ end
158
+
159
+ def check_limits!(params, limits)
160
+ limits.each do |vendor_field, (field, max)|
161
+ Validation.max_length!(params[vendor_field], max, field, vendor_field) if params.key?(vendor_field)
162
+ end
163
+ params
164
+ end
165
+
166
+ def validate!(invoice)
167
+ validate_contact!(invoice.buyer)
168
+ validate_delivery!(invoice)
169
+ validate_zero_rate!(invoice)
170
+ end
171
+
172
+ def validate_contact!(buyer)
173
+ if buyer.email.nil? && buyer.phone.nil?
174
+ Validation.fail!(:buyer, "buyer needs an email or a phone number (CustomerEmail / CustomerPhone)",
175
+ "買受人的電子信箱與手機號碼不可同時為空白(CustomerEmail / CustomerPhone)",
176
+ "buyer にはメールアドレスか電話番号のどちらかが必要です(CustomerEmail / CustomerPhone)")
177
+ end
178
+ return unless buyer.phone
179
+
180
+ Validation.format!(buyer.phone, /\A\d+\z/, :"buyer.phone", "CustomerPhone", "must contain digits only", "只能包含數字",
181
+ "数字のみである必要があります")
182
+ end
183
+
184
+ # How the buyer receives the invoice: on paper, in a carrier, or (for a
185
+ # donated invoice) not at all.
186
+ def validate_delivery!(invoice)
187
+ carrier = invoice.carrier
188
+ if invoice.business? && carrier.nil? && !invoice.print?
189
+ Validation.fail!(:carrier, "an invoice with a tax ID needs a carrier or print: true (CarrierType / Print)",
190
+ "有統一編號的發票須選擇載具或索取紙本(CarrierType / Print)",
191
+ "統一編号のある発票には、キャリア(carrier)か print: true のどちらかが必要です(CarrierType / Print)")
192
+ end
193
+ return unless invoice.print?
194
+
195
+ # Only a business invoice saved to a mobile barcode may also be printed.
196
+ if carrier && !(invoice.business? && carrier.type == :mobile_barcode)
197
+ Validation.fail!(:print, "a printed invoice cannot use a #{carrier.type.inspect} carrier (Print / CarrierType); " \
198
+ "pass print: false or carrier: false", "列印的發票不可使用 #{carrier.type.inspect} 載具(Print / CarrierType),請設定 print: false 或 carrier: false",
199
+ "印刷する発票では #{carrier.type.inspect} キャリアを使用できません(Print / CarrierType)。print: false または carrier: false を指定してください")
200
+ end
201
+ {name: "CustomerName", address: "CustomerAddr"}.each do |attribute, vendor_field|
202
+ next if invoice.buyer.public_send(attribute)
203
+
204
+ Validation.fail!(:"buyer.#{attribute}", "buyer.#{attribute} (#{vendor_field}) is required for a printed invoice",
205
+ "列印發票時 buyer.#{attribute}(#{vendor_field})為必填",
206
+ "印刷する発票では buyer.#{attribute}(#{vendor_field})が必須です")
207
+ end
208
+ end
209
+
210
+ def validate_zero_rate!(invoice)
211
+ return unless invoice.tax_type == :zero_rated || invoice.items.any? { |item| item.tax_type == :zero_rated }
212
+
213
+ if invoice.customs_clearance.nil?
214
+ Validation.fail!(:customs_clearance, "customs_clearance (ClearanceMark) is required for zero-rated sales: :customs or :non_customs",
215
+ "零稅率銷售必須指定 customs_clearance(ClearanceMark)::customs 或 :non_customs",
216
+ "ゼロ税率の販売では customs_clearance(ClearanceMark)が必須です。:customs または :non_customs を指定してください")
217
+ end
218
+ Validation.one_of!(invoice.zero_tax_rate_reason, ZERO_TAX_RATE_REASONS, :zero_tax_rate_reason, "ZeroTaxRateReason")
219
+ end
220
+ end
221
+ end
222
+ end
@@ -0,0 +1,188 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ module ECPay
5
+ # Client for ECPay's all-in-one payment product (全方位金流 AIO).
6
+ #
7
+ # @example
8
+ # client = TaiwanPayments::ECPay::PaymentClient.sandbox
9
+ # form = client.checkout(order_no: "ORD1001", amount: 1200, description: "Order 1001",
10
+ # items: ["Widget x2"], return_url: "https://shop.example/webhooks/ecpay")
11
+ class PaymentClient
12
+ PROVIDER = "ECPay"
13
+ HOSTS = {sandbox: "https://payment-stage.ecpay.com.tw", production: "https://payment.ecpay.com.tw"}.freeze
14
+ QUERY_PATH = "/Cashier/QueryTradeInfo/V5"
15
+ ACTION_PATH = "/CreditDetail/DoAction"
16
+ NOT_FOUND = "10200047"
17
+ # Published by ECPay for anyone to test with: https://developers.ecpay.com.tw/?p=2856
18
+ SANDBOX_CREDENTIALS = {merchant_id: "3002607", hash_key: "pwFHCqoQZGmho4w6", hash_iv: "EkRm7iFT261dpevs"}.freeze
19
+ # Rails adds these to `params`. They were never signed by ECPay, so they
20
+ # are dropped for anyone who passes `params` instead of the POST body.
21
+ ROUTING_KEYS = %w[controller action].freeze
22
+ CREDIT_ACTIONS = {capture: "C", refund: "R", cancel_capture: "E", void_authorization: "N"}.freeze
23
+
24
+ attr_reader :credentials, :env, :platform_id
25
+
26
+ # @param env [Symbol] :sandbox or :production. Required, so that going
27
+ # live is always a deliberate choice.
28
+ # @param platform_id [String, nil] only for platform merchants (特約合作平台商)
29
+ def initialize(merchant_id:, hash_key:, hash_iv:, env:, platform_id: nil, http: HttpClient.new)
30
+ @credentials = Credentials.new(merchant_id: merchant_id, hash_key: hash_key, hash_iv: hash_iv)
31
+ @env = Environment.normalize(env)
32
+ @platform_id = platform_id
33
+ @http = http
34
+ freeze
35
+ end
36
+
37
+ # A client for ECPay's shared public test merchant. Nothing to sign up for.
38
+ def self.sandbox(**options)
39
+ new(**SANDBOX_CREDENTIALS, env: :sandbox, **options)
40
+ end
41
+
42
+ # Builds the form that sends the customer to ECPay's payment page.
43
+ #
44
+ # @param options see {Checkout#initialize}
45
+ # @return [HostedForm] render it in the customer's browser; ECPay rejects
46
+ # server-side submissions
47
+ def checkout(**options)
48
+ HostedForm.new(action_url: url(Checkout::PATH), fields: sign(Checkout.new(**options).to_vendor_params))
49
+ end
50
+
51
+ # Verifies and wraps a callback ECPay POSTed to ReturnURL,
52
+ # OrderResultURL, PaymentInfoURL or ClientRedirectURL.
53
+ #
54
+ # @param params [Hash, #to_unsafe_h] the POST body. In Rails prefer
55
+ # `request.request_parameters`, which excludes route parameters.
56
+ # @raise [SignatureError] the payload was not signed with this merchant's keys
57
+ def notification(params)
58
+ fields = (params.respond_to?(:to_unsafe_h) ? params.to_unsafe_h : params.to_h)
59
+ .to_h { |name, value| [name.to_s, value.to_s] }
60
+ .except(*ROUTING_KEYS)
61
+
62
+ unless CheckMacValue.valid?(fields, hash_key: credentials.hash_key, hash_iv: credentials.hash_iv)
63
+ raise SignatureError.new("ECPay notification failed CheckMacValue verification",
64
+ zh: "綠界通知的 CheckMacValue 驗證失敗", ja: "ECPay からの通知の CheckMacValue 検証に失敗しました")
65
+ end
66
+
67
+ PaymentNotification.new(fields)
68
+ end
69
+
70
+ # Asks ECPay for the current state of an order. Use it to reconcile
71
+ # orders whose webhook never arrived; ECPay recommends waiting about ten
72
+ # minutes after a card payment before the first query.
73
+ #
74
+ # @return [TradeInfo, nil] nil when ECPay has no trade for this order
75
+ # number, which is normal if the customer never reached the payment page
76
+ # @raise [RateLimitedError] ECPay blocks callers that poll too fast
77
+ def query(order_no:)
78
+ response = post(QUERY_PATH, {"MerchantTradeNo" => order_no, "TimeStamp" => Time.now.to_i}, "query")
79
+ fields = ResponseBody.parse(response.body)
80
+ raise unexpected_response(response) unless fields.key?("TradeStatus")
81
+
82
+ # Failure responses are acted on before the signature check: they never
83
+ # produce a successful result, and when our keys are wrong the response
84
+ # signature cannot verify, which would hide ECPay's actual explanation.
85
+ if fields["TradeNo"].to_s.empty?
86
+ return nil if fields["TradeStatus"] == NOT_FOUND
87
+
88
+ raise api_error(fields["TradeStatus"], fields["RtnMsg"], fields)
89
+ end
90
+
91
+ verify_response!(response.body, fields)
92
+ TradeInfo.new(fields)
93
+ end
94
+
95
+ # Settles an authorised card payment (關帳). Only needed when automatic
96
+ # capture is switched off for the merchant.
97
+ # @return [CreditActionResult]
98
+ def capture(order_no:, trade_no:, amount:)
99
+ credit_action(:capture, order_no, trade_no, amount)
100
+ end
101
+
102
+ # Refunds part or all of a captured card payment (退刷). Instalment and
103
+ # reward-point payments can only be refunded in full.
104
+ # @return [CreditActionResult]
105
+ def refund(order_no:, trade_no:, amount:)
106
+ credit_action(:refund, order_no, trade_no, amount)
107
+ end
108
+
109
+ # Undoes a capture that has not been settled yet (取消關帳).
110
+ # @return [CreditActionResult]
111
+ def cancel_capture(order_no:, trade_no:, amount:)
112
+ credit_action(:cancel_capture, order_no, trade_no, amount)
113
+ end
114
+
115
+ # Releases an authorisation that will never be captured (放棄).
116
+ # @return [CreditActionResult]
117
+ def void_authorization(order_no:, trade_no:, amount:)
118
+ credit_action(:void_authorization, order_no, trade_no, amount)
119
+ end
120
+
121
+ # @return [String] CheckMacValue for arbitrary parameters, for debugging
122
+ def check_mac_value(params)
123
+ CheckMacValue.generate(params, hash_key: credentials.hash_key, hash_iv: credentials.hash_iv)
124
+ end
125
+
126
+ def inspect
127
+ "#<#{self.class.name} merchant_id=#{credentials.merchant_id.inspect} env=#{env.inspect}>"
128
+ end
129
+
130
+ private
131
+
132
+ def url(path)
133
+ "#{HOSTS.fetch(env)}#{path}"
134
+ end
135
+
136
+ def sign(params)
137
+ fields = {"MerchantID" => credentials.merchant_id}.merge(params)
138
+ fields["PlatformID"] = platform_id.to_s if platform_id
139
+ fields.merge(CheckMacValue::FIELD => check_mac_value(fields))
140
+ end
141
+
142
+ def post(path, params, operation)
143
+ fields = sign(params.transform_values(&:to_s))
144
+ response = @http.post_form(url(path), fields, log: {provider: PROVIDER, operation: operation, params: fields})
145
+ if response.status == 403
146
+ raise RateLimitedError.new("ECPay refused the request (HTTP 403): too many calls; wait about 30 minutes",
147
+ status: 403, body: response.body, zh: "綠界拒絕請求(HTTP 403):呼叫過於頻繁,請約 30 分鐘後再試",
148
+ ja: "ECPay がリクエストを拒否しました(HTTP 403)。呼び出しが多すぎます。30 分ほど待ってから再試行してください")
149
+ end
150
+ response
151
+ end
152
+
153
+ def credit_action(action, order_no, trade_no, amount)
154
+ params = {
155
+ "MerchantTradeNo" => order_no,
156
+ "TradeNo" => Validation.present!(trade_no, :trade_no, "TradeNo"),
157
+ "Action" => CREDIT_ACTIONS.fetch(action),
158
+ "TotalAmount" => Money.twd!(amount, :amount, "TotalAmount")
159
+ }
160
+ response = post(ACTION_PATH, params, action.to_s)
161
+ fields = ResponseBody.parse(response.body)
162
+ raise unexpected_response(response) unless fields.key?("RtnCode")
163
+ raise api_error(fields["RtnCode"], fields["RtnMsg"], fields) unless fields["RtnCode"] == "1"
164
+
165
+ CreditActionResult.new(order_no: fields["MerchantTradeNo"], trade_no: fields["TradeNo"], message: fields["RtnMsg"], raw: fields.freeze)
166
+ end
167
+
168
+ def verify_response!(body, fields)
169
+ keys = {hash_key: credentials.hash_key, hash_iv: credentials.hash_iv}
170
+ return if CheckMacValue.valid_body?(body, **keys) || CheckMacValue.valid?(fields, **keys)
171
+
172
+ raise SignatureError.new("ECPay response failed CheckMacValue verification",
173
+ zh: "綠界回應的 CheckMacValue 驗證失敗", ja: "ECPay のレスポンスの CheckMacValue 検証に失敗しました")
174
+ end
175
+
176
+ def api_error(code, vendor_message, raw)
177
+ ApiError.new(code: code, provider: PROVIDER, vendor_message: vendor_message,
178
+ translation: ErrorCodes.translate(:ecpay_payment, code), translation_ja: ErrorCodes.translate(:ecpay_payment, code, :ja), raw: raw)
179
+ end
180
+
181
+ def unexpected_response(response)
182
+ HttpError.new("unexpected response from ECPay (HTTP #{response.status})", status: response.status,
183
+ body: response.body, zh: "綠界回應格式不符預期(HTTP #{response.status})",
184
+ ja: "ECPay から想定外のレスポンスが返されました(HTTP #{response.status})")
185
+ end
186
+ end
187
+ end
188
+ end