taiwan_payments 0.1.0

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 +7 -0
  2. data/CHANGELOG.md +24 -0
  3. data/LICENSE.txt +21 -0
  4. data/README.ja.md +293 -0
  5. data/README.md +291 -0
  6. data/README.zh-TW.md +293 -0
  7. data/docs/ecpay-invoices.md +202 -0
  8. data/docs/ecpay-payments.md +191 -0
  9. data/docs/glossary/concepts.ja.md +33 -0
  10. data/docs/glossary/concepts.md +34 -0
  11. data/docs/glossary/ecpay-invoice.ja.md +113 -0
  12. data/docs/glossary/ecpay-invoice.md +114 -0
  13. data/docs/glossary/ecpay-payment.ja.md +64 -0
  14. data/docs/glossary/ecpay-payment.md +65 -0
  15. data/docs/rails.md +184 -0
  16. data/docs/sandbox-setup.md +104 -0
  17. data/docs/taiwan-payments-101.ja.md +138 -0
  18. data/docs/taiwan-payments-101.md +138 -0
  19. data/docs/taiwan-payments-101.zh-TW.md +138 -0
  20. data/docs/testing.md +140 -0
  21. data/docs/webhooks.md +113 -0
  22. data/exe/taiwan_payments +6 -0
  23. data/lib/generators/taiwan_payments/install/install_generator.rb +41 -0
  24. data/lib/generators/taiwan_payments/install/templates/ecpay_controller.rb.tt +26 -0
  25. data/lib/generators/taiwan_payments/install/templates/initializer.rb.tt +38 -0
  26. data/lib/taiwan_payments/cli.rb +271 -0
  27. data/lib/taiwan_payments/configuration.rb +86 -0
  28. data/lib/taiwan_payments/credentials.rb +27 -0
  29. data/lib/taiwan_payments/decimal.rb +36 -0
  30. data/lib/taiwan_payments/ecpay/aes_cipher.rb +36 -0
  31. data/lib/taiwan_payments/ecpay/check_mac_value.rb +63 -0
  32. data/lib/taiwan_payments/ecpay/checkout.rb +154 -0
  33. data/lib/taiwan_payments/ecpay/invoice_client.rb +253 -0
  34. data/lib/taiwan_payments/ecpay/invoice_mapper.rb +222 -0
  35. data/lib/taiwan_payments/ecpay/payment_client.rb +188 -0
  36. data/lib/taiwan_payments/ecpay/payment_methods.rb +40 -0
  37. data/lib/taiwan_payments/ecpay/payment_notification.rb +127 -0
  38. data/lib/taiwan_payments/ecpay/response_body.rb +30 -0
  39. data/lib/taiwan_payments/ecpay/trade_info.rb +68 -0
  40. data/lib/taiwan_payments/ecpay.rb +19 -0
  41. data/lib/taiwan_payments/environment.rb +22 -0
  42. data/lib/taiwan_payments/error_codes/ecpay_invoice.yml +80 -0
  43. data/lib/taiwan_payments/error_codes/ecpay_payment.yml +59 -0
  44. data/lib/taiwan_payments/error_codes.rb +23 -0
  45. data/lib/taiwan_payments/errors.rb +71 -0
  46. data/lib/taiwan_payments/form_helper.rb +21 -0
  47. data/lib/taiwan_payments/glossary/concepts.yml +122 -0
  48. data/lib/taiwan_payments/glossary/ecpay_invoice.yml +523 -0
  49. data/lib/taiwan_payments/glossary/ecpay_payment.yml +278 -0
  50. data/lib/taiwan_payments/glossary.rb +106 -0
  51. data/lib/taiwan_payments/hosted_form.rb +46 -0
  52. data/lib/taiwan_payments/http_client.rb +62 -0
  53. data/lib/taiwan_payments/instrumentation.rb +42 -0
  54. data/lib/taiwan_payments/invoice.rb +235 -0
  55. data/lib/taiwan_payments/money.rb +32 -0
  56. data/lib/taiwan_payments/php_compat.rb +39 -0
  57. data/lib/taiwan_payments/railtie.rb +23 -0
  58. data/lib/taiwan_payments/redactor.rb +29 -0
  59. data/lib/taiwan_payments/taipei_time.rb +42 -0
  60. data/lib/taiwan_payments/tax_id.rb +26 -0
  61. data/lib/taiwan_payments/testing.rb +152 -0
  62. data/lib/taiwan_payments/validation.rb +56 -0
  63. data/lib/taiwan_payments/version.rb +5 -0
  64. data/lib/taiwan_payments/webhooks.rb +54 -0
  65. data/lib/taiwan_payments.rb +67 -0
  66. metadata +118 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 8cb277eb9ab96ba32085d93c3db3be50141a445adb2d2e6757254ed4b2c788ef
