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.zh-TW.md ADDED
@@ -0,0 +1,322 @@
1
+ # Einvoice
2
+
3
+ [English](README.md) | 繁體中文
4
+
5
+ > 本文譯自英文版。兩者不一致時,以英文版為準。
6
+
7
+ [![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)
8
+
9
+ 不綁定特定加值中心的**台灣電子發票 SDK**(財政部 MIG 4.1)。核心只定義一次五個操作:開立(issue)、作廢(void)、折讓(allowance)、折讓作廢(void-allowance)、查詢(query)。這些操作由一套 unified value model 和 `Einvoice::Provider` contract 表達。每一家加值中心是一個輕量的 adapter,負責在 unified model 和該家的傳輸格式之間轉換。所以業務程式碼不會綁定在某一家加值中心。
10
+
11
+ > **2.0 是全新改寫的版本,1.x 已經進入維護模式。** 1.x 是只支援關貿(Tradevan)一家的傳輸格式 client,API 也不一樣。如果你依賴 1.x,請鎖定 `~> 1.4`。1.x 會在 [`1-x-stable`](https://github.com/abookyun/einvoice/tree/1-x-stable) branch 繼續維護。2.0 的 unified model 和 1.x 不相容。要升級到 2.0,請見[從 1.x 升級到 2.0](docs/upgrading-to-2.0.zh-TW.md)。
12
+
13
+ ## 這是什麼
14
+
15
+ 台灣每一家加值中心包裝的都是財政部同一份 MIG 規格,差別只在傳輸格式:欄位名稱、簽章、封包結構。這個 SDK 只定義一次操作,每一家加值中心都只是輕量的 adapter。應用程式只依賴 `Einvoice::Provider` 和 unified 型別,所以換到另一家加值中心,第一步是換 constructor。各家能做的事仍然不同。每個 adapter 會透過 capabilities、`query_statuses` 和 `UnsupportedError` 說明這些差異,所以你可以在換之前先檢查。
16
+
17
+ ## 狀態
18
+
19
+ 正在朝 2.0 積極開發。不綁定加值中心的**核心**已經完成,包括:value 型別、`Provider` contract、capabilities、統一的錯誤類別階層、輸入檢查,以及在記憶體中執行的 `MockProvider`。第一個真正的 adapter **ECPay(綠界)** 也一起提供:五個操作加上載具驗證,都已經對 ECPay 公開的 stage API 驗證過。
20
+
21
+ 第二個 adapter **Amego 光貿** 提供五個操作,已經對 Amego 公開的測試帳號驗證過。
22
+
23
+ **ezPay 簡單行動支付** adapter 目前是實驗性質:它依 ezPay 公開的手冊寫成,還沒有對 ezPay 執行過。
24
+
25
+ **關貿 DEFAULTAPI** adapter 目前是實驗性質:它從 1.x client 移植而來,還沒有對 live API 執行過。
26
+
27
+ 其他加值中心會陸續加入。它們的涵蓋範圍和完整度會不一樣:這些加值中心的文件比較不完整,也沒有公開的測試環境。所以只依文件寫出來的 adapter,在真正上線使用並確認之前,會有一些不確定性。
28
+
29
+ ## 安裝
30
+
31
+ 2.0 還在 alpha 階段,API 在不同的 alpha 之間仍可能改變。請鎖定確切的版本:
32
+
33
+ ```ruby
34
+ gem "einvoice", "2.0.0.alpha2"
35
+ ```
36
+
37
+ 如果想追蹤最新的進度,可以改從 `2.0.0-alpha` branch 安裝:
38
+
39
+ ```ruby
40
+ gem "einvoice", git: "https://github.com/abookyun/einvoice", branch: "2.0.0-alpha"
41
+ ```
42
+
43
+ `require "einvoice"` 只會載入 core 和 `MockProvider`。請 require 你使用的加值中心,只有它會被載入:
44
+
45
+ ```ruby
46
+ require "einvoice/ecpay" # or einvoice/amego, einvoice/ezpay, einvoice/tradevan
47
+ require "einvoice/mof" # the 財政部 lookups, if you use them
48
+ ```
49
+
50
+ ## 使用方式
51
+
52
+ 請依賴 `Einvoice::Provider` contract,不要依賴特定的 adapter。每個 provider 都是各自建立的實例(沒有全域設定),所以多商家的應用程式只要為每一組帳號各建立一個 provider。
53
+
54
+ ```ruby
55
+ # Any adapter — here the in-memory reference provider — is an Einvoice::Provider.
56
+ provider = Einvoice::MockProvider.new
57
+
58
+ result = provider.issue(
59
+ order_id: "ORDER_1",
60
+ buyer: { email: "buyer@example.com" }, # a ubn present ⇒ B2B (三聯式)
61
+ items: [
62
+ { description: "咖啡拿鐵", quantity: 1, unit_price: 100, amount: 100 }
63
+ ],
64
+ tax_type: "TAXABLE",
65
+ price_mode: "TAX_INCLUSIVE",
66
+ carrier: { type: "MEMBER" }
67
+ )
68
+
69
+ result.invoice_number # => "MK10000000"
70
+ result.status # => :issued
71
+
72
+ invoice = provider.query(invoice: result.reference)
73
+ invoice.status # => :issued,加值中心分辨不出時為 nil
74
+ provider.query_statuses # => [:issued, :voided, :allowance]
75
+
76
+ provider.void(invoice: result.reference, reason: "客戶取消")
77
+ ```
78
+
79
+ `result.reference` 是一個 `InvoiceReference`。它記錄之後作廢、折讓或查詢這張發票時,加值中心會要的資料:號碼、`invoice_datetime`、`random_code`、`order_id`、`total_amount`、`buyer_ubn`,以及它的 `tax_type` 和 `tax_rate`。請把 `result.reference.to_h` 和訂單一起存起來。它只包含 JSON 安全的值(`invoice_datetime` 是 UTC+8 的 ISO 8601 字串),可以直接存進 JSON 欄位。之後原樣用 `invoice:` 傳回來,或直接傳 reference 本身。存起來的時間必須帶時區:`"2026-08-01 10:00"` 會被拒絕,不會被當成錯的時區;只有日期的 `"2026-08-01"` 視為台北當天。也可以只傳發票號碼,但如果加值中心需要更多資料,會丟出 `ValidationError` 並說明缺少哪個欄位。沒有發票號碼時,可以在宣告 `QUERY_BY_ORDER_ID` 的加值中心用 `invoice: { order_id: "ORDER_1" }` 查詢。`void_allowance` 收 `allowance:`,也就是 `AllowanceResult#reference` 回傳的 `AllowanceReference`。
80
+
81
+ 輸入可以直接傳一般的 Hash,key 用字串或 symbol 都可以。列舉欄位可以傳標準的 symbol(`:taxable`),也可以傳傳輸格式的字串(`"TAXABLE"`)。在送出任何網路請求之前,輸入會先經過檢查,並轉換成不可變的 value object。格式錯誤的請求會在本地端丟出 `Einvoice::ValidationError`。用 `.new` 自己建立的 value object 也會經過同樣的檢查。
82
+
83
+ 檢查的規則:
84
+
85
+ - 買方的 `ubn` 是 8 位數字,也就是企業的統一編號。(MIG 表 4-7 允許 8 到 10 位的 BAN,9 位和 10 位的形式不用在買方。)B2B 發票一定要有統編;明確指定 `category` 時,必須和統編一致。
86
+ - 總計是整數,而且不能是負數。品項的數量、單價、金額是數字,最多 7 位小數。發票的品項可以是負數,作為折扣列。折讓的品項不能是負數(MIG 4.1)。
87
+ - 手機條碼是 `/` 加 7 個字元。自然人憑證是 2 個英文字母加 14 個數字。這些格式來自加值中心的文件,MIG 只列出載具類別。愛心碼是 3 到 7 位數字。
88
+ - `tax_rate` 是小數,例如 `0.05`,而且必須是 MIG 規定的稅率。開立時的預設值由品項決定,不看表頭:有應稅品項時是 `0.05`,否則是 `0`。有特種稅額品項時一定要給。應稅品項的稅率不能是 `0`。
89
+ - 零稅率發票必須給 `customs_clearance_mark`,值是 `"1"` 或 `"2"`,對應 MIG 的 CustomsClearanceMark。`zero_tax_rate_reason` 是 `"71"` 到 `"79"`,對應 MIG 的 ZeroTaxRateReason。MIG 也規定零稅率發票要有零稅率原因,但 ECPay 可以從後台設定取得,所以 core 不要求。Amego 會要求。
90
+ - 金額必須和品項一致(見下一節)。
91
+ - MIG 的欄位長度:`remark` 200、買方 `name` 60、`address` 100、`email` 400、`phone` 26、載具 `code` 400、品項 `description` 500、`unit` 6、`remark` 120。消費者的名稱不能是 `0` 到 `0000`,載具號碼的開頭和結尾不能有空白。provider 自己的上限比較短時,丟 `UnsupportedError`。
92
+ - 作廢原因最多 20 個字。作廢折讓的原因沒給時,預設是 `作廢折讓`。
93
+
94
+ ### 金額與稅額
95
+
96
+ 稅額由 core 依品項計算。`price_mode` 說明品項金額是否含稅,`tax_type` 是整張發票的稅別(品項可以有自己的),`tax_rate` 是稅率。計算結果是 `input.tax_breakdown`:每一列的未稅金額、稅額、含稅金額,以及 MIG 的各項合計。adapter 讀取它,不自己計算稅額。core 不會改動你的品項。
97
+
98
+ `amount` 是選填。沒給時,core 從計算結果填入。有給時,會拿來和計算結果核對,所以你自己算的合計不會和品項對不上。發票照 F0401:買方是消費者時,稅額含在 `sales_amount` 裡,`tax_amount` 是 `0`。買方是營業人時,`tax_amount` 是 `round(應稅銷售額 × tax_rate)`:
99
+
100
+ ```ruby
101
+ amount: { sales_amount: 95, tax_amount: 5, total_amount: 100 } # 含稅 100,開給營業人
102
+ ```
103
+
104
+ 折讓照 G0401:`sales_amount` 不含稅,買方是消費者時也一樣。折讓的 `tax_type` 和 `tax_rate` 從發票的 reference 取得,所以傳 `issued.reference` 即可,也可以自己給。沒有預設值,所以零稅率的發票不會被折讓出 5% 的稅。原發票是混合稅時,每個品項都要給 `tax_type`。
105
+
106
+ ```ruby
107
+ provider.allowance(
108
+ invoice: issued.reference, allowance_id: "AL_1", price_mode: "TAX_INCLUSIVE",
109
+ items: [{ description: "退貨", quantity: 1, unit_price: 100, amount: 100 }],
110
+ amount: { sales_amount: 95, tax_amount: 5, total_amount: 100 }
111
+ )
112
+ ```
113
+
114
+ ### 錯誤
115
+
116
+ 每一種失敗都是 `Einvoice::Error` 的子類別,包含:
117
+
118
+ - 固定不變的 `#code`。
119
+ - 加值中心原始的 `#raw_code` 和 `#raw_message`。
120
+ - 選填的 `#reason`,說明呼叫端接下來該怎麼處理。
121
+ - `#group`,說明是哪一方失敗:`:invoice`(請求違反財政部的規則,或發票的狀態不對)或 `:provider`(帳號、連線,或加值中心自己的服務)。
122
+
123
+ 可以只 rescue 特定類別,也可以一次 rescue 全部:
124
+
125
+ ```ruby
126
+ begin
127
+ provider.void(invoice: invoice.reference, reason: "customer cancelled")
128
+ rescue Einvoice::ConflictError => e
129
+ # Only :already_voided means that the invoice is voided. Another reason,
130
+ # such as :void_blocked_by_allowance, means that it is not.
131
+ raise unless e.reason == :already_voided
132
+ rescue Einvoice::Error => e
133
+ e.code # => :network, :auth, :not_found, …
134
+ raise
135
+ end
136
+ ```
137
+
138
+ 錯誤類別說明下一步該怎麼做,每一家加值中心都一樣:
139
+
140
+ - `ValidationError`:輸入違反 MIG 的規則,任何加值中心都不會接受。請修正輸入。
141
+ - `UnsupportedError`:這家加值中心不接受這個輸入,或沒有這項功能。別家可能接受。
142
+ - `NetworkError`:請求可能沒有送到加值中心。請重試。`issue` 逾時後,發票可能其實已經開立。請用同一個 `order_id` 重試:如果收到 `reason` 為 `:duplicate_order` 的 `ConflictError`,就代表發票已經存在。
143
+ - `allowance` 逾時後,重試可能會折讓兩次,所以要先確認。Amego 會使用你的 `allowance_id`,收到重複的折讓時,會丟出 `reason` 為 `:duplicate_allowance` 的錯誤。ECPay 和 ezPay 由加值中心自己配發折讓單號,所以 adapter 找不到已經成功的那張折讓。重試前請先到加值中心的後台確認。關貿也會使用 `allowance_id`,但還沒有人確認過它會不會拒絕重複的折讓。
144
+ - `void` 或 `void_allowance` 逾時後,可以安全重試,因為同一張不會被作廢兩次。收到 `reason` 為 `:already_voided` 的 `ConflictError`,就代表第一次已經成功。
145
+ - 任何類別帶有 `reason: :rate_limited`:加值中心要求你放慢速度。請稍後重試。
146
+ - `ConflictError` 帶有 `reason: :retry_later`:加值中心還在處理這張發票。請稍後再試。
147
+
148
+ ### 帳號金鑰與買方資料
149
+
150
+ - 結果物件的 `inspect`、`to_s` 和 `pp` 會把 `raw` 顯示成 `[FILTERED]`,因為 `raw` 是加值中心的回應,裡面有買方的資料。需要時,請直接讀 `#raw`。`Buyer` 的姓名、email、地址和電話也會顯示成 `[FILTERED]`,不論它在哪個輸入或結果裡;`ubn` 照常顯示。adapter 的 client 也會把金鑰顯示成 `[FILTERED]`。
151
+ - `base_url` 必須使用 https。只有 localhost 可以用 http,方便測試。網址裡不能有帳號、密碼、查詢字串或 fragment。
152
+
153
+ ### Capabilities
154
+
155
+ 每個 provider 會宣告自己支援哪些功能。請先檢查功能是否支援,不要等到請求失敗才發現。
156
+
157
+ ```ruby
158
+ provider.supports?(Einvoice::Capability::FOREIGN_CURRENCY) # => true / false
159
+ provider.assert_supports!(Einvoice::Capability::B2B) # raises UnsupportedError if absent
160
+ provider.query_statuses # => the statuses that query can return
161
+ ```
162
+
163
+ ## 加值中心
164
+
165
+ ### ECPay 綠界
166
+
167
+ ```ruby
168
+ require "einvoice/ecpay"
169
+
170
+ provider = Einvoice::ECPay::Provider.new(
171
+ merchant_id: "2000132",
172
+ hash_key: "...", # 16 bytes, server-side only
173
+ hash_iv: "...", # 16 bytes, server-side only
174
+ mode: :production # :test (default) targets the stage host
175
+ )
176
+ ```
177
+
178
+ 上面的用法全部不用改。`issue`、`void`、`allowance`、`void_allowance`、`query` 收一樣的 unified 輸入,也回傳一樣的 value 型別。AES-128-CBC 封包、ECPay 的兩層結果代碼,以及它的欄位規則,都封裝在 adapter 裡面。
179
+
180
+ 沒有帳號也可以試用。請用 ECPay 公開的測試帳號。這組帳號由所有開發者共用,不要用在任何正式的資料上:
181
+
182
+ ```ruby
183
+ provider = Einvoice::ECPay::Provider.new(**Einvoice::ECPay::SANDBOX)
184
+ ```
185
+
186
+ 幾件需要知道的事:
187
+
188
+ - **紙本或電子由 adapter 判斷。** 有載具或捐贈的發票是電子發票(`Print=0`),其他的都會列印。列印時 ECPay 要求買方名稱、地址,以及 email 或電話。
189
+ - **混合稅率也由 adapter 判斷。** 如果品項的 `tax_type` 不一致,就會開成混合稅率(TaxType 9)發票,不用另外指定。
190
+ - **作廢、折讓、用號碼查詢都需要發票的開立日期**,從 `invoice.invoice_datetime` 取得。如果 reference 沒有日期但有 `order_id`,查詢改用訂單編號,作廢和折讓會先查詢補上日期。查詢失敗時丟出 `ProviderError`,`reason` 是 `:lookup_failed`。只有號碼是不夠的。
191
+ - **作廢折讓需要發票號碼**,所以請傳 `AllowanceReference`,不要只傳折讓單號。
192
+ - **不支援外幣。** ECPay 的 B2C API 沒有外幣欄位,所以 `currency` 不是 TWD 時會丟出 `UnsupportedError`,不會被當成 TWD 開立。
193
+ - **應稅發票固定是 5%。** ECPay 依課稅別決定稅率,所以其他的 `tax_rate` 會丟出 `UnsupportedError`。
194
+ - **載具驗證**:`validate_carrier({ type: "MOBILE_BARCODE", code: "/ABC1234" })`(`CARRIER_VALIDATION` 對應的 `Provider` 方法;ECPay 只能檢查手機條碼)、`validate_love_code("168001")`、`love_code_organ_name("168001")`。這些方法會詢問 ECPay,所以需要這個 adapter 和它的帳號。捐贈碼(愛心碼)另外可以用下面的 `Einvoice::MOF::DonationCodes`,它直接詢問財政部,不需要 adapter,也不需要帳號。
195
+ - **其他功能**:ECPay 另外有大約 25 個 B2C endpoint(延遲開立、字軌設定、列印、通知……)。請用 `provider.raw(path, payload)` 呼叫。它會處理封包、加密和錯誤對應。
196
+
197
+ ### Amego 光貿
198
+
199
+ ```ruby
200
+ require "einvoice/amego"
201
+
202
+ provider = Einvoice::Amego::Provider.new(
203
+ ban: "12345678", # the seller's 統一編號
204
+ app_key: "..." # from Amego support, server-side only
205
+ )
206
+ ```
207
+
208
+ 沒有帳號也可以試用。請用 Amego 公開的測試帳號。這組帳號由所有開發者共用,不要用在任何正式的資料上:`Einvoice::Amego::Provider.new(**Einvoice::Amego::SANDBOX)`。Amego 的測試和正式環境用同一個主機,由帳號決定是哪一個環境。
209
+
210
+ - **發票號碼由 Amego 配發**(自動配號)。
211
+ - **作廢會進入佇列。** Amego 會馬上接受作廢,但作廢後馬上查詢,結果仍可能是已開立。
212
+ - **折讓需要原發票的買方資料和日期。** reference 有日期和統一編號,但沒有買方名稱,所以 adapter 會先查詢原發票取得名稱。如果要省略查詢(例如超過 180 天的發票),請傳 `provider_options: { buyer_name: }`。折讓日期是今天(Asia/Taipei)。
213
+ - **折讓單號由你指定。** `allowance_id` 會當成 Amego 的 `AllowanceNumber` 送出(最多 16 字元,同一帳號內不能重複)。
214
+ - **混合稅率由品項判斷**,和 ECPay 相同。
215
+ - **不支援**:特種稅率和外幣。`tax_rate` 只能是 0 或 0.05。
216
+ - **載具驗證**:`validate_carrier({ type: "MOBILE_BARCODE", code: "/ABC1234" })` 會向 Amego 查詢手機條碼是否已註冊。Amego 只能檢查手機條碼。愛心碼請用 `Einvoice::MOF::DonationCodes`(見下方)。
217
+ - **其他功能**:其他 endpoint 請用 `provider.raw(path, payload)` 呼叫。note 的第 3 節列出了這些 endpoint。
218
+ - 細節和待解問題見 [`docs/providers/amego/api.zh-TW.md`](docs/providers/amego/api.zh-TW.md)。
219
+
220
+ ### ezPay 簡單行動支付(實驗性質)
221
+
222
+ ```ruby
223
+ require "einvoice/ezpay"
224
+
225
+ provider = Einvoice::EzPay::Provider.new(
226
+ merchant_id: "...", # 商店代號
227
+ hash_key: "...", hash_iv: "...", # 32 and 16 bytes, server-side only
228
+ mode: :test # or :production
229
+ )
230
+ ```
231
+
232
+ - **實驗性質。** ezPay 沒有共用的測試帳號,也沒有人對 ezPay 執行過這個 adapter。它的加密和 `CheckCode` 和 ezPay 手冊的範例逐 byte 吻合。請先用你自己的測試商店測試,再正式使用。
233
+ - **查詢需要隨機碼。** `issue` 或 `query` 回傳的 reference 裡有隨機碼。
234
+ - **折讓需要原發票的訂單編號。** reference 裡有訂單編號。沒有時,adapter 會先用發票號碼查詢。折讓單號由 ezPay 配發,所以不會送出 `allowance_id`。折讓日期是今天(Asia/Taipei)。
235
+ - **查詢分不出有沒有折讓。** ezPay 只說明發票是否已作廢。未作廢的發票,查詢結果的狀態是 `nil`。`query_statuses` 是 `[:voided]`。
236
+ - **作廢要等上傳之後。** ezPay 在隔天早上上傳前一天的發票,上傳前不能作廢。
237
+ - **價格依發票類別決定。** ezPay 要求 B2C 價格含稅,B2B 價格未稅。adapter 從 core 的明細取得價格,所以任何 `price_mode` 都可以。品項數量和單價必須是整數。
238
+ - **不支援**:訂單編號查詢、特種稅率、外幣、B2B 發票的混合稅率,以及載具驗證 API。`tax_rate` 只能是 0 或 0.05。
239
+ - **其他功能**:`provider.raw(path, version, fields)`,例如 `provider.raw("/Api/invoice_touch_issue", "1.0", { ... })`。
240
+ - 細節和待解問題見 [`docs/providers/ezpay/invoice.zh-TW.md`](docs/providers/ezpay/invoice.zh-TW.md)。
241
+
242
+ ### 關貿 Tradevan(DEFAULTAPI,實驗性質)
243
+
244
+ ```ruby
245
+ require "einvoice/tradevan"
246
+
247
+ provider = Einvoice::Tradevan::DefaultAPI::Provider.new(
248
+ acnt: "...", acntp: "...",
249
+ key1: "...", key2: "...", # 16 bytes each, server-side only
250
+ base_url: "https://...", # your Tradevan host; there is no default
251
+ company_un: "12345678", org_id: "ABCDE",
252
+ paper_print_mode: "0", invoice_alarm_mode: "4",
253
+ invoice_paper_returned: "N", allowance_paper_returned: "N",
254
+ member_carrier_type: "1K0001" # only needed for MEMBER carriers
255
+ )
256
+ ```
257
+
258
+ - **實驗性質。** 這個 adapter 依據 1.x client、它的 validator 和 README 範例移植而來。關貿沒有公開 API 文件,也沒有人對 live API 執行過這個 adapter。請先用你自己的帳號測試,再正式使用。1.x client 繼續留在 `1-x-stable`。
259
+ - **作廢和折讓需要原發票的 `saleIdentifier`。** DEFAULTAPI 用它識別發票。adapter 依序從 `provider_options: { sale_identifier: }` 取得(1.x client 開立的發票請用這個方式),或用 reference 的訂單編號組出,或用發票號碼查詢。折讓另外需要原發票日期,從 reference 或同一次查詢取得。`issue` 回傳的 reference 都有這些值。
260
+ - **折讓需要稅別和稅率**,而且在查詢之前就要有。`issue` 或 `query` 回傳的 reference 都有。只有發票號碼時,請在折讓的輸入中傳入 `tax_type:`,有應稅品項時也要傳入 `tax_rate:`。
261
+ - **查詢結果的 `status` 常常是 `nil`。** DEFAULTAPI 狀態代碼的意思還不清楚,所以 adapter 不猜。發票有折讓時 `status` 為 `:allowance`,其他情況為 `nil`。`query_statuses` 是 `[:allowance]`。原始代碼在 `result.raw["status"]`。
262
+ - **送出的價格含稅。** adapter 從 core 的稅額明細取得價格,所以任何 `price_mode` 都可以。應稅的 `tax_rate` 必須是 0.05。折讓的回應沒有日期時,折讓日期是今天(Asia/Taipei)。
263
+ - **不支援**:用訂單編號查詢、混合稅率、特種稅率,以及外幣。
264
+ - **其他功能**:其他 DEFAULTAPI endpoint 請用 `provider.raw(path, params)` 呼叫,例如 `provider.raw("get/getInvoiceMarkInfo", { ... })`。
265
+ - 細節和待解問題見 [`docs/providers/tradevan/defaultapi.zh-TW.md`](docs/providers/tradevan/defaultapi.zh-TW.md)。
266
+
267
+ ## 財政部查詢
268
+
269
+ 直接使用財政部公開服務的 client,不綁定任何加值中心。它們不開立任何東西,也不需要帳號,所以不論你用哪一家加值中心都可以用,甚至還沒選定加值中心時也可以用。
270
+
271
+ ```ruby
272
+ require "einvoice/mof"
273
+
274
+ codes = Einvoice::MOF::DonationCodes.new
275
+
276
+ codes.lookup("2718")
277
+ # => #<data Einvoice::MOF::DonationCode code="2718",
278
+ # name="社團法人台北市喜願協會", short_name="喜願協會",
279
+ # ubn="92000392", city="臺北市">
280
+
281
+ codes.exist?("105") # => false — well-formed, not registered
282
+ codes.for_ubn("92000392") # => every 愛心碼 that organisation holds
283
+ codes.all # => the whole dataset (~2,000, five requests)
284
+ ```
285
+
286
+ 這個 client **刻意不**接到 `Input`。`Input` 的檢查在本地端同步執行,而開立發票絕對不能依賴第三方服務是否連得上。`Input` 只檢查捐贈碼的格式。這個捐贈碼是否已經*登記*,請在適合的時候自己查詢:可以在下訂單時查,也可以在啟動時用 `#all` 抓一次完整清單,之後在本地端檢查。
287
+
288
+ 這份資料集目前不需要帳號。但是它公開的 OpenAPI 文件宣告了 `api_key` 和 `oauth2` 兩種驗證方式。所以如果收到 401 或 403,client 會丟出 `Einvoice::AuthError` 並說明原因,不會變成難以理解的解析錯誤。
289
+
290
+ ## 開發
291
+
292
+ ```bash
293
+ bin/setup # install dependencies
294
+ bundle exec rspec # run the specs
295
+ bundle exec rake # default task: rspec
296
+ ```
297
+
298
+ `spec/support/shared_examples/` 裡的 shared examples 是可以執行的 contract。每個 adapter 都要執行 `"an invoice provider"`,每個 adapter 的 client 都要執行 `"a provider client"`。新的 adapter 只要引用它們,就能證明自己遵守 unified model。新的 adapter 也要有自己的入口檔 `lib/einvoice/<name>.rb`,在裡面 require `einvoice`。`lib/einvoice.rb` 不載入它,`spec/spec_helper.rb` 會載入它。
299
+
300
+ 要寫新的 adapter,請從 [`docs/providers/`](docs/providers/README.zh-TW.md) 的加值中心筆記開始。閱讀順序:先讀財政部 MIG 筆記(所有加值中心都遵循的規格),再讀 ECPay 筆記(第一個 adapter,可以看筆記怎麼對應到程式碼),接著讀你要做的那一家的筆記,最後讀上面提到的 shared examples。
301
+
302
+ ECPay adapter 的測試分成三層,其中兩層在 CI 中離線執行:
303
+
304
+ 1. **用模擬傳輸格式的 fake 跑 contract。** shared examples 透過一個在同一個 process 中執行的 fake 來跑。這個 fake 實作真正的協定:AES 封包、PHP URL encoding,以及 ECPay 自己的 RtnCode。所以只有加密和欄位對應都正確時,請求才會通過。fake 會保留狀態,所以 contract 可以依序執行開立、折讓、作廢。
305
+ 2. **錄製的真實回應(VCR)。** `spec/einvoice/ecpay/recorded_spec.rb` 重播從 ECPay stage host 錄下來的 cassette。所以測試用到的欄位名稱、值的型別和錯誤代碼,都是 ECPay 實際回傳的,不是我們對文件的解讀。要重新錄製,請先調整該 spec 裡的 epoch,再用 `VCR_RECORD=1` 執行。cassette 只會包含測試環境的流量。
306
+ 3. **選擇性執行的 live API 測試。** 用來確認前兩層沒有偏離真實的 API:
307
+
308
+ ```bash
309
+ ECPAY_LIVE=1 bundle exec rspec spec/einvoice/ecpay/live_spec.rb
310
+ ```
311
+
312
+ 預設使用公開的測試帳號,所以不需要任何設定。如果要改用你自己的 stage 帳號,請設定 `ECPAY_MERCHANT_ID`、`ECPAY_HASH_KEY`、`ECPAY_HASH_IV`。這層不在 CI 中執行,因為它需要網路,而且測試帳號是共用的。
313
+
314
+ Amego 也有 live 測試,使用 Amego 公開的測試帳號:
315
+
316
+ ```bash
317
+ AMEGO_LIVE=1 bundle exec rspec spec/einvoice/amego/live_spec.rb
318
+ ```
319
+
320
+ ## 授權
321
+
322
+ 本 gem 以 [MIT 授權](http://opensource.org/licenses/MIT)開放原始碼。
data/Rakefile CHANGED
@@ -1,57 +1,8 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require "bundler/gem_tasks"
2
4
  require "rspec/core/rake_task"
3
5
 
4
6
  RSpec::Core::RakeTask.new(:spec)
5
7
 
6
8
  task default: :spec
7
-
8
- desc "Download latest e-invoice donation unit list and convert it to JSON"
9
- task :update_donation_unit do
10
- require "csv"
11
- require "json"
12
- require "faraday"
13
-
14
- # From https://data.gov.tw/dataset/31868
15
- url = "https://dataset.einvoice.nat.gov.tw/ods/portal/ODS303W/download/3886F055-EB77-4DF9-98E2-F3F49A7D3434/1/8B227A99-042A-4903-8B34-5715442A227D/0/?fileType=csv"
16
- response = Faraday.get(url)
17
- raise "Download failed: HTTP #{response.status}" unless response.status == 200
18
-
19
- body = response.body
20
-
21
- possible = ["UTF-8", "Big5"]
22
- chosen = nil
23
- utf8_text = nil
24
-
25
- possible.each do |code|
26
- begin
27
- str = body.dup.force_encoding(code)
28
- candidate = str.encode("UTF-8")
29
- if candidate.valid_encoding?
30
- chosen = code
31
- utf8_text = candidate
32
- break
33
- end
34
- rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError
35
- next
36
- end
37
- end
38
-
39
- unless chosen
40
- chosen = "fallback(replace)"
41
- utf8_text = body.dup.force_encoding("UTF-8").scrub("?")
42
- puts "::warning::Used fallback encoding with replacement; some characters may be lost"
43
- end
44
-
45
- utf8_text = utf8_text.delete_prefix("\uFEFF") # remove possible UTF-8 BOM
46
- csv = CSV.parse(utf8_text, headers: true)
47
-
48
- orgs = csv.map do |row|
49
- code = (row['捐贈碼'] || row[2]).to_s.strip
50
- name = (row['受捐贈機關或團體名稱'] || row[1]).to_s.strip
51
- [code, name]
52
- end.sort_by { |code, _| [code.to_i, code] }
53
-
54
- File.write "lib/einvoice/donation_unit_list.json", JSON.pretty_generate(orgs.to_h)
55
-
56
- puts "Wrote lib/einvoice/donation_unit_list.json (#{orgs.length} entries)"
57
- end
data/bin/console CHANGED
@@ -1,11 +1,8 @@
1
1
  #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
2
3
 
3
4
  require "bundler/setup"
4
5
  require "einvoice"
6
+ require "irb"
5
7
 
6
- # You can add fixtures and/or initialization code here to make experimenting
7
- # with your gem easier. You can also use a different console, if you like.
8
-
9
- # (If you use this, don't forget to add pry to your Gemfile!)
10
- require "pry"
11
- Pry.start
8
+ IRB.start(__FILE__)
data/einvoice.gemspec CHANGED
@@ -1,7 +1,8 @@
1
- # coding: utf-8
2
- lib = File.expand_path('../lib', __FILE__)
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path("lib", __dir__)
3
4
  $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
- require 'einvoice/version'
5
+ require "einvoice/version"
5
6
 
6
7
  Gem::Specification.new do |spec|
7
8
  spec.name = "einvoice"
@@ -9,34 +10,31 @@ Gem::Specification.new do |spec|
9
10
  spec.authors = ["David Yun"]
10
11
  spec.email = ["abookyun@gmail.com"]
11
12
 
12
- spec.summary = %q{An API wrapper for Taiwan e-invoice services.}
13
+ spec.summary = "Provider-agnostic Taiwan e-invoice SDK (unified model + per-provider adapters)."
13
14
  spec.homepage = "https://github.com/abookyun/einvoice"
14
15
  spec.license = "MIT"
15
16
 
16
17
  spec.metadata = {
17
18
  "source_code_uri" => "https://github.com/abookyun/einvoice",
18
- "changelog_uri" => "https://github.com/abookyun/einvoice/blob/main/CHANGELOG.md",
19
+ "changelog_uri" => "https://github.com/abookyun/einvoice/blob/v#{spec.version}/CHANGELOG.md",
19
20
  "bug_tracker_uri" => "https://github.com/abookyun/einvoice/issues",
20
21
  "rubygems_mfa_required" => "true"
21
22
  }
22
23
 
23
- spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
24
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features|docs)/}) }
24
25
  spec.bindir = "exe"
