taiwan-payment-skill 1.5.13 → 1.5.15

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 (53) hide show
  1. package/README.md +104 -105
  2. package/assets/taiwan-payment/CLAUDE.md +1 -1
  3. package/assets/taiwan-payment/EXAMPLES.md +36 -26
  4. package/assets/taiwan-payment/README.md +104 -105
  5. package/assets/taiwan-payment/README.zh-TW.md +138 -0
  6. package/assets/taiwan-payment/SKILL.md +131 -860
  7. package/assets/taiwan-payment/data/error-codes-payuni-1.csv +786 -786
  8. package/assets/taiwan-payment/data/error-codes-payuni-2.csv +719 -719
  9. package/assets/taiwan-payment/data/error-codes-tappay.csv +474 -474
  10. package/assets/taiwan-payment/data/error-codes.csv +1047 -1004
  11. package/assets/taiwan-payment/data/field-mappings.csv +20 -20
  12. package/assets/taiwan-payment/data/operations.csv +26 -26
  13. package/assets/taiwan-payment/data/payment-methods.csv +42 -42
  14. package/assets/taiwan-payment/data/pending.csv +59 -0
  15. package/assets/taiwan-payment/data/providers.csv +15 -15
  16. package/assets/taiwan-payment/data/reasoning.csv +46 -46
  17. package/assets/taiwan-payment/data/troubleshooting.csv +47 -47
  18. package/assets/taiwan-payment/evals/RESULTS.md +33 -0
  19. package/assets/taiwan-payment/evals/cases.json +193 -0
  20. package/assets/taiwan-payment/evals/grade.py +121 -0
  21. package/assets/taiwan-payment/examples/linepay-payment-example.py +18 -23
  22. package/assets/taiwan-payment/examples/newebpay-payment-example.py +4 -2
  23. package/assets/taiwan-payment/examples/paynow-payment-example.py +31 -39
  24. package/assets/taiwan-payment/examples/payuni-payment-example.py +3 -3
  25. package/assets/taiwan-payment/examples/pchomepay-payment-example.py +6 -3
  26. package/assets/taiwan-payment/examples/shopline-payment-example.py +85 -89
  27. package/assets/taiwan-payment/examples/tappay-payment-example.py +25 -22
  28. package/assets/taiwan-payment/references/audit-20261117.md +432 -0
  29. package/assets/taiwan-payment/references/ecpay-payment-api.md +78 -28
  30. package/assets/taiwan-payment/references/ezpay-payment-api.md +18 -3
  31. package/assets/taiwan-payment/references/gomypay-payment-api.md +21 -13
  32. package/assets/taiwan-payment/references/implementation-guide.md +771 -0
  33. package/assets/taiwan-payment/references/jkopay-payment-api.md +7 -6
  34. package/assets/taiwan-payment/references/linepay-payment-api.md +286 -199
  35. package/assets/taiwan-payment/references/newebpay-payment-api.md +52 -26
  36. package/assets/taiwan-payment/references/opay-payment-api.md +33 -18
  37. package/assets/taiwan-payment/references/paynow-payment-api.md +215 -114
  38. package/assets/taiwan-payment/references/payuni-payment-api.md +373 -337
  39. package/assets/taiwan-payment/references/pchomepay-payment-api.md +26 -23
  40. package/assets/taiwan-payment/references/shopline-payment-api.md +213 -178
  41. package/assets/taiwan-payment/references/smilepay-payment-api.md +6 -0
  42. package/assets/taiwan-payment/references/sunpay-payment-api.md +33 -21
  43. package/assets/taiwan-payment/references/tappay-payment-api.md +434 -302
  44. package/assets/taiwan-payment/references/twqr-ewallet-landscape.md +2 -2
  45. package/assets/taiwan-payment/requirements.txt +4 -0
  46. package/assets/taiwan-payment/scripts/check_numbers.py +205 -0
  47. package/assets/taiwan-payment/scripts/core.py +17 -0
  48. package/assets/taiwan-payment/scripts/search.py +15 -2
  49. package/assets/taiwan-payment/scripts/test_payment.py +38 -16
  50. package/assets/taiwan-payment/scripts/test_skill.py +202 -0
  51. package/assets/templates/base/skill-content.md +129 -856
  52. package/dist/index.js +10 -1
  53. package/package.json +1 -1
package/README.md CHANGED
@@ -1,139 +1,138 @@
1
- <h1 align="center">taiwan-payment-skill</h1>
1
+ # taiwan-payment
2
2
 
3
- <h3 align="center">台灣金流 AI 開發技能包</h3>
3
+ A Claude skill for integrating Taiwan payment gateways: request signing, encryption, payment callbacks, refunds and error codes, based on each provider's official documentation.
4
4
 
