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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +24 -0
- data/LICENSE.txt +21 -0
- data/README.ja.md +293 -0
- data/README.md +291 -0
- data/README.zh-TW.md +293 -0
- data/docs/ecpay-invoices.md +202 -0
- data/docs/ecpay-payments.md +191 -0
- data/docs/glossary/concepts.ja.md +33 -0
- data/docs/glossary/concepts.md +34 -0
- data/docs/glossary/ecpay-invoice.ja.md +113 -0
- data/docs/glossary/ecpay-invoice.md +114 -0
- data/docs/glossary/ecpay-payment.ja.md +64 -0
- data/docs/glossary/ecpay-payment.md +65 -0
- data/docs/rails.md +184 -0
- data/docs/sandbox-setup.md +104 -0
- data/docs/taiwan-payments-101.ja.md +138 -0
- data/docs/taiwan-payments-101.md +138 -0
- data/docs/taiwan-payments-101.zh-TW.md +138 -0
- data/docs/testing.md +140 -0
- data/docs/webhooks.md +113 -0
- data/exe/taiwan_payments +6 -0
- data/lib/generators/taiwan_payments/install/install_generator.rb +41 -0
- data/lib/generators/taiwan_payments/install/templates/ecpay_controller.rb.tt +26 -0
- data/lib/generators/taiwan_payments/install/templates/initializer.rb.tt +38 -0
- data/lib/taiwan_payments/cli.rb +271 -0
- data/lib/taiwan_payments/configuration.rb +86 -0
- data/lib/taiwan_payments/credentials.rb +27 -0
- data/lib/taiwan_payments/decimal.rb +36 -0
- data/lib/taiwan_payments/ecpay/aes_cipher.rb +36 -0
- data/lib/taiwan_payments/ecpay/check_mac_value.rb +63 -0
- data/lib/taiwan_payments/ecpay/checkout.rb +154 -0
- data/lib/taiwan_payments/ecpay/invoice_client.rb +253 -0
- data/lib/taiwan_payments/ecpay/invoice_mapper.rb +222 -0
- data/lib/taiwan_payments/ecpay/payment_client.rb +188 -0
- data/lib/taiwan_payments/ecpay/payment_methods.rb +40 -0
- data/lib/taiwan_payments/ecpay/payment_notification.rb +127 -0
- data/lib/taiwan_payments/ecpay/response_body.rb +30 -0
- data/lib/taiwan_payments/ecpay/trade_info.rb +68 -0
- data/lib/taiwan_payments/ecpay.rb +19 -0
- data/lib/taiwan_payments/environment.rb +22 -0
- data/lib/taiwan_payments/error_codes/ecpay_invoice.yml +80 -0
- data/lib/taiwan_payments/error_codes/ecpay_payment.yml +59 -0
- data/lib/taiwan_payments/error_codes.rb +23 -0
- data/lib/taiwan_payments/errors.rb +71 -0
- data/lib/taiwan_payments/form_helper.rb +21 -0
- data/lib/taiwan_payments/glossary/concepts.yml +122 -0
- data/lib/taiwan_payments/glossary/ecpay_invoice.yml +523 -0
- data/lib/taiwan_payments/glossary/ecpay_payment.yml +278 -0
- data/lib/taiwan_payments/glossary.rb +106 -0
- data/lib/taiwan_payments/hosted_form.rb +46 -0
- data/lib/taiwan_payments/http_client.rb +62 -0
- data/lib/taiwan_payments/instrumentation.rb +42 -0
- data/lib/taiwan_payments/invoice.rb +235 -0
- data/lib/taiwan_payments/money.rb +32 -0
- data/lib/taiwan_payments/php_compat.rb +39 -0
- data/lib/taiwan_payments/railtie.rb +23 -0
- data/lib/taiwan_payments/redactor.rb +29 -0
- data/lib/taiwan_payments/taipei_time.rb +42 -0
- data/lib/taiwan_payments/tax_id.rb +26 -0
- data/lib/taiwan_payments/testing.rb +152 -0
- data/lib/taiwan_payments/validation.rb +56 -0
- data/lib/taiwan_payments/version.rb +5 -0
- data/lib/taiwan_payments/webhooks.rb +54 -0
- data/lib/taiwan_payments.rb +67 -0
- metadata +118 -0
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module TaiwanPayments
|
|
4
|
+
# A Taiwanese e-invoice (電子發票) to be issued, described independently of
|
|
5
|
+
# the vendor that will issue it. See docs/taiwan-payments-101.md for the
|
|
6
|
+
# concepts (carriers, donation codes, tax IDs).
|
|
7
|
+
#
|
|
8
|
+
# @example Consumer invoice saved to the buyer's mobile barcode carrier
|
|
9
|
+
# TaiwanPayments::Invoice.new(
|
|
10
|
+
# order_no: "ORD1001",
|
|
11
|
+
# buyer: {email: "buyer@example.com"},
|
|
12
|
+
# carrier: "/ABC+123",
|
|
13
|
+
# items: [{name: "Oolong tea", quantity: 2, unit_price: 500}]
|
|
14
|
+
# )
|
|
15
|
+
class Invoice
|
|
16
|
+
TAX_TYPES = %i[taxable zero_rated exempt mixed].freeze
|
|
17
|
+
ITEM_TAX_TYPES = %i[taxable zero_rated exempt].freeze
|
|
18
|
+
CUSTOMS_CLEARANCE = %i[customs non_customs].freeze
|
|
19
|
+
DONATION_CODE = /\A\d{3,7}\z/
|
|
20
|
+
|
|
21
|
+
# Who the invoice is made out to. Everything is optional for a consumer
|
|
22
|
+
# invoice except a way to notify them (vendors require email or phone).
|
|
23
|
+
# A `tax_id` (統一編號) makes it a business invoice.
|
|
24
|
+
Buyer = Data.define(:name, :email, :phone, :address, :tax_id, :customer_id)
|
|
25
|
+
|
|
26
|
+
class Buyer
|
|
27
|
+
def self.coerce(value)
|
|
28
|
+
value.is_a?(Buyer) ? value : new(**value.to_h.transform_keys(&:to_sym))
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def initialize(name: nil, email: nil, phone: nil, address: nil, tax_id: nil, customer_id: nil)
|
|
32
|
+
values = {name:, email:, phone:, address:, tax_id:, customer_id:}
|
|
33
|
+
super(**values.transform_values { |value| value.to_s.strip.then { |text| text.empty? ? nil : text } })
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# 載具: where a paperless invoice is stored so the buyer can claim lottery
|
|
38
|
+
# prizes. `:member` is the issuing vendor's own carrier, keyed by the
|
|
39
|
+
# buyer's email or phone and needing no number.
|
|
40
|
+
Carrier = Data.define(:type, :number)
|
|
41
|
+
|
|
42
|
+
class Carrier
|
|
43
|
+
TYPES = %i[member mobile_barcode citizen_certificate].freeze
|
|
44
|
+
# Formats are fixed by the Ministry of Finance.
|
|
45
|
+
FORMATS = {mobile_barcode: %r{\A/[0-9A-Z+\-.]{7}\z}, citizen_certificate: /\A[A-Z]{2}\d{14}\z/}.freeze
|
|
46
|
+
FORMAT_HINTS = {
|
|
47
|
+
mobile_barcode: ["must be '/' followed by 7 of 0-9, A-Z, + - .", "必須為 / 開頭加上 7 碼(0-9、A-Z、+、-、.)",
|
|
48
|
+
"「/」に続けて 7 文字(0-9、A-Z、+、-、.)である必要があります"],
|
|
49
|
+
citizen_certificate: ["must be 2 capital letters followed by 14 digits", "必須為 2 碼大寫英文加 14 碼數字",
|
|
50
|
+
"大文字の英字 2 文字に続けて数字 14 桁である必要があります"]
|
|
51
|
+
}.freeze
|
|
52
|
+
|
|
53
|
+
def self.member = new(type: :member)
|
|
54
|
+
|
|
55
|
+
def self.mobile_barcode(number) = new(type: :mobile_barcode, number: number)
|
|
56
|
+
|
|
57
|
+
def self.citizen_certificate(number) = new(type: :citizen_certificate, number: number)
|
|
58
|
+
|
|
59
|
+
# Accepts a Carrier, a type symbol, `{type:, number:}`, or just the
|
|
60
|
+
# number, whose format identifies its type.
|
|
61
|
+
def self.coerce(value)
|
|
62
|
+
case value
|
|
63
|
+
when Carrier then value
|
|
64
|
+
when Symbol then new(type: value)
|
|
65
|
+
when Hash then new(**value.transform_keys(&:to_sym))
|
|
66
|
+
else
|
|
67
|
+
type = FORMATS.find { |_, format| format.match?(value.to_s) }&.first
|
|
68
|
+
type ? new(type: type, number: value.to_s) : mobile_barcode(value)
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def initialize(type:, number: nil)
|
|
73
|
+
type = Validation.one_of!(type.to_s.to_sym, TYPES, :carrier)
|
|
74
|
+
number = number.to_s.strip
|
|
75
|
+
if (format = FORMATS[type])
|
|
76
|
+
Validation.format!(number, format, :carrier, type, *FORMAT_HINTS.fetch(type))
|
|
77
|
+
end
|
|
78
|
+
super(type: type, number: number.empty? ? nil : number)
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# One invoice line. Prices include tax, which is how consumer prices are
|
|
83
|
+
# quoted in Taiwan.
|
|
84
|
+
Item = Data.define(:name, :quantity, :unit, :unit_price, :amount, :tax_type, :remark)
|
|
85
|
+
|
|
86
|
+
class Item
|
|
87
|
+
# 式 ("lot") is the customary unit when nothing more specific applies,
|
|
88
|
+
# for example services and shipping.
|
|
89
|
+
DEFAULT_UNIT = "式"
|
|
90
|
+
|
|
91
|
+
def self.coerce(value)
|
|
92
|
+
value.is_a?(Item) ? value : new(**value.to_h.transform_keys(&:to_sym))
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# @param amount [Numeric, nil] line total; defaults to quantity x unit_price
|
|
96
|
+
# @param tax_type [Symbol, nil] only needed on a :mixed invoice
|
|
97
|
+
def initialize(name:, unit_price:, quantity: 1, unit: DEFAULT_UNIT, amount: nil, tax_type: nil, remark: nil)
|
|
98
|
+
Validation.present!(name, :"items.name")
|
|
99
|
+
quantity = Decimal.parse(quantity, :"items.quantity")
|
|
100
|
+
unit_price = Decimal.parse(unit_price, :"items.unit_price")
|
|
101
|
+
amount = amount.nil? ? quantity * unit_price : Decimal.parse(amount, :"items.amount")
|
|
102
|
+
unless quantity.positive?
|
|
103
|
+
Validation.fail!(:"items.quantity", "items.quantity must be greater than 0 (#{name})", "items.quantity 必須大於 0(#{name})",
|
|
104
|
+
"items.quantity は 0 より大きい必要があります(#{name})")
|
|
105
|
+
end
|
|
106
|
+
tax_type = Validation.one_of!(tax_type.to_sym, ITEM_TAX_TYPES, :"items.tax_type") if tax_type
|
|
107
|
+
|
|
108
|
+
super(name: name.to_s, quantity:, unit: unit.to_s, unit_price:, amount:, tax_type:, remark: remark&.to_s)
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
attr_reader :order_no, :buyer, :carrier, :donation_code, :items, :tax_type, :customs_clearance,
|
|
113
|
+
:zero_tax_rate_reason, :remark
|
|
114
|
+
|
|
115
|
+
# @param order_no [String] your unique reference for this invoice
|
|
116
|
+
# @param items [Array<Item, Hash>]
|
|
117
|
+
# @param buyer [Buyer, Hash]
|
|
118
|
+
# @param carrier [Carrier, Symbol, String, Hash, false, nil] nil picks a
|
|
119
|
+
# sensible default (see below); false means no carrier
|
|
120
|
+
# @param donation_code [String, nil] 捐贈碼 of the charity receiving the invoice
|
|
121
|
+
# @param print [Boolean, nil] the buyer gets a printed copy; nil picks a default
|
|
122
|
+
# @param tax_type [Symbol] one of TAX_TYPES
|
|
123
|
+
# @param customs_clearance [Symbol, nil] :customs or :non_customs, for zero-rated sales
|
|
124
|
+
# @param zero_tax_rate_reason [String, Integer, nil] statutory reason code for zero-rated sales
|
|
125
|
+
# @param remark [String, nil] printed on the invoice
|
|
126
|
+
def initialize(order_no:, items:, buyer: {}, carrier: nil, donation_code: nil, print: nil, tax_type: :taxable,
|
|
127
|
+
customs_clearance: nil, zero_tax_rate_reason: nil, remark: nil)
|
|
128
|
+
@order_no = Validation.present!(order_no, :order_no).to_s
|
|
129
|
+
@buyer = Buyer.coerce(buyer)
|
|
130
|
+
@items = (items.is_a?(Hash) ? [items] : Array(items)).map { |item| Item.coerce(item) }.freeze
|
|
131
|
+
@donation_code = donation_code.to_s.strip.then { |code| code.empty? ? nil : code }
|
|
132
|
+
@tax_type = Validation.one_of!(tax_type.to_s.to_sym, TAX_TYPES, :tax_type)
|
|
133
|
+
@customs_clearance = customs_clearance && Validation.one_of!(customs_clearance.to_sym, CUSTOMS_CLEARANCE, :customs_clearance)
|
|
134
|
+
@zero_tax_rate_reason = zero_tax_rate_reason&.to_s
|
|
135
|
+
@remark = remark&.to_s
|
|
136
|
+
@carrier = resolve_carrier(carrier, print)
|
|
137
|
+
# A business invoice with no carrier has to be handed over on paper.
|
|
138
|
+
@print = if print.nil?
|
|
139
|
+
business? && @carrier.nil?
|
|
140
|
+
else
|
|
141
|
+
(print ? true : false)
|
|
142
|
+
end
|
|
143
|
+
validate!
|
|
144
|
+
freeze
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# @return [Boolean] true when the buyer gave a tax ID (B2B invoice)
|
|
148
|
+
def business? = !buyer.tax_id.nil?
|
|
149
|
+
|
|
150
|
+
def donation? = !donation_code.nil?
|
|
151
|
+
|
|
152
|
+
def print? = @print
|
|
153
|
+
|
|
154
|
+
# @return [Integer] invoice total in TWD, tax included
|
|
155
|
+
def total
|
|
156
|
+
Decimal.round(items.sum(0r, &:amount))
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
private
|
|
160
|
+
|
|
161
|
+
# A consumer invoice must end up somewhere the buyer can reach it: a
|
|
162
|
+
# carrier, a charity, or paper. When the caller picks none of these, the
|
|
163
|
+
# vendor's member carrier is used, which stores the invoice and notifies
|
|
164
|
+
# the buyer by email or SMS. That is what Taiwanese online shops normally
|
|
165
|
+
# do, and it spares newcomers from issuing an invoice nobody can claim.
|
|
166
|
+
def resolve_carrier(carrier, print)
|
|
167
|
+
return nil if carrier == false
|
|
168
|
+
return Carrier.coerce(carrier) unless carrier.nil?
|
|
169
|
+
|
|
170
|
+
Carrier.member unless business? || donation? || print
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
def validate!
|
|
174
|
+
Validation.fail!(:items, "items must contain at least one item", "items 至少需要一個品項", "items には少なくとも 1 つの品目が必要です") if items.empty?
|
|
175
|
+
unless total.positive?
|
|
176
|
+
Validation.fail!(:items, "invoice total must be greater than 0 (got #{total})", "發票總金額必須大於 0(目前 #{total})",
|
|
177
|
+
"発票の合計金額は 0 より大きい必要があります(現在 #{total})")
|
|
178
|
+
end
|
|
179
|
+
if buyer.tax_id
|
|
180
|
+
Validation.format!(buyer.tax_id, TaxId::FORMAT, :"buyer.tax_id", "統一編號", "must be 8 digits", "必須為 8 碼數字",
|
|
181
|
+
"8 桁の数字である必要があります")
|
|
182
|
+
end
|
|
183
|
+
validate_donation!
|
|
184
|
+
validate_mixed_tax!
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
def validate_donation!
|
|
188
|
+
return unless donation?
|
|
189
|
+
|
|
190
|
+
Validation.format!(donation_code, DONATION_CODE, :donation_code, "捐贈碼", "must be 3 to 7 digits", "必須為 3 至 7 碼數字",
|
|
191
|
+
"3〜7 桁の数字である必要があります")
|
|
192
|
+
if business?
|
|
193
|
+
Validation.fail!(:donation_code, "an invoice with a tax ID cannot be donated", "有統一編號的發票不可捐贈",
|
|
194
|
+
"統一編号のある発票は寄付できません")
|
|
195
|
+
end
|
|
196
|
+
Validation.fail!(:print, "a donated invoice cannot be printed", "捐贈的發票不可列印", "寄付する発票は印刷できません") if print?
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
def validate_mixed_tax!
|
|
200
|
+
return unless tax_type == :mixed && items.any? { |item| item.tax_type.nil? }
|
|
201
|
+
|
|
202
|
+
Validation.fail!(:"items.tax_type", "every item on a :mixed invoice needs its own tax_type", "混合稅率發票的每個品項都必須指定 tax_type",
|
|
203
|
+
":mixed の発票では、すべての品目に tax_type を指定する必要があります")
|
|
204
|
+
end
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# An invoice that has been issued.
|
|
208
|
+
#
|
|
209
|
+
# @!attribute invoice_no [String] 發票號碼, two letters and eight digits
|
|
210
|
+
# @!attribute issued_at [Time, nil]
|
|
211
|
+
# @!attribute random_number [String] 隨機碼, printed on the invoice and used to look it up
|
|
212
|
+
# @!attribute raw [Hash] the vendor's response
|
|
213
|
+
InvoiceResult = Data.define(:invoice_no, :issued_at, :random_number, :raw)
|
|
214
|
+
|
|
215
|
+
# A credit note (折讓) issued against an invoice.
|
|
216
|
+
#
|
|
217
|
+
# @!attribute remaining_amount [Integer] what can still be credited against the invoice
|
|
218
|
+
AllowanceResult = Data.define(:allowance_no, :invoice_no, :issued_at, :remaining_amount, :raw)
|
|
219
|
+
|
|
220
|
+
# An invoice held by the vendor for later issuing.
|
|
221
|
+
ScheduledInvoice = Data.define(:reference, :raw)
|
|
222
|
+
|
|
223
|
+
# An issued invoice as the vendor has it on record.
|
|
224
|
+
InvoiceRecord = Data.define(:invoice_no, :order_no, :total, :tax_amount, :issued_at, :random_number, :buyer,
|
|
225
|
+
:carrier_type, :carrier_number, :donation_code, :voided, :uploaded, :printed, :remaining_allowance_amount, :raw)
|
|
226
|
+
|
|
227
|
+
class InvoiceRecord
|
|
228
|
+
def voided? = voided
|
|
229
|
+
|
|
230
|
+
# @return [Boolean] whether it has been reported to the Ministry of Finance
|
|
231
|
+
def uploaded? = uploaded
|
|
232
|
+
|
|
233
|
+
def printed? = printed
|
|
234
|
+
end
|
|
235
|
+
end
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module TaiwanPayments
|
|
4
|
+
# TWD has no minor unit and every vendor API takes whole dollars, so a
|
|
5
|
+
# fractional amount is a caller bug rather than something to round away.
|
|
6
|
+
module Money
|
|
7
|
+
module_function
|
|
8
|
+
|
|
9
|
+
def twd!(value, field, vendor_field = nil)
|
|
10
|
+
amount = whole_number(value)
|
|
11
|
+
name = Validation.label(field, vendor_field)
|
|
12
|
+
if amount.nil?
|
|
13
|
+
Validation.fail!(field, "#{name} must be a whole number of TWD (got #{value.inspect})",
|
|
14
|
+
"#{name} 必須是新台幣整數金額(收到 #{value.inspect})",
|
|
15
|
+
"#{name} は新台湾ドル(TWD)の整数である必要があります(受け取った値: #{value.inspect})")
|
|
16
|
+
end
|
|
17
|
+
unless amount.positive?
|
|
18
|
+
Validation.fail!(field, "#{name} must be greater than 0 (got #{amount})", "#{name} 必須大於 0(收到 #{amount})",
|
|
19
|
+
"#{name} は 0 より大きい必要があります(受け取った値: #{amount})")
|
|
20
|
+
end
|
|
21
|
+
amount
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def whole_number(value)
|
|
25
|
+
case value
|
|
26
|
+
when Integer then value
|
|
27
|
+
when String then Integer(value, 10, exception: false)
|
|
28
|
+
when Numeric then (value.finite? && value == value.to_i) ? value.to_i : nil
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module TaiwanPayments
|
|
4
|
+
# ECPay and NewebPay publish their signing algorithms as PHP samples, so
|
|
5
|
+
# signatures only match if we reproduce PHP's `urlencode` and
|
|
6
|
+
# `http_build_query` byte for byte. Ruby's own encoders differ on "~", "*"
|
|
7
|
+
# and space, which is enough to break a checksum.
|
|
8
|
+
module PhpCompat
|
|
9
|
+
ESCAPED = /[^A-Za-z0-9\-_.]/n
|
|
10
|
+
|
|
11
|
+
module_function
|
|
12
|
+
|
|
13
|
+
# PHP urlencode (RFC 1738): keeps alphanumerics and "-_.", turns space into
|
|
14
|
+
# "+", and percent-encodes everything else with uppercase hex.
|
|
15
|
+
def urlencode(value)
|
|
16
|
+
value.to_s.b.gsub(ESCAPED) { |char| (char == " ") ? "+" : format("%%%02X", char.ord) }.force_encoding(Encoding::US_ASCII)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def urldecode(value)
|
|
20
|
+
decoded = value.to_s.b.tr("+", " ").gsub(/%([0-9A-Fa-f]{2})/n) { $1.hex.chr }
|
|
21
|
+
decoded.force_encoding(Encoding::UTF_8)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# Insertion order is kept because NewebPay encrypts this string as-is and
|
|
25
|
+
# stable output keeps recorded fixtures reproducible.
|
|
26
|
+
def http_build_query(params)
|
|
27
|
+
params.map { |key, value| "#{urlencode(key)}=#{urlencode(value)}" }.join("&")
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def parse_query(string)
|
|
31
|
+
string.to_s.split("&").each_with_object({}) do |pair, hash|
|
|
32
|
+
key, value = pair.split("=", 2)
|
|
33
|
+
next if key.nil? || key.empty?
|
|
34
|
+
|
|
35
|
+
hash[urldecode(key)] = urldecode(value)
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rails/railtie"
|
|
4
|
+
require_relative "form_helper"
|
|
5
|
+
require_relative "webhooks"
|
|
6
|
+
|
|
7
|
+
module TaiwanPayments
|
|
8
|
+
# Rails integration. Loaded only when Rails is already present, so the gem
|
|
9
|
+
# keeps working, with no extra dependencies, everywhere else.
|
|
10
|
+
class Railtie < ::Rails::Railtie
|
|
11
|
+
initializer "taiwan_payments.form_helper" do
|
|
12
|
+
ActiveSupport.on_load(:action_view) { include TaiwanPayments::FormHelper }
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# Republishes the gem's events so they can be consumed like any other
|
|
16
|
+
# Rails event: ActiveSupport::Notifications.subscribe("request.taiwan_payments").
|
|
17
|
+
initializer "taiwan_payments.notifications" do
|
|
18
|
+
TaiwanPayments::Instrumentation.subscribe do |name, payload|
|
|
19
|
+
ActiveSupport::Notifications.instrument(name, payload)
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module TaiwanPayments
|
|
4
|
+
# Applied to every payload handed to instrumentation subscribers, because
|
|
5
|
+
# those payloads end up in application logs and error trackers. Covers keys
|
|
6
|
+
# and customer PII; matching ignores case since vendor fields are PascalCase.
|
|
7
|
+
module Redactor
|
|
8
|
+
SENSITIVE_KEYS = %w[
|
|
9
|
+
hash_key hashkey hash_iv hashiv checkmacvalue
|
|
10
|
+
customername customeraddr customerphone customeremail notifymail notifyphone carriernum
|
|
11
|
+
email phone
|
|
12
|
+
].freeze
|
|
13
|
+
MASK = "[REDACTED]"
|
|
14
|
+
|
|
15
|
+
module_function
|
|
16
|
+
|
|
17
|
+
def call(value)
|
|
18
|
+
case value
|
|
19
|
+
when Hash then value.to_h { |key, inner| [key, sensitive?(key) ? MASK : call(inner)] }
|
|
20
|
+
when Array then value.map { |inner| call(inner) }
|
|
21
|
+
else value
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def sensitive?(key)
|
|
26
|
+
SENSITIVE_KEYS.include?(key.to_s.downcase)
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module TaiwanPayments
|
|
4
|
+
# Vendors send and expect wall-clock times in Taiwan time with no zone
|
|
5
|
+
# marker. Taiwan has no daylight saving, so a fixed offset is exact and
|
|
6
|
+
# avoids depending on the host's TZ database or ActiveSupport.
|
|
7
|
+
module TaipeiTime
|
|
8
|
+
OFFSET = "+08:00"
|
|
9
|
+
PATTERN = %r{\A(\d{4})[/-](\d{1,2})[/-](\d{1,2})(?:[ T](\d{1,2}):(\d{2}):(\d{2}))?}
|
|
10
|
+
|
|
11
|
+
module_function
|
|
12
|
+
|
|
13
|
+
def format(time, pattern)
|
|
14
|
+
time.getlocal(OFFSET).strftime(pattern)
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
# @param end_of_day [Boolean] date-only deadlines (e.g. ATM ExpireDate) run
|
|
18
|
+
# until 23:59:59 that day, so midnight would be a day early.
|
|
19
|
+
# @return [Time, nil] nil for blank or unrecognised input; vendor callbacks
|
|
20
|
+
# legitimately leave dates empty and must not blow up while parsing.
|
|
21
|
+
def parse(string, end_of_day: false)
|
|
22
|
+
match = PATTERN.match(string.to_s.strip)
|
|
23
|
+
return nil unless match
|
|
24
|
+
|
|
25
|
+
year, month, day, hour, minute, second = match.captures.map { |part| part&.to_i }
|
|
26
|
+
hour, minute, second = end_of_day ? [23, 59, 59] : [0, 0, 0] if hour.nil?
|
|
27
|
+
Time.new(year, month, day, hour, minute, second, OFFSET)
|
|
28
|
+
rescue ArgumentError
|
|
29
|
+
nil
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# @param value [Time, Date, String] anything identifying a calendar day
|
|
33
|
+
# @return [String] "yyyy-MM-dd" in Taiwan time
|
|
34
|
+
def date(value)
|
|
35
|
+
case value
|
|
36
|
+
when Time then format(value, "%Y-%m-%d")
|
|
37
|
+
when String then (parsed = parse(value)) ? format(parsed, "%Y-%m-%d") : value
|
|
38
|
+
else value.strftime("%Y-%m-%d")
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module TaiwanPayments
|
|
4
|
+
# 統一編號: the 8-digit number identifying a Taiwanese company or organisation.
|
|
5
|
+
# A buyer supplies one when they need a business (B2B) invoice.
|
|
6
|
+
module TaxId
|
|
7
|
+
FORMAT = /\A\d{8}\z/
|
|
8
|
+
WEIGHTS = [1, 2, 1, 2, 1, 2, 4, 1].freeze
|
|
9
|
+
|
|
10
|
+
module_function
|
|
11
|
+
|
|
12
|
+
# Checks the Ministry of Finance checksum, so a typo can be caught in a
|
|
13
|
+
# form before the vendor rejects the invoice.
|
|
14
|
+
def valid?(value)
|
|
15
|
+
text = value.to_s
|
|
16
|
+
return false unless FORMAT.match?(text)
|
|
17
|
+
|
|
18
|
+
digits = text.chars.map(&:to_i)
|
|
19
|
+
sum = digits.zip(WEIGHTS).sum { |digit, weight| (digit * weight).digits.sum }
|
|
20
|
+
# Since 2023 the sum must be divisible by 5 (previously 10), a change
|
|
21
|
+
# made to enlarge the number space. When the seventh digit is 7 its
|
|
22
|
+
# product is 28, whose digits may count as either 10 or 1.
|
|
23
|
+
(sum % 5).zero? || (digits[6] == 7 && ((sum + 1) % 5).zero?)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../taiwan_payments"
|
|
4
|
+
|
|
5
|
+
module TaiwanPayments
|
|
6
|
+
# Builds vendor payloads that are signed or encrypted exactly as the vendor
|
|
7
|
+
# would, so an application can test its webhook endpoints and API handling
|
|
8
|
+
# without a sandbox account or network access.
|
|
9
|
+
#
|
|
10
|
+
# require "taiwan_payments/testing"
|
|
11
|
+
# params = TaiwanPayments::Testing.ecpay_payment_notification(client, order_no: "ORD1", amount: 500)
|
|
12
|
+
# post "/webhooks/ecpay", params: params
|
|
13
|
+
module Testing
|
|
14
|
+
ECPAY_TIME = "%Y/%m/%d %H:%M:%S"
|
|
15
|
+
|
|
16
|
+
module_function
|
|
17
|
+
|
|
18
|
+
# A payment result as POSTed to ReturnURL / OrderResultURL.
|
|
19
|
+
#
|
|
20
|
+
# @param paid [Boolean] false builds a failed payment
|
|
21
|
+
# @param simulated [Boolean] true marks it as a back-office "simulate payment"
|
|
22
|
+
# @param vendor_fields [Hash] extra or overriding raw ECPay fields
|
|
23
|
+
# @return [Hash{String => String}]
|
|
24
|
+
def ecpay_payment_notification(client, order_no:, amount:, paid: true, simulated: false,
|
|
25
|
+
payment_type: "Credit_CreditCard", trade_no: nil, paid_at: Time.now, **vendor_fields)
|
|
26
|
+
fields = ecpay_common_fields(client, order_no, amount, trade_no, paid_at).merge(
|
|
27
|
+
"RtnCode" => paid ? "1" : "10100058",
|
|
28
|
+
"RtnMsg" => paid ? "交易成功" : "Pay fail.",
|
|
29
|
+
"PaymentDate" => paid ? TaipeiTime.format(paid_at, ECPAY_TIME) : "",
|
|
30
|
+
"PaymentType" => payment_type,
|
|
31
|
+
"PaymentTypeChargeFee" => "0",
|
|
32
|
+
"SimulatePaid" => simulated ? "1" : "0"
|
|
33
|
+
)
|
|
34
|
+
ecpay_sign(client, fields, vendor_fields)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# A "payment code issued" callback as POSTed to PaymentInfoURL for ATM,
|
|
38
|
+
# convenience store code and barcode payments.
|
|
39
|
+
#
|
|
40
|
+
# @param payment_method [Symbol] :atm, :cvs or :barcode
|
|
41
|
+
# @return [Hash{String => String}]
|
|
42
|
+
def ecpay_payment_code_notification(client, order_no:, amount:, payment_method: :atm,
|
|
43
|
+
trade_no: nil, expires_at: Time.now + (3 * 86_400), **vendor_fields)
|
|
44
|
+
specifics =
|
|
45
|
+
case payment_method
|
|
46
|
+
when :atm
|
|
47
|
+
{"RtnCode" => "2", "RtnMsg" => "Get VirtualAccount Succeeded", "PaymentType" => "ATM_LAND",
|
|
48
|
+
"BankCode" => "005", "vAccount" => "5219111811417485", "ExpireDate" => TaipeiTime.format(expires_at, "%Y/%m/%d")}
|
|
49
|
+
when :cvs
|
|
50
|
+
{"RtnCode" => "10100073", "RtnMsg" => "Get CVS Code Succeeded.", "PaymentType" => "CVS_CVS", "PaymentNo" => "LLL22251222",
|
|
51
|
+
"Barcode1" => "", "Barcode2" => "", "Barcode3" => "", "ExpireDate" => TaipeiTime.format(expires_at, ECPAY_TIME)}
|
|
52
|
+
when :barcode
|
|
53
|
+
{"RtnCode" => "10100073", "RtnMsg" => "Get CVS Code Succeeded.", "PaymentType" => "BARCODE_BARCODE", "PaymentNo" => "",
|
|
54
|
+
"Barcode1" => "1511236EA", "Barcode2" => "3453011539919158", "Barcode3" => "151123000000100",
|
|
55
|
+
"ExpireDate" => TaipeiTime.format(expires_at, ECPAY_TIME)}
|
|
56
|
+
else
|
|
57
|
+
raise ArgumentError, "payment_method must be :atm, :cvs or :barcode"
|
|
58
|
+
end
|
|
59
|
+
ecpay_sign(client, ecpay_common_fields(client, order_no, amount, trade_no, Time.now).merge(specifics), vendor_fields)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# The body QueryTradeInfo answers with, for stubbing the HTTP call.
|
|
63
|
+
#
|
|
64
|
+
# @param status [Symbol] :paid, :unpaid or :failed
|
|
65
|
+
# @return [String]
|
|
66
|
+
def ecpay_trade_query_body(client, order_no:, amount:, status: :paid, payment_type: "Credit_CreditCard",
|
|
67
|
+
trade_no: nil, paid_at: Time.now, **vendor_fields)
|
|
68
|
+
paid = status == :paid
|
|
69
|
+
fields = ecpay_common_fields(client, order_no, amount, trade_no, paid_at).except("RtnCode", "RtnMsg").merge(
|
|
70
|
+
"HandlingCharge" => "0",
|
|
71
|
+
"ItemName" => "Test item",
|
|
72
|
+
"PaymentDate" => paid ? TaipeiTime.format(paid_at, ECPAY_TIME) : "",
|
|
73
|
+
"PaymentType" => paid ? payment_type : "",
|
|
74
|
+
"PaymentTypeChargeFee" => "0",
|
|
75
|
+
"TradeStatus" => {paid: "1", unpaid: "0", failed: "10200095"}.fetch(status)
|
|
76
|
+
).merge(vendor_fields.transform_keys(&:to_s)).transform_values(&:to_s)
|
|
77
|
+
|
|
78
|
+
# ECPay sends these bodies unescaped and in signing order.
|
|
79
|
+
ordered = fields.sort_by { |name, _| name.downcase }
|
|
80
|
+
"#{ordered.map { |name, value| "#{name}=#{value}" }.join("&")}&CheckMacValue=#{client.check_mac_value(fields)}"
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# A response body from ECPay's e-invoice API, encrypted with the client's
|
|
84
|
+
# keys, for stubbing the HTTP call.
|
|
85
|
+
#
|
|
86
|
+
# stub_request(:post, %r{/B2CInvoice/Issue})
|
|
87
|
+
# .to_return(body: TaiwanPayments::Testing.ecpay_invoice_issued_body(client))
|
|
88
|
+
#
|
|
89
|
+
# @param client [ECPay::InvoiceClient]
|
|
90
|
+
# @param data [Hash] the decrypted payload, e.g. {"RtnCode" => 1, "InvoiceNo" => "AB12345678"}
|
|
91
|
+
# @return [String]
|
|
92
|
+
def ecpay_invoice_body(client, data)
|
|
93
|
+
credentials = client.credentials
|
|
94
|
+
JSON.generate(
|
|
95
|
+
"PlatformID" => 0,
|
|
96
|
+
"MerchantID" => credentials.merchant_id,
|
|
97
|
+
"RpHeader" => {"Timestamp" => Time.now.to_i},
|
|
98
|
+
"TransCode" => 1,
|
|
99
|
+
"TransMsg" => "Success",
|
|
100
|
+
"Data" => ECPay::AesCipher.encrypt(data.transform_keys(&:to_s), hash_key: credentials.hash_key, hash_iv: credentials.hash_iv)
|
|
101
|
+
)
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# The body of a successful Issue call.
|
|
105
|
+
#
|
|
106
|
+
# @return [String]
|
|
107
|
+
def ecpay_invoice_issued_body(client, invoice_no: "AB12345678", issued_at: Time.now, random_number: "1234")
|
|
108
|
+
ecpay_invoice_body(client, "RtnCode" => 1, "RtnMsg" => "開立發票成功", "InvoiceNo" => invoice_no,
|
|
109
|
+
"InvoiceDate" => TaipeiTime.format(issued_at, "%Y-%m-%d %H:%M:%S"), "RandomNumber" => random_number)
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# A refusal from any e-invoice call, e.g. code 5070357 when the order
|
|
113
|
+
# number already has an invoice.
|
|
114
|
+
#
|
|
115
|
+
# @return [String]
|
|
116
|
+
def ecpay_invoice_error_body(client, code:, message: "")
|
|
117
|
+
ecpay_invoice_body(client, "RtnCode" => code, "RtnMsg" => message)
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
# Decrypts a request body the InvoiceClient sent, to assert on what would
|
|
121
|
+
# have reached ECPay.
|
|
122
|
+
#
|
|
123
|
+
# expect(a_request(:post, %r{/B2CInvoice/Issue}).with { |request|
|
|
124
|
+
# TaiwanPayments::Testing.ecpay_invoice_request(client, request.body)["SalesAmount"] == 1000
|
|
125
|
+
# }).to have_been_made
|
|
126
|
+
#
|
|
127
|
+
# @return [Hash] the vendor fields
|
|
128
|
+
def ecpay_invoice_request(client, body)
|
|
129
|
+
credentials = client.credentials
|
|
130
|
+
ECPay::AesCipher.decrypt(JSON.parse(body).fetch("Data"), hash_key: credentials.hash_key, hash_iv: credentials.hash_iv)
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def ecpay_common_fields(client, order_no, amount, trade_no, time)
|
|
134
|
+
{
|
|
135
|
+
"MerchantID" => client.credentials.merchant_id,
|
|
136
|
+
"MerchantTradeNo" => order_no,
|
|
137
|
+
"StoreID" => "",
|
|
138
|
+
"TradeNo" => trade_no || TaipeiTime.format(time, "%y%m%d%H%M%S") + "0001",
|
|
139
|
+
"TradeAmt" => amount,
|
|
140
|
+
"TradeDate" => TaipeiTime.format(time - 60, ECPAY_TIME),
|
|
141
|
+
"CustomField1" => "", "CustomField2" => "", "CustomField3" => "", "CustomField4" => ""
|
|
142
|
+
}
|
|
143
|
+
end
|
|
144
|
+
private_class_method :ecpay_common_fields
|
|
145
|
+
|
|
146
|
+
def ecpay_sign(client, fields, overrides)
|
|
147
|
+
fields = fields.merge(overrides.transform_keys(&:to_s)).transform_values(&:to_s)
|
|
148
|
+
fields.merge("CheckMacValue" => client.check_mac_value(fields))
|
|
149
|
+
end
|
|
150
|
+
private_class_method :ecpay_sign
|
|
151
|
+
end
|
|
152
|
+
end
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module TaiwanPayments
|
|
4
|
+
# Shared guards for request builders. Messages name both our keyword and the
|
|
5
|
+
# vendor's field so a developer can find the rule in either set of docs.
|
|
6
|
+
module Validation
|
|
7
|
+
module_function
|
|
8
|
+
|
|
9
|
+
def fail!(field, english, chinese, japanese)
|
|
10
|
+
raise ValidationError.new(english, field: field, zh: chinese, ja: japanese)
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def label(field, vendor_field)
|
|
14
|
+
vendor_field ? "#{field} (#{vendor_field})" : field.to_s
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def present!(value, field, vendor_field = nil)
|
|
18
|
+
name = label(field, vendor_field)
|
|
19
|
+
fail!(field, "#{name} is required", "#{name} 為必填", "#{name} は必須です") if value.to_s.strip.empty?
|
|
20
|
+
value
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def max_length!(value, max, field, vendor_field = nil)
|
|
24
|
+
return value if value.to_s.length <= max
|
|
25
|
+
|
|
26
|
+
name = label(field, vendor_field)
|
|
27
|
+
fail!(field, "#{name} must be at most #{max} characters (got #{value.to_s.length})",
|
|
28
|
+
"#{name} 長度不可超過 #{max} 個字元(目前 #{value.to_s.length})",
|
|
29
|
+
"#{name} は #{max} 文字以内で指定してください(現在 #{value.to_s.length} 文字)")
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Each hint completes the sentence "<name> ..." in its language.
|
|
33
|
+
def format!(value, pattern, field, vendor_field, english_hint, chinese_hint, japanese_hint)
|
|
34
|
+
return value if pattern.match?(value.to_s)
|
|
35
|
+
|
|
36
|
+
name = label(field, vendor_field)
|
|
37
|
+
fail!(field, "#{name} #{english_hint} (got #{value.inspect})", "#{name} #{chinese_hint}(收到 #{value.inspect})",
|
|
38
|
+
"#{name} は#{japanese_hint}(受け取った値: #{value.inspect})")
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def http_url!(value, field, vendor_field = nil, max: 200)
|
|
42
|
+
format!(value, %r{\Ahttps?://\S+\z}i, field, vendor_field, "must be an http(s) URL", "必須是 http(s) 網址",
|
|
43
|
+
"http(s) の URL である必要があります")
|
|
44
|
+
max_length!(value, max, field, vendor_field)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def one_of!(value, allowed, field, vendor_field = nil)
|
|
48
|
+
return value if allowed.include?(value)
|
|
49
|
+
|
|
50
|
+
name = label(field, vendor_field)
|
|
51
|
+
list = allowed.map(&:inspect).join(", ")
|
|
52
|
+
fail!(field, "#{name} must be one of #{list} (got #{value.inspect})", "#{name} 必須是 #{list} 其中之一(收到 #{value.inspect})",
|
|
53
|
+
"#{name} は #{list} のいずれかである必要があります(受け取った値: #{value.inspect})")
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|