25
26
  spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
27
  spec.require_paths = ["lib"]
27
28
 
28
- spec.required_ruby_version = '>= 3.1'
29
- spec.add_dependency "faraday", "~> 2.1"
30
- spec.add_dependency "multi_xml"
31
- spec.add_dependency "activemodel"
32
- spec.add_dependency "activesupport"
29
+ # Data.define (Ruby 3.2) is the backbone of the value model.
30
+ spec.required_ruby_version = ">= 3.2"
31
+
32
+ # The core has zero runtime dependencies — the unified model, validation, and
33
+ # error handling are plain Ruby + stdlib. Adapters add only what their wire
34
+ # format needs (openssl/json are stdlib); HTTP is stdlib Net::HTTP.
33
35
 
34
- spec.add_development_dependency "bundler", "> 1.17"
35
36
  spec.add_development_dependency "rake", "~> 13.0"
36
- spec.add_development_dependency "pry"
37
- spec.add_development_dependency "rspec"
38
- spec.add_development_dependency "factory_bot"
39
- spec.add_development_dependency "shoulda-matchers"
40
- spec.add_development_dependency "vcr"
41
- spec.add_development_dependency "webmock"
37
+ spec.add_development_dependency "rspec", "~> 3.13"
38
+ spec.add_development_dependency "vcr", "~> 6.3"
39
+ spec.add_development_dependency "webmock", "~> 3.23"
42
40
  end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+ require "digest"
