einvoice 1.5.0 → 2.0.0.beta1
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/.github/workflows/cron.yml +4 -2
- data/CHANGELOG.md +63 -44
- data/Gemfile +3 -10
- data/README.md +284 -325
- data/README.zh-TW.md +381 -0
- data/Rakefile +2 -51
- data/bin/console +3 -6
- data/einvoice.gemspec +17 -18
- data/lib/einvoice/amego/client.rb +116 -0
- data/lib/einvoice/amego/errors.rb +84 -0
- data/lib/einvoice/amego/payload.rb +270 -0
- data/lib/einvoice/amego/provider.rb +272 -0
- data/lib/einvoice/amego.rb +27 -0
- data/lib/einvoice/capability.rb +79 -0
- data/lib/einvoice/ecpay/client.rb +184 -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 +371 -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 +253 -0
- data/lib/einvoice/ezpay.rb +19 -0
- data/lib/einvoice/input.rb +547 -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 +91 -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 +112 -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 +353 -0
- data/lib/einvoice/tradevan/default_api/rules.rb +314 -0
- data/lib/einvoice/tradevan.rb +25 -0
- data/lib/einvoice/types.rb +365 -0
- data/lib/einvoice/version.rb +3 -1
- data/lib/einvoice.rb +21 -9
- metadata +52 -144
- 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,220 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "openssl"
|
|
5
|
+
require "timeout"
|
|
6
|
+
|
|
7
|
+
module Einvoice
|
|
8
|
+
# Normalized, action-oriented reason symbols — one level finer than the error
|
|
9
|
+
# class. The classes are deliberately coarse ({ConflictError} alone covers
|
|
10
|
+
# duplicate-order, void-blocked-by-allowance, already-voided and past-deadline,
|
|
11
|
+
# which a caller handles completely differently), so `reason` carries the
|
|
12
|
+
# distinction. `nil` when the adapter cannot determine one.
|
|
13
|
+
#
|
|
14
|
+
# Each value implies a concrete consumer action, e.g. +:duplicate_order+ →
|
|
15
|
+
# query-and-adopt the existing invoice; +:void_blocked_by_allowance+ → issue an
|
|
16
|
+
# allowance instead; +:already_voided+ → treat as idempotent success.
|
|
17
|
+
#
|
|
18
|
+
# That last one is why the two "wrong state" reasons are separate. Voiding an
|
|
19
|
+
# already-voided invoice reached the state the caller wanted, so doing nothing
|
|
20
|
+
# is correct. Crediting a voided invoice did not: no allowance exists, and
|
|
21
|
+
# treating it as success would record a refund that never happened.
|
|
22
|
+
module Reason
|
|
23
|
+
DUPLICATE_ORDER = :duplicate_order
|
|
24
|
+
# 作廢 refused: the invoice carries a live 折讓 — void that first.
|
|
25
|
+
VOID_BLOCKED_BY_ALLOWANCE = :void_blocked_by_allowance
|
|
26
|
+
# 折讓 refused: the invoice is already 作廢 — there is nothing to credit, and
|
|
27
|
+
# nothing was credited. Not idempotent success; the caller has to reconcile.
|
|
28
|
+
ALLOWANCE_BLOCKED_BY_VOID = :allowance_blocked_by_void
|
|
29
|
+
# 作廢 of an invoice already 作廢 — the requested state, so safe to ignore.
|
|
30
|
+
ALREADY_VOIDED = :already_voided
|
|
31
|
+
DUPLICATE_ALLOWANCE = :duplicate_allowance
|
|
32
|
+
PAST_DEADLINE = :past_deadline
|
|
33
|
+
CARRIER_NOT_REGISTERED = :carrier_not_registered
|
|
34
|
+
RATE_LIMITED = :rate_limited
|
|
35
|
+
CREDENTIALS_INVALID = :credentials_invalid
|
|
36
|
+
NOT_ENROLLED = :not_enrolled
|
|
37
|
+
CONTRACT_EXPIRED = :contract_expired
|
|
38
|
+
IP_BLOCKED = :ip_blocked
|
|
39
|
+
ACCOUNT_SUSPENDED = :account_suspended
|
|
40
|
+
# The provider refused the request time. The caller's server clock is off.
|
|
41
|
+
# An AuthError at every provider: the request is checked with its time, and
|
|
42
|
+
# a retry fails the same way until the clock is fixed. The shared ECPay
|
|
43
|
+
# fixtures, which the TypeScript SDK runs too, pin it as AUTH.
|
|
44
|
+
STALE_TIMESTAMP = :stale_timestamp
|
|
45
|
+
# The adapter queried the provider on its own, to fill a field the call did
|
|
46
|
+
# not give, and that query failed. +cause+ holds the error of the query.
|
|
47
|
+
# A provider error: the invoice of the call may well exist.
|
|
48
|
+
LOOKUP_FAILED = :lookup_failed
|
|
49
|
+
# The provider says "not now": the invoice is still being issued, a change
|
|
50
|
+
# waits in its queue, or it is not uploaded yet. The same call may work
|
|
51
|
+
# later. A ConflictError, as the state is wrong for now.
|
|
52
|
+
RETRY_LATER = :retry_later
|
|
53
|
+
|
|
54
|
+
ALL = [
|
|
55
|
+
DUPLICATE_ORDER, VOID_BLOCKED_BY_ALLOWANCE, ALLOWANCE_BLOCKED_BY_VOID,
|
|
56
|
+
ALREADY_VOIDED, DUPLICATE_ALLOWANCE,
|
|
57
|
+
PAST_DEADLINE, CARRIER_NOT_REGISTERED, RATE_LIMITED, CREDENTIALS_INVALID,
|
|
58
|
+
NOT_ENROLLED, CONTRACT_EXPIRED, IP_BLOCKED, ACCOUNT_SUSPENDED, STALE_TIMESTAMP,
|
|
59
|
+
LOOKUP_FAILED, RETRY_LATER
|
|
60
|
+
].freeze
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Base class for every error the SDK raises. Adapters map provider/MOF error
|
|
64
|
+
# codes onto a subclass, preserving the provider's raw code/message/payload.
|
|
65
|
+
#
|
|
66
|
+
# Rescue precisely (`rescue Einvoice::ConflictError`) or broadly
|
|
67
|
+
# (`rescue Einvoice::Error`) — the subclass hierarchy replaces the string
|
|
68
|
+
# matching the legacy client forced on callers. Each subclass exposes a stable
|
|
69
|
+
# {#code} symbol so two-way parity with the TypeScript SDK's InvoiceErrorCode
|
|
70
|
+
# holds.
|
|
71
|
+
class Error < StandardError
|
|
72
|
+
# Stable, provider-independent code for the base class. Subclasses override.
|
|
73
|
+
CODE = :unknown
|
|
74
|
+
# Which side failed. +:invoice+: the request breaks a rule of the MOF, or the
|
|
75
|
+
# invoice is not in the state it needs. These mean the same at every
|
|
76
|
+
# provider. +:provider+: the account, the connection, the provider's own
|
|
77
|
+
# service, or a feature it lacks.
|
|
78
|
+
GROUP = :provider
|
|
79
|
+
# The low-level errors that mean the connection failed. Clients rescue only
|
|
80
|
+
# these, so a bug in an adapter is not reported as a NetworkError.
|
|
81
|
+
NETWORK_ERRORS = [
|
|
82
|
+
IOError, SocketError, SystemCallError, Timeout::Error, EOFError,
|
|
83
|
+
OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::ProtocolError
|
|
84
|
+
].freeze
|
|
85
|
+
|
|
86
|
+
attr_reader :provider, :reason, :raw_code, :raw_message, :raw
|
|
87
|
+
|
|
88
|
+
def initialize(message = nil, provider:, reason: nil, raw_code: nil, raw_message: nil,
|
|
89
|
+
raw: nil, cause: nil)
|
|
90
|
+
super(message)
|
|
91
|
+
@provider = provider
|
|
92
|
+
@reason = reason
|
|
93
|
+
@raw_code = raw_code
|
|
94
|
+
@raw_message = raw_message
|
|
95
|
+
@raw = raw
|
|
96
|
+
@explicit_cause = cause
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# The stable {InvoiceErrorCode}-equivalent symbol, e.g. +:conflict+.
|
|
100
|
+
def code
|
|
101
|
+
self.class::CODE
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# +:invoice+ or +:provider+. See {GROUP}.
|
|
105
|
+
def group
|
|
106
|
+
self.class::GROUP
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# Preserve an explicitly-passed cause, else fall back to Ruby's ambient one.
|
|
110
|
+
def cause
|
|
111
|
+
@explicit_cause || super
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# Structured-logging shape. Omits +raw+ (can be large / carry PII — read it
|
|
115
|
+
# off the instance when needed) and drops nil fields.
|
|
116
|
+
def to_h
|
|
117
|
+
{
|
|
118
|
+
provider: provider,
|
|
119
|
+
code: code,
|
|
120
|
+
group: group,
|
|
121
|
+
reason: reason,
|
|
122
|
+
message: message,
|
|
123
|
+
raw_code: raw_code,
|
|
124
|
+
raw_message: raw_message
|
|
125
|
+
}.compact
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# Build the subclass for a normalized code symbol. Adapters resolve a
|
|
129
|
+
# provider code to one of our codes, then `raise Einvoice::Error.for(code, …)`.
|
|
130
|
+
def self.for(code, message = nil, **options)
|
|
131
|
+
CODE_TO_CLASS.fetch(code, UnknownError).new(message, **options)
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# Auth / signature / credential failure.
|
|
136
|
+
class AuthError < Error
|
|
137
|
+
CODE = :auth
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# Request failed local or remote validation.
|
|
141
|
+
class ValidationError < Error
|
|
142
|
+
CODE = :validation
|
|
143
|
+
GROUP = :invoice
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
# Referenced invoice/allowance does not exist.
|
|
147
|
+
class NotFoundError < Error
|
|
148
|
+
CODE = :not_found
|
|
149
|
+
GROUP = :invoice
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
# Operation invalid for the invoice's current state (e.g. void a voided one).
|
|
153
|
+
class ConflictError < Error
|
|
154
|
+
CODE = :conflict
|
|
155
|
+
GROUP = :invoice
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# 字軌 / 配號 exhausted — no invoice number available.
|
|
159
|
+
class NumberExhaustedError < Error
|
|
160
|
+
CODE = :number_exhausted
|
|
161
|
+
GROUP = :invoice
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# Network / timeout / transport failure, and HTTP 5xx or 429. The caller can
|
|
165
|
+
# retry.
|
|
166
|
+
class NetworkError < Error
|
|
167
|
+
CODE = :network
|
|
168
|
+
|
|
169
|
+
# The error for an HTTP status that means "try again", or nil.
|
|
170
|
+
def self.for_status(response, provider:)
|
|
171
|
+
status = response.code.to_i
|
|
172
|
+
return unless status == 429 || status >= 500
|
|
173
|
+
|
|
174
|
+
reason = status == 429 ? Reason::RATE_LIMITED : nil
|
|
175
|
+
new("#{provider} returned HTTP #{status}", provider: provider, reason: reason, raw_code: response.code)
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
# The error for a connection failure. +response+ is the response whose
|
|
179
|
+
# headers had arrived before the failure, or nil. Its status is kept, so a
|
|
180
|
+
# body that failed to arrive after HTTP 429 is still RATE_LIMITED. +name+
|
|
181
|
+
# is the provider's name for the message, such as "ECPay".
|
|
182
|
+
def self.for_failure(cause, provider:, name: provider, response: nil)
|
|
183
|
+
message = "#{name} request failed: #{cause.message}"
|
|
184
|
+
return new(message, provider: provider, cause: cause) unless response
|
|
185
|
+
|
|
186
|
+
reason = response.code.to_i == 429 ? Reason::RATE_LIMITED : nil
|
|
187
|
+
new("#{message} (HTTP #{response.code})", provider: provider, reason: reason, raw_code: response.code,
|
|
188
|
+
cause: cause)
|
|
189
|
+
end
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
# Provider returned an error we could not map.
|
|
193
|
+
class ProviderError < Error
|
|
194
|
+
CODE = :provider
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
# The provider does not support the requested operation/feature.
|
|
198
|
+
class UnsupportedError < Error
|
|
199
|
+
CODE = :unsupported
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
# Anything else.
|
|
203
|
+
class UnknownError < Error
|
|
204
|
+
CODE = :unknown
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
class Error
|
|
208
|
+
CODE_TO_CLASS = {
|
|
209
|
+
auth: AuthError,
|
|
210
|
+
validation: ValidationError,
|
|
211
|
+
not_found: NotFoundError,
|
|
212
|
+
conflict: ConflictError,
|
|
213
|
+
number_exhausted: NumberExhaustedError,
|
|
214
|
+
network: NetworkError,
|
|
215
|
+
provider: ProviderError,
|
|
216
|
+
unsupported: UnsupportedError,
|
|
217
|
+
unknown: UnknownError
|
|
218
|
+
}.freeze
|
|
219
|
+
end
|
|
220
|
+
end
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "uri"
|
|
5
|
+
require "json"
|
|
6
|
+
|
|
7
|
+
module Einvoice
|
|
8
|
+
module EzPay
|
|
9
|
+
# Speaks ezPay's wire protocol: a form POST of +MerchantID_+ and the
|
|
10
|
+
# encrypted +PostData_+, then the +Status+ / +Message+ / +Result+ answer.
|
|
11
|
+
# +Result+ is itself a JSON string, so it is parsed a second time.
|
|
12
|
+
class Client
|
|
13
|
+
PROVIDER = "ezpay"
|
|
14
|
+
BASE_URL = {
|
|
15
|
+
ProviderMode::TEST => "https://cinv.ezpay.com.tw",
|
|
16
|
+
ProviderMode::PRODUCTION => "https://inv.ezpay.com.tw"
|
|
17
|
+
}.freeze
|
|
18
|
+
SUCCESS = "SUCCESS"
|
|
19
|
+
|
|
20
|
+
attr_reader :merchant_id, :mode, :base_url, :timeout
|
|
21
|
+
|
|
22
|
+
def initialize(merchant_id:, hash_key:, hash_iv:, mode: ProviderMode::TEST, base_url: nil, timeout: 30,
|
|
23
|
+
clock: -> { Time.now })
|
|
24
|
+
if [merchant_id, hash_key, hash_iv].any? { |value| value.to_s.empty? }
|
|
25
|
+
raise ValidationError.new("ezPay merchant_id, hash_key and hash_iv are required", provider: PROVIDER)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
@merchant_id = merchant_id.to_s
|
|
29
|
+
@hash_key = hash_key.to_s
|
|
30
|
+
@hash_iv = hash_iv.to_s
|
|
31
|
+
@mode = mode
|
|
32
|
+
@base_url = Redaction.base_url!(base_url || BASE_URL.fetch(mode) do
|
|
33
|
+
raise ValidationError.new("Unknown ezPay mode: #{mode.inspect}", provider: PROVIDER)
|
|
34
|
+
end, provider: PROVIDER)
|
|
35
|
+
@timeout = timeout
|
|
36
|
+
@clock = clock
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def inspect
|
|
40
|
+
"#<#{self.class.name} merchant_id=#{@merchant_id.inspect} mode=#{@mode.inspect} " \
|
|
41
|
+
"base_url=#{@base_url.inspect} hash_key=#{Redaction::FILTERED} hash_iv=#{Redaction::FILTERED}>"
|
|
42
|
+
end
|
|
43
|
+
alias to_s inspect
|
|
44
|
+
|
|
45
|
+
# POST +fields+ to +path+ (for example +"/Api/invoice_issue"+) under the
|
|
46
|
+
# API +version+, and return the parsed +Result+ Hash. A +Status+ other
|
|
47
|
+
# than +SUCCESS+ raises; +operation+ picks the guesses in {Errors::CONTEXT}.
|
|
48
|
+
def request(path, version, fields, operation: nil)
|
|
49
|
+
payload = { "RespondType" => "JSON", "Version" => version, "TimeStamp" => @clock.call.to_i.to_s }
|
|
50
|
+
.merge(fields.transform_keys(&:to_s))
|
|
51
|
+
post_data = Crypto.encrypt(Crypto.build_query(payload), @hash_key, @hash_iv)
|
|
52
|
+
read(send_request(path, { "MerchantID_" => @merchant_id, "PostData_" => post_data }), operation)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Raise {ProviderError} unless +result+ carries the CheckCode that the
|
|
56
|
+
# HashKey and HashIV give for it.
|
|
57
|
+
def verify_check_code!(result)
|
|
58
|
+
return if result["CheckCode"].to_s == Crypto.check_code(result, @hash_key, @hash_iv)
|
|
59
|
+
|
|
60
|
+
raise ProviderError.new("ezPay CheckCode does not match the result", provider: PROVIDER, raw: result)
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
private
|
|
64
|
+
|
|
65
|
+
def send_request(path, form)
|
|
66
|
+
uri = URI("#{@base_url}#{path}")
|
|
67
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
68
|
+
http.use_ssl = uri.scheme == "https"
|
|
69
|
+
http.open_timeout = @timeout
|
|
70
|
+
http.read_timeout = @timeout
|
|
71
|
+
|
|
72
|
+
post = Net::HTTP::Post.new(uri.request_uri)
|
|
73
|
+
post.set_form_data(form)
|
|
74
|
+
response = nil
|
|
75
|
+
http.request(post) { |res| (response = res).read_body }
|
|
76
|
+
parse(response)
|
|
77
|
+
rescue *Error::NETWORK_ERRORS => e
|
|
78
|
+
raise NetworkError.for_failure(e, provider: PROVIDER, name: "ezPay", response: response)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# A body that ezPay wrote (a JSON object with +Status+) decides the
|
|
82
|
+
# error, whatever the HTTP status. Any other body falls back to the
|
|
83
|
+
# status: HTTP 429 and 5xx are a NetworkError, so the caller can retry
|
|
84
|
+
# (docs/providers/README.md, "The unified model").
|
|
85
|
+
def parse(response)
|
|
86
|
+
body = JSON.parse(response.body.to_s)
|
|
87
|
+
return body if body.is_a?(Hash) && body.key?("Status")
|
|
88
|
+
|
|
89
|
+
raise_for_status!(response)
|
|
90
|
+
body
|
|
91
|
+
rescue JSON::ParserError => e
|
|
92
|
+
raise_for_status!(response)
|
|
93
|
+
raise ProviderError.new("ezPay returned a non-JSON response (HTTP #{response.code})",
|
|
94
|
+
provider: PROVIDER, raw_code: response.code, cause: e)
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def raise_for_status!(response)
|
|
98
|
+
error = NetworkError.for_status(response, provider: PROVIDER)
|
|
99
|
+
raise error if error
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def read(body, operation)
|
|
103
|
+
unless body.is_a?(Hash) && body.key?("Status")
|
|
104
|
+
raise ProviderError.new("ezPay returned an unexpected response", provider: PROVIDER, raw: body)
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
status = body["Status"].to_s
|
|
108
|
+
return parse_result(body) if status == SUCCESS
|
|
109
|
+
|
|
110
|
+
message = body["Message"].to_s
|
|
111
|
+
code, reason = Errors.classify(status, operation)
|
|
112
|
+
raise Einvoice::Error.for(code, message.empty? ? "ezPay returned #{status}" : message,
|
|
113
|
+
provider: PROVIDER, reason: reason, raw_code: status,
|
|
114
|
+
raw_message: message, raw: body)
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# +Result+ is a JSON string. It may also be empty, or already a Hash.
|
|
118
|
+
def parse_result(body)
|
|
119
|
+
result = body["Result"]
|
|
120
|
+
result = JSON.parse(result) if result.is_a?(String) && !result.strip.empty?
|
|
121
|
+
return result if result.is_a?(Hash)
|
|
122
|
+
return {} if result.nil? || result == ""
|
|
123
|
+
|
|
124
|
+
raise ProviderError.new("ezPay returned an unexpected Result", provider: PROVIDER, raw: body)
|
|
125
|
+
rescue JSON::ParserError => e
|
|
126
|
+
raise ProviderError.new("ezPay returned a Result that is not JSON", provider: PROVIDER, raw: body, cause: e)
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
end
|
|
130
|
+
end
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "digest"
|
|
5
|
+
|
|
6
|
+
module Einvoice
|
|
7
|
+
module EzPay
|
|
8
|
+
# The ezPay payload is a PHP +http_build_query+ string, padded with PKCS#7
|
|
9
|
+
# to a multiple of 32 bytes, encrypted with AES-256-CBC, and hex encoded
|
|
10
|
+
# (docs/providers/ezpay/invoice.md, section 2.2).
|
|
11
|
+
#
|
|
12
|
+
# Results carry a +CheckCode+: SHA-256 over five sorted result fields,
|
|
13
|
+
# wrapped in the HashIV and the HashKey (section 2.4).
|
|
14
|
+
module Crypto
|
|
15
|
+
BLOCK = 32
|
|
16
|
+
# PHP +urlencode+ keeps only these bytes. +rawurlencode+ also keeps +~+.
|
|
17
|
+
URLENCODE_KEEP = /[^a-zA-Z0-9\-_.]/n
|
|
18
|
+
RAWURLENCODE_KEEP = /[^a-zA-Z0-9\-_.~]/n
|
|
19
|
+
CHECK_FIELDS = %w[InvoiceTransNo MerchantID MerchantOrderNo RandomNum TotalAmt].freeze
|
|
20
|
+
|
|
21
|
+
module_function
|
|
22
|
+
|
|
23
|
+
# PHP +http_build_query+ over an ordered Hash: +urlencode+ on keys and
|
|
24
|
+
# values, so a space is +++.
|
|
25
|
+
def build_query(fields)
|
|
26
|
+
fields.map { |key, value| "#{urlencode(key)}=#{urlencode(value)}" }.join("&")
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# PHP +urlencode+.
|
|
30
|
+
def urlencode(value)
|
|
31
|
+
value.to_s.b.gsub(URLENCODE_KEEP) { |byte| byte == " " ? "+" : format("%%%02X", byte.ord) }
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# PHP +rawurlencode+ (RFC 3986): a space is +%20+.
|
|
35
|
+
def rawurlencode(value)
|
|
36
|
+
value.to_s.b.gsub(RAWURLENCODE_KEEP) { |byte| format("%%%02X", byte.ord) }
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# PHP +urldecode+, for reading a payload back (the fake uses it).
|
|
40
|
+
def urldecode(value)
|
|
41
|
+
value.to_s.tr("+", " ").b.gsub(/%([0-9A-Fa-f]{2})/) { ::Regexp.last_match(1).hex.chr }
|
|
42
|
+
.force_encoding(Encoding::UTF_8)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def parse_query(query)
|
|
46
|
+
query.to_s.split("&").to_h do |pair|
|
|
47
|
+
key, value = pair.split("=", 2)
|
|
48
|
+
[urldecode(key), urldecode(value)]
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Query string → PostData_. PKCS#7 always adds padding, so a string that
|
|
53
|
+
# is already a multiple of 32 bytes gets a full block of 32.
|
|
54
|
+
def encrypt(plaintext, key, iv)
|
|
55
|
+
bytes = plaintext.to_s.b
|
|
56
|
+
pad = BLOCK - (bytes.bytesize % BLOCK)
|
|
57
|
+
cipher = new_cipher(key, iv, :encrypt)
|
|
58
|
+
(cipher.update(bytes + (pad.chr * pad)) + cipher.final).unpack1("H*")
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def decrypt(hex, key, iv)
|
|
62
|
+
cipher = new_cipher(key, iv, :decrypt)
|
|
63
|
+
bytes = cipher.update([hex.to_s].pack("H*")) + cipher.final
|
|
64
|
+
pad = bytes.empty? ? 0 : bytes.getbyte(-1)
|
|
65
|
+
raise ArgumentError, "bad padding" unless pad.between?(1, BLOCK) && bytes.bytesize >= pad
|
|
66
|
+
|
|
67
|
+
bytes[0...-pad].force_encoding(Encoding::UTF_8)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# The CheckCode of an issue or query result.
|
|
71
|
+
def check_code(result, key, iv)
|
|
72
|
+
joined = CHECK_FIELDS.sort.map { |field| "#{field}=#{result[field]}" }.join("&")
|
|
73
|
+
Digest::SHA256.hexdigest("HashIV=#{iv}&#{joined}&HashKey=#{key}").upcase
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def new_cipher(key, iv, direction)
|
|
77
|
+
cipher = OpenSSL::Cipher.new("aes-256-cbc").public_send(direction)
|
|
78
|
+
cipher.key = key.to_s.b
|
|
79
|
+
cipher.iv = iv.to_s.b
|
|
80
|
+
cipher.padding = 0
|
|
81
|
+
cipher
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
module EzPay
|
|
5
|
+
# Maps ezPay's +Status+ codes onto the unified {Einvoice::Error} tree, from
|
|
6
|
+
# the code list in the manual (docs/providers/ezpay/invoice.md, section 6.4).
|
|
7
|
+
#
|
|
8
|
+
# The list has no code for an allowance on a voided invoice, for an
|
|
9
|
+
# allowance that does not exist, or for a duplicate allowance. {CONTEXT}
|
|
10
|
+
# holds our guesses for those cases, by operation, so that real codes can
|
|
11
|
+
# replace them in one place. Voiding an allowance twice has no code either.
|
|
12
|
+
# The fake assumes LIB10005, which the main table already reads as
|
|
13
|
+
# ConflictError.
|
|
14
|
+
module Errors
|
|
15
|
+
# code => [error class code, Reason or nil]
|
|
16
|
+
CODES = {
|
|
17
|
+
"KEY10002" => [:auth, Reason::CREDENTIALS_INVALID], # cannot decrypt
|
|
18
|
+
"KEY10004" => [:validation, nil], # data incomplete
|
|
19
|
+
"KEY10006" => [:auth, Reason::NOT_ENROLLED],
|
|
20
|
+
"KEY10007" => [:auth, Reason::STALE_TIMESTAMP], # open more than 30 minutes
|
|
21
|
+
"KEY10010" => [:validation, nil],
|
|
22
|
+
"KEY10011" => [:validation, nil],
|
|
23
|
+
"KEY10012" => [:provider, nil], # data transfer error
|
|
24
|
+
"KEY10013" => [:validation, nil],
|
|
25
|
+
"KEY10014" => [:network, nil], # timeout
|
|
26
|
+
"KEY10015" => [:validation, nil],
|
|
27
|
+
"INV10003" => [:validation, nil],
|
|
28
|
+
"INV10004" => [:validation, nil],
|
|
29
|
+
"INV10006" => [:validation, nil],
|
|
30
|
+
"INV10012" => [:validation, nil],
|
|
31
|
+
"INV10013" => [:validation, nil],
|
|
32
|
+
"INV10014" => [:validation, nil],
|
|
33
|
+
"INV10015" => [:validation, nil],
|
|
34
|
+
"INV10016" => [:validation, nil],
|
|
35
|
+
"INV10017" => [:validation, nil],
|
|
36
|
+
"INV10019" => [:validation, nil],
|
|
37
|
+
"INV10020" => [:auth, Reason::ACCOUNT_SUSPENDED],
|
|
38
|
+
"INV10021" => [:auth, Reason::ACCOUNT_SUSPENDED],
|
|
39
|
+
"INV20006" => [:not_found, nil],
|
|
40
|
+
"INV70001" => [:validation, nil],
|
|
41
|
+
"INV70002" => [:conflict, nil], # upload failed, cannot void
|
|
42
|
+
"INV90005" => [:auth, Reason::CONTRACT_EXPIRED],
|
|
43
|
+
"INV90006" => [:number_exhausted, nil],
|
|
44
|
+
"NOR10001" => [:network, nil],
|
|
45
|
+
"LIB10003" => [:conflict, Reason::DUPLICATE_ORDER],
|
|
46
|
+
"LIB10005" => [:conflict, Reason::ALREADY_VOIDED],
|
|
47
|
+
"LIB10007" => [:conflict, Reason::VOID_BLOCKED_BY_ALLOWANCE],
|
|
48
|
+
"LIB10008" => [:conflict, Reason::PAST_DEADLINE],
|
|
49
|
+
"LIB10009" => [:conflict, Reason::RETRY_LATER] # not uploaded yet, cannot void
|
|
50
|
+
}.freeze
|
|
51
|
+
|
|
52
|
+
# Guesses for the cases the code list does not cover. On an allowance,
|
|
53
|
+
# "already voided" means the invoice is voided, so nothing was credited.
|
|
54
|
+
# On an allowance void, IAI10002 (query failed) is the closest to "no
|
|
55
|
+
# such allowance".
|
|
56
|
+
CONTEXT = {
|
|
57
|
+
allowance: { "LIB10005" => [:conflict, Reason::ALLOWANCE_BLOCKED_BY_VOID] },
|
|
58
|
+
void_allowance: { "IAI10002" => [:not_found, nil] }
|
|
59
|
+
}.freeze
|
|
60
|
+
|
|
61
|
+
module_function
|
|
62
|
+
|
|
63
|
+
# @return [Array(Symbol, Symbol)] the error class code and the Reason
|
|
64
|
+
# (or nil). Unknown codes, and IAI10001 to IAI10006 outside the
|
|
65
|
+
# guesses above, are +:provider+.
|
|
66
|
+
def classify(code, operation = nil)
|
|
67
|
+
code = code.to_s
|
|
68
|
+
CONTEXT.fetch(operation, {})[code] || CODES[code] || [:provider, nil]
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|