4
+ data.tar.gz: b1b7e3b7d8235b92ad3a9f3ac49213b292bdd59e617a89c4046131eaaf217784
5
+ SHA512:
6
+ metadata.gz: 7aceaa4323ee0bbe8494e50f39dff2582bba39ce14d09922a0ee34d874c1452e3c695a1b29adaa84432f62684c55a0dc9ab0420b264ae1aabbcb51ff2df54f0b
7
+ data.tar.gz: f1a174a9d8c32aff99bd1e97809b10d92efb911d320a268460934e336ae8e68630d6d07cf19c7ae0ccb1b732f76167ab8b3965f0cfa8db43250460d49daab962
data/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project follows [Semantic Versioning](https://semver.org/).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.1.0] - 2026-12-03
8
+
9
+ First release. ECPay payments and e-invoices.
10
+
11
+ ### Added
12
+
13
+ - `TaiwanPayments::ECPay::PaymentClient`: hosted checkout form, verified callbacks, order query, and card capture, refund, cancel and void.
14
+ - `TaiwanPayments::ECPay::InvoiceClient`: issue, schedule and trigger, void, allowance, void allowance, lookup, print link, and donation code and mobile barcode checks.
15
+ - `TaiwanPayments::Invoice`, a provider-neutral invoice model with exact decimal arithmetic and sensible defaults for carriers.
16
+ - `TaiwanPayments::TaxId.valid?` for company tax IDs (統一編號).
17
+ - Errors that carry an English, a Chinese and a Japanese message, with English and Japanese explanations for common ECPay codes. `TaiwanPayments.locale` chooses which one `message` returns.
18
+ - `TaiwanPayments::Testing`: signed callbacks and encrypted API responses for application specs.
19
+ - Optional Rails integration: `taiwan_payments_form`, the `TaiwanPayments::Webhooks` concern, an install generator and an `ActiveSupport::Notifications` bridge.
20
+ - `TaiwanPayments.configure` for apps with one merchant per product.
21
+ - The `taiwan_payments` command: glossary lookup, tax ID check, CheckMacValue and e-invoice payload debugging, and test checkouts, queries and invoices against ECPay's stage environment.
22
+ - Glossaries that map every ECPay field to its Chinese name and its meaning in English and Japanese.
23
+ - A README and a primer on payments and invoices in Taiwan, in English, Traditional Chinese and Japanese.
24
+ - A guide site for any programming language, in English, Traditional Chinese and Japanese. It explains ECPay's payment and e-invoice APIs and NewebPay's signing step by step, with tested examples in curl, Ruby, PHP, Node.js, Python and Go, error code tables, a glossary of payment and invoice terms in Chinese, English and Japanese, and a list of maintained libraries for each language.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Jay W
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.ja.md ADDED
@@ -0,0 +1,293 @@
1
+ # taiwan_payments
2
+
3
+ [English](README.md) | [繁體中文](README.zh-TW.md) | **日本語**
4
+
5
+ [![Buy me a coffee](https://img.shields.io/badge/Buy%20me%20a%20coffee-ffdd00?logo=buymeacoffee&logoColor=black)](https://buymeacoffee.com/randomizor)
6
+
7
+ Ruby で台湾の決済を受け付け、電子発票(電子發票)を発行できます。現在は ECPay(綠界科技)の決済と電子発票に対応しています。次に NewebPay(藍新金流)の決済と ezPay(簡單付)の電子発票に対応する予定です。
8
+
9
+ ```ruby
10
+ payments = TaiwanPayments::ECPay::PaymentClient.sandbox # ECPay の公開テスト加盟店。アカウント登録は不要です
11
+ form = payments.checkout(order_no: "ORD1001", amount: 1200, description: "Order 1001",
12
+ items: ["Oolong tea x2"], return_url: "https://shop.example/webhooks/ecpay/payment")
13
+ form.to_html # これを購入者のブラウザーに送ると、ECPay の決済ページに移動します
14
+ ```
15
+
16
+ ## この gem を選ぶ理由
17
+
18
+ - **1 分で動きます。** ECPay の公開テスト加盟店を組み込んであるので、アカウントを作る前から決済と発票の発行を試せます。
19
+ - **決済と電子発票をまとめて扱えます。** 台湾で販売するには両方が必要です。決済を受け、その取引に対して、政府が定める統一発票(統一發票)を発行します。
20
+ - **中国語が読めない人にも、読める人にも使いやすくしています。** API とドキュメントは英語が基本です。エラーメッセージは英語・中国語・日本語で用意しています。[用語集](docs/glossary/)では、ベンダーのすべてのフィールドについて、中国語名と意味を確認できます。
21
+ - **依存ライブラリはありません。** 標準ライブラリだけで動く素の Ruby です。Rails 連携は、Rails があるときだけ読み込まれます。
22
+ - **推測ではなく、検証しています。** 署名と暗号化は、ECPay が公開しているテストベクターで検証済みです。すべての API 呼び出しを ECPay のテスト環境で実行し、その実際のレスポンスを spec のフィクスチャにしています。行カバレッジと分岐カバレッジはどちらも 100% です。
23
+ - **既定で安全です。** コールバック(Webhook 通知)は、署名検証を通過するまで読めません。キーと購入者の情報は、ログではマスクされます。お金が動く処理は、自動ではリトライしません。
24
+ - **テストしやすくしています。** ヘルパーを使うと、正しく署名された偽のコールバックと、暗号化された偽の API レスポンスを作れます。アプリの spec にネットワークは必要ありません。
25
+
26
+ | | 決済 | 電子発票 |
27
+ | --- | --- | --- |
28
+ | ECPay | 対応済み | 対応済み。B2C API が対象で、会社の統一編号(統一編號)付きの発票も発行できます。 |
29
+ | NewebPay | 0.2 で対応予定 | |
30
+ | ezPay | | 0.3 で対応予定 |
31
+
32
+ 台湾の決済が初めての方は、まず[台湾決済入門](docs/taiwan-payments-101.ja.md)を読んでください。キャリア(載具)、統一編号、コンビニ決済、統一発票の宝くじを 10 分で説明しています。
33
+
34
+ Ruby 以外の言語を使う場合は、[API ガイド](https://randomizor.github.io/taiwan_payments/ja/)を参照してください。同じリクエスト、署名、コールバックを、どの言語でも使えるように、curl、PHP、Node.js、Python、Go の実行できる例付きで説明しています。英語、繁体字中国語、日本語で読めます。[用語集](https://randomizor.github.io/taiwan_payments/ja/glossary.html)では、載具、折譲、字軌などの用語を中国語、英語、日本語で対照できます。
35
+
36
+ ## インストール
37
+
38
+ ```ruby
39
+ # Gemfile
40
+ gem "taiwan_payments"
41
+ ```
42
+
43
+ Ruby 3.2 以降が必要です。Rails は必須ではありません。Rails 7.1 から 8.1 までをテストしています。
44
+
45
+ ## Rails でのクイックスタート
46
+
47
+ ```sh
48
+ bin/rails generate taiwan_payments:install
49
+ ```
50
+
51
+ このコマンドは、`config/initializers/taiwan_payments.rb`、`Webhooks::EcpayController`、そのルートを生成します。本番環境以外では、initializer は ECPay のテスト加盟店を使います。本番環境では、Rails credentials からキーを読み込みます。
52
+
53
+ 購入者を決済ページへ送ります。
54
+
55
+ ```ruby
56
+ class CheckoutsController < ApplicationController
57
+ def create
58
+ order = current_user.orders.find(params[:order_id])
59
+ @form = TaiwanPayments.ecpay_payments.checkout(
60
+ order_no: order.number,
61
+ amount: order.total,
62
+ description: "Order #{order.number}",
63
+ items: order.line_items.map(&:name),
64
+ return_url: webhooks_ecpay_payment_url,
65
+ client_back_url: order_url(order)
66
+ )
67
+ end
68
+ end
69
+ ```
70
+
71
+ ```erb
72
+ <%# app/views/checkouts/create.html.erb %>
73
+ <%= taiwan_payments_form(@form) %>
74
+ ```
75
+
76
+ 購入者が支払いを終えると、ECPay がサーバーを呼び出します。
77
+
78
+ ```ruby
79
+ module Webhooks
80
+ class EcpayController < ApplicationController
81
+ include TaiwanPayments::Webhooks
82
+
83
+ def payment
84
+ notification = ecpay_payment_notification # 検証済み。検証に失敗したリクエストには 400 を返します
85
+ order = Order.find_by!(number: notification.order_no)
86
+ order.mark_paid!(trade_no: notification.trade_no) if notification.paid? && !order.paid?
87
+ render_ecpay_ack # ECPay は "1|OK" を受け取るまで再送します
88
+ end
89
+ end
90
+ end
91
+ ```
92
+
93
+ `return_url` には、ECPay からアクセスできる公開 URL が必要です。開発中は ngrok や cloudflared などのトンネルを使ってください。[Webhooks](docs/webhooks.md) では、3 種類のコールバックと、注文の取りこぼしにつながる間違いを説明しています。[Rails](docs/rails.md) では、ヘルパー、concern、ジェネレーターを説明しています。
94
+
95
+ ## 決済
96
+
97
+ <!-- runnable -->
98
+ ```ruby
99
+ require "taiwan_payments"
100
+
101
+ payments = TaiwanPayments::ECPay::PaymentClient.sandbox
102
+ # 自分のキーを使う場合:
103
+ # TaiwanPayments::ECPay::PaymentClient.new(merchant_id: "...", hash_key: "...", hash_iv: "...", env: :production)
104
+
105
+ form = payments.checkout(
106
+ order_no: "ORD1001", # 自社で決める注文番号。一意で、英数字 20 文字まで
107
+ amount: 1200, # 新台湾ドル(TWD)の整数
108
+ description: "Order 1001",
109
+ items: ["Oolong tea x2", "Shipping"],
110
+ return_url: "https://shop.example/webhooks/ecpay/payment",
111
+ payment_method: :credit # ほかに :atm、:cvs、:barcode、:web_atm、:apple_pay など。既定値は :all
112
+ )
113
+
114
+ form.action_url # => "https://payment-stage.ecpay.com.tw/Cashier/AioCheckOut/V5"
115
+ form.fields["TotalAmount"] # => "1200"
116
+ form.fields["ChoosePayment"] # => "Credit"
117
+ ```
118
+
119
+ ECPay は、購入者のブラウザーからフォームの POST として届いた決済リクエストだけを受け付けます。そのため、この gem は ECPay を直接呼び出さず、フォームを返します。`form.to_html` を出力するか、`form.action_url` と `form.fields` から自分でフォームを組み立ててください。
120
+
121
+ コールバックが届いたら、POST されたフィールドを `notification` に渡します。ECPay が加盟店のキーで署名したデータでなければ、`TaiwanPayments::SignatureError` が発生します。
122
+
123
+ <!-- runnable -->
124
+ ```ruby
125
+ require "taiwan_payments/testing" # ここでは ECPay の代わりに、署名付きのコールバックを作ります
126
+ params = TaiwanPayments::Testing.ecpay_payment_notification(payments, order_no: "ORD1001", amount: 1200)
127
+
128
+ notification = payments.notification(params)
129
+ notification.paid? # => true
130
+ notification.order_no # => "ORD1001"
131
+ notification.amount # => 1200
132
+ notification.payment_method # => :credit
133
+ notification.status # => :paid
134
+ notification.ack # => "1|OK"
135
+ ```
136
+
137
+ `status` は `:paid`、`:awaiting_payment`、`:simulated`、`:failed` のいずれかです。`:awaiting_payment` は、ATM 振込用のバーチャル口座またはコンビニ決済コード(超商代碼)が発行済みで、購入者の支払いを待っている状態です。`:simulated` は、ECPay の管理画面で誰かが「支払いシミュレーション」(模擬付款)ボタンを押したことを表し、お金は動いていません。
138
+
139
+ コールバックが届かない場合は、ECPay に照会します。
140
+
141
+ <!-- runnable -->
142
+ ```ruby
143
+ trade = payments.query(order_no: "ORD1001") # ECPay にその注文がない場合は nil
144
+ trade.paid? # => true
145
+ trade.amount # => 1200
146
+ trade.trade_no # => "2612031748190001"
147
+ ```
148
+
149
+ クレジットカード決済は `payments.refund(order_no:, trade_no:, amount:)` で返金できます。すべてのオプション、各支払い方法、分割払い、売上確定(請款)と返金については、[ECPay payments](docs/ecpay-payments.md) を参照してください。
150
+
151
+ ## 電子発票
152
+
153
+ 発票の内容は一度だけ記述します。このモデルは ECPay に依存していないので、同じオブジェクトを ezPay でも使えるようになります。
154
+
155
+ <!-- runnable -->
156
+ ```ruby
157
+ invoice = TaiwanPayments::Invoice.new(
158
+ order_no: "ORD1001",
159
+ buyer: {email: "buyer@example.com"},
160
+ items: [
161
+ {name: "Oolong tea", quantity: 2, unit_price: 500},
162
+ {name: "Shipping", unit_price: 50}
163
+ ]
164
+ )
165
+ invoice.total # => 1050
166
+
167
+ invoices = TaiwanPayments::ECPay::InvoiceClient.sandbox
168
+ result = invoices.issue(invoice)
169
+ result.invoice_no # => "OQ13570511"
170
+ result.random_number # => "5248"
171
+ ```
172
+
173
+ 購入者が発票をどう受け取るかは、初めての人が戸惑いやすい部分です。モデルは一般的な既定値を選びます。必要に応じて上書きできます。
174
+
175
+ | 購入者の状況 | 渡す引数 | 結果 |
176
+ | --- | --- | --- |
177
+ | 特に指定しない | なし | ECPay の会員キャリア(會員載具)に保存されます。ECPay が購入者にメールを送ります。 |
178
+ | モバイルバーコード(手機條碼)を持っている | `carrier: "/ABC+123"` | 購入者自身のキャリアに保存されます。 |
179
+ | 発票を寄付したい | `donation_code: "168001"` | その慈善団体に寄付されます。 |
180
+ | 会社として購入する | `buyer: {tax_id: "53538851", name: "...", address: "...", email: "..."}` | 事業者向けの発票になり、印刷されます。 |
181
+ | 紙で受け取りたい | `print: true` と、購入者の氏名と住所 | 印刷されます。 |
182
+
183
+ 返金時の発票の処理は 2 通りあります。2 か月の課税期間内であれば、発票を無効化(作廢)します。期間を過ぎた場合や一部返金の場合は、折譲(折讓、発行後の減額)を発行します。折譲はクレジットノートにあたります。
184
+
185
+ <!-- runnable -->
186
+ ```ruby
187
+ invoices.void(invoice_no: "OQ13570511", issued_on: result.issued_at, reason: "Order cancelled") # => true
188
+
189
+ credit = invoices.allowance(invoice_no: "OQ13570511", issued_on: result.issued_at,
190
+ items: [{name: "Shipping", unit_price: 50}], email: "buyer@example.com")
191
+ credit.remaining_amount # => 1000
192
+
193
+ record = invoices.find(order_no: "ORD1001") # 該当する発票がない場合は nil
194
+ record.voided? # => false
195
+ record.total # => 1050
196
+ ```
197
+
198
+ [ECPay e-invoices](docs/ecpay-invoices.md) では、課税区分、ゼロ税率の販売、発票の予約発行、印刷、寄付コード(愛心碼)とモバイルバーコードの確認を説明しています。
199
+
200
+ ## 3 言語のエラーメッセージ
201
+
202
+ この gem が発生させる例外はすべて `TaiwanPayments::Error` で、英語・中国語・日本語のメッセージを持っています。ECPay 自身のメッセージは中国語なので、よくあるコードには英語と日本語の説明を用意しています。
203
+
204
+ <!-- runnable -->
205
+ ```ruby
206
+ begin
207
+ invoices.issue(invoice) # この注文番号は上で使用済みなので、ECPay が拒否します
208
+ rescue TaiwanPayments::ApiError => error
209
+ error.code # => "5070357"
210
+ error.message # => "ECPay error 5070357: This order number (RelateNumber) already has an invoice."
211
+ error.message_zh # => "ECPay 錯誤 5070357:B2C開立發票 自訂編號重覆,請重新設定"
212
+ error.message_ja # => "ECPay エラー 5070357:この注文番号(RelateNumber)の発票はすでに発行されています。"
213
+ end
214
+ ```
215
+
216
+ | エラー | 意味 |
217
+ | --- | --- |
218
+ | `ValidationError` | 入力がベンダーの規則に違反しています。ネットワーク呼び出しの前に発生します。`error.field` で該当する引数がわかります。 |
219
+ | `ApiError` | ベンダーがリクエストを拒否しました。`error.code` はベンダーのコードです。 |
220
+ | `SignatureError` | コールバックまたはレスポンスが、加盟店のキーで署名されていません。悪意のあるものとして扱ってください。 |
221
+ | `TransportError` | ネットワークでエラーが発生しました。`HttpError` と `RateLimitedError` はそのサブクラスです。 |
222
+ | `ConfigurationError` | 認証情報が不足しているか、形式が正しくありません。 |
223
+
224
+ `TaiwanPayments.locale = :ja` を設定すると、`message` が日本語のメッセージを返します。`:zh_tw` を設定すると中国語になります。
225
+
226
+ ## アプリのテスト
227
+
228
+ <!-- runnable -->
229
+ ```ruby
230
+ require "taiwan_payments/testing"
231
+
232
+ # コントローラーが本物として受け付けるコールバック:
233
+ params = TaiwanPayments::Testing.ecpay_payment_notification(payments, order_no: "ORD1001", amount: 1200)
234
+
235
+ # WebMock などでスタブするための、暗号化済みの API レスポンス:
236
+ body = TaiwanPayments::Testing.ecpay_invoice_issued_body(invoices, invoice_no: "AB12345678")
237
+ ```
238
+
239
+ ```ruby
240
+ # request spec の中で:
241
+ post webhooks_ecpay_payment_path, params: params
242
+ expect(response.body).to eq("1|OK")
243
+ ```
244
+
245
+ 失敗した決済、ATM 振込とコンビニ決済コード、送信内容の検証については、[Testing](docs/testing.md) を参照してください。
246
+
247
+ ## コマンドライン
248
+
249
+ ```sh
250
+ taiwan_payments glossary 載具 # キャリア(載具)とは何か、どのフィールドにあたるかを調べます
251
+ taiwan_payments glossary RelateNumber
252
+ taiwan_payments tax-id 53538851 # 会社の統一編号を検証します
253
+ taiwan_payments ecpay checkout --open # テスト用の決済ページをブラウザーで開きます
254
+ taiwan_payments ecpay query ORD1001 # ECPay に注文を照会します
255
+ taiwan_payments ecpay invoice # テスト用の発票を発行します
256
+ taiwan_payments ecpay mac 'A=1&B=2' # CheckMacValue を計算または検証します
257
+ taiwan_payments ecpay decrypt 'BASE64' # 電子発票のペイロードを読みます
258
+ ```
259
+
260
+ ## ドキュメント
261
+
262
+ 以下のガイドは、特に記載がない限り英語です。
263
+
264
+ - [API ガイド](https://randomizor.github.io/taiwan_payments/ja/):ベンダーの API を、どの言語でも使えるように解説(日本語、English、繁體中文)
265
+ - [用語集](https://randomizor.github.io/taiwan_payments/ja/glossary.html):決済と発票の用語を中国語、英語、日本語で対照
266
+ - [台湾決済入門](docs/taiwan-payments-101.ja.md)([English](docs/taiwan-payments-101.md)、[繁體中文](docs/taiwan-payments-101.zh-TW.md))
267
+ - [ECPay payments](docs/ecpay-payments.md):ECPay の決済
268
+ - [ECPay e-invoices](docs/ecpay-invoices.md):ECPay の電子発票
269
+ - [Webhooks](docs/webhooks.md):コールバックの受信
270
+ - [Rails](docs/rails.md)
271
+ - [Testing](docs/testing.md):テスト
272
+ - [Sandbox setup](docs/sandbox-setup.md):テスト環境の準備
273
+ - 用語集(日本語):[用語](docs/glossary/concepts.ja.md)、[ECPay の決済フィールド](docs/glossary/ecpay-payment.ja.md)、[ECPay の電子発票フィールド](docs/glossary/ecpay-invoice.ja.md)。英語版:[concepts](docs/glossary/concepts.md)、[ECPay payment fields](docs/glossary/ecpay-payment.md)、[ECPay e-invoice fields](docs/glossary/ecpay-invoice.md)
274
+
275
+ ## 開発
276
+
277
+ ```sh
278
+ bundle install
279
+ bundle exec rake # spec と lint
280
+ TAIWAN_PAYMENTS_SANDBOX=1 bundle exec rspec --tag sandbox # ECPay のテスト環境も呼び出します
281
+ ```
282
+
283
+ [CONTRIBUTING.md](CONTRIBUTING.md) を参照してください。セキュリティ上の問題は、[SECURITY.md](SECURITY.md) に記載の方法で報告してください。
284
+
285
+ ## サポート
286
+
287
+ この gem が役に立ったら、[コーヒーをおごって](https://buymeacoffee.com/randomizor)いただけるとうれしいです。
288
+
289
+ ## ライセンス
290
+
291
+ MIT ライセンスです。[LICENSE.txt](LICENSE.txt) を参照してください。
292
+
293
+ このプロジェクトは ECPay、NewebPay、ezPay とは関係ありません。
data/README.md ADDED
@@ -0,0 +1,291 @@
1
+ # taiwan_payments
2
+
3
+ **English** | [繁體中文](README.zh-TW.md) | [日本語](README.ja.md)
4
+
5
+ [![Buy me a coffee](https://img.shields.io/badge/Buy%20me%20a%20coffee-ffdd00?logo=buymeacoffee&logoColor=black)](https://buymeacoffee.com/randomizor)
6
+
7
+ Take payments and issue e-invoices in Taiwan from Ruby. ECPay (綠界) payments and e-invoices work today. NewebPay (藍新) payments and ezPay e-invoices are next.
8
+
9
+ ```ruby
10
+ payments = TaiwanPayments::ECPay::PaymentClient.sandbox # ECPay's public test merchant, nothing to sign up for
11
+ form = payments.checkout(order_no: "ORD1001", amount: 1200, description: "Order 1001",
12
+ items: ["Oolong tea x2"], return_url: "https://shop.example/webhooks/ecpay/payment")
13
+ form.to_html # send this to the customer's browser and they land on ECPay's payment page
14
+ ```
15
+
16
+ ## Why this gem
17
+
18
+ - **Runs in a minute.** ECPay's public test merchants are built in, so a checkout and an invoice work before you have an account.
19
+ - **Payments and e-invoices together.** Selling in Taiwan needs both: a payment, then a government-regulated invoice (統一發票) for it.
20
+ - **Written for people who do not read Chinese, and those who do.** English API and docs, errors in English, Chinese and Japanese, and a [glossary](docs/glossary/) that maps every vendor field to its Chinese name and its meaning.
21
+ - **No dependencies.** Plain Ruby on the standard library. The Rails integration loads only when Rails is there.
22
+ - **Verified, not guessed.** Signatures and encryption are checked against ECPay's published test vectors. Every API call was run against ECPay's stage environment and its real responses are the spec fixtures. 100% line and branch coverage.
23
+ - **Safe by default.** Callbacks must pass signature verification before you can read them. Keys and customer details are masked in logs. Nothing that moves money is retried automatically.
24
+ - **Testable.** Helpers build correctly signed fake callbacks and encrypted fake API responses, so your own specs need no network.
25
+
26
+ | | Payments | E-invoices |
27
+ | --- | --- | --- |
28
+ | ECPay 綠界 | Yes | Yes (B2C API, including invoices with a company tax ID) |
29
+ | NewebPay 藍新 | Planned for 0.2 | |
30
+ | ezPay 簡單付 | | Planned for 0.3 |
31
+
32
+ New to payments in Taiwan? Read [Taiwan payments 101](docs/taiwan-payments-101.md) first. It explains carriers, tax IDs, convenience store payments and the receipt lottery in ten minutes.
33
+
34
+ Not writing Ruby? The [API guide](https://randomizor.github.io/taiwan_payments/) explains the same requests, signatures and callbacks for any language, with runnable examples in curl, PHP, Node.js, Python and Go, in English, 繁體中文 and 日本語. Its [glossary](https://randomizor.github.io/taiwan_payments/glossary.html) gives terms such as 載具, 折讓 and 字軌 in Chinese, English and Japanese.
35
+
36
+ ## Install
37
+
38
+ ```ruby
39
+ # Gemfile
40
+ gem "taiwan_payments"
41
+ ```
42
+
43
+ Ruby 3.2 or newer. Rails is optional; 7.1 through 8.1 are tested.
44
+
45
+ ## Quick start with Rails
46
+
47
+ ```sh
48
+ bin/rails generate taiwan_payments:install
49
+ ```
50
+
51
+ This writes `config/initializers/taiwan_payments.rb`, a `Webhooks::EcpayController` and its route. Outside production the initializer uses ECPay's test merchants. For production it reads your keys from Rails credentials.
52
+
53
+ Send the customer to pay:
54
+
55
+ ```ruby
56
+ class CheckoutsController < ApplicationController
57
+ def create
58
+ order = current_user.orders.find(params[:order_id])
59
+ @form = TaiwanPayments.ecpay_payments.checkout(
60
+ order_no: order.number,
61
+ amount: order.total,
62
+ description: "Order #{order.number}",
63
+ items: order.line_items.map(&:name),
64
+ return_url: webhooks_ecpay_payment_url,
65
+ client_back_url: order_url(order)
66
+ )
67
+ end
68
+ end
69
+ ```
70
+
71
+ ```erb
72
+ <%# app/views/checkouts/create.html.erb %>
73
+ <%= taiwan_payments_form(@form) %>
74
+ ```
75
+
76
+ ECPay then calls your server when the customer has paid:
77
+
78
+ ```ruby
79
+ module Webhooks
80
+ class EcpayController < ApplicationController
81
+ include TaiwanPayments::Webhooks
82
+
83
+ def payment
84
+ notification = ecpay_payment_notification # verified, or the request is answered with 400
85
+ order = Order.find_by!(number: notification.order_no)
86
+ order.mark_paid!(trade_no: notification.trade_no) if notification.paid? && !order.paid?
87
+ render_ecpay_ack # ECPay retries until it reads "1|OK"
88
+ end
89
+ end
90
+ end
91
+ ```
92
+
93
+ ECPay needs a public URL for `return_url`, so use a tunnel such as ngrok or cloudflared in development. [Webhooks](docs/webhooks.md) covers the three kinds of callback and the mistakes that lose orders. [Rails](docs/rails.md) covers the helper, the concern and the generator.
94
+
95
+ ## Payments
96
+
97
+ <!-- runnable -->
98
+ ```ruby
99
+ require "taiwan_payments"
100
+
101
+ payments = TaiwanPayments::ECPay::PaymentClient.sandbox
102
+ # With your own keys:
103
+ # TaiwanPayments::ECPay::PaymentClient.new(merchant_id: "...", hash_key: "...", hash_iv: "...", env: :production)
104
+
105
+ form = payments.checkout(
106
+ order_no: "ORD1001", # yours, unique, up to 20 letters and digits
107
+ amount: 1200, # whole TWD
108
+ description: "Order 1001",
109
+ items: ["Oolong tea x2", "Shipping"],
110
+ return_url: "https://shop.example/webhooks/ecpay/payment",
111
+ payment_method: :credit # or :atm, :cvs, :barcode, :web_atm, :apple_pay, ... default :all
112
+ )
113
+
114
+ form.action_url # => "https://payment-stage.ecpay.com.tw/Cashier/AioCheckOut/V5"
115
+ form.fields["TotalAmount"] # => "1200"
116
+ form.fields["ChoosePayment"] # => "Credit"
117
+ ```
118
+
119
+ ECPay only accepts a checkout that arrives as a form POST from the customer's browser, so the gem hands you the form instead of calling ECPay itself. Render `form.to_html`, or build your own form from `form.action_url` and `form.fields`.
120
+
121
+ When the callback arrives, pass the POSTed fields to `notification`. It raises `TaiwanPayments::SignatureError` unless ECPay signed them with your keys.
122
+
123
+ <!-- runnable -->
124
+ ```ruby
125
+ require "taiwan_payments/testing" # builds a signed callback, standing in for ECPay here
126
+ params = TaiwanPayments::Testing.ecpay_payment_notification(payments, order_no: "ORD1001", amount: 1200)
127
+
128
+ notification = payments.notification(params)
129
+ notification.paid? # => true
130
+ notification.order_no # => "ORD1001"
131
+ notification.amount # => 1200
132
+ notification.payment_method # => :credit
133
+ notification.status # => :paid
134
+ notification.ack # => "1|OK"
135
+ ```
136
+
137
+ `status` is `:paid`, `:awaiting_payment` (an ATM account or convenience store code was issued and the customer still has to pay), `:simulated` (someone pressed "simulate payment" in ECPay's back office, so no money moved) or `:failed`.
138
+
139
+ If a callback never arrives, ask ECPay:
140
+
141
+ <!-- runnable -->
142
+ ```ruby
143
+ trade = payments.query(order_no: "ORD1001") # nil when ECPay has never seen the order
144
+ trade.paid? # => true
145
+ trade.amount # => 1200
146
+ trade.trade_no # => "2612031748190001"
147
+ ```
148
+
149
+ Card payments can be refunded with `payments.refund(order_no:, trade_no:, amount:)`. See [ECPay payments](docs/ecpay-payments.md) for every option, each payment method, instalments, and capture and refund.
150
+
151
+ ## E-invoices
152
+
153
+ Describe the invoice once. The model is not tied to ECPay, so the same object will work with ezPay.
154
+
155
+ <!-- runnable -->
156
+ ```ruby
157
+ invoice = TaiwanPayments::Invoice.new(
158
+ order_no: "ORD1001",
159
+ buyer: {email: "buyer@example.com"},
160
+ items: [
161
+ {name: "Oolong tea", quantity: 2, unit_price: 500},
162
+ {name: "Shipping", unit_price: 50}
163
+ ]
164
+ )
165
+ invoice.total # => 1050
166
+
167
+ invoices = TaiwanPayments::ECPay::InvoiceClient.sandbox
168
+ result = invoices.issue(invoice)
169
+ result.invoice_no # => "OQ13570511"
170
+ result.random_number # => "5248"
171
+ ```
172
+
173
+ How the buyer receives the invoice is the part that surprises newcomers. The model picks the usual default and lets you override it:
174
+
175
+ | The buyer | Pass | Result |
176
+ | --- | --- | --- |
177
+ | gave nothing special | nothing | Stored in ECPay's member carrier. ECPay emails the buyer. |
178
+ | has a mobile barcode (手機條碼) | `carrier: "/ABC+123"` | Stored in their own carrier |
179
+ | wants to donate it | `donation_code: "168001"` | Given to that charity |
180
+ | is a company | `buyer: {tax_id: "53538851", name: "...", address: "...", email: "..."}` | Business invoice, printed |
181
+ | wants paper | `print: true` and the buyer's name and address | Printed |
182
+
183
+ Refunds have two forms. Within the two-month tax period you void the invoice. After it, or for a partial refund, you issue an allowance (折讓), which is a credit note.
184
+
185
+ <!-- runnable -->
186
+ ```ruby
187
+ invoices.void(invoice_no: "OQ13570511", issued_on: result.issued_at, reason: "Order cancelled") # => true
188
+
189
+ credit = invoices.allowance(invoice_no: "OQ13570511", issued_on: result.issued_at,
190
+ items: [{name: "Shipping", unit_price: 50}], email: "buyer@example.com")
191
+ credit.remaining_amount # => 1000
192
+
193
+ record = invoices.find(order_no: "ORD1001") # nil when there is no such invoice
194
+ record.voided? # => false
195
+ record.total # => 1050
196
+ ```
197
+
198
+ [ECPay e-invoices](docs/ecpay-invoices.md) covers tax types, zero-rated sales, scheduled invoices, printing, and checking donation codes and mobile barcodes.
199
+
200
+ ## Errors in three languages
201
+
202
+ Everything the gem raises is a `TaiwanPayments::Error` carrying an English, a Chinese and a Japanese message. ECPay's own messages are Chinese, so common codes come with an English and a Japanese explanation.
203
+
204
+ <!-- runnable -->
205
+ ```ruby
206
+ begin
207
+ invoices.issue(invoice) # the order number was used above, so ECPay refuses
208
+ rescue TaiwanPayments::ApiError => error
209
+ error.code # => "5070357"
210
+ error.message # => "ECPay error 5070357: This order number (RelateNumber) already has an invoice."
211
+ error.message_zh # => "ECPay 錯誤 5070357:B2C開立發票 自訂編號重覆,請重新設定"
212
+ error.message_ja # => "ECPay エラー 5070357:この注文番号(RelateNumber)の発票はすでに発行されています。"
213
+ end
214
+ ```
215
+
216
+ | Error | Meaning |
217
+ | --- | --- |
218
+ | `ValidationError` | Your input breaks a vendor rule. Raised before any network call. `error.field` names the argument. |
219
+ | `ApiError` | The vendor refused the request. `error.code` is the vendor's code. |
220
+ | `SignatureError` | A callback or response was not signed with your keys. Treat it as hostile. |
221
+ | `TransportError` | The network failed. `HttpError` and `RateLimitedError` are subclasses. |
222
+ | `ConfigurationError` | Missing or malformed credentials. |
223
+
224
+ Set `TaiwanPayments.locale = :zh_tw` or `:ja` to make `message` return that language.
225
+
226
+ ## Testing your app
227
+
228
+ <!-- runnable -->
229
+ ```ruby
230
+ require "taiwan_payments/testing"
231
+
232
+ # A callback your controller will accept as genuine:
233
+ params = TaiwanPayments::Testing.ecpay_payment_notification(payments, order_no: "ORD1001", amount: 1200)
234
+
235
+ # An encrypted API response to stub with WebMock or similar:
236
+ body = TaiwanPayments::Testing.ecpay_invoice_issued_body(invoices, invoice_no: "AB12345678")
237
+ ```
238
+
239
+ ```ruby
240
+ # In a request spec:
241
+ post webhooks_ecpay_payment_path, params: params
242
+ expect(response.body).to eq("1|OK")
243
+ ```
244
+
245
+ See [Testing](docs/testing.md) for failed payments, ATM and convenience store codes, and asserting on what you sent.
246
+
247
+ ## Command line
248
+
249
+ ```sh
250
+ taiwan_payments glossary 載具 # what is a carrier, and which field is it?
251
+ taiwan_payments glossary RelateNumber
252
+ taiwan_payments tax-id 53538851 # check a company tax ID
253
+ taiwan_payments ecpay checkout --open # open a test payment page in your browser
254
+ taiwan_payments ecpay query ORD1001 # ask ECPay about an order
255
+ taiwan_payments ecpay invoice # issue a test invoice
256
+ taiwan_payments ecpay mac 'A=1&B=2' # compute or verify a CheckMacValue
257
+ taiwan_payments ecpay decrypt 'BASE64' # read an e-invoice payload
258
+ ```
259
+
260
+ ## Documentation
261
+
262
+ - [API guide](https://randomizor.github.io/taiwan_payments/): the vendors' APIs explained for any language, in English, 繁體中文 and 日本語
263
+ - [Glossary of terms](https://randomizor.github.io/taiwan_payments/glossary.html): payment and invoice vocabulary side by side in Chinese, English and Japanese
264
+ - [Taiwan payments 101](docs/taiwan-payments-101.md) ([繁體中文](docs/taiwan-payments-101.zh-TW.md), [日本語](docs/taiwan-payments-101.ja.md))
265
+ - [ECPay payments](docs/ecpay-payments.md)
266
+ - [ECPay e-invoices](docs/ecpay-invoices.md)
267
+ - [Webhooks](docs/webhooks.md)
268
+ - [Rails](docs/rails.md)
269
+ - [Testing](docs/testing.md)
270
+ - [Sandbox setup](docs/sandbox-setup.md)
271
+ - Glossaries: [concepts](docs/glossary/concepts.md), [ECPay payment fields](docs/glossary/ecpay-payment.md), [ECPay e-invoice fields](docs/glossary/ecpay-invoice.md). In Japanese: [用語](docs/glossary/concepts.ja.md), [決済フィールド](docs/glossary/ecpay-payment.ja.md), [電子発票フィールド](docs/glossary/ecpay-invoice.ja.md)
272
+
273
+ ## Development
274
+
275
+ ```sh
276
+ bundle install
277
+ bundle exec rake # specs and lint
278
+ TAIWAN_PAYMENTS_SANDBOX=1 bundle exec rspec --tag sandbox # also call ECPay's stage environment
279
+ ```
280
+
281
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Report security problems as described in [SECURITY.md](SECURITY.md).
282
+
283
+ ## Support
284
+
285
+ If this gem saved you time, you can [buy me a coffee](https://buymeacoffee.com/randomizor).
286
+
287
+ ## License
288
+
289
+ MIT. See [LICENSE.txt](LICENSE.txt).
290
+
291
+ This project is not affiliated with ECPay, NewebPay or ezPay.