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.
Files changed (66) hide show
  1. checksums.yaml +4 -4
  2. data/.coderabbit.yaml +6 -8
  3. data/.github/workflows/build.yml +6 -3
  4. data/CHANGELOG.md +43 -44
  5. data/Gemfile +3 -10
  6. data/README.md +221 -328
  7. data/README.zh-TW.md +322 -0
  8. data/Rakefile +2 -51
  9. data/bin/console +3 -6
  10. data/einvoice.gemspec +16 -18
  11. data/lib/einvoice/amego/client.rb +116 -0
  12. data/lib/einvoice/amego/errors.rb +84 -0
  13. data/lib/einvoice/amego/payload.rb +276 -0
  14. data/lib/einvoice/amego/provider.rb +267 -0
  15. data/lib/einvoice/amego.rb +27 -0
  16. data/lib/einvoice/capability.rb +79 -0
  17. data/lib/einvoice/ecpay/client.rb +183 -0
  18. data/lib/einvoice/ecpay/crypto.rb +85 -0
  19. data/lib/einvoice/ecpay/errors.rb +115 -0
  20. data/lib/einvoice/ecpay/payload.rb +241 -0
  21. data/lib/einvoice/ecpay/provider.rb +362 -0
  22. data/lib/einvoice/ecpay.rb +31 -0
  23. data/lib/einvoice/error.rb +220 -0
  24. data/lib/einvoice/ezpay/client.rb +130 -0
  25. data/lib/einvoice/ezpay/crypto.rb +85 -0
  26. data/lib/einvoice/ezpay/errors.rb +72 -0
  27. data/lib/einvoice/ezpay/payload.rb +269 -0
  28. data/lib/einvoice/ezpay/provider.rb +235 -0
  29. data/lib/einvoice/ezpay.rb +19 -0
  30. data/lib/einvoice/input.rb +494 -0
  31. data/lib/einvoice/mock_provider.rb +191 -0
  32. data/lib/einvoice/mof/donation_codes.rb +157 -0
  33. data/lib/einvoice/mof.rb +16 -0
  34. data/lib/einvoice/number.rb +51 -0
  35. data/lib/einvoice/provider.rb +57 -13
  36. data/lib/einvoice/redaction.rb +54 -0
  37. data/lib/einvoice/taipei.rb +89 -0
  38. data/lib/einvoice/tax_split.rb +124 -0
  39. data/lib/einvoice/tradevan/default_api/client.rb +175 -0
  40. data/lib/einvoice/tradevan/default_api/crypto.rb +90 -0
  41. data/lib/einvoice/tradevan/default_api/errors.rb +54 -0
  42. data/lib/einvoice/tradevan/default_api/payload.rb +259 -0
  43. data/lib/einvoice/tradevan/default_api/provider.rb +366 -0
  44. data/lib/einvoice/tradevan/default_api/rules.rb +314 -0
  45. data/lib/einvoice/tradevan.rb +25 -0
  46. data/lib/einvoice/types.rb +323 -0
  47. data/lib/einvoice/version.rb +3 -1
  48. data/lib/einvoice.rb +21 -9
  49. metadata +52 -145
  50. data/.github/workflows/cron.yml +0 -31
  51. data/docs/Tradevan E-Invoice APIs.md +0 -201
  52. data/docs/neweb.md +0 -347
  53. data/lib/einvoice/client.rb +0 -21
  54. data/lib/einvoice/configuration.rb +0 -49
  55. data/lib/einvoice/connection.rb +0 -31
  56. data/lib/einvoice/donation_unit_list.json +0 -2025
  57. data/lib/einvoice/result.rb +0 -21
  58. data/lib/einvoice/tradevan/model/base.rb +0 -34
  59. data/lib/einvoice/tradevan/model/issue_data.rb +0 -129
  60. data/lib/einvoice/tradevan/model/issue_item.rb +0 -41
  61. data/lib/einvoice/tradevan/model/void_data.rb +0 -35
  62. data/lib/einvoice/tradevan/provider.rb +0 -139
  63. data/lib/einvoice/tradevan/result.rb +0 -25
  64. data/lib/einvoice/tradevan/validator/issue_data_validator.rb +0 -80
  65. data/lib/faraday/response/decode_tradevan.rb +0 -37
  66. data/lib/faraday/response/parse_xml.rb +0 -14
data/README.md CHANGED
@@ -1,419 +1,312 @@
1
1
  # Einvoice