5
- <p align="center">
6
- <strong>14 家金流平台一次串接</strong>
7
- </p>
5
+ [![npm version](https://img.shields.io/npm/v/taiwan-payment-skill)](https://www.npmjs.com/package/taiwan-payment-skill)
6
+ [![License: MIT](https://img.shields.io/github/license/Moksa1123/taiwan-ecommerce-toolkit)](https://github.com/Moksa1123/taiwan-ecommerce-toolkit/blob/main/LICENSE)
8
7
 
9
- <p align="center">
10
- ECPay · NewebPay · PAYUNi · SmilePay · PChomePay · ezPay · PayNow · Shopline · LINE Pay · TapPay
11
- </p>
8
+ English | [繁體中文](https://github.com/Moksa1123/taiwan-ecommerce-toolkit/blob/main/taiwan-payment/README.zh-TW.md)
12
9
 
13
- <p align="center">
14
- <a href="https://www.npmjs.com/package/taiwan-payment-skill"><img src="https://img.shields.io/npm/v/taiwan-payment-skill?style=flat-square&logo=npm" alt="npm version"></a>
15
- <a href="https://www.npmjs.com/package/taiwan-payment-skill"><img src="https://img.shields.io/npm/dm/taiwan-payment-skill?style=flat-square&label=downloads" alt="npm downloads"></a>
16
- <img src="https://img.shields.io/badge/providers-14-success?style=flat-square" alt="14 Providers">
17
- <img src="https://img.shields.io/badge/AI%20platforms-14-blue?style=flat-square" alt="14 AI Platforms">
18
- <a href="https://github.com/Moksa1123/taiwan-ecommerce-toolkit/blob/main/LICENSE"><img src="https://img.shields.io/github/license/Moksa1123/taiwan-ecommerce-toolkit?style=flat-square" alt="License"></a>
19
- </p>
10
+ This is an unofficial project. It is not affiliated with or endorsed by ECPay, NewebPay, PAYUNi, LINE, TapPay, JKOPAY or any other company named here. Brand names are written the way each company writes them and belong to their owners.
20
11
 
21
- <p align="center">
22
- <a href="https://paypal.me/cccsubcom"><img src="https://img.shields.io/badge/PayPal-支持開發-00457C?style=for-the-badge&logo=paypal&logoColor=white" alt="PayPal"></a>
23
- </p>
12
+ ## What it does
24
13
 
25
- ---
14
+ - Covers 14 Taiwan payment providers: ECPay, NewebPay, PAYUNi, SmilePay, PChomePay, ezPay, PayNow, Shopline Payments, LINE Pay v4, TapPay, O'Pay, JKOPAY, SunPay and GoMyPay.
15
+ - Gives Claude each provider's signing and encryption rules (CheckMacValue, TradeSha, AES-256-CBC, AES-256-GCM, RSA, JWT, HMAC-SHA256) with runnable Python examples.
16
+ - Searches 3212 rows of official data offline with `scripts/search.py`: error codes, API operations, field mappings, payment methods and troubleshooting notes.
17
+ - Suggests a provider from plain-language requirements with `scripts/recommend.py`.
18
+ - Links each task (credit card, ATM, CVS code, e-wallet, Apple Pay, Google Pay, TWQR, BNPL, recurring billing, refunds) to the right reference file in `references/`.
26
19
 
27
- ## 安裝
20
+ ## When to use
28
21
 
29
- ```bash
30
- npm install -g taiwan-payment-skill
31
- ```
22
+ Use it when you are:
32
23
 
33
- ## 快速開始
24
+ - building or debugging a checkout that talks to one of the providers above;
25
+ - verifying a payment notification (CheckMacValue, TradeSha, HashInfo, webhook signatures);
26
+ - looking up what a provider's error or status code means;
27
+ - choosing between providers for a project.
34
28
 
35
- ```bash
36
- cd /path/to/your/project
29
+ Use something else for:
37
30
 
38
- taiwan-payment init # 互動式
39
- taiwan-payment init --ai claude # Claude Code
40
- taiwan-payment init --ai cursor # Cursor
41
- taiwan-payment init --ai windsurf # Windsurf
42
- taiwan-payment init --ai all # 全部安裝
43
- ```
31
+ - issuing, voiding or adjusting e-invoices: use [taiwan-invoice](https://github.com/Moksa1123/taiwan-ecommerce-toolkit/tree/main/taiwan-invoice);
32
+ - shipping, convenience-store pickup, store maps or tracking, even with ECPay, NewebPay or PAYUNi: use [taiwan-logistics](https://github.com/Moksa1123/taiwan-ecommerce-toolkit/tree/main/taiwan-logistics);
33
+ - payment providers outside Taiwan, or direct bank and card-network integrations: not covered.
34
+
35
+ ## Install
36
+
37
+ Requirements: Python 3 for the scripts, which use only the standard library. The files in `examples/` and the network options of `scripts/test_payment.py` also need `pycryptodome` (AES) and `requests`; install them with `pip install -r requirements.txt`. Node.js 18 or later is needed only for the npx installer. Works on Windows, macOS and Linux.
44
38
 
45
- 安裝完後,AI 助手裡用自然語言:
39
+ Claude Code plugin (installs all three Taiwan skills: invoice, payment, logistics):
46
40
 
41
+ ```text
42
+ /plugin marketplace add Moksa1123/taiwan-ecommerce-toolkit
43
+ /plugin install taiwan-ecommerce@taiwan-ecommerce-toolkit
47
44
  ```
48
- 建立 ECPay 信用卡付款訂單,金額 2500 元
49
- NewebPay MPG 整合 LINE Pay + Apple Pay
50
- PChomePay 拍錢包訂單,5% P 幣回饋
51
- PayNow PaymentIntent,啟用 LINE Pay 線上+線下扣款
52
- TapPay 用 Prime 一次付清,remember=true 存成 card_token 供下次自動扣款
45
+
46
+ npx (copies the skill into the current project; `--ai` also accepts other agents such as `cursor` or `codex`, `--global` installs into your home directory):
47
+
48
+ ```bash
49
+ npx taiwan-payment-skill@1.5.15 init --ai claude
53
50
  ```
54
51
 
55
- ---
52
+ Manual copy:
53
+
54
+ ```bash
55
+ git clone https://github.com/Moksa1123/taiwan-ecommerce-toolkit.git
56
+ cp -r taiwan-ecommerce-toolkit/taiwan-payment ~/.claude/skills/
57
+ ```
56
58
 
57
- ## 14 家金流平台
59
+ ## Quick start
58
60
 
59
- | 服務商 | 加密 / 認證 | 特色 |
60
- |---|---|---|
61
- | **ECPay 綠界** | SHA256 CheckMacValue | 市佔率最高、文檔最完整 |
62
- | **NewebPay 藍新** | AES-256-CBC + SHA256 | MPG 整合、信用卡記憶、13 種支付 |
63
- | **PAYUNi 統一** | AES-256-GCM + SHA256 | RESTful JSON、AFTEE、iCash |
64
- | **SmilePay 速買配** | Verify_key + 加權檢核碼 | 無 AES、ibon / FamiPort 直接打單 |
65
- | **PChomePay 拍錢包** | Basic Auth → 8h pcpay-token | PChome 生態、5% P 幣回饋、金物流二合一 |
66
- | **ezPay 簡單付** | AES-256-CBC(32-byte padding)+ SHA256 | 電子支付機構;境內 TWQR / ezPay 錢包,跨境支付寶 / 微信 |
67
- | **PayNow 立吉富** | JWT Bearer (現代) / 動態 AES-256 (傳統) | 雙 API、Stripe-like、Apple Pay 完整 |
68
- | **Shopline Payments** | merchantId + apiKey | 金額以分為單位、HMAC-SHA256 webhook |
69
- | **LINE Pay v4** | Channel ID/Secret + HMAC-SHA256 + Nonce | Request→Confirm 兩段、Preapproved Pay |
70
- | **TapPay** | Partner Key (Header) | PCI 隔離、Prime 兩段式、Card Token |
71
- | **O'Pay 歐付寶** | SHA256 CheckMacValue(同 ECPay) | 與 ECPay 同源架構、AccountLink 銀行快付、延遲撥款 |
72
- | **JKOPAY 街口** | api-key Header + HMAC-SHA256 digest | 線上支付 / POS / 授權扣款 |
73
- | **SunPay 紅陽** | RSA 分段加密 + SHA256 check_value | 金流 + 發票 + 超商代收 |
74
- | **GoMyPay** | 需向 GoMyPay 申請規格 | 完整 API 規格未公開 |
61
+ Ask Claude, for example:
75
62
 
76
- O'Pay、GoMyPay 以外皆附可執行 Python 範例,加解密以官方測試向量驗證;錯誤碼見 `data/error-codes*.csv`。
63
+ - "Create an ECPay credit-card order in Python and verify the payment notification."
64
+ - "My NewebPay TradeInfo fails to decrypt. What is wrong with my padding?"
65
+ - "Which provider should I use for LINE Pay plus recurring card payments?"
77
66
 
78
- ## 技能包內容
67
+ Or search the data yourself from the skill folder:
79
68
 
69
+ ```bash
70
+ python3 scripts/search.py "10100058" --domain error --max 1
80
71
  ```
81
- taiwan-payment/
82
- ├── SKILL.md # AI 技能主文檔
83
- ├── EXAMPLES.md # 實戰範例集
84
- ├── references/ # 各服務商 API 規格
85
- │ ├── ecpay-payment-api.md
86
- │ ├── newebpay-payment-api.md
87
- │ ├── payuni-payment-api.md
88
- │ ├── smilepay-payment-api.md # Mid_smilepay 加權檢核碼
89
- │ ├── pchomepay-payment-api.md # 含 8h token 流程
90
- │ ├── ezpay-payment-api.md # 電子支付平台 + 跨境(依官方手冊)
91
- │ ├── paynow-payment-api.md # 雙 API 並行
92
- │ ├── shopline-payment-api.md # Redirect + Embedded
93
- │ ├── linepay-payment-api.md # HMAC + Preapproved
94
- │ ├── tappay-payment-api.md # Prime + Token 重複扣款
95
- │ ├── opay-payment-api.md
96
- │ ├── jkopay-payment-api.md
97
- │ ├── sunpay-payment-api.md
98
- │ ├── gomypay-payment-api.md
99
- │ └── twqr-ewallet-landscape.md # 電子支付/TWQR 生態
100
- ├── examples/ # 可執行 Python 範例
101
- └── data/ # search / recommend 使用的 CSV
102
- ├── providers.csv
103
- ├── operations.csv
104
- ├── payment-methods.csv
105
- ├── error-codes*.csv # 各家官方錯誤碼(依 256 KiB 上限分檔)
106
- └── ...
72
+
73
+ Expected output (shortened):
74
+
75
+ ```text
76
+ 搜索域: error
77
+ 找到 1 筆結果
78
+ [結果 #1] 評分: 6.04
79
+ Provider : ecpay
80
+ Code : 10100058
81
+ Message Zh : Pay fail(3D 驗證未完成)
82
+ Solution : 請消費者更換瀏覽器或裝置、關閉 VPN、切換網路取得新 IP;...
83
+ Doc Url : https://developers.ecpay.com.tw/
84
+ Trust : 官方文件
107
85
  ```
108
86
 
109
- ## CLI 指令
87
+ ## Trigger phrases
110
88
 
111
- ```bash
112
- taiwan-payment list # 列出 AI 平台
113
- taiwan-payment info # 技能資訊
114
- taiwan-payment update # 檢查更新
115
- taiwan-payment init --force # 覆蓋安裝
116
- taiwan-payment init --global # 全域安裝
117
- ```
89
+ English: Taiwan payment gateway, ECPay, NewebPay, PAYUNi, LINE Pay, TapPay, JKOPAY, credit card payment, ATM virtual account, CVS payment code, Apple Pay, Google Pay, TWQR, BNPL, CheckMacValue, payment notification, refund, recurring payment.
90
+
91
+ 中文:金流串接、綠界、藍新、統一金流、信用卡付款、ATM 虛擬帳號、超商代碼、LINE Pay、Apple Pay、街口、CheckMacValue、TradeSha、付款通知、退款、定期定額。
118
92
 
119
- ## 14 個 AI 平台支援
93
+ ## What it runs and connects to
120
94
 
121
- Claude Code · Cursor · Windsurf · Antigravity · GitHub Copilot · Kiro · Codex · Qoder · Cline · Gemini · Trae · OpenCode · Continue · CodeBuddy
95
+ The skill is Markdown documentation, CSV data and local Python scripts. It never sends data anywhere on its own. Network calls happen only when you run a connectivity option of the test script or run an example file.
122
96
 
123
- ## 相關套件
97
+ | Script | What it does | Network | Files written |
98
+ |---|---|---|---|
99
+ | `scripts/search.py` | Searches `data/*.csv` | None | None |
100
+ | `scripts/recommend.py` | Suggests a provider from `data/*.csv` | None | None |
101
+ | `scripts/test_payment.py` | Known-answer tests of ECPay, NewebPay and PAYUNi signing; offline by default | `--live`: HEAD request to the sandbox of ECPay (`payment-stage.ecpay.com.tw`), NewebPay (`ccore.newebpay.com`) and PAYUNi (`sandbox-api.payuni.com.tw`). `--query`: POST to the ECPay sandbox order query | `--create`: an `ecpay_test_<order>.html` form in the current folder |
102
+ | `scripts/check_numbers.py` | Checks that every number in `SKILL.md` and these READMEs matches the data | None | With `--fix`, those three files |
103
+ | `scripts/test_skill.py` | Self-test; runs the checks above offline | None | None |
104
+ | `examples/*.py` | Reference clients for each provider | When run directly, calls the sandbox or production host defined at the top of that file | None |
124
105
 
125
- 本套件是 **[Taiwan E-Commerce Toolkit](https://github.com/Moksa1123/taiwan-ecommerce-toolkit)** 的一部分:
106
+ Credentials (merchant ID, HashKey and HashIV, LINE Pay Channel ID and Channel Secret, TapPay Partner Key, API keys) are supplied by you in your own code or configuration, for example environment variables. The repository stores no real credentials. Test values that appear in the docs and scripts are the providers' published sandbox values.
126
107
 
127
- - [taiwan-invoice-skill](https://www.npmjs.com/package/taiwan-invoice-skill) — 7 家電子發票加值中心 + 財政部大平台查詢
128
- - [taiwan-logistics-skill](https://www.npmjs.com/package/taiwan-logistics-skill) — 7 家物流 aggregator + HCT 直連 + 2 家即時配送
108
+ ## How it's verified
129
109
 
130
- ## 授權
110
+ - Data source: official provider documentation, PDF specifications and official SDKs or plugins. Every source is registered in [`sources/official-sources.json`](https://github.com/Moksa1123/taiwan-ecommerce-toolkit/blob/main/sources/official-sources.json), and each data row carries `doc_url` and `trust`.
111
+ - Last audit against the official docs: 2026-11-17, recorded in [`references/audit-20261117.md`](https://github.com/Moksa1123/taiwan-ecommerce-toolkit/blob/main/taiwan-payment/references/audit-20261117.md).
112
+ - Self-test: `python3 scripts/test_skill.py` runs 50 checks, 0 failures (run on 2026-11-17).
113
+ - Evals: on the 10 scored questions, Claude answered 10 correctly with the skill and 0 without it. See [`evals/RESULTS.md`](https://github.com/Moksa1123/taiwan-ecommerce-toolkit/blob/main/taiwan-payment/evals/RESULTS.md).
114
+ - CI runs `scripts/verify-examples.py`, which compares the example code byte for byte with expected values produced by the providers' own SDKs and spec samples ([`tests/vectors/`](https://github.com/Moksa1123/taiwan-ecommerce-toolkit/tree/main/tests/vectors)).
131
115
 
132
- [MIT License](https://github.com/Moksa1123/taiwan-ecommerce-toolkit/blob/main/LICENSE)
116
+ ## Limits
117
+
118
+ - O'Pay and GoMyPay have no runnable example. The full GoMyPay API specification is not public; you have to request it from GoMyPay.
119
+ - The JKOPAY documentation site did not resolve during the latest audit, so the JKOPAY reference is based on the last saved copy of the official pages.
120
+ - Known gaps and unanswered questions are tracked in [`data/pending.csv`](https://github.com/Moksa1123/taiwan-ecommerce-toolkit/blob/main/taiwan-payment/data/pending.csv).
121
+ - Rows marked `trust=推論` (recommendations, troubleshooting) are inferred from the official docs. Treat them as advice, not as provider rules.
122
+
123
+ ## Repo layout
124
+
125
+ ```text
126
+ taiwan-payment/
127
+ ├── SKILL.md # instructions Claude reads
128
+ ├── EXAMPLES.md # longer code examples
129
+ ├── references/ # one API reference per provider, plus the audit log
130
+ ├── examples/ # runnable Python clients
131
+ ├── data/ # CSV data for search.py and recommend.py; pending.csv
132
+ ├── scripts/ # search, recommend, tests, number check
133
+ └── evals/ # eval questions, grader and results
134
+ ```
133
135
 
134
- ---
136
+ ## License & author
135
137
 
136
- <p align="center">
137
- <sub>Made by <strong>Moksa</strong></sub><br>
138
- <sub>service@moksaweb.com</sub>
139
- </p>
138
+ MIT License. Made by Moksa ([moksaweb.com](https://moksaweb.com)). Part of [Taiwan E-commerce Toolkit](https://github.com/Moksa1123/taiwan-ecommerce-toolkit).
@@ -319,7 +319,7 @@ HashIV: 請至後台申請
319
319
  HashKey: 請至後台申請
320
320
  HashIV: 請至後台申請
321
321
  測試網址: https://sandbox-api.payuni.com.tw/api/upp
322
- 測試卡號: 4000-2211-1111-1111
322
+ 測試卡號: 4147631000000001(官方 page 374)
323
323
  ```
324
324
 
325
325
  ## Publishing Workflow
@@ -317,7 +317,7 @@ class PAYUNiService {
317
317
  method: 'POST',
318
318
  fields: {
319
319
  MerID: this.merID,
320
- Version: '1.0',
320
+ Version: '2.0',
321
321
  EncryptInfo: encryptInfo,
322
322
  HashInfo: this.hashInfo(encryptInfo),
323
323
  },
@@ -982,7 +982,7 @@ export async function POST(request: Request) {
982
982
  status: 'PENDING',
983
983
  amount: plan.price,
984
984
  frequency: plan.frequency, // 'M' = 月, 'Y' = 年
985
- totalTimes: plan.totalTimes || 999, // 999 = 無限次
985
+ totalTimes: plan.totalTimes || (plan.frequency === 'Y' ? 99 : 999), // ECPay 上限:D、M 999 次,Y 99 次,沒有無限次
986
986
  }
987
987
  })
988
988
 
@@ -1031,6 +1031,7 @@ export async function POST(request: Request) {
1031
1031
  // app/api/subscription/callback/route.ts
1032
1032
 
1033
1033
  import { prisma } from '@/lib/prisma'
1034
+ import { ECPayPaymentService } from '@/lib/services/ecpay-payment-service'
1034
1035
 
1035
1036
  export async function POST(request: Request) {
1036
1037
  const formData = await request.formData()
@@ -1038,15 +1039,18 @@ export async function POST(request: Request) {
1038
1039
 
1039
1040
  console.log('[INFO] 收到訂閱授權通知:', params)
1040
1041
 
1042
+ if (!new ECPayPaymentService(false).verifyCallback(params)) {
1043
+ return new Response('0|CheckMacValue Error', { status: 400 })
1044
+ }
1045
+
1041
1046
  const merchantTradeNo = params.MerchantTradeNo
1042
- const isPaid = params.RtnCode === '1'
1047
+ const isPaid = params.RtnCode === '1' && params.SimulatePaid !== '1'
1043
1048
 
1044
- // 更新訂閱狀態
1049
+ // 第 1 次授權結果送 ReturnURL;第 2 次起送 PeriodReturnURL,MerchantTradeNo 每期相同
1045
1050
  await prisma.subscription.update({
1046
1051
  where: { merchantTradeNo },
1047
1052
  data: {
1048
- status: isPaid ? 'ACTIVE' : 'FAILED',
1049
- gwsr: params.gwsr, // 綠界週期編號(重要:後續扣款需要)
1053
+ status: isPaid ? 'ACTIVE' : 'FAILED', // 第 1 次失敗不會進排程,須重建訂單
1050
1054
  firstPaidAt: isPaid ? new Date() : null,
1051
1055
  }
1052
1056
  })
@@ -1063,6 +1067,7 @@ export async function POST(request: Request) {
1063
1067
  // app/api/subscription/periodic-callback/route.ts
1064
1068
 
1065
1069
  import { prisma } from '@/lib/prisma'
1070
+ import { ECPayPaymentService } from '@/lib/services/ecpay-payment-service'
1066
1071
 
1067
1072
  export async function POST(request: Request) {
1068
1073
  const formData = await request.formData()
@@ -1070,13 +1075,16 @@ export async function POST(request: Request) {
1070
1075
 
1071
1076
  console.log('[INFO] 收到週期扣款通知:', params)
1072
1077
 
1073
- const gwsr = params.gwsr // 綠界週期編號
1074
- const isPaid = params.RtnCode === '1'
1075
- const execTimes = parseInt(params.ExecTimes) // 當前第幾次扣款
1078
+ if (!new ECPayPaymentService(false).verifyCallback(params)) {
1079
+ return new Response('0|CheckMacValue Error', { status: 400 })
1080
+ }
1081
+
1082
+ const isPaid = params.RtnCode === '1' && params.SimulatePaid !== '1'
1083
+ const execTimes = parseInt(params.TotalSuccessTimes) // 已成功次數;ExecTimes 是訂單設定的總次數
1076
1084
 
1077
- // 1. 更新訂閱記錄
1085
+ // 1. 用 MerchantTradeNo 找訂閱(每期相同;gwsr 是本次授權單號,每期不同)
1078
1086
  const subscription = await prisma.subscription.findFirst({
1079
- where: { gwsr }
1087
+ where: { merchantTradeNo: params.MerchantTradeNo }
1080
1088
  })
1081
1089
 
1082
1090
  if (subscription) {
@@ -1086,7 +1094,8 @@ export async function POST(request: Request) {
1086
1094
  subscriptionId: subscription.id,
1087
1095
  merchantTradeNo: params.MerchantTradeNo,
1088
1096
  tradeNo: params.TradeNo,
1089
- amount: parseInt(params.amount),
1097
+ amount: parseInt(params.Amount), // PeriodReturnURL 欄位是大寫 Amount
1098
+ gwsr: params.gwsr, // 本次授權交易單號
1090
1099
  execTimes: execTimes,
1091
1100
  status: isPaid ? 'PAID' : 'FAILED',
1092
1101
  paidAt: isPaid ? new Date() : null,
@@ -1165,7 +1174,7 @@ console.assert(got === 'D5499ADD6F1D331B09D196D56C672A3A6E0D4FE31C1B19E10378B67A
1165
1174
 
1166
1175
  ### 錯誤 2: AES 加解密錯誤
1167
1176
 
1168
- **錯誤訊息:** NewebPay 回傳 `MPG02001`(檢查碼錯誤);PAYUNi 解密失敗或 HashInfo 不符
1177
+ **錯誤訊息:** NewebPay 回傳 `MPG03009`(交易資料 SHA256 檢查不符或 TradeInfo 解密失敗);PAYUNi 解密失敗或 HashInfo 不符
1169
1178
 
1170
1179
  **NewebPay 常見錯誤:**
1171
1180
 
@@ -1204,7 +1213,7 @@ console.assert(HashInfo === '6563710212EB74701B34AB4D510DC05AC0775CFCEEB1FBE44CF
1204
1213
  SmilePay 採用 `Verify_key` + `mid` 共享密鑰機制,無 AES 加密,整合最簡單。回應為 XML(部分欄位可能是 BIG-5 編碼,需轉 UTF-8)。
1205
1214
 
1206
1215
  ### 完整 Python 範例
1207
- 請見 [`examples/smilepay-payment-example.py`](examples/smilepay-payment-example.py) — 涵蓋 ATM (Pay_zg=2) / Barcode (Pay_zg=3) / ibon (Pay_zg=4) / FamiPort (Pay_zg=6) / 信用卡 (Pay_zg=1) / 信用卡分期 / 聯合信用卡 (Pay_zg=11) 七種付款方式。
1216
+ 請見 [`examples/smilepay-payment-example.py`](examples/smilepay-payment-example.py) — 涵蓋 ATM (Pay_zg=2) / Barcode (Pay_zg=3) / ibon (Pay_zg=4) / FamiPort (Pay_zg=6) / 信用卡 (Pay_zg=1) / 信用卡分期 / 銀聯卡 (Pay_zg=11) 七種付款方式。
1208
1217
 
1209
1218
  ### 五大踩坑
1210
1219
 
@@ -1216,7 +1225,7 @@ SmilePay 採用 `Verify_key` + `mid` 共享密鑰機制,無 AES 加密,整
1216
1225
 
1217
1226
  ---
1218
1227
 
1219
- ## PChomePay 拍錢包範例
1228
+ ## PChomePay 支付連範例
1220
1229
 
1221
1230
  PChomePay 採用 **HTTP Basic Auth → pcpay-token** 兩階段認證:先用 APP_ID + SECRET 取得 token(8 小時有效),後續 API 帶 `pcpay-token` header。
1222
1231
 
@@ -1225,7 +1234,7 @@ PChomePay 採用 **HTTP Basic Auth → pcpay-token** 兩階段認證:先用 AP
1225
1234
 
1226
1235
  ### 四大要點
1227
1236
 
1228
- 1. **白名單 IP**:PChomePay notify 的來源 IP 是 `113.196.231.190`,**必須加入後台白名單**。
1237
+ 1. **白名單 IP**:PChomePay notify 的來源 IP 是 `113.196.231.190`,有防火牆時**必須放行此 IP**(後台的 IP 白名單則是限制「你的伺服器」呼叫 API 的來源)。
1229
1238
  2. **Token 機制**:開立 token 預設 28800 秒(8h)有效;要在程式自行 cache 並避免逾期重發。
1230
1239
  3. **沙箱測試靠金額尾數**:例如 ATM 訂單金額尾數 `0-7` 自動付款成功、`8` 過期、`9` 5 分鐘後過期。
1231
1240
  4. **退款手續費**:除信用卡免手續費外,ATM/超商等需「退款金額 + 退款手續費」共同從餘額扣除;退款手續費為 NT$15(依官方)。
@@ -1234,11 +1243,12 @@ PChomePay 採用 **HTTP Basic Auth → pcpay-token** 兩階段認證:先用 AP
1234
1243
 
1235
1244
  ## ezPay 簡單付範例
1236
1245
 
1237
- ezPay 簡單付是**電子支付機構**,官方提供兩組 API(演算法相同、欄位與網址不同):
1246
+ ezPay 簡單付是**電子支付機構**,官方提供三類 API(演算法相同、欄位與網址不同;範例涵蓋前兩類):
1238
1247
 
1239
1248
  - **電子支付平台(境內)**:`https://(c)payment.ezpay.com.tw/API/Twqr/{APIID}`,外層 `APIID` + `Version=1.0` + `UID` + `EncryptData` + `HashData`;
1240
1249
  收 ezPay 帳戶、約定連結存款帳戶、ezPay 約定信用卡與 **TWQR**(台灣 Pay、街口、全支付…掃碼)。
1241
1250
  - **跨境(支付寶 / 微信)**:`https://(c)payment.ezpay.com.tw/MPG/mpg_gateway`,`TradeInfo` / `TradeSha`,Version 1.0。
1251
+ - **跨境實體商店**:`https://(c)o2o.ezpay.com.tw/APIS/Trade`、`/APIS/Query`,外層同電子支付平台,Version 2.0(退款 3.0),門市掃消費者支付寶/微信條碼;見 reference。
1242
1252
 
1243
1253
  ### 完整 Python 範例
1244
1254
  請見 [`examples/ezpay-payment-example.py`](examples/ezpay-payment-example.py):`EzPayWalletService`(7 支境內 API)與
@@ -1256,7 +1266,7 @@ ezPay 簡單付是**電子支付機構**,官方提供兩組 API(演算法相
1256
1266
 
1257
1267
  PayNow 有**兩代 API 並行**:
1258
1268
  - **傳統版(cashflow)**:form-post,動態 AES-256(每次以 GP/GK 檢核碼即時取得 Key/IV)
1259
- - **現代版(apidoc)**:JWT Bearer + RESTful JSON + PaymentIntent / Customer / Card Token(接近 Stripe)
1269
+ - **現代版(apidoc)**:Bearer 私鑰 + RESTful JSON + PaymentIntent / Customer / Card Token(接近 Stripe);API 主機 `api.paynow.com.tw`(測試 `sandboxapi.paynow.com.tw`)
1260
1270
 
1261
1271
  新專案應優先採用現代版。
1262
1272
 
@@ -1266,9 +1276,9 @@ PayNow 有**兩代 API 並行**:
1266
1276
  ### 五大要點
1267
1277
 
1268
1278
  1. **新專案走現代版**:傳統版的 GP/GK 動態金鑰機制學習成本高、易出錯;只有舊系統相容才需要。
1269
- 2. **Apple Pay 完整支援**:含 v1 / v2 一般流程 + Deferred 延遲扣款(PayNow 獨家)。
1279
+ 2. **Apple Pay 完整支援**:session 請求(v2)與確認(v1)兩支端點 + Deferred 延遲扣款。
1270
1280
  3. **Card Token 可跨訂單記憶**:透過 Customer + Card Token 機制做訂閱、回購快速結帳。
1271
- 4. **`webhookUrl` 是現代版的 callback 機制**:不同於傳統版的 `Roturl`。
1281
+ 4. **`webhookUrl` 是現代版的 callback 機制**:以私鑰 HMAC-SHA256 驗證 `X-Payment-Center-Hmac-Sha256`;傳統版的回傳網址在商家專區設定、以 SHA-1 PassCode 驗證。
1272
1282
  5. **`channelId` 對 LINE Pay 必須額外設定**:`paymentMethodType=LINEPayOnline` 時需提供 PayNow 簽發的 channelId。
1273
1283
 
1274
1284
  ---
@@ -1278,7 +1288,7 @@ PayNow 有**兩代 API 並行**:
1278
1288
  Shopline Payments (SLP) 採 **HTTP Header `merchantId` + `apiKey`** 認證,所有金額以**分**為單位(NT$1000 = 100000)。提供 Redirect 與 Embedded SDK 雙模式,Webhook 用 HMAC-SHA256 驗章。
1279
1289
 
1280
1290
  ### 完整 Python 範例
1281
- 請見 [`examples/shopline-payment-example.py`](examples/shopline-payment-example.py) — 涵蓋 sessions/create / sessionQuery / refund / Webhook 驗章。
1291
+ 請見 [`examples/shopline-payment-example.py`](examples/shopline-payment-example.py) — 涵蓋 sessions/create、sessions/query、payment/get、refund、capture/cancel 與 Webhook 驗章。所有 API 皆為 POST + JSON,Header 必帶 `merchantId`、`apiKey`、`requestId`。
1282
1292
 
1283
1293
  ### 三大要點
1284
1294
 
@@ -1300,23 +1310,23 @@ LINE Pay 採 **兩段式流程**:`Request → Confirm`。每次請求需產生
1300
1310
  1. **HMAC string-to-sign 公式**:`ChannelSecret + ApiPath + Body + Nonce` (POST) / `ChannelSecret + ApiPath + QueryString + Nonce` (GET),結果 Base64。v3、v4 相同(官方 developers-pay.line.me/online/prerequisites;API 變更紀錄亦寫「same as online API v3, v4」)。
1301
1311
  2. **transactionId 是 19 位數字**:在 JS 直接用 number 會被 IEEE-754 截斷,**永遠用字串處理**。
1302
1312
  3. **Confirm 的 amount/currency 必須與 Request 完全一致**:官方 v4 Confirm 的相關錯誤碼含 `1124`(金額資訊錯誤);`1183` 是「低於最低金額」,不在 Confirm 的錯誤清單。
1303
- 4. **Capture 兩階段授權**:建立時 `options.payment.capture=false` 只授權;之後手動呼叫 `/capture` 請款,可分批請款多次。
1313
+ 4. **Capture 兩階段授權**:建立時 `options.payment.capture=false` 只授權;之後在 `authorizationExpireDate` 前呼叫 `/capture` 請款(金額可與請求金額不同),回 `1199` 或 `1280`–`1298` 時付款會自動取消。
1304
1314
  5. **Preapproved Pay 自動扣款**:建立時帶 `payType=PREAPPROVED` 取得 `regKey`,之後用 `/preapprovedPay/{regKey}/payment` 直接扣款,免使用者再次確認。
1305
1315
 
1306
1316
  ---
1307
1317
 
1308
1318
  ## TapPay 範例
1309
1319
 
1310
- TapPay 是 **PCI 隔離設計**:前端 SDK 取 Prime(60 秒 TTL)→ 後端用 Prime 呼叫 pay-by-prime。商家從不接觸卡號。
1320
+ TapPay 是 **PCI 隔離設計**:前端 SDK 取 Prime(90 秒效期)→ 後端用 Prime 呼叫 pay-by-prime。商家從不接觸卡號。
1311
1321
 
1312
1322
  ### 完整 Python 範例
1313
- 請見 [`examples/tappay-payment-example.py`](examples/tappay-payment-example.py) — 涵蓋 pay-by-prime / pay-by-card-token (重複扣款) / refund / query / remove-card。
1323
+ 請見 [`examples/tappay-payment-example.py`](examples/tappay-payment-example.py) — 涵蓋 pay-by-prime / pay-by-token (重複扣款) / refund / query / remove-card。
1314
1324
 
1315
1325
  ### 四大要點
1316
1326
 
1317
1327
  1. **三段式金鑰**:`Partner Key` (後端密鑰) / `App Key` (前端 SDK 公鑰) / `Merchant ID`。**Partner Key 絕對不可放前端**。
1318
- 2. **Prime 是 60 秒一次性 token**:前端取 Prime 後要立刻送後端付款;過期或重用會 status=3。
1319
- 3. **重複扣款**:`pay-by-prime` 帶 `remember=true` 後,回應內 `card_secret` 含 `card_key + card_token`,存起來下次直接 `pay-by-card-token`,免再過 SDK。適合訂閱與快速結帳。
1328
+ 2. **Prime 是 90 秒一次性 token**:前端取 Prime 後要立刻送後端付款;過期回 status=91。
1329
+ 3. **重複扣款**:`pay-by-prime` 帶 `remember=true` 後,回應內 `card_secret` 含 `card_key + card_token`,存起來下次直接 `pay-by-token`,免再過 SDK。適合訂閱與快速結帳。
1320
1330
  4. **status=0 才是成功**:別只看 HTTP 200;TapPay HTTP 200 但 status≠0 是業務失敗。
1321
1331
 
1322
1332
  ## O'Pay 歐付寶範例