einvoice 1.5.0 → 2.0.0.alpha2
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 +4 -4
- data/.coderabbit.yaml +6 -8
- data/.github/workflows/build.yml +6 -3
- data/CHANGELOG.md +43 -44
- data/Gemfile +3 -10
- data/README.md +221 -328
- data/README.zh-TW.md +322 -0
- data/Rakefile +2 -51
- data/bin/console +3 -6
- data/einvoice.gemspec +16 -18
- data/lib/einvoice/amego/client.rb +116 -0
- data/lib/einvoice/amego/errors.rb +84 -0
- data/lib/einvoice/amego/payload.rb +276 -0
- data/lib/einvoice/amego/provider.rb +267 -0
- data/lib/einvoice/amego.rb +27 -0
- data/lib/einvoice/capability.rb +79 -0
- data/lib/einvoice/ecpay/client.rb +183 -0
- data/lib/einvoice/ecpay/crypto.rb +85 -0
- data/lib/einvoice/ecpay/errors.rb +115 -0
- data/lib/einvoice/ecpay/payload.rb +241 -0
- data/lib/einvoice/ecpay/provider.rb +362 -0
- data/lib/einvoice/ecpay.rb +31 -0
- data/lib/einvoice/error.rb +220 -0
- data/lib/einvoice/ezpay/client.rb +130 -0
- data/lib/einvoice/ezpay/crypto.rb +85 -0
- data/lib/einvoice/ezpay/errors.rb +72 -0
- data/lib/einvoice/ezpay/payload.rb +269 -0
- data/lib/einvoice/ezpay/provider.rb +235 -0
- data/lib/einvoice/ezpay.rb +19 -0
- data/lib/einvoice/input.rb +494 -0
- data/lib/einvoice/mock_provider.rb +191 -0
- data/lib/einvoice/mof/donation_codes.rb +157 -0
- data/lib/einvoice/mof.rb +16 -0
- data/lib/einvoice/number.rb +51 -0
- data/lib/einvoice/provider.rb +57 -13
- data/lib/einvoice/redaction.rb +54 -0
- data/lib/einvoice/taipei.rb +89 -0
- data/lib/einvoice/tax_split.rb +124 -0
- data/lib/einvoice/tradevan/default_api/client.rb +175 -0
- data/lib/einvoice/tradevan/default_api/crypto.rb +90 -0
- data/lib/einvoice/tradevan/default_api/errors.rb +54 -0
- data/lib/einvoice/tradevan/default_api/payload.rb +259 -0
- data/lib/einvoice/tradevan/default_api/provider.rb +366 -0
- data/lib/einvoice/tradevan/default_api/rules.rb +314 -0
- data/lib/einvoice/tradevan.rb +25 -0
- data/lib/einvoice/types.rb +323 -0
- data/lib/einvoice/version.rb +3 -1
- data/lib/einvoice.rb +21 -9
- metadata +52 -145
- data/.github/workflows/cron.yml +0 -31
- data/docs/Tradevan E-Invoice APIs.md +0 -201
- data/docs/neweb.md +0 -347
- data/lib/einvoice/client.rb +0 -21
- data/lib/einvoice/configuration.rb +0 -49
- data/lib/einvoice/connection.rb +0 -31
- data/lib/einvoice/donation_unit_list.json +0 -2025
- data/lib/einvoice/result.rb +0 -21
- data/lib/einvoice/tradevan/model/base.rb +0 -34
- data/lib/einvoice/tradevan/model/issue_data.rb +0 -129
- data/lib/einvoice/tradevan/model/issue_item.rb +0 -41
- data/lib/einvoice/tradevan/model/void_data.rb +0 -35
- data/lib/einvoice/tradevan/provider.rb +0 -139
- data/lib/einvoice/tradevan/result.rb +0 -25
- data/lib/einvoice/tradevan/validator/issue_data_validator.rb +0 -80
- data/lib/faraday/response/decode_tradevan.rb +0 -37
- data/lib/faraday/response/parse_xml.rb +0 -14
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
# Feature flags a provider may or may not support. Every adapter declares its
|
|
5
|
+
# own set so callers feature-detect at runtime ({Capability::Support#supports?})
|
|
6
|
+
# instead of discovering a gap only when a request fails.
|
|
7
|
+
#
|
|
8
|
+
# The five core operations are listed so a degraded/partial adapter can be
|
|
9
|
+
# honest about what it omits; the rest cover optional behaviour that genuinely
|
|
10
|
+
# differs between value-added centers.
|
|
11
|
+
module Capability
|
|
12
|
+
# 開立發票.
|
|
13
|
+
ISSUE = :issue
|
|
14
|
+
# 作廢發票.
|
|
15
|
+
VOID = :void
|
|
16
|
+
# 開立折讓.
|
|
17
|
+
ALLOWANCE = :allowance
|
|
18
|
+
# 作廢折讓.
|
|
19
|
+
VOID_ALLOWANCE = :void_allowance
|
|
20
|
+
# 查詢發票.
|
|
21
|
+
QUERY = :query
|
|
22
|
+
# Issue to a business buyer with a 統一編號 (B2B).
|
|
23
|
+
B2B = :b2b
|
|
24
|
+
# Mixed tax-rate invoice (應稅 + 零稅率 + 免稅 in one document).
|
|
25
|
+
MIXED_TAX = :mixed_tax
|
|
26
|
+
# Look up an invoice by the merchant order id, not just the invoice number.
|
|
27
|
+
QUERY_BY_ORDER_ID = :query_by_order_id
|
|
28
|
+
# Schedule an invoice to be issued automatically at a future date. No
|
|
29
|
+
# adapter declares it and the unified model has no method for it yet: at
|
|
30
|
+
# ECPay a delayed issue calls the merchant back, and 2.0 has no callbacks.
|
|
31
|
+
# It stays so that a later version can add the feature.
|
|
32
|
+
SCHEDULED_ISSUE = :scheduled_issue
|
|
33
|
+
# Validate a carrier (手機條碼 / 愛心碼) against the tax authority.
|
|
34
|
+
CARRIER_VALIDATION = :carrier_validation
|
|
35
|
+
# Annotate a foreign-currency sale via currency + exchange_rate. Statutory
|
|
36
|
+
# amounts are still filed in integer TWD; providers that don't support it
|
|
37
|
+
# reject a non-TWD currency instead of silently dropping it.
|
|
38
|
+
FOREIGN_CURRENCY = :foreign_currency
|
|
39
|
+
|
|
40
|
+
ALL = [
|
|
41
|
+
ISSUE, VOID, ALLOWANCE, VOID_ALLOWANCE, QUERY, B2B, MIXED_TAX,
|
|
42
|
+
QUERY_BY_ORDER_ID, SCHEDULED_ISSUE, CARRIER_VALIDATION, FOREIGN_CURRENCY
|
|
43
|
+
].freeze
|
|
44
|
+
|
|
45
|
+
# Mixed into anything that exposes a +#capabilities+ set and a +#name+.
|
|
46
|
+
module Support
|
|
47
|
+
# The MIG filing currency. Anything else needs FOREIGN_CURRENCY.
|
|
48
|
+
TWD = "TWD"
|
|
49
|
+
|
|
50
|
+
# Whether this provider declares support for +capability+.
|
|
51
|
+
def supports?(capability)
|
|
52
|
+
capabilities.include?(capability)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Raise {UnsupportedError} unless this provider supports +capability+.
|
|
56
|
+
def assert_supports!(capability)
|
|
57
|
+
return if supports?(capability)
|
|
58
|
+
|
|
59
|
+
raise Einvoice::UnsupportedError.new(
|
|
60
|
+
%(Provider "#{name}" does not support capability "#{capability}"),
|
|
61
|
+
provider: name
|
|
62
|
+
)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Statutory amounts are always filed in TWD, so a +currency+ is an
|
|
66
|
+
# annotation of the original sale that only some centers can carry. Every
|
|
67
|
+
# adapter owes the caller the same answer here — refuse rather than file a
|
|
68
|
+
# foreign-currency sale as though it were TWD — so the check lives once.
|
|
69
|
+
#
|
|
70
|
+
# It belongs to the provider rather than to {Input}, which knows a provider
|
|
71
|
+
# only by name and has no capability set to consult.
|
|
72
|
+
def assert_currency_supported!(currency)
|
|
73
|
+
return if currency.nil? || currency == TWD
|
|
74
|
+
|
|
75
|
+
assert_supports!(Capability::FOREIGN_CURRENCY)
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "uri"
|
|
5
|
+
require "json"
|
|
6
|
+
|
|
7
|
+
module Einvoice
|
|
8
|
+
module ECPay
|
|
9
|
+
# Speaks the ECPay B2C wire protocol: wrap a payload Hash as
|
|
10
|
+
# <tt>{ MerchantID, RqHeader: { Timestamp, Revision }, Data: <encrypted> }</tt>,
|
|
11
|
+
# POST it as JSON, then unwrap and check both result layers, raising the
|
|
12
|
+
# matching {Einvoice::Error} subclass.
|
|
13
|
+
#
|
|
14
|
+
# Callers get the decrypted business payload back and never see the envelope.
|
|
15
|
+
class Client
|
|
16
|
+
PROVIDER = "ecpay"
|
|
17
|
+
|
|
18
|
+
# B2C 電子發票 hosts.
|
|
19
|
+
BASE_URL = {
|
|
20
|
+
test: "https://einvoice-stage.ecpay.com.tw",
|
|
21
|
+
production: "https://einvoice.ecpay.com.tw"
|
|
22
|
+
}.freeze
|
|
23
|
+
|
|
24
|
+
# Sent in every RqHeader. The current B2C docs do not list Revision, and
|
|
25
|
+
# the stage API accepts a request without it (verified 2026-08-15). It
|
|
26
|
+
# stays until docs/providers/ecpay/b2c.md, open question 1, is settled.
|
|
27
|
+
REVISION = "3.0.0"
|
|
28
|
+
|
|
29
|
+
attr_reader :merchant_id, :mode, :base_url, :timeout
|
|
30
|
+
|
|
31
|
+
def initialize(merchant_id:, hash_key:, hash_iv:, mode: ProviderMode::TEST,
|
|
32
|
+
base_url: nil, timeout: 30)
|
|
33
|
+
@merchant_id = merchant_id.to_s
|
|
34
|
+
@hash_key = hash_key.to_s
|
|
35
|
+
@hash_iv = hash_iv.to_s
|
|
36
|
+
@mode = mode
|
|
37
|
+
@base_url = Redaction.base_url!(base_url || BASE_URL.fetch(mode) do
|
|
38
|
+
raise ValidationError.new("Unknown ECPay mode: #{mode.inspect}", provider: PROVIDER)
|
|
39
|
+
end, provider: PROVIDER)
|
|
40
|
+
@timeout = timeout
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# The HashKey and HashIV stay out of logs and consoles.
|
|
44
|
+
def inspect
|
|
45
|
+
"#<#{self.class.name} merchant_id=#{@merchant_id.inspect} mode=#{@mode.inspect} " \
|
|
46
|
+
"base_url=#{@base_url.inspect} hash_key=#{Redaction::FILTERED} hash_iv=#{Redaction::FILTERED}>"
|
|
47
|
+
end
|
|
48
|
+
alias to_s inspect
|
|
49
|
+
|
|
50
|
+
# POST +data+ to +path+ and return the decrypted business payload.
|
|
51
|
+
#
|
|
52
|
+
# @param success_codes [Array<Integer>] extra +RtnCode+s to accept besides +1+
|
|
53
|
+
# @param plain_data [Boolean] the endpoint answers with unencrypted +Data+
|
|
54
|
+
def request(path, data, success_codes: [], plain_data: false)
|
|
55
|
+
envelope = post(path, build_body(data))
|
|
56
|
+
check_transport!(envelope)
|
|
57
|
+
|
|
58
|
+
result = plain_data ? envelope["Data"] : decrypt_data(envelope["Data"])
|
|
59
|
+
check_business!(result, success_codes)
|
|
60
|
+
result
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
private
|
|
64
|
+
|
|
65
|
+
def build_body(data)
|
|
66
|
+
{
|
|
67
|
+
"MerchantID" => @merchant_id,
|
|
68
|
+
"RqHeader" => { "Timestamp" => Time.now.to_i, "Revision" => REVISION },
|
|
69
|
+
# MerchantID is required in the encrypted payload as well as the envelope.
|
|
70
|
+
"Data" => Crypto.encrypt_data(
|
|
71
|
+
{ "MerchantID" => @merchant_id }.merge(stringify(data)), @hash_key, @hash_iv
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# Omit nils rather than sending JSON nulls: an absent optional field is the
|
|
77
|
+
# shape ECPay's own SDKs produce, and the shape these endpoints were verified
|
|
78
|
+
# against. Top-level only — nested payloads are built without nils.
|
|
79
|
+
def stringify(data)
|
|
80
|
+
data.each_with_object({}) do |(key, value), out|
|
|
81
|
+
out[key.to_s] = value unless value.nil?
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def post(path, body)
|
|
86
|
+
uri = URI("#{@base_url}#{path}")
|
|
87
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
88
|
+
http.use_ssl = uri.scheme == "https"
|
|
89
|
+
http.open_timeout = @timeout
|
|
90
|
+
http.read_timeout = @timeout
|
|
91
|
+
|
|
92
|
+
response = nil
|
|
93
|
+
http.request(post_request(uri, body)) { |res| (response = res).read_body }
|
|
94
|
+
check_rate_limit!(response)
|
|
95
|
+
parse_json(response)
|
|
96
|
+
rescue *Error::NETWORK_ERRORS => e
|
|
97
|
+
raise NetworkError.for_failure(e, provider: PROVIDER, name: "ECPay", response: response)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# ECPay answers HTTP 403 when a merchant calls too often, and asks it to wait
|
|
101
|
+
# 30 minutes. The caller can retry later.
|
|
102
|
+
def check_rate_limit!(response)
|
|
103
|
+
return unless response.code.to_i == 403
|
|
104
|
+
|
|
105
|
+
raise NetworkError.new("ECPay returned HTTP 403: too many calls, wait 30 minutes",
|
|
106
|
+
provider: PROVIDER, reason: Reason::RATE_LIMITED, raw_code: response.code)
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def post_request(uri, body)
|
|
110
|
+
request = Net::HTTP::Post.new(uri.request_uri)
|
|
111
|
+
request["Content-Type"] = "application/json"
|
|
112
|
+
request.body = JSON.generate(body)
|
|
113
|
+
request
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# ECPay answers some errors with HTTP 500 and a normal envelope (a wrong
|
|
117
|
+
# HashKey gives TransCode 110), so the body decides when it can be read.
|
|
118
|
+
# Only a body that is not JSON falls back to the HTTP status.
|
|
119
|
+
# A body that ECPay wrote (a JSON object with +TransCode+) decides the
|
|
120
|
+
# error, whatever the HTTP status. Any other body falls back to the
|
|
121
|
+
# status: HTTP 429 and 5xx are a NetworkError, such as a gateway's own
|
|
122
|
+
# JSON error page (docs/providers/README.md, "The unified model").
|
|
123
|
+
def parse_json(response)
|
|
124
|
+
body = JSON.parse(response.body.to_s)
|
|
125
|
+
unless body.is_a?(Hash) && body.key?("TransCode")
|
|
126
|
+
status_error = NetworkError.for_status(response, provider: PROVIDER)
|
|
127
|
+
raise status_error if status_error
|
|
128
|
+
end
|
|
129
|
+
body
|
|
130
|
+
rescue JSON::ParserError => e
|
|
131
|
+
status_error = NetworkError.for_status(response, provider: PROVIDER)
|
|
132
|
+
raise status_error if status_error
|
|
133
|
+
|
|
134
|
+
raise ProviderError.new(
|
|
135
|
+
"ECPay returned a non-JSON response (HTTP #{response.code})",
|
|
136
|
+
provider: PROVIDER, raw_code: response.code, cause: e
|
|
137
|
+
)
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# Layer 1 — the envelope. A failure here means the request never reached the
|
|
141
|
+
# business logic (bad credentials, skewed clock, malformed encryption).
|
|
142
|
+
def check_transport!(envelope)
|
|
143
|
+
trans_code = envelope["TransCode"]
|
|
144
|
+
return if trans_code.to_i == 1 && !blank?(envelope["Data"])
|
|
145
|
+
|
|
146
|
+
code, reason = Errors.classify_transport(trans_code)
|
|
147
|
+
message = envelope["TransMsg"].to_s
|
|
148
|
+
raise Einvoice::Error.for(
|
|
149
|
+
code, message.empty? ? "ECPay transport error" : message,
|
|
150
|
+
provider: PROVIDER, reason: reason, raw_code: trans_code.to_s,
|
|
151
|
+
raw_message: message, raw: envelope
|
|
152
|
+
)
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
# Layer 2 — the business result, only reachable once the envelope was good.
|
|
156
|
+
def check_business!(result, success_codes)
|
|
157
|
+
unless result.is_a?(Hash)
|
|
158
|
+
raise ProviderError.new("ECPay returned an unexpected Data payload", provider: PROVIDER,
|
|
159
|
+
raw: result)
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
rtn_code = result["RtnCode"].to_i
|
|
163
|
+
return if rtn_code == 1 || success_codes.include?(rtn_code)
|
|
164
|
+
|
|
165
|
+
message = result["RtnMsg"].to_s
|
|
166
|
+
code, reason = Errors.classify(rtn_code, message)
|
|
167
|
+
raise Einvoice::Error.for(
|
|
168
|
+
code, message.empty? ? "ECPay returned an error" : message,
|
|
169
|
+
provider: PROVIDER, reason: reason, raw_code: rtn_code.to_s,
|
|
170
|
+
raw_message: message, raw: result
|
|
171
|
+
)
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
def decrypt_data(data)
|
|
175
|
+
Crypto.decrypt_data(data, @hash_key, @hash_iv)
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
def blank?(value)
|
|
179
|
+
value.nil? || (value.respond_to?(:empty?) && value.empty?)
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
end
|
|
183
|
+
end
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "json"
|
|
5
|
+
|
|
6
|
+
module Einvoice
|
|
7
|
+
module ECPay
|
|
8
|
+
# The ECPay B2C envelope's +Data+ field is
|
|
9
|
+
# <tt>JSON → PHP urlencode → AES-128-CBC (PKCS7) → Base64</tt>, and the reverse
|
|
10
|
+
# on the way back.
|
|
11
|
+
#
|
|
12
|
+
# The PHP url(en|de)code semantics are the part that trips implementations up:
|
|
13
|
+
# a space is +++ (not +%20+) and +!*'()~+ are percent-encoded, neither of which
|
|
14
|
+
# Ruby's own helpers do (+CGI.escape+ leaves +~+ alone). Encoding is done over
|
|
15
|
+
# bytes so UTF-8 payloads survive.
|
|
16
|
+
#
|
|
17
|
+
# Verified byte-for-byte against ECPay's published cross-language AES vectors
|
|
18
|
+
# (2026-08-15) — see the crypto spec.
|
|
19
|
+
module Crypto
|
|
20
|
+
# PHP +urlencode+ keeps only these unreserved bytes; everything else is %XX.
|
|
21
|
+
UNRESERVED = /[^a-zA-Z0-9\-_.]/n
|
|
22
|
+
|
|
23
|
+
module_function
|
|
24
|
+
|
|
25
|
+
# PHP +urlencode+: space → +++, every other non-unreserved byte → +%XX+.
|
|
26
|
+
def php_url_encode(value)
|
|
27
|
+
value.to_s.b.gsub(UNRESERVED) { |byte| byte == " " ? "+" : format("%%%02X", byte.ord) }
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# PHP +urldecode+: +++ → space, then percent-decode back to UTF-8.
|
|
31
|
+
def php_url_decode(value)
|
|
32
|
+
value.to_s.tr("+", " ")
|
|
33
|
+
.gsub(/%([0-9A-Fa-f]{2})/) { ::Regexp.last_match(1).hex.chr }
|
|
34
|
+
.force_encoding(Encoding::UTF_8)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# AES-128-CBC + PKCS7, Base64-encoded. +key+/+iv+ are the 16-byte HashKey/HashIV.
|
|
38
|
+
def encrypt(plaintext, key, iv)
|
|
39
|
+
cipher = new_cipher(key, iv, :encrypt)
|
|
40
|
+
[cipher.update(plaintext.to_s) + cipher.final].pack("m0")
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Reverse of {encrypt}. Raises {Einvoice::ProviderError} on a corrupt payload.
|
|
44
|
+
def decrypt(base64, key, iv)
|
|
45
|
+
cipher = new_cipher(key, iv, :decrypt)
|
|
46
|
+
(cipher.update(base64.to_s.unpack1("m")) + cipher.final).force_encoding(Encoding::UTF_8)
|
|
47
|
+
rescue OpenSSL::Cipher::CipherError, ArgumentError => e
|
|
48
|
+
raise ProviderError.new("Could not decrypt the ECPay response payload",
|
|
49
|
+
provider: "ecpay", cause: e)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Build a request +Data+ value from a payload Hash.
|
|
53
|
+
def encrypt_data(data, key, iv)
|
|
54
|
+
encrypt(php_url_encode(JSON.generate(data)), key, iv)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Read a response +Data+ value back into a Hash.
|
|
58
|
+
def decrypt_data(base64, key, iv)
|
|
59
|
+
JSON.parse(php_url_decode(decrypt(base64, key, iv)))
|
|
60
|
+
rescue JSON::ParserError => e
|
|
61
|
+
raise ProviderError.new("ECPay returned a malformed JSON payload",
|
|
62
|
+
provider: "ecpay", cause: e)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# AES-128 needs exactly 16 bytes of key and IV; a merchant pasting the wrong
|
|
66
|
+
# credential is the common cause, so say which one is wrong up front.
|
|
67
|
+
def new_cipher(key, iv, direction)
|
|
68
|
+
assert_length!(key, "hash_key")
|
|
69
|
+
assert_length!(iv, "hash_iv")
|
|
70
|
+
cipher = OpenSSL::Cipher.new("aes-128-cbc").public_send(direction)
|
|
71
|
+
cipher.key = key
|
|
72
|
+
cipher.iv = iv
|
|
73
|
+
cipher
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def assert_length!(value, field)
|
|
77
|
+
size = value.to_s.bytesize
|
|
78
|
+
return if size == 16
|
|
79
|
+
|
|
80
|
+
raise ValidationError.new("ECPay #{field} must be 16 bytes (AES-128-CBC), got #{size}",
|
|
81
|
+
provider: "ecpay")
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
module ECPay
|
|
5
|
+
# Maps ECPay's two failure channels onto the unified {Einvoice::Error} tree.
|
|
6
|
+
#
|
|
7
|
+
# A B2C response has two independent result fields and both must be checked:
|
|
8
|
+
# the outer +TransCode+ (transport — did the envelope decrypt and parse?) and,
|
|
9
|
+
# after decrypting +Data+, the inner +RtnCode+ (business). Success is the
|
|
10
|
+
# integer +1+ on each.
|
|
11
|
+
#
|
|
12
|
+
# Business codes are the awkward part: they span unrelated ranges (+2+,
|
|
13
|
+
# +1600003+, +5070357+, +5000022+ …) and the same condition can surface under
|
|
14
|
+
# different numbers per endpoint, so the Chinese +RtnMsg+ is the more reliable
|
|
15
|
+
# signal. Classification therefore tries the table of codes confirmed against
|
|
16
|
+
# the live stage API first, then falls back to matching the message.
|
|
17
|
+
module Errors
|
|
18
|
+
# Transport-level codes. 110 was seen live (2026-08-15, stage). 104 and 115
|
|
19
|
+
# come from the shared wire fixtures. Any other code is a ProviderError.
|
|
20
|
+
TRANSPORT = {
|
|
21
|
+
104 => [:auth, Reason::STALE_TIMESTAMP], # Timestamp is over 10 minutes...
|
|
22
|
+
110 => [:auth, Reason::CREDENTIALS_INVALID], # The parameter [Data] decrypt fail.
|
|
23
|
+
115 => [:auth, Reason::NOT_ENROLLED] # B2C/B2B功能尚未開通
|
|
24
|
+
}.freeze
|
|
25
|
+
|
|
26
|
+
# Business codes confirmed by driving the stage API (2026-08-15). Kept small
|
|
27
|
+
# and specific on purpose — a code whose meaning is endpoint-dependent (e.g.
|
|
28
|
+
# a bare +2+) is left to the message matcher instead.
|
|
29
|
+
BUSINESS = {
|
|
30
|
+
1_600_003 => [:not_found, nil], # 無發票號碼資料
|
|
31
|
+
2_000_039 => [:not_found, nil], # 查無折讓單資料
|
|
32
|
+
2_000_042 => [:conflict, Reason::ALLOWANCE_BLOCKED_BY_VOID], # 作廢發票號碼不能折讓
|
|
33
|
+
2_000_063 => [:conflict, Reason::ALREADY_VOIDED], # 該折讓單已作廢過
|
|
34
|
+
5_070_357 => [:conflict, Reason::DUPLICATE_ORDER], # 自訂編號重覆
|
|
35
|
+
5_070_450 => [:conflict, Reason::VOID_BLOCKED_BY_ALLOWANCE], # 該發票已被折讓過
|
|
36
|
+
5_070_453 => [:conflict, Reason::ALREADY_VOIDED], # 該發票已被作廢過
|
|
37
|
+
9_000_001 => [:network, nil], # 呼叫財政部API失敗
|
|
38
|
+
# From the shared wire fixtures.
|
|
39
|
+
4_000_001 => [:not_found, nil], # 不存在此交易單號
|
|
40
|
+
1_100_040 => [:number_exhausted, nil], # 發票字軌已用完
|
|
41
|
+
5_070_250 => [:conflict, nil] # 線上折讓已同意,不可作廢
|
|
42
|
+
}.freeze
|
|
43
|
+
|
|
44
|
+
# 財政部 upstream trouble is transient and retryable — never the caller's input.
|
|
45
|
+
UPSTREAM_DOWN = /財政部.*(失敗|維護)|呼叫.*API失敗/
|
|
46
|
+
CREDENTIALS = /金鑰|簽章|未授權/
|
|
47
|
+
NOT_ENROLLED = /特店.*不存在|平台商.*不存在/
|
|
48
|
+
EXHAUSTED = /字軌.*(用罄|用完|不足|已滿)|號碼.*(用罄|用完)/
|
|
49
|
+
# 重複 and 重覆 are both current spellings and ECPay uses both — matching only
|
|
50
|
+
# one silently demotes a duplicate-order conflict to a generic validation error.
|
|
51
|
+
DUPLICATE = /重[複覆]/
|
|
52
|
+
# Two different conflicts that both mention 作廢, and they call for opposite
|
|
53
|
+
# responses. 已作廢 on a void means the invoice already reached the state
|
|
54
|
+
# asked for — safe to treat as success. "作廢…不能…" means the operation was
|
|
55
|
+
# refused *because* the invoice is voided, and nothing happened; treating
|
|
56
|
+
# that as success would record a credit that does not exist.
|
|
57
|
+
# ECPay writes both 已作廢 and 已被作廢; matching only the first meant the
|
|
58
|
+
# fallback missed 5070453's actual wording, which went unnoticed because
|
|
59
|
+
# that code is in the table above.
|
|
60
|
+
ALREADY_VOID = /已(被)?作廢/
|
|
61
|
+
BLOCKED_BY_VOID = /作廢.*不能/
|
|
62
|
+
ALLOWANCE_MADE = /已折讓|折讓過/
|
|
63
|
+
CONFLICTING = /已開立|已存在|同意/
|
|
64
|
+
MISSING = /查無|查不到|無.*資料|不存在/
|
|
65
|
+
BUSY = /系統(錯誤|異常|忙碌)|請稍後/
|
|
66
|
+
|
|
67
|
+
module_function
|
|
68
|
+
|
|
69
|
+
# Classify a transport failure → +[code, reason]+.
|
|
70
|
+
def classify_transport(trans_code)
|
|
71
|
+
TRANSPORT.fetch(trans_code.to_i, [:provider, nil])
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Classify a business failure → +[code, reason]+.
|
|
75
|
+
def classify(rtn_code, rtn_msg = "")
|
|
76
|
+
known = BUSINESS[rtn_code.to_i]
|
|
77
|
+
return known if known
|
|
78
|
+
|
|
79
|
+
[message_code(rtn_msg.to_s), message_reason(rtn_msg.to_s)]
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# The fallback matcher. Anything unrecognized is treated as field/business
|
|
83
|
+
# validation, which is what the long tail of ECPay's codes actually is.
|
|
84
|
+
def message_code(msg)
|
|
85
|
+
case msg
|
|
86
|
+
when UPSTREAM_DOWN then :network
|
|
87
|
+
when CREDENTIALS, NOT_ENROLLED then :auth
|
|
88
|
+
when EXHAUSTED then :number_exhausted
|
|
89
|
+
when DUPLICATE, ALREADY_VOID, BLOCKED_BY_VOID, ALLOWANCE_MADE, CONFLICTING then :conflict
|
|
90
|
+
# AUTH already claimed 特店/平台商不存在 above, so a bare 不存在 here is a
|
|
91
|
+
# missing record rather than an unknown merchant.
|
|
92
|
+
when MISSING then :not_found
|
|
93
|
+
when BUSY then :provider
|
|
94
|
+
else :validation
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def message_reason(msg)
|
|
99
|
+
case msg
|
|
100
|
+
when CREDENTIALS then Reason::CREDENTIALS_INVALID
|
|
101
|
+
when NOT_ENROLLED then Reason::NOT_ENROLLED
|
|
102
|
+
# Checked before ALREADY_VOID: a message carrying both ("已作廢,不能折讓")
|
|
103
|
+
# is a refusal, and the refusal is the actionable half.
|
|
104
|
+
when BLOCKED_BY_VOID then Reason::ALLOWANCE_BLOCKED_BY_VOID
|
|
105
|
+
when ALREADY_VOID then Reason::ALREADY_VOIDED
|
|
106
|
+
# Only the void API emits 已折讓/折讓過, so it always means "void the
|
|
107
|
+
# allowance first" rather than a plain conflict.
|
|
108
|
+
when ALLOWANCE_MADE then Reason::VOID_BLOCKED_BY_ALLOWANCE
|
|
109
|
+
when DUPLICATE then Reason::DUPLICATE_ORDER
|
|
110
|
+
when BUSY then Reason::RATE_LIMITED
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
end
|