2
- [![Build Status](https://github.com/abookyun/einvoice/actions/workflows/build.yml/badge.svg)](https://github.com/abookyun/einvoice/actions/workflows/build.yml)
3
- [![codecov](https://codecov.io/github/abookyun/einvoice/graph/badge.svg?token=yxJNmXiUyp)](https://codecov.io/github/abookyun/einvoice)
4
2
 
5
- > **The 1.x line is moving to maintenance mode.** A provider-agnostic 2.0
6
- > rewrite is in progress on `main`; once it lands, 1.x continues on the
7
- > [`1-x-stable`](https://github.com/abookyun/einvoice/tree/1-x-stable) branch.
8
- > If you depend on the current Tradevan client, pin `~> 1.4`.
3
+ English | [繁體中文](README.zh-TW.md)
9
4
 
10
- ## What's E-Invoice
5
+ [![Build Status](https://github.com/abookyun/einvoice/actions/workflows/build.yml/badge.svg)](https://github.com/abookyun/einvoice/actions/workflows/build.yml) [![codecov](https://codecov.io/github/abookyun/einvoice/graph/badge.svg?token=yxJNmXiUyp)](https://codecov.io/github/abookyun/einvoice)
11
6
 
12
- To support the thriving e-commerce industry and lower the business costs and barriers associated with printing paper receipts, the Taiwan Executive Yuan announced plans in August 2000 to implement electronic receipts in Taiwan and launched a comprehensive project in May 2010 to promote e-invoice applications. This initiative employs innovative approaches such as allowing consumers to claim virtual receipts via multiple devices, offering automatic checking of receipt lottery numbers, and providing a variety of channels for retailers to issue receipts.
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.
13
8
 
14
- Hence, there are several e-invoice services for B2B, B2C in Taiwan as the intermediate and value-adding platform like [CHT](https://invoice.cht.com.tw/invoice/login.jsp), [allPay](https://www.allpay.com.tw/Business/invoice), [Tradevan](http://www.tradevan.com.tw/services/index.do?act=services_info&type=16), Neweb, ..[etc](https://www.einvoice.nat.gov.tw/index!showAddCenter?linkIsNew=Y&CSRT=3716270004994188830).
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).
15
10
 
16
- ## Supported E-Invoice Providers
11
+ ## What this is
17
12
 
18
- * Tradevan
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.
19
14
 
20
- ## Installation
21
-
22
- Add this line to your application's Gemfile:
15
+ ## Status
23
16
 
24
- ```ruby
25
- gem 'einvoice'
26
- ```
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.
27
18
 
28
- And then execute:
19
+ A second adapter, **Amego 光貿**, covers the five operations and is checked against Amego's public test account.
29
20
 
30
- $ bundle
21
+ An **ezPay 簡單行動支付** adapter is experimental: it is built from ezPay's public manuals, and has not run against ezPay.
31
22
 
32
- Or install it yourself as:
23
+ A **Tradevan 關貿 DEFAULTAPI** adapter is experimental: it is ported from the 1.x client and has not been run against the live API.
33
24
 
34
- $ gem install einvoice
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.
35
26
 
36
- ## Usage
27
+ ## Installation
37
28
 
38
- ### Configure
29
+ 2.0 is in alpha, and its API can still change between alphas. Pin the exact version:
39
30
 
40
31
  ```ruby
41
- Einvoice.configure do |config|
42
- config.endpoint = ENV['EINVOICE_ENDPOINT']
43
- # endpoint_url will override endpoint for testing purpose
44
- # config.endpoint_url = ENV['EINVOICE_ENDPOINT_URL']
45
- config.client_id = ENV['EINVOICE_CLIENT_ID']
46
- config.client_secret = ENV['EINVOICE_CLIENT_SECRET']
47
- config.encryption_keys = ENV['ENCRYPTION_KEYS']
48
- config.format = "json"
49
- # config.ssl_verify = false # disable TLS certificate verification (default: true)
50
- end
32
+ gem "einvoice", "2.0.0.alpha2"
51
33
  ```
52
- ### SSL certificate verification
53
34
 
54
- By default, `einvoice` verifies the TLS certificate of the configured
55
- endpoint (`config.ssl_verify` defaults to `true`). If you need to disable
56
- this — for example when testing against an endpoint with an incomplete
57
- certificate chain — you can opt out:
35
+ To follow the latest work, install from the `2.0.0-alpha` branch instead:
58
36
 
59
37
  ```ruby
60
- config.ssl_verify = false
38
+ gem "einvoice", git: "https://github.com/abookyun/einvoice", branch: "2.0.0-alpha"
61
39
  ```
62
40
 
63
- Or per-provider:
41
+ `require "einvoice"` loads the core and `MockProvider` only. Require the provider you use, and only that one is loaded:
64
42
 
65
43
  ```ruby
66
- Einvoice::Tradevan::Provider.new(ssl_verify: false)
44
+ require "einvoice/ecpay" # or einvoice/amego, einvoice/ezpay, einvoice/tradevan
45
+ require "einvoice/mof" # the 財政部 lookups, if you use them
67
46
  ```
68
47
 
69
- ### Initialize
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.
70
51
 
71
52
  ```ruby
72
- client = Einvoice::Client.new(Einvoice::Tradevan::Provider.new)
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: "客戶取消")
73
75
  ```
74
76
 
75
- ### Issue an invoice (開立電子發票)
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`.
76
78
 
77
- ```ruby
78
- payload = {
79
- companyUn: "12345678",
80
- orgId: "ABCDE",
81
- type: "I",
82
- saleIdentifier: "12345678_ABCDE_53b2a44e4b3c",
83
- transactionNumber: "53b2a44e4b3c",
84
- transactionDate: "20160425",
85
- transactionTime: "12:34:56",
86
- total: "20000",
87
- paperPrintMode: "0",
88
- invoiceAlarmMode: "4",
89
- donate: "N",
90
- donationUnit: nil,
91
- carrierType: "3J0002",
92
- carrierId: "TP03000001234567",
93
- carrierIdHidden: "TP03000001234567",
94
- receiverName: "John Appleseed",
95
- receiverAddrZip: "95014",
96
- receiverAddrRoad: "1 Infinite Loop - Cupertino CA",
97
- receiverEmail: "john@gmail.com",
98
- receiverMobile: "415-284-0579",
99
- memberId: nil,
100
- itemList: [
101
- {
102
- saleIdentifier: "12345678_ABCDE_53b2a44e4b3c",
103
- serialNumber: "0001",
104
- productName: "Coffee Latte",
105
- qty: "4000",
106
- price: "5",
107
- itemTotal: "20000",
108
- taxType: "T",
109
- tax: "952"
110
- }
111
- ]
112
- }
113
- ```
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.
114
80
 
115
- ```ruby
116
- result = client.issue(payload)
117
- result.successful?
118
- #=> true
119
- result.data
120
- #=>
121
- # {
122
- # "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
123
- # "issueStatus"=>"Y",
124
- # "failReason"=>"",
125
- # "invoiceNumber"=>"GX38551078",
126
- # "checkNumber"=>"4229",
127
- # "invoiceDate"=>"20160425",
128
- # "invoiceTime"=>"12:34:58",
129
- # "texclusiveAmount"=>"19048",
130
- # "oexclusiveAmount"=>"0",
131
- # "zexclusiveAmount"=>"0",
132
- # "tax"=>"952",
133
- # "inclusiveAmount"=>"20000",
134
- # "mainRemark"=>"",
135
- # "invoiceType"=>"",
136
- # "invoiceStatus"=>"V",
137
- # "allowanceNumber"=>"",
138
- # "allowanceDate"=>"",
139
- # "allowanceExclusiveAmount"=>"",
140
- # "allowanceTax"=>"",
141
- # "allowanceTotalAmount"=>"0",
142
- # "allowanceStatus"=>""
143
- # }
144
- ```
81
+ The checks:
145
82
 
146
- ### Cancel an invoice (作廢電子發票)
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 `作廢折讓`.
91
+
92
+ ### Amounts and tax
93
+
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.
95
+
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)`:
147
97
 
148
98
  ```ruby
149
- payload = {
150
- type: "I",
151
- saleIdentifier: "12345678_ABCDE_53b2a44e4b3c",
152
- invoiceNumber: "GX38551078",
153
- invoicePaperReturned: "Y",
154
- }
99
+ amount: { sales_amount: 95, tax_amount: 5, total_amount: 100 } # 100 with tax, to a business
155
100
  ```
156
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
+
157
104
  ```ruby
158
- result = client.cancel(payload)
159
- result.successful?
160
- #=> true
161
- result.data
162
- #=>
163
- # {
164
- # "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
165
- # "voidStatus"=>"Y",
166
- # "failReason"=>"",
167
- # "type"=>"I",
168
- # "invoiceNumber"=>"GX38551078",
169
- # "allowanceNumber"=>""
170
- # }
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
+ )
171
110
  ```
172
111
 
173
- ### Issue an allowance (開立折讓單)
112
+ ### Errors
174
113
 
175
- An allowance against a previously issued invoice is sent through `issue` with `type: "A"`. Each item must reference the original invoice (`invoiceNumber` / `invoiceDate`) and carry its tax-exclusive amount (`itemExclude`).
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:
176
115
 
177
116
  ```ruby
178
- payload = {
179
- companyUn: "12345678",
180
- orgId: "ABCDE",
181
- type: "A",
182
- allowanceIdentifier: "12345678_ABCDE_53b2a44e4b3d",
183
- transactionNumber: "53b2a44e4b3d",
184
- transactionDate: "20160426",
185
- paperPrintMode: "0",
186
- invoiceAlarmMode: "4",
187
- allowanceExclusiveAmount: "95",
188
- allowanceTax: "5",
189
- allowanceInclusiveAmount: "100",
190
- allowancePaperReturned: "N",
191
- invoicePaperReturned: "N",
192
- receiverName: "John Appleseed",
193
- receiverEmail: "john@gmail.com",
194
- itemList: [
195
- {
196
- saleIdentifier: "12345678_ABCDE_53b2a44e4b3c",
197
- serialNumber: "0001",
198
- invoiceNumber: "GX38551078",
199
- invoiceDate: "20160425",
200
- productName: "Coffee Latte",
201
- qty: "1000",
202
- price: "100",
203
- itemExclude: "95",
204
- tax: "5",
205
- itemTotal: "100",
206
- taxType: "T"
207
- }
208
- ]
209
- }
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
210
127
  ```
211
128
 
212
- ```ruby
213
- result = client.issue(payload)
214
- result.successful?
215
- #=> true
216
- ```
129
+ The class tells you what to do next, the same way at every provider:
217
130
 
218
- Notes:
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.
219
138
 
220
- * `allowanceIdentifier` must be prefixed with `"#{companyUn}_#{orgId}_"`, like `saleIdentifier` on invoices.
221
- * `allowanceExclusiveAmount` + `allowanceTax` = `allowanceInclusiveAmount`.
139
+ ### Credentials and buyer data
222
140
 
223
- ### Void an allowance (作廢折讓單)
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.
224
143
 
225
- ```ruby
226
- payload = {
227
- type: "A",
228
- companyUn: "12345678",
229
- allowanceNumber: "ABCDE20160426001",
230
- allowancePaperReturned: "Y",
231
- }
232
- ```
144
+ ### Capabilities
145
+
146
+ A provider declares what it supports; feature-detect instead of discovering a gap when a request fails.
233
147
 
234
148
  ```ruby
235
- result = client.cancel(payload)
236
- result.successful?
237
- #=> true
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
238
152
  ```
239
153
 
240
- ### Search invoice by memberId/sellTargetCode (載具/會員發票查詢)
154
+ ## Providers
241
155
 
242
- ```ruby
243
- payload = {
244
- companyUn: "12345678",
245
- invoiceStartDate: "20160401",
246
- invoiceEndDate: "20160425",
247
- carrierId: "TP03000001234567",
248
- memberId: "",
249
- sellTargetCode: "",
250
- }
251
- ```
156
+ ### ECPay 綠界
252
157
 
253
158
  ```ruby
254
- result = client.search_invoice_by_member_id(payload)
255
- result.successful?
256
- #=> true
257
- result.data
258
- #=>
259
- # [
260
- # {
261
- # "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
262
- # "invoiceNumber"=>"GX38551078",
263
- # "checkNumber"=>"4229",
264
- # "invoiceDate"=>"20160425",
265
- # "invoiceTime"=>"12:34:58",
266
- # "exclusiveAmount"=>"19048",
267
- # "tax"=>"952",
268
- # "total"=>"20000",
269
- # "status"=>"V",
270
- # "hasAllowance"=>"N",
271
- # "sellerName"=>"Starbucks",
272
- # "sellerUN"=>"12345678",
273
- # "sellerAddr"=>"1 Infinite Loop - Cupertino CA",
274
- # "sellerTel"=>"415-284-0579",
275
- # "receiverName"=>"John Appleseed",
276
- # "receiverAddr"=>"1 Infinite Loop - Cupertino CA",
277
- # "paper"=>"N",
278
- # "win"=>"N",
279
- # "donate"=>"N",
280
- # "carrierType"=>"CQ0001",
281
- # "carrierId"=>"TP03000001234567"
282
- # }
283
- # ]
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
+ )
284
167
  ```
285
168
 
286
- ### Search invoice detail (發票開立明細查詢)
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):
287
172
 
288
173
  ```ruby
289
- result = client.search_invoice_detail("GX38551078")
290
- result.successful?
291
- #=> true
292
- result.data
293
- #=>
294
- # {
295
- # "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
296
- # "invoiceNumber"=>"GX38551078",
297
- # "checkNumber"=>"4229",
298
- # "invoiceDate"=>"20160425",
299
- # "invoiceTime"=>"12:34:58",
300
- # "exclusiveAmount"=>"19048",
301
- # "tax"=>"952",
302
- # "total"=>"20000",
303
- # "status"=>"I",
304
- # "hasAllowance"=>"N",
305
- # "sellerName"=>"Starbucks",
306
- # "sellerUN"=>"12345678",
307
- # "sellerAddr"=>"1 Infinite Loop - Cupertino CA",
308
- # "sellerTel"=>"415-284-0579",
309
- # "receiverName"=>"John Appleseed",
310
- # "receiverAddr"=>"1 Infinite Loop - Cupertino CA",
311
- # "receiverPhone"=>"415-284-0579",
312
- # "paper"=>"Y",
313
- # "win"=>"N",
314
- # "donate"=>"N",
315
- # "carrierType"=>"CQ0001",
316
- # "detailList"=>[
317
- # {
318
- # "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
319
- # "serialNumber"=>"0001",
320
- # "productName"=>"Coffee Latte",
321
- # "qty"=>"4000",
322
- # "price"=>"5",
323
- # "total"=>"20000",
324
- # "taxType"=>"T"
325
- # }
326
- # ]
327
- # }
174
+ provider = Einvoice::ECPay::Provider.new(**Einvoice::ECPay::SANDBOX)
328
175
  ```
329
176
 
330
- ### Send card info to customer (電子發票載具歸戶/中獎通知作業)
177
+ A few things worth knowing:
331
178
 
332
- ```ruby
333
- payload = {
334
- companyUn: "12345678",
335
- sellTargetCode: "xxx",
336
- invoiceStartYM: "201604",
337
- invoiceEndYM: "201604",
338
- receiverEmail: "john@gmail.com",
339
- receiverMobile: "",
340
- }
341
- ```
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 光貿
342
189
 
343
190
  ```ruby
344
- result = client.send_card_info_to_cust(payload)
345
- result.successful?
346
- #=> true
347
- result.data
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
+ )
348
197
  ```
349
198
 
350
- ### Get invoice mark info (電子發票字軌號碼配額取號/分配作業)
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.
351
200
 
352
- ```ruby
353
- payload = {
354
- companyUn: "12345678",
355
- orgId: "ABCDE",
356
- uniFiedNumber: "12345678",
357
- bookType: "API",
358
- period: "201604",
359
- }
360
- ```
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)
361
212
 
362
213
  ```ruby
363
- result = client.get_invoice_mark_info(payload)
364
- result.successful?
365
- #=> true
366
- result.data
367
- #=>
368
- # [
369
- # {
370
- # "unifiedNumber"=>"12345678",
371
- # "bookNumber"=>"API_M1",
372
- # "bookType"=>"API",
373
- # "period"=>"201604",
374
- # "duration"=>"201604",
375
- # "mark"=>"GX",
376
- # "start"=>"38551050",
377
- # "end"=>"38551249"
378
- # }
379
- # ]
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
+ )
380
221
  ```
381
222
 
382
- ### Get donate unit list (受贈機關/社福團體愛心碼清單查詢)
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)
383
234
 
384
235
  ```ruby
385
- client.get_donate_unit_list("12345678")
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
+ )
386
247
  ```
387
248
 
388
- ### Get invoice content (電子發票內容查詢)
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).
389
257
 
390
- ```ruby
391
- payload = {
392
- invoiceNumber: "GX38551078",
393
- sellTargetCode: "",
394
- invoiceStartDate: "",
395
- invoiceEndDate: "",
396
- }
397
- ```
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.
398
261
 
399
262
  ```ruby
400
- result = client.get_invoice_content(payload)
401
- result.successful?
402
- #=> true
403
- result.data
404
- #=>
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)
405
275
  ```
406
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
+
407
281
  ## Development
408
282
 
409
- After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
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.
410
292
 
411
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
293
+ The ECPay adapter is tested in three layers, two of which run offline in CI:
412
294
 
413
- ## Contributing
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:
414
298
 
415
- Bug reports and pull requests are welcome on GitHub at https://github.com/abookyun/einvoice.
299
+ ```bash
300
+ ECPAY_LIVE=1 bundle exec rspec spec/einvoice/ecpay/live_spec.rb
301
+ ```
416
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
+ ```
417
310
 
418
311
  ## License
419
312