7
+
8
+ module Einvoice
9
+ module Amego
10
+ # Speaks Amego's wire protocol: a form POST with +invoice+, +data+ (the
11
+ # JSON payload), +time+ and +sign+, then reads the +code+ / +msg+ envelope
12
+ # and raises the matching {Einvoice::Error} subclass.
13
+ #
14
+ # Amego has no encryption. +sign+ is +md5(data + time + app_key)+ over the
15
+ # JSON string before URL encoding, so it only proves that the caller knows
16
+ # the App Key.
17
+ class Client
18
+ PROVIDER = "amego"
19
+ # One host for test and production. The credentials pick the environment.
20
+ BASE_URL = "https://invoice-api.amego.tw"
21
+
22
+ attr_reader :base_url, :timeout
23
+
24
+ def initialize(ban:, app_key:, base_url: BASE_URL, timeout: 30, clock: -> { Time.now })
25
+ if ban.to_s.empty? || app_key.to_s.empty?
26
+ raise ValidationError.new("Amego ban and app_key are required", provider: PROVIDER)
27
+ end
28
+
29
+ @ban = ban.to_s
30
+ @app_key = app_key.to_s
31
+ @base_url = Redaction.base_url!(base_url, provider: PROVIDER)
32
+ @timeout = timeout
33
+ @clock = clock
34
+ end
35
+
36
+ def inspect
37
+ "#<#{self.class.name} ban=#{@ban.inspect} base_url=#{@base_url.inspect} app_key=#{Redaction::FILTERED}>"
38
+ end
39
+ alias to_s inspect
40
+
41
+ # POST +payload+ to +path+ (for example +"/json/f0401"+) and return the
42
+ # parsed response body, with +code+ 0. Any other +code+ raises.
43
+ def request(path, payload)
44
+ data = JSON.generate(payload)
45
+ time = @clock.call.to_i.to_s
46
+ form = { "invoice" => @ban, "data" => data, "time" => time, "sign" => sign(data, time) }
47
+ read(send_request(path, form))
48
+ end
49
+
50
+ def sign(data, time)
51
+ Digest::MD5.hexdigest("#{data}#{time}#{@app_key}")
52
+ end
53
+
54
+ # Encode every value with +%20+ for a space, not +++. Amego URL decodes
55
+ # the POST data once, and both of PHP's decoders read +%20+ as a space.
56
+ def self.encode_form(form)
57
+ form.map { |key, value| "#{key}=#{URI.encode_uri_component(value)}" }.join("&")
58
+ end
59
+
60
+ private
61
+
62
+ def send_request(path, form)
63
+ uri = URI("#{@base_url}#{path}")
64
+ http = Net::HTTP.new(uri.host, uri.port)
65
+ http.use_ssl = uri.scheme == "https"
66
+ http.open_timeout = @timeout
67
+ http.read_timeout = @timeout
68
+
69
+ post = Net::HTTP::Post.new(uri.request_uri)
70
+ post["Content-Type"] = "application/x-www-form-urlencoded"
71
+ post["Accept"] = "application/json"
72
+ post.body = self.class.encode_form(form)
73
+ response = nil
74
+ http.request(post) { |res| (response = res).read_body }
75
+ parse(response)
76
+ rescue *Error::NETWORK_ERRORS => e
77
+ raise NetworkError.for_failure(e, provider: PROVIDER, name: "Amego", response: response)
78
+ end
79
+
80
+ # A body that Amego wrote (a JSON object with +code+) decides the error,
81
+ # whatever the HTTP status. Any other body falls back to the status:
82
+ # HTTP 429 and 5xx are a NetworkError, so the caller can retry
83
+ # (docs/providers/README.md, "The unified model").
84
+ def parse(response)
85
+ body = JSON.parse(response.body.to_s)
86
+ return body if body.is_a?(Hash) && body.key?("code")
87
+
88
+ raise_for_status!(response)
89
+ body
90
+ rescue JSON::ParserError => e
91
+ raise_for_status!(response)
92
+ raise ProviderError.new("Amego returned a non-JSON response (HTTP #{response.code})",
93
+ provider: PROVIDER, raw_code: response.code, cause: e)
94
+ end
95
+
96
+ def raise_for_status!(response)
97
+ error = NetworkError.for_status(response, provider: PROVIDER)
98
+ raise error if error
99
+ end
100
+
101
+ def read(body)
102
+ unless body.is_a?(Hash) && body.key?("code")
103
+ raise ProviderError.new("Amego returned an unexpected response", provider: PROVIDER, raw: body)
104
+ end
105
+ return body if body["code"].to_s == "0"
106
+
107
+ message = body["msg"].to_s
108
+ code, reason = Errors.classify(body["code"])
109
+ raise Einvoice::Error.for(
110
+ code, message.empty? ? "Amego returned code #{body['code']}" : message,
111
+ provider: PROVIDER, reason: reason, raw_code: body["code"].to_s, raw_message: message, raw: body
112
+ )
113
+ end
114
+ end
115
+ end
116
+ end