einvoice 1.4.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 +12 -0
- data/.github/workflows/build.yml +7 -4
- data/CHANGELOG.md +55 -35
- data/Gemfile +3 -2
- data/README.md +230 -265
- data/README.zh-TW.md +322 -0
- data/Rakefile +2 -13
- data/bin/console +3 -6
- data/einvoice.gemspec +24 -21
- 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 -14
- 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 -10
- metadata +60 -176
- 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 -2022
- 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 -140
- data/lib/einvoice/tradevan/result.rb +0 -25
- data/lib/einvoice/tradevan/validator/issue_data_validator.rb +0 -80
- data/lib/einvoice/utils.rb +0 -13
- data/lib/faraday/response/decode_tradevan.rb +0 -38
data/README.md
CHANGED
|
@@ -1,347 +1,312 @@
|
|
|
1
1
|
# Einvoice
|
|
2
|
-
[](https://github.com/abookyun/einvoice/actions/workflows/build.yml)
|
|
3
|
-
[](https://codecov.io/github/abookyun/einvoice)
|
|
4
2
|
|
|
5
|
-
|
|
3
|
+
English | [繁體中文](README.zh-TW.md)
|
|
6
4
|
|
|
7
|
-
|
|
5
|
+
[](https://github.com/abookyun/einvoice/actions/workflows/build.yml) [](https://codecov.io/github/abookyun/einvoice)
|
|
8
6
|
|
|
9
|
-
|
|
7
|
+
A provider-agnostic **Taiwan e-invoice SDK** (財政部 MIG 4.1). The core models the five operations once: issue (開立), void (作廢), allowance (折讓), void-allowance (折讓作廢) and query (查詢). It has a unified value model and an `Einvoice::Provider` contract. Each value-added center is a thin adapter that maps the unified model to its wire format and back, so your business code does not depend on one center.
|
|
10
8
|
|
|
11
|
-
|
|
9
|
+
> **2.0 is a ground-up rewrite, and the 1.x line is now in maintenance mode.** 1.x was a single-provider (Tradevan) wire-format client with a different API. If you depend on that, pin `~> 1.4`. It continues on the [`1-x-stable`](https://github.com/abookyun/einvoice/tree/1-x-stable) branch. 2.0's unified model is not backward compatible. To move to 2.0, read [Upgrading from 1.x to 2.0](docs/upgrading-to-2.0.md).
|
|
12
10
|
|
|
13
|
-
|
|
11
|
+
## What this is
|
|
14
12
|
|
|
15
|
-
|
|
13
|
+
Every Taiwan value-added center wraps the same MOF MIG spec; only the wire format (field names, signing, envelope) differs. This SDK models the operations once and keeps each provider a thin adapter. Application code depends only on `Einvoice::Provider` and the unified types, so moving to another center starts with a new constructor. The centers still differ in what they can do. Each adapter says so through its capabilities, `query_statuses` and `UnsupportedError`, so you can check a center before you switch to it.
|
|
16
14
|
|
|
17
|
-
|
|
15
|
+
## Status
|
|
18
16
|
|
|
19
|
-
|
|
20
|
-
gem 'einvoice'
|
|
21
|
-
```
|
|
17
|
+
Under active development toward 2.0. The provider-agnostic **core** is in place: value types, the `Provider` contract, capabilities, the normalized error hierarchy, input validation, and an in-memory `MockProvider`. The first real adapter, **ECPay (綠界)**, ships with it. It has the five operations plus carrier validation, verified against ECPay's public stage API.
|
|
22
18
|
|
|
23
|
-
|
|
19
|
+
A second adapter, **Amego 光貿**, covers the five operations and is checked against Amego's public test account.
|
|
24
20
|
|
|
25
|
-
|
|
21
|
+
An **ezPay 簡單行動支付** adapter is experimental: it is built from ezPay's public manuals, and has not run against ezPay.
|
|
26
22
|
|
|
27
|
-
|
|
23
|
+
A **Tradevan 關貿 DEFAULTAPI** adapter is experimental: it is ported from the 1.x client and has not been run against the live API.
|
|
28
24
|
|
|
29
|
-
|
|
25
|
+
Other centers follow. Coverage and completeness for those will vary: their docs are less complete and they have no public sandbox, so an adapter built from docs alone carries some uncertainty until real production use confirms it.
|
|
30
26
|
|
|
31
|
-
##
|
|
27
|
+
## Installation
|
|
32
28
|
|
|
33
|
-
|
|
29
|
+
2.0 is in alpha, and its API can still change between alphas. Pin the exact version:
|
|
34
30
|
|
|
35
31
|
```ruby
|
|
36
|
-
|
|
37
|
-
config.endpoint = ENV['EINVOICE_ENDPOINT']
|
|
38
|
-
# endpoint_url will override endpoint for testing purpose
|
|
39
|
-
# config.endpoint_url = ENV['EINVOICE_ENDPOINT_URL']
|
|
40
|
-
config.client_id = ENV['EINVOICE_CLIENT_ID']
|
|
41
|
-
config.client_secret = ENV['EINVOICE_CLIENT_SECRET']
|
|
42
|
-
config.encryption_keys = ENV['ENCRYPTION_KEYS']
|
|
43
|
-
config.format = "json"
|
|
44
|
-
# config.ssl_verify = false # disable TLS certificate verification (default: true)
|
|
45
|
-
end
|
|
32
|
+
gem "einvoice", "2.0.0.alpha2"
|
|
46
33
|
```
|
|
47
|
-
### SSL certificate verification
|
|
48
34
|
|
|
49
|
-
|
|
50
|
-
endpoint (`config.ssl_verify` defaults to `true`). If you need to disable
|
|
51
|
-
this — for example when testing against an endpoint with an incomplete
|
|
52
|
-
certificate chain — you can opt out:
|
|
35
|
+
To follow the latest work, install from the `2.0.0-alpha` branch instead:
|
|
53
36
|
|
|
54
37
|
```ruby
|
|
55
|
-
|
|
38
|
+
gem "einvoice", git: "https://github.com/abookyun/einvoice", branch: "2.0.0-alpha"
|
|
56
39
|
```
|
|
57
40
|
|
|
58
|
-
|
|
41
|
+
`require "einvoice"` loads the core and `MockProvider` only. Require the provider you use, and only that one is loaded:
|
|
59
42
|
|
|
60
43
|
```ruby
|
|
61
|
-
|
|
44
|
+
require "einvoice/ecpay" # or einvoice/amego, einvoice/ezpay, einvoice/tradevan
|
|
45
|
+
require "einvoice/mof" # the 財政部 lookups, if you use them
|
|
62
46
|
```
|
|
63
47
|
|
|
64
|
-
|
|
48
|
+
## Usage
|
|
49
|
+
|
|
50
|
+
Depend on the `Einvoice::Provider` contract, not a concrete adapter. Every provider is constructed per-instance (no global configuration), so a multi-merchant app just holds one provider per set of credentials.
|
|
65
51
|
|
|
66
52
|
```ruby
|
|
67
|
-
|
|
53
|
+
# Any adapter — here the in-memory reference provider — is an Einvoice::Provider.
|
|
54
|
+
provider = Einvoice::MockProvider.new
|
|
55
|
+
|
|
56
|
+
result = provider.issue(
|
|
57
|
+
order_id: "ORDER_1",
|
|
58
|
+
buyer: { email: "buyer@example.com" }, # a ubn present ⇒ B2B (三聯式)
|
|
59
|
+
items: [
|
|
60
|
+
{ description: "咖啡拿鐵", quantity: 1, unit_price: 100, amount: 100 }
|
|
61
|
+
],
|
|
62
|
+
tax_type: "TAXABLE",
|
|
63
|
+
price_mode: "TAX_INCLUSIVE",
|
|
64
|
+
carrier: { type: "MEMBER" }
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
result.invoice_number # => "MK10000000"
|
|
68
|
+
result.status # => :issued
|
|
69
|
+
|
|
70
|
+
invoice = provider.query(invoice: result.reference)
|
|
71
|
+
invoice.status # => :issued, or nil when the provider cannot tell
|
|
72
|
+
provider.query_statuses # => [:issued, :voided, :allowance]
|
|
73
|
+
|
|
74
|
+
provider.void(invoice: result.reference, reason: "客戶取消")
|
|
68
75
|
```
|
|
69
76
|
|
|
70
|
-
|
|
77
|
+
`result.reference` is an `InvoiceReference`. It holds the facts about the invoice that providers ask for when you void, credit or query it later: the number, `invoice_datetime`, `random_code`, `order_id`, `total_amount`, `buyer_ubn`, and its `tax_type` and `tax_rate`. Store `result.reference.to_h` with your order. It holds JSON-safe values only (`invoice_datetime` is an ISO 8601 string in UTC+8), so it survives a JSON column. Pass it back as it is as `invoice:`, or pass the reference itself. A stored time has to carry its offset: `"2026-08-01 10:00"` is refused rather than read in the wrong zone, and a plain `"2026-08-01"` is that day in Taipei. A plain invoice number also works, but a provider that needs more raises `ValidationError` and names the field. To find an invoice without its number, query `invoice: { order_id: "ORDER_1" }` on a provider that declares `QUERY_BY_ORDER_ID`. `void_allowance` takes `allowance:`, an `AllowanceReference` from `AllowanceResult#reference`.
|
|
71
78
|
|
|
72
|
-
|
|
73
|
-
payload = {
|
|
74
|
-
companyUn: "12345678",
|
|
75
|
-
orgId: "ABCDE",
|
|
76
|
-
type: "I",
|
|
77
|
-
saleIdentifier: "12345678_ABCDE_53b2a44e4b3c",
|
|
78
|
-
transactionNumber: "53b2a44e4b3c",
|
|
79
|
-
transactionDate: "20160425",
|
|
80
|
-
transactionTime: "12:34:56",
|
|
81
|
-
total: "20000",
|
|
82
|
-
paperPrintMode: "0",
|
|
83
|
-
invoiceAlarmMode: "4",
|
|
84
|
-
donate: "N",
|
|
85
|
-
donationUnit: nil,
|
|
86
|
-
carrierType: "3J0002",
|
|
87
|
-
carrierId: "TP03000001234567",
|
|
88
|
-
carrierIdHidden: "TP03000001234567",
|
|
89
|
-
receiverName: "John Appleseed",
|
|
90
|
-
receiverAddrZip: "95014",
|
|
91
|
-
receiverAddrRoad: "1 Infinite Loop - Cupertino CA",
|
|
92
|
-
receiverEmail: "john@gmail.com",
|
|
93
|
-
receiverMobile: "415-284-0579",
|
|
94
|
-
memberId: nil,
|
|
95
|
-
itemList: [
|
|
96
|
-
{
|
|
97
|
-
saleIdentifier: "12345678_ABCDE_53b2a44e4b3c",
|
|
98
|
-
serialNumber: "0001",
|
|
99
|
-
productName: "Coffee Latte",
|
|
100
|
-
qty: "4000",
|
|
101
|
-
price: "5",
|
|
102
|
-
itemTotal: "20000",
|
|
103
|
-
taxType: "T",
|
|
104
|
-
tax: "952"
|
|
105
|
-
}
|
|
106
|
-
]
|
|
107
|
-
}
|
|
108
|
-
```
|
|
79
|
+
Inputs accept plain hashes (string or symbol keys). Enum fields take the canonical symbol (`:taxable`) or a wire-style string (`"TAXABLE"`). They are validated and coerced into immutable value objects before anything hits the network; a malformed request raises `Einvoice::ValidationError` locally. A value object you build with `.new` goes through the same checks.
|
|
109
80
|
|
|
110
|
-
|
|
111
|
-
result = client.issue(payload)
|
|
112
|
-
result.successful?
|
|
113
|
-
#=> true
|
|
114
|
-
result.data
|
|
115
|
-
#=>
|
|
116
|
-
# {
|
|
117
|
-
# "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
|
|
118
|
-
# "issueStatus"=>"Y",
|
|
119
|
-
# "failReason"=>"",
|
|
120
|
-
# "invoiceNumber"=>"GX38551078",
|
|
121
|
-
# "checkNumber"=>"4229",
|
|
122
|
-
# "invoiceDate"=>"20160425",
|
|
123
|
-
# "invoiceTime"=>"12:34:58",
|
|
124
|
-
# "texclusiveAmount"=>"19048",
|
|
125
|
-
# "oexclusiveAmount"=>"0",
|
|
126
|
-
# "zexclusiveAmount"=>"0",
|
|
127
|
-
# "tax"=>"952",
|
|
128
|
-
# "inclusiveAmount"=>"20000",
|
|
129
|
-
# "mainRemark"=>"",
|
|
130
|
-
# "invoiceType"=>"",
|
|
131
|
-
# "invoiceStatus"=>"V",
|
|
132
|
-
# "allowanceNumber"=>"",
|
|
133
|
-
# "allowanceDate"=>"",
|
|
134
|
-
# "allowanceExclusiveAmount"=>"",
|
|
135
|
-
# "allowanceTax"=>"",
|
|
136
|
-
# "allowanceTotalAmount"=>"0",
|
|
137
|
-
# "allowanceStatus"=>""
|
|
138
|
-
# }
|
|
139
|
-
```
|
|
81
|
+
The checks:
|
|
140
82
|
|
|
141
|
-
|
|
83
|
+
- A buyer `ubn` is 8 digits, a company's 統一編號. (MIG 表 4-7 allows a BAN of 8 to 10 digits; the 9- and 10-digit forms are not used for a buyer.) A B2B invoice needs one, and an explicit `category` has to agree with it.
|
|
84
|
+
- Totals are whole numbers and not negative. Item quantity, price and amount are numbers with at most 7 decimal places. An invoice item may be negative, as a discount line. An allowance item may not (MIG 4.1).
|
|
85
|
+
- A mobile barcode is `/` and 7 characters. A citizen certificate is 2 letters and 14 digits. These formats come from the providers' docs; the MIG lists the carrier types only. A 愛心碼 is 3 to 7 digits.
|
|
86
|
+
- `tax_rate` is a decimal, such as `0.05`, and has to be a MIG rate. On an issue the lines decide its default, not the header: `0.05` when a line is taxable, else `0`. A special-tax line needs it. A taxable line cannot have rate `0`.
|
|
87
|
+
- A zero-rated invoice needs `customs_clearance_mark`, `"1"` or `"2"` (MIG CustomsClearanceMark). `zero_tax_rate_reason` is `"71"` to `"79"` (MIG ZeroTaxRateReason). The MIG requires it on a zero-rated invoice too, but ECPay can take it from its back office, so the core does not ask for it. Amego does.
|
|
88
|
+
- The amounts agree with the items (below).
|
|
89
|
+
- The MIG field lengths: `remark` 200, buyer `name` 60, `address` 100, `email` 400, `phone` 26, carrier `code` 400, item `description` 500, `unit` 6 and `remark` 120. A consumer's name must not be `0` to `0000`, and a carrier code must not start or end with a space. A provider with a shorter limit of its own raises `UnsupportedError`.
|
|
90
|
+
- A void reason is at most 20 characters. A void allowance reason defaults to `作廢折讓`.
|
|
142
91
|
|
|
143
|
-
|
|
144
|
-
payload = {
|
|
145
|
-
type: "I",
|
|
146
|
-
saleIdentifier: "12345678_ABCDE_53b2a44e4b3c",
|
|
147
|
-
invoiceNumber: "GX38551078",
|
|
148
|
-
invoicePaperReturned: "Y",
|
|
149
|
-
}
|
|
150
|
-
```
|
|
92
|
+
### Amounts and tax
|
|
151
93
|
|
|
152
|
-
|
|
153
|
-
result = client.cancel(payload)
|
|
154
|
-
result.successful?
|
|
155
|
-
#=> true
|
|
156
|
-
result.data
|
|
157
|
-
#=>
|
|
158
|
-
# {
|
|
159
|
-
# "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
|
|
160
|
-
# "voidStatus"=>"Y",
|
|
161
|
-
# "failReason"=>"",
|
|
162
|
-
# "type"=>"I",
|
|
163
|
-
# "invoiceNumber"=>"GX38551078",
|
|
164
|
-
# "allowanceNumber"=>""
|
|
165
|
-
# }
|
|
166
|
-
```
|
|
94
|
+
The core computes the tax from the items. `price_mode` says if the item amounts include tax, `tax_type` is the type of the whole invoice (an item can have its own), and `tax_rate` is the rate. The result is `input.tax_breakdown`: the net amount, tax and gross amount of each line, and the MIG totals. Adapters read it and do not compute tax themselves. The core never changes your items.
|
|
167
95
|
|
|
168
|
-
|
|
96
|
+
`amount` is optional. Leave it out, and the core fills it from the breakdown. Give it, and it is checked against the breakdown, so your own totals cannot drift from the items. An invoice follows F0401: for a consumer the tax is inside `sales_amount` and `tax_amount` is `0`. For a business buyer `tax_amount` is `round(taxable sales × tax_rate)`:
|
|
169
97
|
|
|
170
98
|
```ruby
|
|
171
|
-
|
|
172
|
-
companyUn: "12345678",
|
|
173
|
-
invoiceStartDate: "20160401",
|
|
174
|
-
invoiceEndDate: "20160425",
|
|
175
|
-
carrierId: "TP03000001234567",
|
|
176
|
-
memberId: "",
|
|
177
|
-
sellTargetCode: "",
|
|
178
|
-
}
|
|
99
|
+
amount: { sales_amount: 95, tax_amount: 5, total_amount: 100 } # 100 with tax, to a business
|
|
179
100
|
```
|
|
180
101
|
|
|
102
|
+
An allowance follows G0401: `sales_amount` excludes tax, for a consumer too. It takes `tax_type` and `tax_rate` from the invoice reference, so pass `issued.reference`, or give them yourself. There is no default, so a zero-rated invoice is never credited with 5% tax. When the invoice has mixed tax, give every item its `tax_type`.
|
|
103
|
+
|
|
181
104
|
```ruby
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
# [
|
|
188
|
-
# {
|
|
189
|
-
# "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
|
|
190
|
-
# "invoiceNumber"=>"GX38551078",
|
|
191
|
-
# "checkNumber"=>"4229",
|
|
192
|
-
# "invoiceDate"=>"20160425",
|
|
193
|
-
# "invoiceTime"=>"12:34:58",
|
|
194
|
-
# "exclusiveAmount"=>"19048",
|
|
195
|
-
# "tax"=>"952",
|
|
196
|
-
# "total"=>"20000",
|
|
197
|
-
# "status"=>"V",
|
|
198
|
-
# "hasAllowance"=>"N",
|
|
199
|
-
# "sellerName"=>"Starbucks",
|
|
200
|
-
# "sellerUN"=>"12345678",
|
|
201
|
-
# "sellerAddr"=>"1 Infinite Loop - Cupertino CA",
|
|
202
|
-
# "sellerTel"=>"415-284-0579",
|
|
203
|
-
# "receiverName"=>"John Appleseed",
|
|
204
|
-
# "receiverAddr"=>"1 Infinite Loop - Cupertino CA",
|
|
205
|
-
# "paper"=>"N",
|
|
206
|
-
# "win"=>"N",
|
|
207
|
-
# "donate"=>"N",
|
|
208
|
-
# "carrierType"=>"CQ0001",
|
|
209
|
-
# "carrierId"=>"TP03000001234567"
|
|
210
|
-
# }
|
|
211
|
-
# ]
|
|
105
|
+
provider.allowance(
|
|
106
|
+
invoice: issued.reference, allowance_id: "AL_1", price_mode: "TAX_INCLUSIVE",
|
|
107
|
+
items: [{ description: "退貨", quantity: 1, unit_price: 100, amount: 100 }],
|
|
108
|
+
amount: { sales_amount: 95, tax_amount: 5, total_amount: 100 }
|
|
109
|
+
)
|
|
212
110
|
```
|
|
213
111
|
|
|
214
|
-
###
|
|
112
|
+
### Errors
|
|
113
|
+
|
|
114
|
+
Every failure is an `Einvoice::Error` subclass carrying a stable `#code`, the provider's `#raw_code` / `#raw_message`, and an optional action-oriented `#reason`. `#group` tells which side failed: `:invoice` (the request breaks a rule of the MOF, or the invoice is not in the state it needs) or `:provider` (the account, the connection, or the provider's own service). Rescue precisely or broadly:
|
|
215
115
|
|
|
216
116
|
```ruby
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
#
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
# "invoiceTime"=>"12:34:58",
|
|
228
|
-
# "exclusiveAmount"=>"19048",
|
|
229
|
-
# "tax"=>"952",
|
|
230
|
-
# "total"=>"20000",
|
|
231
|
-
# "status"=>"I",
|
|
232
|
-
# "hasAllowance"=>"N",
|
|
233
|
-
# "sellerName"=>"Starbucks",
|
|
234
|
-
# "sellerUN"=>"12345678",
|
|
235
|
-
# "sellerAddr"=>"1 Infinite Loop - Cupertino CA",
|
|
236
|
-
# "sellerTel"=>"415-284-0579",
|
|
237
|
-
# "receiverName"=>"John Appleseed",
|
|
238
|
-
# "receiverAddr"=>"1 Infinite Loop - Cupertino CA",
|
|
239
|
-
# "receiverPhone"=>"415-284-0579",
|
|
240
|
-
# "paper"=>"Y",
|
|
241
|
-
# "win"=>"N",
|
|
242
|
-
# "donate"=>"N",
|
|
243
|
-
# "carrierType"=>"CQ0001",
|
|
244
|
-
# "detailList"=>[
|
|
245
|
-
# {
|
|
246
|
-
# "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
|
|
247
|
-
# "serialNumber"=>"0001",
|
|
248
|
-
# "productName"=>"Coffee Latte",
|
|
249
|
-
# "qty"=>"4000",
|
|
250
|
-
# "price"=>"5",
|
|
251
|
-
# "total"=>"20000",
|
|
252
|
-
# "taxType"=>"T"
|
|
253
|
-
# }
|
|
254
|
-
# ]
|
|
255
|
-
# }
|
|
117
|
+
begin
|
|
118
|
+
provider.void(invoice: invoice.reference, reason: "customer cancelled")
|
|
119
|
+
rescue Einvoice::ConflictError => e
|
|
120
|
+
# Only :already_voided means that the invoice is voided. Another reason,
|
|
121
|
+
# such as :void_blocked_by_allowance, means that it is not.
|
|
122
|
+
raise unless e.reason == :already_voided
|
|
123
|
+
rescue Einvoice::Error => e
|
|
124
|
+
e.code # => :network, :auth, :not_found, …
|
|
125
|
+
raise
|
|
126
|
+
end
|
|
256
127
|
```
|
|
257
128
|
|
|
258
|
-
|
|
129
|
+
The class tells you what to do next, the same way at every provider:
|
|
130
|
+
|
|
131
|
+
- `ValidationError`: the input breaks a MIG rule, so no provider takes it. Fix the input.
|
|
132
|
+
- `UnsupportedError`: this provider does not take the input, or lacks the feature. Another provider may take it.
|
|
133
|
+
- `NetworkError`: the request may not have reached the provider. Retry it. After a timeout on `issue`, the invoice may exist anyway. Retry with the same `order_id`: a `ConflictError` with `reason: :duplicate_order` tells you that it does.
|
|
134
|
+
- After a timeout on `allowance`, a retry can credit twice, so check first. Amego takes your `allowance_id` and refuses a second one with `reason: :duplicate_allowance`. ECPay and ezPay assign the allowance number themselves, so the adapter cannot find an allowance that went through. Check the provider's back office before you retry. Tradevan takes `allowance_id` too, but nobody has checked whether it refuses a repeat.
|
|
135
|
+
- After a timeout on `void` or `void_allowance`, a retry is safe, because nothing can be voided twice. A `ConflictError` with `reason: :already_voided` means that the first one went through.
|
|
136
|
+
- `reason: :rate_limited`, on any class: the provider asks you to slow down. Retry later.
|
|
137
|
+
- `ConflictError` with `reason: :retry_later`: the provider is still working on the invoice. Try again later.
|
|
138
|
+
|
|
139
|
+
### Credentials and buyer data
|
|
140
|
+
|
|
141
|
+
- `inspect`, `to_s` and `pp` show results with `raw=[FILTERED]`, because `raw` is the provider's response and holds the buyer's data. Read `#raw` directly when you need it. A `Buyer` shows its name, email, address and phone as `[FILTERED]` too, inside every input and result; its `ubn` stays. An adapter's client shows its keys as `[FILTERED]`.
|
|
142
|
+
- `base_url` has to use https. Only localhost may use http, for tests. It must not carry a user, a password, a query or a fragment.
|
|
143
|
+
|
|
144
|
+
### Capabilities
|
|
145
|
+
|
|
146
|
+
A provider declares what it supports; feature-detect instead of discovering a gap when a request fails.
|
|
259
147
|
|
|
260
148
|
```ruby
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
invoiceStartYM: "201604",
|
|
265
|
-
invoiceEndYM: "201604",
|
|
266
|
-
receiverEmail: "john@gmail.com",
|
|
267
|
-
receiverMobile: "",
|
|
268
|
-
}
|
|
149
|
+
provider.supports?(Einvoice::Capability::FOREIGN_CURRENCY) # => true / false
|
|
150
|
+
provider.assert_supports!(Einvoice::Capability::B2B) # raises UnsupportedError if absent
|
|
151
|
+
provider.query_statuses # => the statuses that query can return
|
|
269
152
|
```
|
|
270
153
|
|
|
154
|
+
## Providers
|
|
155
|
+
|
|
156
|
+
### ECPay 綠界
|
|
157
|
+
|
|
271
158
|
```ruby
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
159
|
+
require "einvoice/ecpay"
|
|
160
|
+
|
|
161
|
+
provider = Einvoice::ECPay::Provider.new(
|
|
162
|
+
merchant_id: "2000132",
|
|
163
|
+
hash_key: "...", # 16 bytes, server-side only
|
|
164
|
+
hash_iv: "...", # 16 bytes, server-side only
|
|
165
|
+
mode: :production # :test (default) targets the stage host
|
|
166
|
+
)
|
|
276
167
|
```
|
|
277
168
|
|
|
278
|
-
|
|
169
|
+
Everything above works unchanged. `issue` / `void` / `allowance` / `void_allowance` / `query` take the same unified input and return the same value types. The AES-128-CBC envelope, ECPay's two layers of result codes, and its field rules stay inside the adapter.
|
|
170
|
+
|
|
171
|
+
To try it without an account, use ECPay's published sandbox credentials (shared with every other developer, never for anything real):
|
|
279
172
|
|
|
280
173
|
```ruby
|
|
281
|
-
|
|
282
|
-
companyUn: "12345678",
|
|
283
|
-
orgId: "ABCDE",
|
|
284
|
-
uniFiedNumber: "12345678",
|
|
285
|
-
bookType: "API",
|
|
286
|
-
period: "201604",
|
|
287
|
-
}
|
|
174
|
+
provider = Einvoice::ECPay::Provider.new(**Einvoice::ECPay::SANDBOX)
|
|
288
175
|
```
|
|
289
176
|
|
|
177
|
+
A few things worth knowing:
|
|
178
|
+
|
|
179
|
+
- **Paper vs. electronic is derived.** An invoice with a carrier or a donation is electronic (`Print=0`); anything else prints, and ECPay then requires a buyer name, an address, and an email or a phone.
|
|
180
|
+
- **Mixed tax rates are derived too.** Items that disagree on `tax_type` produce a 混合稅率 (TaxType 9) invoice; you don't ask for it explicitly.
|
|
181
|
+
- **Void, allowance and a query by number need the invoice's issue date.** It comes from `invoice.invoice_datetime`. If the reference has an `order_id` instead, a query goes by order id, and a void or an allowance looks the date up first. A failed lookup raises `ProviderError` with `reason: :lookup_failed`. A plain number is not enough.
|
|
182
|
+
- **Void allowance needs the invoice number**, so pass the `AllowanceReference`, not only the allowance number.
|
|
183
|
+
- **No foreign currency.** ECPay's B2C API has no such field, so a non-TWD `currency` raises `UnsupportedError` rather than being filed as TWD.
|
|
184
|
+
- **A taxable invoice is 5%.** ECPay fixes the rate by tax type, so another `tax_rate` raises `UnsupportedError`.
|
|
185
|
+
- **Carrier validation**: `validate_carrier({ type: "MOBILE_BARCODE", code: "/ABC1234" })` (the `Provider` method behind `CARRIER_VALIDATION`; ECPay can check a mobile barcode only), `validate_love_code("168001")`, `love_code_organ_name("168001")`. These ask ECPay, so they need this adapter and its credentials. For 愛心碼 there is also `Einvoice::MOF::DonationCodes` (below), which asks 財政部 directly and needs neither.
|
|
186
|
+
- **Anything else**: ECPay has ~25 further B2C endpoints (延遲開立, 字軌設定, 列印, 通知 …). Reach them through `provider.raw(path, payload)`, which applies the envelope, encryption and error mapping for you.
|
|
187
|
+
|
|
188
|
+
### Amego 光貿
|
|
189
|
+
|
|
290
190
|
```ruby
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
# {
|
|
298
|
-
# "unifiedNumber"=>"12345678",
|
|
299
|
-
# "bookNumber"=>"API_M1",
|
|
300
|
-
# "bookType"=>"API",
|
|
301
|
-
# "period"=>"201604",
|
|
302
|
-
# "duration"=>"201604",
|
|
303
|
-
# "mark"=>"GX",
|
|
304
|
-
# "start"=>"38551050",
|
|
305
|
-
# "end"=>"38551249"
|
|
306
|
-
# }
|
|
307
|
-
# ]
|
|
191
|
+
require "einvoice/amego"
|
|
192
|
+
|
|
193
|
+
provider = Einvoice::Amego::Provider.new(
|
|
194
|
+
ban: "12345678", # the seller's 統一編號
|
|
195
|
+
app_key: "..." # from Amego support, server-side only
|
|
196
|
+
)
|
|
308
197
|
```
|
|
309
198
|
|
|
310
|
-
|
|
199
|
+
To try it without an account, use Amego's published test account (shared with every other developer, never for anything real): `Einvoice::Amego::Provider.new(**Einvoice::Amego::SANDBOX)`. Amego has one host for test and production. The account decides which one you use.
|
|
200
|
+
|
|
201
|
+
- **Amego picks the invoice number** (自動配號).
|
|
202
|
+
- **A void is queued.** Amego accepts it at once, but a query right after it can still report the invoice as issued.
|
|
203
|
+
- **An allowance needs the original invoice's buyer and date.** The reference has the date and the 統一編號, but not the buyer's name, so the adapter queries the invoice for it. Pass `provider_options: { buyer_name: }` to skip the query, for example for an invoice older than 180 days. The allowance date is today (Asia/Taipei).
|
|
204
|
+
- **The allowance number is yours.** `allowance_id` is sent as Amego's `AllowanceNumber` (max 16, unique in the account).
|
|
205
|
+
- **Mixed tax rates are derived** from the items, as with ECPay.
|
|
206
|
+
- **Not supported**: special tax rates and foreign currency. `tax_rate` must be 0 or 0.05.
|
|
207
|
+
- **Carrier validation**: `validate_carrier({ type: "MOBILE_BARCODE", code: "/ABC1234" })` asks Amego whether a mobile barcode is registered. Amego can check a mobile barcode only. For 愛心碼, use `Einvoice::MOF::DonationCodes` (below).
|
|
208
|
+
- **Anything else**: reach the other endpoints through `provider.raw(path, payload)`. Section 3 of the note lists them.
|
|
209
|
+
- The details and the open questions are in [`docs/providers/amego/api.md`](docs/providers/amego/api.md).
|
|
210
|
+
|
|
211
|
+
### ezPay 簡單行動支付 (experimental)
|
|
311
212
|
|
|
312
213
|
```ruby
|
|
313
|
-
|
|
214
|
+
require "einvoice/ezpay"
|
|
215
|
+
|
|
216
|
+
provider = Einvoice::EzPay::Provider.new(
|
|
217
|
+
merchant_id: "...", # 商店代號
|
|
218
|
+
hash_key: "...", hash_iv: "...", # 32 and 16 bytes, server-side only
|
|
219
|
+
mode: :test # or :production
|
|
220
|
+
)
|
|
314
221
|
```
|
|
315
222
|
|
|
316
|
-
|
|
223
|
+
- **Experimental.** ezPay has no shared test account, and nobody has run this adapter against ezPay. Its encryption and `CheckCode` match the samples in ezPay's manual byte for byte. Test it against your own test shop before you rely on it.
|
|
224
|
+
- **A query needs the random code.** The reference from `issue` or `query` has it.
|
|
225
|
+
- **An allowance needs the invoice's order id.** The reference has it. Without it, the adapter queries the invoice by number first. ezPay assigns the allowance number, so `allowance_id` is not sent. The allowance date is today (Asia/Taipei).
|
|
226
|
+
- **A query cannot tell an allowance.** ezPay only says if an invoice is voided. An invoice that is not voided reads back with status `nil`. `query_statuses` is `[:voided]`.
|
|
227
|
+
- **A void waits for the upload.** ezPay uploads the day's invoices the next morning, and refuses a void before that.
|
|
228
|
+
- **Prices follow the category.** ezPay wants B2C prices with tax and B2B prices without. The adapter takes them from the core's breakdown, so any `price_mode` works. Item counts and unit prices must be whole numbers.
|
|
229
|
+
- **Not supported**: query by order id, special tax rates, foreign currency, mixed tax on a B2B invoice, and the carrier check APIs. `tax_rate` must be 0 or 0.05.
|
|
230
|
+
- **Anything else**: `provider.raw(path, version, fields)`, for example `provider.raw("/Api/invoice_touch_issue", "1.0", { ... })`.
|
|
231
|
+
- The details and the open questions are in [`docs/providers/ezpay/invoice.md`](docs/providers/ezpay/invoice.md).
|
|
232
|
+
|
|
233
|
+
### Tradevan 關貿 (DEFAULTAPI, experimental)
|
|
317
234
|
|
|
318
235
|
```ruby
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
236
|
+
require "einvoice/tradevan"
|
|
237
|
+
|
|
238
|
+
provider = Einvoice::Tradevan::DefaultAPI::Provider.new(
|
|
239
|
+
acnt: "...", acntp: "...",
|
|
240
|
+
key1: "...", key2: "...", # 16 bytes each, server-side only
|
|
241
|
+
base_url: "https://...", # your Tradevan host; there is no default
|
|
242
|
+
company_un: "12345678", org_id: "ABCDE",
|
|
243
|
+
paper_print_mode: "0", invoice_alarm_mode: "4",
|
|
244
|
+
invoice_paper_returned: "N", allowance_paper_returned: "N",
|
|
245
|
+
member_carrier_type: "1K0001" # only needed for MEMBER carriers
|
|
246
|
+
)
|
|
325
247
|
```
|
|
326
248
|
|
|
249
|
+
- **Experimental.** This adapter is ported from the 1.x client, its validators and its README examples. Tradevan does not publish its API docs, and nobody has run this adapter against the live API. Test it against your own account before you rely on it. The 1.x client stays on `1-x-stable`.
|
|
250
|
+
- **Void and allowance need the original `saleIdentifier`.** DEFAULTAPI identifies an invoice by it. The adapter takes it from `provider_options: { sale_identifier: }` (use this for an invoice that the 1.x client issued), else builds it from the reference's order id, else queries the invoice by number. An allowance also needs the invoice date, from the reference or the same query. The reference from `issue` has all of these.
|
|
251
|
+
- **An allowance needs the tax type and rate** before any lookup. They come from the reference of `issue` or `query`. With only an invoice number, pass `tax_type:` and, for taxable items, `tax_rate:` in the allowance input.
|
|
252
|
+
- **Query status is often `nil`.** The meaning of DEFAULTAPI's status codes is unknown, so the adapter does not guess. `status` is `:allowance` when the invoice has an allowance, and `nil` otherwise. `query_statuses` is `[:allowance]`. The raw code is in `result.raw["status"]`.
|
|
253
|
+
- **Prices include tax on the wire.** The adapter takes them from the core's breakdown, so any `price_mode` works. A taxable `tax_rate` must be 0.05. When the allowance response has no date, the allowance date is today (Asia/Taipei).
|
|
254
|
+
- **Not supported**: query by order id, mixed tax, the special tax rate, and foreign currency.
|
|
255
|
+
- **Anything else**: reach the other DEFAULTAPI endpoints through `provider.raw(path, params)`, for example `provider.raw("get/getInvoiceMarkInfo", { ... })`.
|
|
256
|
+
- The details and the open questions are in [`docs/providers/tradevan/defaultapi.md`](docs/providers/tradevan/defaultapi.md).
|
|
257
|
+
|
|
258
|
+
## 財政部 lookups
|
|
259
|
+
|
|
260
|
+
Provider-independent clients for 財政部's own public services. They issue nothing and hold no credentials, so they work whichever center you use, or before you have picked one.
|
|
261
|
+
|
|
327
262
|
```ruby
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
263
|
+
require "einvoice/mof"
|
|
264
|
+
|
|
265
|
+
codes = Einvoice::MOF::DonationCodes.new
|
|
266
|
+
|
|
267
|
+
codes.lookup("2718")
|
|
268
|
+
# => #<data Einvoice::MOF::DonationCode code="2718",
|
|
269
|
+
# name="社團法人台北市喜願協會", short_name="喜願協會",
|
|
270
|
+
# ubn="92000392", city="臺北市">
|
|
271
|
+
|
|
272
|
+
codes.exist?("105") # => false — well-formed, not registered
|
|
273
|
+
codes.for_ubn("92000392") # => every 愛心碼 that organisation holds
|
|
274
|
+
codes.all # => the whole dataset (~2,000, five requests)
|
|
333
275
|
```
|
|
334
276
|
|
|
277
|
+
This is **not** wired into `Input`, and deliberately so: validation there is local and synchronous, and issuing an invoice must never depend on a third party being reachable. `Input` checks the shape of a 愛心碼; whether it is *registered* is a question you ask when it suits you: at order time, or once at boot via `#all` to build your own set for offline checks.
|
|
278
|
+
|
|
279
|
+
The dataset needs no credentials today. Its published OpenAPI declares `api_key` and `oauth2` schemes even so, so a 401/403 raises `Einvoice::AuthError` saying exactly that rather than surfacing as a parse failure.
|
|
280
|
+
|
|
335
281
|
## Development
|
|
336
282
|
|
|
337
|
-
|
|
283
|
+
```bash
|
|
284
|
+
bin/setup # install dependencies
|
|
285
|
+
bundle exec rspec # run the specs
|
|
286
|
+
bundle exec rake # default task: rspec
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
The shared examples in `spec/support/shared_examples/` are the executable contract. Every adapter runs `"an invoice provider"`, and every adapter's client runs `"a provider client"`, so a new adapter proves that it honours the unified model by including them. A new adapter also gets its own entry file, `lib/einvoice/<name>.rb`, that requires `einvoice`. `lib/einvoice.rb` does not load it, and `spec/spec_helper.rb` does.
|
|
290
|
+
|
|
291
|
+
To write a new adapter, start with the provider notes in [`docs/providers/`](docs/providers/README.md). Read them in this order: the MOF MIG note (the standard every provider follows), then the ECPay note (the first adapter, to see how a note maps to code), then the note for your provider, and then the shared examples above.
|
|
338
292
|
|
|
339
|
-
|
|
293
|
+
The ECPay adapter is tested in three layers, two of which run offline in CI:
|
|
340
294
|
|
|
341
|
-
|
|
295
|
+
1. **The contract, against a wire-format fake.** The shared examples run through an in-process fake that speaks the real protocol: the AES envelope, PHP url-encoding and ECPay's own RtnCodes. So a request only passes if the encryption and field mapping are genuinely correct. It is stateful, which is what lets the contract drive issue → allowance → void as a sequence.
|
|
296
|
+
2. **Recorded real responses (VCR).** `spec/einvoice/ecpay/recorded_spec.rb` replays cassettes captured from ECPay's stage host, so the field names, value types and error codes under test are ECPay's own rather than our reading of the docs. Re-record with `VCR_RECORD=1` after bumping the epoch in that spec. Cassettes only ever hold sandbox traffic.
|
|
297
|
+
3. **The live API, opt-in.** What keeps the other two honest:
|
|
342
298
|
|
|
343
|
-
|
|
299
|
+
```bash
|
|
300
|
+
ECPAY_LIVE=1 bundle exec rspec spec/einvoice/ecpay/live_spec.rb
|
|
301
|
+
```
|
|
344
302
|
|
|
303
|
+
It defaults to the public sandbox credentials, so no setup is needed; override with `ECPAY_MERCHANT_ID` / `ECPAY_HASH_KEY` / `ECPAY_HASH_IV` to point it at your own stage account. Excluded from CI because it needs the network and a shared sandbox.
|
|
304
|
+
|
|
305
|
+
Amego has a live spec too. It runs against Amego's public test account:
|
|
306
|
+
|
|
307
|
+
```bash
|
|
308
|
+
AMEGO_LIVE=1 bundle exec rspec spec/einvoice/amego/live_spec.rb
|
|
309
|
+
```
|
|
345
310
|
|
|
346
311
|
## License
|
|
347
312
|
|