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,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ module ECPay
5
+ # Maps between readable symbols and ECPay's ChoosePayment / PaymentType names.
6
+ module PaymentMethods
7
+ VENDOR_NAMES = {
8
+ all: "ALL",
9
+ credit: "Credit",
10
+ twqr: "TWQR",
11
+ web_atm: "WebATM",
12
+ atm: "ATM",
13
+ cvs: "CVS",
14
+ barcode: "BARCODE",
15
+ apple_pay: "ApplePay",
16
+ bnpl: "BNPL",
17
+ weixin: "WeiXin",
18
+ digital_payment: "DigitalPayment"
19
+ }.freeze
20
+
21
+ module_function
22
+
23
+ # Accepts our symbol or ECPay's own spelling so code copied from vendor
24
+ # docs keeps working.
25
+ def to_vendor(value, field)
26
+ text = value.to_s
27
+ VENDOR_NAMES.each { |symbol, vendor| return vendor if symbol.to_s == text.downcase || vendor.casecmp?(text) }
28
+
29
+ Validation.one_of!(value, VENDOR_NAMES.keys, field, "ChoosePayment")
30
+ end
31
+
32
+ # @param payment_type [String] e.g. "Credit_CreditCard", "ATM_LAND"
33
+ # @return [Symbol, nil] nil for a method this version does not know yet
34
+ def from_vendor(payment_type)
35
+ family = payment_type.to_s.split("_", 2).first.to_s
36
+ VENDOR_NAMES.find { |_, vendor| vendor.casecmp?(family) }&.first
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ module ECPay
5
+ # Where and how the customer pays when the method is not instant.
6
+ #
7
+ # @!attribute payment_method [Symbol] :atm, :cvs or :barcode
8
+ # @!attribute bank_code [String, nil] ATM: bank to transfer to
9
+ # @!attribute virtual_account [String, nil] ATM: account to transfer to
10
+ # @!attribute payment_no [String, nil] CVS: code typed into the store kiosk
11
+ # @!attribute barcodes [Array<String>] BARCODE: three barcode segments
12
+ # @!attribute expires_at [Time, nil] payment deadline
13
+ PaymentInstructions = Data.define(:payment_method, :bank_code, :virtual_account, :payment_no, :barcodes, :expires_at)
14
+
15
+ # A verified callback from ECPay about a payment. The same shape arrives at
16
+ # ReturnURL (paid), OrderResultURL (browser copy of the result) and
17
+ # PaymentInfoURL (ATM/CVS/barcode payment code issued).
18
+ # Reference: https://developers.ecpay.com.tw/?p=2878
19
+ class PaymentNotification
20
+ # ECPay retries the webhook until the response body is exactly this.
21
+ ACK = "1|OK"
22
+ PAID_CODE = "1"
23
+ # RtnCode values meaning "a payment code was issued; the customer has not
24
+ # paid yet": 2 for ATM, 10100073 for convenience store code and barcode.
25
+ CODE_ISSUED = %w[2 10100073].freeze
26
+
27
+ # @return [Hash{String => String}] every field exactly as ECPay sent it
28
+ attr_reader :raw
29
+
30
+ def initialize(raw)
31
+ @raw = raw.to_h { |name, value| [name.to_s, value.to_s] }.freeze
32
+ end
33
+
34
+ def [](vendor_field)
35
+ raw[vendor_field.to_s]
36
+ end
37
+
38
+ def merchant_id = raw["MerchantID"]
39
+
40
+ # @return [String] your order number (MerchantTradeNo)
41
+ def order_no = raw["MerchantTradeNo"]
42
+
43
+ # @return [String] ECPay's transaction number (TradeNo), needed for refunds
44
+ def trade_no = raw["TradeNo"]
45
+
46
+ # @return [Integer] TWD (TradeAmt)
47
+ def amount = raw["TradeAmt"].to_i
48
+
49
+ # @return [String] RtnCode
50
+ def status_code = raw["RtnCode"]
51
+
52
+ # @return [String] RtnMsg, usually Chinese
53
+ def message = raw["RtnMsg"]
54
+
55
+ # @return [String] ECPay's detailed type, e.g. "Credit_CreditCard"
56
+ def payment_type = raw["PaymentType"]
57
+
58
+ # @return [Symbol, nil] e.g. :credit, :atm
59
+ def payment_method = PaymentMethods.from_vendor(payment_type)
60
+
61
+ # @return [Time, nil] PaymentDate
62
+ def paid_at = TaipeiTime.parse(raw["PaymentDate"])
63
+
64
+ # @return [Time, nil] TradeDate
65
+ def ordered_at = TaipeiTime.parse(raw["TradeDate"])
66
+
67
+ # @return [Integer] ECPay's fee for this payment in TWD (PaymentTypeChargeFee)
68
+ def fee = raw["PaymentTypeChargeFee"].to_i
69
+
70
+ def store_id = raw["StoreID"]
71
+
72
+ # @return [Array<String>] CustomField1-4 as sent at checkout
73
+ def custom_fields = (1..4).map { |index| raw["CustomField#{index}"].to_s }
74
+
75
+ # A merchant can press "simulate payment" in ECPay's back office, in
76
+ # production too. ECPay then sends RtnCode=1 with SimulatePaid=1 and pays
77
+ # out nothing, so shipping on it gives goods away.
78
+ def simulated? = raw["SimulatePaid"] == "1"
79
+
80
+ # True only for a real, completed payment. Simulated payments are
81
+ # excluded; check {#simulated?} if a test flow needs them.
82
+ def paid? = status_code == PAID_CODE && !simulated?
83
+
84
+ # A payment code or virtual account was issued and the customer still
85
+ # has to pay. A separate paid notification follows later.
86
+ def awaiting_payment? = CODE_ISSUED.include?(status_code)
87
+
88
+ def failed? = !paid? && !simulated? && !awaiting_payment?
89
+
90
+ # @return [Symbol] :paid, :simulated, :awaiting_payment or :failed
91
+ def status
92
+ return :simulated if simulated?
93
+ return :paid if paid?
94
+
95
+ awaiting_payment? ? :awaiting_payment : :failed
96
+ end
97
+
98
+ # @return [PaymentInstructions, nil] present when {#awaiting_payment?}
99
+ def payment_instructions
100
+ return nil unless awaiting_payment?
101
+
102
+ PaymentInstructions.new(
103
+ payment_method: payment_method,
104
+ bank_code: presence(raw["BankCode"]),
105
+ virtual_account: presence(raw["vAccount"]),
106
+ payment_no: presence(raw["PaymentNo"]),
107
+ barcodes: [raw["Barcode1"], raw["Barcode2"], raw["Barcode3"]].map(&:to_s).reject(&:empty?),
108
+ # ATM deadlines are a bare date and run to the end of that day.
109
+ expires_at: TaipeiTime.parse(raw["ExpireDate"], end_of_day: true)
110
+ )
111
+ end
112
+
113
+ # @return [String] the body your webhook must answer with
114
+ def ack = ACK
115
+
116
+ def inspect
117
+ "#<#{self.class.name} order_no=#{order_no.inspect} status=#{status.inspect} amount=#{amount}>"
118
+ end
119
+
120
+ private
121
+
122
+ def presence(value)
123
+ value.to_s.empty? ? nil : value
124
+ end
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ module ECPay
5
+ # Parser for the `k=v&k=v` bodies ECPay's payment APIs answer with.
6
+ module ResponseBody
7
+ FIELD_START = /\A[A-Za-z][A-Za-z0-9_]*=/
8
+
9
+ module_function
10
+
11
+ # ECPay does not URL-encode these bodies, so an "&" inside a value
12
+ # ("ItemName=Salt & Pepper") is indistinguishable from a separator. A
13
+ # segment therefore only starts a new field when it looks like `Name=`;
14
+ # anything else is glued back onto the previous value. Decoding is also
15
+ # skipped on purpose: it would turn a literal "+" into a space.
16
+ #
17
+ # @return [Hash{String => String}]
18
+ def parse(body)
19
+ body.to_s.strip.split("&").each_with_object({}) do |segment, fields|
20
+ if FIELD_START.match?(segment) || fields.empty?
21
+ name, value = segment.split("=", 2)
22
+ fields[name] = value.to_s
23
+ else
24
+ fields[fields.keys.last] += "&#{segment}"
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ module ECPay
5
+ # The state of one order as reported by QueryTradeInfo/V5.
6
+ # Reference: https://developers.ecpay.com.tw/?p=2890
7
+ class TradeInfo
8
+ UNPAID = "0"
9
+ PAID = "1"
10
+
11
+ # @return [Hash{String => String}] every field exactly as ECPay sent it
12
+ attr_reader :raw
13
+
14
+ def initialize(raw)
15
+ @raw = raw.freeze
16
+ end
17
+
18
+ def [](vendor_field)
19
+ raw[vendor_field.to_s]
20
+ end
21
+
22
+ def order_no = raw["MerchantTradeNo"]
23
+
24
+ def trade_no = raw["TradeNo"]
25
+
26
+ def amount = raw["TradeAmt"].to_i
27
+
28
+ # @return [String] TradeStatus: "0" unpaid, "1" paid, anything else is a failure code
29
+ def status_code = raw["TradeStatus"]
30
+
31
+ # @return [Symbol] :unpaid, :paid or :failed
32
+ def status
33
+ case status_code
34
+ when UNPAID then :unpaid
35
+ when PAID then :paid
36
+ else :failed
37
+ end
38
+ end
39
+
40
+ def paid? = status == :paid
41
+
42
+ def unpaid? = status == :unpaid
43
+
44
+ def failed? = status == :failed
45
+
46
+ def payment_type = raw["PaymentType"]
47
+
48
+ def payment_method = PaymentMethods.from_vendor(payment_type)
49
+
50
+ def paid_at = TaipeiTime.parse(raw["PaymentDate"])
51
+
52
+ def ordered_at = TaipeiTime.parse(raw["TradeDate"])
53
+
54
+ def fee = raw["PaymentTypeChargeFee"].to_i
55
+
56
+ def item_name = raw["ItemName"]
57
+
58
+ def custom_fields = (1..4).map { |index| raw["CustomField#{index}"].to_s }
59
+
60
+ def inspect
61
+ "#<#{self.class.name} order_no=#{order_no.inspect} status=#{status.inspect} amount=#{amount}>"
62
+ end
63
+ end
64
+
65
+ # Outcome of a credit card capture, refund or cancellation (DoAction).
66
+ CreditActionResult = Data.define(:order_no, :trade_no, :message, :raw)
67
+ end
68
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "ecpay/check_mac_value"
4
+ require_relative "ecpay/aes_cipher"
5
+ require_relative "ecpay/response_body"
6
+ require_relative "ecpay/payment_methods"
7
+ require_relative "ecpay/checkout"
8
+ require_relative "ecpay/payment_notification"
9
+ require_relative "ecpay/trade_info"
10
+ require_relative "ecpay/payment_client"
11
+ require_relative "ecpay/invoice_mapper"
12
+ require_relative "ecpay/invoice_client"
13
+
14
+ module TaiwanPayments
15
+ # ECPay (綠界科技). Payments and e-invoicing are separate ECPay products with
16
+ # separate merchant keys, so each has its own client.
17
+ module ECPay
18
+ end
19
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ module Environment
5
+ # Each vendor names its test environment differently (stage, test, 測試區),
6
+ # so the common spellings are accepted instead of failing on a synonym.
7
+ ALIASES = {
8
+ sandbox: :sandbox, stage: :sandbox, staging: :sandbox, test: :sandbox, development: :sandbox,
9
+ production: :production, prod: :production, live: :production
10
+ }.freeze
11
+
12
+ module_function
13
+
14
+ def normalize(env)
15
+ ALIASES.fetch(env.to_s.downcase.to_sym) do
16
+ raise ConfigurationError.new("unknown env #{env.inspect}; use :sandbox or :production",
17
+ zh: "未知的環境 #{env.inspect},請使用 :sandbox 或 :production",
18
+ ja: "不明な環境 #{env.inspect} です。:sandbox または :production を指定してください")
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,80 @@
1
+ # ECPay B2C e-invoice (電子發票) codes.
2
+ # zh is ECPay's wording; en and ja are our translations.
3
+ # Sources: https://developers.ecpay.com.tw/7954/ and responses observed on the stage environment.
4
+ # TransCode values (request envelope) are prefixed with "T" to keep them apart from RtnCode values.
5
+ "T104":
6
+ zh: "Timestamp is over 10 minutes than it just produced."
7
+ en: "The request Timestamp differs from ECPay's clock by more than 10 minutes. Check the server clock."
8
+ ja: "リクエストの Timestamp が ECPay の時刻と 10 分を超えてずれています。サーバーの時刻を確認してください。"
9
+ "T110":
10
+ zh: "The parameter [Data] decrypt fail."
11
+ en: "ECPay could not decrypt Data. Check hash_key and hash_iv; the e-invoice product has its own keys, separate from payments."
12
+ ja: "ECPay が Data を復号できませんでした。hash_key と hash_iv を確認してください。電子発票のキーは決済用のキーとは別に発行されます。"
13
+ "2":
14
+ zh: "查無發票資料,請重新確認"
15
+ en: "No invoice found."
16
+ ja: "発票が見つかりません。"
17
+ "7":
18
+ zh: "查無資料"
19
+ en: "No data found. Only invoices issued with print enabled can be printed."
20
+ ja: "データが見つかりません。印刷できるのは、印刷を有効にして発行した発票だけです。"
21
+ "1200024":
22
+ zh: "客戶(買受人)電子信箱及手機號碼不可同時為空白"
23
+ en: "Customer email and mobile number cannot both be blank."
24
+ ja: "購入者のメールアドレスと携帯電話番号の両方を空にすることはできません。"
25
+ "1500047":
26
+ zh: "字軌設定錯誤"
27
+ en: "Invoice number track (字軌) problem: not added, not enabled, or used up."
28
+ ja: "発票番号の割当枠(字軌)に問題があります。未登録、未有効化、または使い切りのいずれかです。"
29
+ "2001016":
30
+ zh: "捐贈碼格式錯誤"
31
+ en: "The donation code (捐贈碼) format is invalid."
32
+ ja: "寄付コード(捐贈碼)の形式が正しくありません。"
33
+ "2001098":
34
+ zh: "零稅率原因格式錯誤"
35
+ en: "The zero tax rate reason (ZeroTaxRateReason) is invalid. Use a code from 71 to 79."
36
+ ja: "ゼロ税率の理由(ZeroTaxRateReason)が正しくありません。71 から 79 のコードを指定してください。"
37
+ "2019001":
38
+ zh: "手機條碼為8碼,以/開頭的0-9A-Z+-.所組成之字串"
39
+ en: "A mobile barcode is 8 characters: '/' followed by 7 of 0-9, A-Z, '+', '-' or '.'."
40
+ ja: "モバイルバーコードは 8 文字です。「/」に続けて 0-9、A-Z、「+」「-」「.」のいずれかを 7 文字指定します。"
41
+ "4000001":
42
+ zh: "不存在此交易單號"
43
+ en: "No scheduled invoice has this reference (Tsr)."
44
+ ja: "この参照番号(Tsr)の予約発票は存在しません。"
45
+ "5000022":
46
+ zh: "驗證發票金額發現錯誤,與商品合計金額不符"
47
+ en: "The invoice total does not match the sum of the item amounts."
48
+ ja: "発票の合計金額が品目の金額の合計と一致しません。"
49
+ "5000028":
50
+ zh: "客戶資訊已填入統編,須請選擇載具類別或索取紙本發票"
51
+ en: "A tax ID was given, so the invoice needs either a carrier or print enabled."
52
+ ja: "統一編号が指定されているため、キャリアを指定するか、紙の発票の印刷を有効にする必要があります。"
53
+ "5000032":
54
+ zh: "無效的手機條碼"
55
+ en: "Invalid mobile barcode."
56
+ ja: "無効なモバイルバーコードです。"
57
+ "5000034":
58
+ zh: "客戶統一編號格式不正確,請確認"
59
+ en: "The customer tax ID (統一編號) is not valid."
60
+ ja: "購入者の統一編号(統一編號)が正しくありません。"
61
+ "5070350":
62
+ zh: "字軌設定錯誤"
63
+ en: "Invoice number track (字軌) problem: not added, not enabled, or used up."
64
+ ja: "発票番号の割当枠(字軌)に問題があります。未登録、未有効化、または使い切りのいずれかです。"
65
+ "5070357":
66
+ zh: "B2C開立發票 自訂編號重覆,請重新設定"
67
+ en: "This order number (RelateNumber) already has an invoice."
68
+ ja: "この注文番号(RelateNumber)の発票はすでに発行されています。"
69
+ "5070450":
70
+ zh: "B2C作廢發票 該發票已被折讓過,無法直接作廢發票並請確認該發票所開立的折讓單是否全部已作廢"
71
+ en: "This invoice has allowances. Void every allowance before voiding the invoice."
72
+ ja: "この発票には折譲があります。発票を無効化する前に、すべての折譲を無効化してください。"
73
+ "5070453":
74
+ zh: "B2C作廢發票 該發票已被作廢過"
75
+ en: "This invoice has already been voided."
76
+ ja: "この発票はすでに無効化されています。"
77
+ "9000001":
78
+ zh: "財政部API呼叫失敗"
79
+ en: "The Ministry of Finance verification service could not be reached. Try again later."
80
+ ja: "財政部の検証サービスに接続できませんでした。しばらくしてからもう一度お試しください。"
@@ -0,0 +1,59 @@
1
+ # ECPay all-in-one payment (全方位金流) status codes.
2
+ # zh is ECPay's wording; en and ja are our translations.
3
+ # Sources: https://developers.ecpay.com.tw/5740/ and responses observed on the stage environment.
4
+ "10100058":
5
+ zh: "Pay fail."
6
+ en: "Payment failed."
7
+ ja: "決済に失敗しました。"
8
+ "10100248":
9
+ zh: "因應資訊安全及避免有心人利用錯誤訊息進行測試。故錯誤代碼及訊息無法詳盡告知。"
10
+ en: "The card issuer declined the transaction. ECPay withholds the detailed reason for security."
11
+ ja: "カード発行会社が取引を拒否しました。ECPay はセキュリティ上の理由から詳しい原因を開示しません。"
12
+ "10200047":
13
+ zh: "查無訂單資料"
14
+ en: "No trade exists for this order number."
15
+ ja: "この注文番号の取引は存在しません。"
16
+ "10200073":
17
+ zh: "CheckMacValue Error"
18
+ en: "CheckMacValue verification failed. Check hash_key and hash_iv, and that they belong to this environment."
19
+ ja: "CheckMacValue の検証に失敗しました。hash_key と hash_iv が正しいか、この環境のものかを確認してください。"
20
+ "10200084":
21
+ zh: "TimeStamp 已逾時"
22
+ en: "The request TimeStamp is outside ECPay's 3-minute window. Check the server clock."
23
+ ja: "リクエストの TimeStamp が ECPay の許容時間(3 分)を過ぎています。サーバーの時刻を確認してください。"
24
+ "10200095":
25
+ zh: "交易訂單未成立,消費者未完成付款作業"
26
+ en: "The order was not completed: the customer did not finish paying."
27
+ ja: "注文は成立していません。購入者が支払いを完了していません。"
28
+ "10200141":
29
+ zh: "商店未開啟收款服務"
30
+ en: "The merchant has not enabled payment collection."
31
+ ja: "この加盟店では決済サービスが有効になっていません。"
32
+ "10200146":
33
+ zh: "此商店不支援信用卡分期"
34
+ en: "This merchant does not support credit card instalments."
35
+ ja: "この加盟店はクレジットカードの分割払いに対応していません。"
36
+ "10200163":
37
+ zh: "無卡分期申請失敗"
38
+ en: "The buy-now-pay-later application was not approved."
39
+ ja: "後払い(BNPL)の申し込みが承認されませんでした。"
40
+ "10300023":
41
+ zh: "本次交易未提供任何付款方式"
42
+ en: "No payment method is available for this transaction."
43
+ ja: "この取引で利用できる支払い方法がありません。"
44
+ "10300024":
45
+ zh: "資料驗證錯誤,請回到原廠商頁面重新操作"
46
+ en: "Data validation failed. Return to the merchant site and start again."
47
+ ja: "データの検証に失敗しました。加盟店のサイトに戻ってやり直してください。"
48
+ "10800001":
49
+ zh: "此刷卡行為已觸動綠界風險控管條件(連續刷卡,可疑電話號碼..等)。"
50
+ en: "The card activity triggered ECPay's risk controls (repeated charges, suspicious phone number, etc.)."
51
+ ja: "このカード利用は ECPay のリスク管理の条件に該当しました(連続決済、不審な電話番号など)。"
52
+ "5100070":
53
+ zh: "建立訂單失敗"
54
+ en: "Order creation failed: the amount is outside the allowed range or no payment method supports it."
55
+ ja: "注文の作成に失敗しました。金額が許容範囲外か、対応する支払い方法がありません。"
56
+ "5100071":
57
+ zh: "建立訂單失敗"
58
+ en: "Order creation failed: the service is not enabled for embedded checkout."
59
+ ja: "注文の作成に失敗しました。埋め込み型決済のサービスが有効になっていません。"
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+
5
+ module TaiwanPayments
6
+ # English and Japanese renderings of vendor status codes. The vendors only publish their
7
+ # full code lists inside the merchant back office, in Chinese, so each table
8
+ # holds the codes confirmed from public docs or observed in the sandbox.
9
+ # Unknown codes fall back to the vendor's own message.
10
+ module ErrorCodes
11
+ TABLES = Dir[File.join(__dir__, "error_codes", "*.yml")].to_h do |path|
12
+ [File.basename(path, ".yml").to_sym, YAML.safe_load_file(path).freeze]
13
+ end.freeze
14
+
15
+ module_function
16
+
17
+ # @param locale [Symbol] :en or :ja. Chinese is the vendor's own message.
18
+ # @return [String, nil] our wording for the code, if known
19
+ def translate(table, code, locale = :en)
20
+ TABLES.fetch(table).dig(code.to_s, locale.to_s)
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ # Every error carries each language so an app can show the vendor's original
5
+ # Chinese to local support staff, and English or Japanese to engineers who
6
+ # cannot read it.
7
+ class Error < StandardError
8
+ attr_reader :message_en, :message_zh, :message_ja
9
+
10
+ def initialize(message_en = nil, zh: nil, ja: nil)
11
+ @message_en = (message_en || self.class.name).to_s
12
+ @message_zh = (zh || @message_en).to_s
13
+ @message_ja = (ja || @message_en).to_s
14
+ super({zh_tw: @message_zh, ja: @message_ja}.fetch(TaiwanPayments.locale, @message_en))
15
+ end
16
+ end
17
+
18
+ class ConfigurationError < Error; end
19
+
20
+ # Raised before any network call when the vendor would reject the input.
21
+ # Failing locally gives a readable message instead of an opaque vendor code.
22
+ class ValidationError < Error
23
+ attr_reader :field
24
+
25
+ def initialize(message_en = nil, field: nil, zh: nil, ja: nil)
26
+ @field = field
27
+ super(message_en, zh: zh, ja: ja)
28
+ end
29
+ end
30
+
31
+ # A webhook or response whose signature does not match. Treat as hostile.
32
+ class SignatureError < Error; end
33
+
34
+ class DecryptionError < Error; end
35
+
36
+ # Network-level failure. The original exception is available via #cause.
37
+ class TransportError < Error; end
38
+
39
+ class HttpError < TransportError
40
+ attr_reader :status, :body
41
+
42
+ def initialize(message_en = nil, status:, body: nil, zh: nil, ja: nil)
43
+ @status = status
44
+ @body = body
45
+ super(message_en, zh: zh, ja: ja)
46
+ end
47
+ end
48
+
49
+ # ECPay answers HTTP 403 when a merchant polls too fast and keeps refusing
50
+ # for about 30 minutes, so callers need to tell this apart and back off.
51
+ class RateLimitedError < HttpError; end
52
+
53
+ # The vendor understood the request and answered with a failure code.
54
+ class ApiError < Error
55
+ attr_reader :code, :provider, :raw
56
+
57
+ # @param vendor_message [String] the vendor's own text, usually Chinese
58
+ # @param translation [String, nil] our English rendering when the code is known
59
+ # @param translation_ja [String, nil] our Japanese rendering when the code is known
60
+ def initialize(code:, provider:, vendor_message:, translation: nil, translation_ja: nil, raw: nil)
61
+ @code = code.to_s
62
+ @provider = provider
63
+ @raw = raw
64
+ vendor_message = vendor_message.to_s
65
+ english = translation || (vendor_message.empty? ? "request failed" : vendor_message)
66
+ chinese = vendor_message.empty? ? english : vendor_message
67
+ super("#{provider} error #{@code}: #{english}", zh: "#{provider} 錯誤 #{@code}:#{chinese}",
68
+ ja: "#{provider} エラー #{@code}:#{translation_ja || english}")
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TaiwanPayments
4
+ # View helper, mixed into ActionView by the Railtie.
5
+ module FormHelper
6
+ # Renders a checkout form that sends the customer's browser to the
7
+ # vendor's payment page.
8
+ #
9
+ # <%= taiwan_payments_form(@form) %>
10
+ #
11
+ # @param hosted_form [HostedForm] from a client's `checkout`
12
+ # @param options see {HostedForm#to_html}; `auto_submit: false` shows a button
13
+ def taiwan_payments_form(hosted_form, **options)
14
+ # Apps with a strict Content-Security-Policy block inline scripts that
15
+ # lack the request's nonce, which would leave the customer on a blank page.
16
+ options[:nonce] ||= content_security_policy_nonce if respond_to?(:content_security_policy_nonce)
17
+ # to_html escapes every value it interpolates.
18
+ hosted_form.to_html(**options).html_safe
19
+ end
20
+ end
21
+ end