taiwan-payment-skill 1.5.2 → 1.5.3

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 (33) hide show
  1. package/assets/taiwan-payment/CLAUDE.md +40 -18
  2. package/assets/taiwan-payment/EXAMPLES.md +196 -414
  3. package/assets/taiwan-payment/README.md +2 -2
  4. package/assets/taiwan-payment/SKILL.md +113 -167
  5. package/assets/taiwan-payment/data/error-codes.csv +1106 -114
  6. package/assets/taiwan-payment/data/field-mappings.csv +10 -10
  7. package/assets/taiwan-payment/data/operations.csv +7 -7
  8. package/assets/taiwan-payment/data/payment-methods.csv +25 -25
  9. package/assets/taiwan-payment/data/providers.csv +1 -1
  10. package/assets/taiwan-payment/data/troubleshooting.csv +9 -4
  11. package/assets/taiwan-payment/examples/ecpay-payment-example.py +32 -6
  12. package/assets/taiwan-payment/examples/ezpay-payment-example.py +291 -613
  13. package/assets/taiwan-payment/examples/linepay-payment-example.py +12 -4
  14. package/assets/taiwan-payment/examples/newebpay-payment-example.py +106 -21
  15. package/assets/taiwan-payment/examples/paynow-payment-example.py +2 -1
  16. package/assets/taiwan-payment/examples/payuni-payment-example.py +185 -349
  17. package/assets/taiwan-payment/examples/shopline-payment-example.py +25 -25
  18. package/assets/taiwan-payment/examples/smilepay-payment-example.py +5 -3
  19. package/assets/taiwan-payment/examples/sunpay-payment-example.py +39 -8
  20. package/assets/taiwan-payment/references/ezpay-payment-api.md +235 -561
  21. package/assets/taiwan-payment/references/linepay-payment-api.md +37 -43
  22. package/assets/taiwan-payment/references/newebpay-payment-api.md +60 -47
  23. package/assets/taiwan-payment/references/opay-payment-api.md +25 -17
  24. package/assets/taiwan-payment/references/payuni-payment-api.md +160 -338
  25. package/assets/taiwan-payment/references/shopline-payment-api.md +9 -5
  26. package/assets/taiwan-payment/references/smilepay-payment-api.md +30 -56
  27. package/assets/taiwan-payment/references/sunpay-payment-api.md +35 -1
  28. package/assets/taiwan-payment/references/tappay-payment-api.md +17 -15
  29. package/assets/taiwan-payment/references/twqr-ewallet-landscape.md +5 -3
  30. package/assets/taiwan-payment/scripts/test_payment.py +65 -50
  31. package/assets/templates/base/quick-reference.md +9 -9
  32. package/assets/templates/base/skill-content.md +113 -168
  33. package/package.json +1 -1
@@ -247,151 +247,104 @@ async function createNewebPayMPG() {
247
247
 
248
248
  ---
249
249
 
250
- ### 範例 3: PAYUNi RESTful API
250
+ ### 範例 3: PAYUNi 整合支付頁(UPP)
251
251
 
252
- **場景:** 使用統一金流 RESTful JSON API 建立付款
252
+ **場景:** 使用統一金流 UPP 建立信用卡付款
253
253
 
254
254
  **Claude 提示詞:**
255
255
  ```
256
- 使用 PAYUNi RESTful API 建立信用卡付款
256
+ 使用 PAYUNi UPP 建立信用卡付款
257
257
  - 金額: 3000 元
258
- - JSON 格式
259
258
  - AES-256-GCM 加密
260
259
  ```
261
260
 
262
261
  **生成的程式碼:**
263
262
 
263
+ > 欄位與流程對照統一金流官方外掛 PAYUNi_for_WooCommerce 1.2.8 的 `uppOnePointHandler()`;
264
+ > 加密演算法見 SKILL.md「2. 加密實作」(已由 CI 以官方外掛產生的標準答案驗證)。
265
+
264
266
  ```typescript
265
267
  import crypto from 'crypto'
266
- import axios from 'axios'
267
268
 
268
269
  class PAYUNiService {
269
- private merchantID: string
270
+ private merID: string
270
271
  private hashKey: string
271
272
  private hashIV: string
272
- private apiUrl: string
273
+ private uppUrl: string
273
274
 
274
275
  constructor(isProd: boolean = false) {
275
- this.merchantID = isProd
276
- ? process.env.PAYUNI_MERCHANT_ID_PROD!
277
- : process.env.PAYUNI_MERCHANT_ID_TEST!
278
- this.hashKey = isProd
279
- ? process.env.PAYUNI_HASH_KEY_PROD!
280
- : process.env.PAYUNI_HASH_KEY_TEST!
281
- this.hashIV = isProd
282
- ? process.env.PAYUNI_HASH_IV_PROD!
283
- : process.env.PAYUNI_HASH_IV_TEST!
284
- this.apiUrl = isProd
276
+ this.merID = process.env.PAYUNI_MER_ID!
277
+ this.hashKey = process.env.PAYUNI_HASH_KEY!
278
+ this.hashIV = process.env.PAYUNI_HASH_IV!
279
+ this.uppUrl = isProd
285
280
  ? 'https://api.payuni.com.tw/api/upp'
286
281
  : 'https://sandbox-api.payuni.com.tw/api/upp'
287
282
  }
288
283
 
289
- private encrypt(data: Record<string, any>): { EncryptInfo: string, HashInfo: string } {
290
- // 1. JSON 字串化
291
- const jsonString = JSON.stringify(data)
292
-
293
- // 2. AES-256-GCM 加密
284
+ // EncryptInfo = hex( base64(密文) + ":::" + base64(tag) )
285
+ private encrypt(data: Record<string, any>): string {
294
286
  const cipher = crypto.createCipheriv('aes-256-gcm', this.hashKey, this.hashIV)
295
- let encrypted = cipher.update(jsonString, 'utf8', 'hex')
296
- encrypted += cipher.final('hex')
297
-
298
- // 3. 取得 Auth Tag
299
- const authTag = cipher.getAuthTag().toString('hex')
300
-
301
- // 4. 組合加密資料
302
- const encryptInfo = encrypted + authTag
303
-
304
- // 5. SHA256 簽章
305
- const hashInfo = crypto
306
- .createHash('sha256')
307
- .update(`HashKey=${this.hashKey}&${encryptInfo}&HashIV=${this.hashIV}`)
308
- .digest('hex')
309
- .toUpperCase()
310
-
311
- return {
312
- EncryptInfo: encryptInfo,
313
- HashInfo: hashInfo
314
- }
287
+ const encrypted = Buffer.concat([cipher.update(new URLSearchParams(data).toString(), 'utf8'), cipher.final()])
288
+ const tag = cipher.getAuthTag()
289
+ return Buffer.from(`${encrypted.toString('base64')}:::${tag.toString('base64')}`).toString('hex')
315
290
  }
316
291
 
317
- async createOrder(userId: string, orderData: any) {
318
- const merchantOrderNo = `UNI${Date.now()}`
319
-
320
- const tradeData = {
321
- MerchantID: this.merchantID,
322
- MerchantOrderNo: merchantOrderNo,
323
- Amount: orderData.amount,
324
- ItemDescription: orderData.itemDesc || '商品購買',
325
- ReturnURL: orderData.returnURL,
326
- NotifyURL: orderData.notifyURL,
327
- Email: orderData.email,
328
- PaymentMethod: 'CREDIT', // 信用卡
329
- TimeStamp: Math.floor(Date.now() / 1000)
330
- }
331
-
332
- // 加密
333
- const { EncryptInfo, HashInfo } = this.encrypt(tradeData)
334
-
335
- try {
336
- // RESTful POST 請求
337
- const response = await axios.post(this.apiUrl, {
338
- MerchantID: this.merchantID,
339
- EncryptInfo: EncryptInfo,
340
- HashInfo: HashInfo
341
- }, {
342
- headers: {
343
- 'Content-Type': 'application/json'
344
- }
345
- })
292
+ // HashInfo = SHA256( HashKey + EncryptInfo + HashIV )
293
+ private hashInfo(encryptInfo: string): string {
294
+ return crypto.createHash('sha256').update(this.hashKey + encryptInfo + this.hashIV).digest('hex').toUpperCase()
295
+ }
346
296
 
347
- console.log('[OK] PAYUNi 訂單建立')
348
- console.log('訂單編號:', merchantOrderNo)
349
- console.log('回應狀態:', response.data.Status)
297
+ /**
298
+ * UPP 是「瀏覽器表單 POST」到 /api/upp,由統一金流顯示付款頁;
299
+ * 不是伺服器端呼叫的 JSON API。回傳表單內容給前端自動送出。
300
+ */
301
+ buildUppForm(order: { merTradeNo: string, amount: number, prodDesc: string, email: string,
302
+ returnURL: string, notifyURL: string }) {
303
+ const encryptInfo = this.encrypt({
304
+ MerID: this.merID,
305
+ MerTradeNo: order.merTradeNo,
306
+ TradeAmt: order.amount,
307
+ ProdDesc: order.prodDesc,
308
+ UsrMail: order.email,
309
+ ReturnURL: order.returnURL, // 前景(消費者瀏覽器)
310
+ NotifyURL: order.notifyURL, // 背景(伺服器對伺服器)
311
+ Timestamp: Math.floor(Date.now() / 1000),
312
+ Credit: 1, // 啟用信用卡;可再加 ATM、CVS 等
313
+ })
350
314
 
351
- return {
352
- success: response.data.Status === 'SUCCESS',
353
- merchantTradeNo: merchantOrderNo,
354
- paymentUrl: response.data.Data?.PaymentURL,
355
- message: response.data.Message
356
- }
357
- } catch (error) {
358
- console.error('[ERROR] PAYUNi 請求失敗:', error)
359
- throw error
315
+ return {
316
+ action: this.uppUrl,
317
+ method: 'POST',
318
+ fields: {
319
+ MerID: this.merID,
320
+ Version: '1.0',
321
+ EncryptInfo: encryptInfo,
322
+ HashInfo: this.hashInfo(encryptInfo),
323
+ },
360
324
  }
361
325
  }
362
326
  }
363
327
 
364
328
  // 使用範例
365
- async function createPAYUNiOrder() {
366
- const service = new PAYUNiService(false)
367
-
368
- const result = await service.createOrder('user-123', {
369
- amount: 3000,
370
- itemDesc: '會員升級方案',
371
- returnURL: 'https://yourdomain.com/payment/return',
372
- notifyURL: 'https://yourdomain.com/api/payment/callback',
373
- email: 'test@example.com'
374
- })
375
-
376
- if (result.success) {
377
- console.log('請導向:', result.paymentUrl)
378
- }
379
-
380
- return result
381
- }
329
+ const form = new PAYUNiService(false).buildUppForm({
330
+ merTradeNo: `UNI${Date.now()}`,
331
+ amount: 3000,
332
+ prodDesc: '會員升級方案',
333
+ email: 'test@example.com',
334
+ returnURL: 'https://yourdomain.com/payment/return',
335
+ notifyURL: 'https://yourdomain.com/api/payment/callback',
336
+ })
337
+ console.log('[OK] PAYUNi UPP 表單', form.action, Object.keys(form.fields))
382
338
  ```
383
339
 
384
340
  **重要說明:**
385
- - PAYUNi 使用 RESTful JSON API(與 ECPay/NewebPay 的 Form POST 不同)
386
- - AES-256-GCM 加密需要附加 Auth Tag(最後 32 字元)
387
- - 回應為 JSON 格式,包含 PaymentURL 導向連結
341
+ - UPP 以瀏覽器表單 POST 送出(外層只有 `MerID`、`Version`、`EncryptInfo`、`HashInfo` 四個欄位)
342
+ - 交易欄位名稱是 `MerID` / `MerTradeNo` / `TradeAmt` / `ProdDesc`,不是藍新的 `MerchantID` / `MerchantOrderNo` / `Amt`
343
+ - 付款結果以同樣的 `EncryptInfo` + `HashInfo` 回傳到 NotifyURL:先驗 HashInfo,再解密
388
344
 
389
345
  **預期輸出:**
390
346
  ```
391
- [OK] PAYUNi 訂單建立
392
- 訂單編號: UNI1738123456789
393
- 回應狀態: SUCCESS
394
- 請導向: https://sandbox-api.payuni.com.tw/trade/payment?token=xxx
347
+ [OK] PAYUNi UPP 表單 https://sandbox-api.payuni.com.tw/api/upp [ 'MerID', 'Version', 'EncryptInfo', 'HashInfo' ]
395
348
  ```
396
349
 
397
350
  ---
@@ -570,168 +523,98 @@ export async function POST(request: Request) {
570
523
 
571
524
  **生成的程式碼:**
572
525
 
526
+ > 此模組由 CI 以三家業者官方實作產生的標準答案驗證(`scripts/verify-examples.py`、`tests/vectors/`)。
527
+
528
+ <!-- verify: ecpay-cmv-sha256 newebpay payuni -->
573
529
  ```typescript
574
530
  // lib/utils/payment-encryption.ts
575
531
 
576
532
  import crypto from 'crypto'
577
533
 
578
- /**
579
- * ECPay CheckMacValue 計算(SHA256)
580
- */
581
- export function generateECPayCheckMacValue(
582
- params: Record<string, any>,
583
- hashKey: string,
584
- hashIV: string
585
- ): string {
586
- // 1. 移除 CheckMacValue 本身
587
- const { CheckMacValue, ...cleanParams } = params
534
+ const sha256Upper = (s: string) => crypto.createHash('sha256').update(s).digest('hex').toUpperCase()
588
535
 
589
- // 2. 依照 key 排序(字母順序)
590
- const sortedKeys = Object.keys(cleanParams).sort()
536
+ /** 常數時間比較(避免以回應時間差逐字元猜出正確雜湊) */
537
+ function safeEqual(a: string, b: string): boolean {
538
+ const x = Buffer.from(a.toUpperCase()), y = Buffer.from(b.toUpperCase())
539
+ return x.length === y.length && crypto.timingSafeEqual(x, y)
540
+ }
591
541
 
592
- // 3. 組合參數字串
593
- const paramString = sortedKeys
594
- .map(key => `${key}=${cleanParams[key]}`)
595
- .join('&')
542
+ // ---------------------------------------------------------------------------
543
+ // ECPay CheckMacValue(金流 SHA256;國內物流改用 md5)
544
+ // ---------------------------------------------------------------------------
545
+
546
+ /** 與綠界官方 SDK UrlService::ecpayUrlEncode 相同:PHP urlencode → 小寫 → .NET 字元還原 */
547
+ function ecpayUrlEncode(text: string): string {
548
+ return encodeURIComponent(text)
549
+ .replace(/%20/g, '+')
550
+ .replace(/[!'()*~]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())
551
+ .toLowerCase()
552
+ .replace(/%21/g, '!').replace(/%2a/g, '*').replace(/%28/g, '(').replace(/%29/g, ')')
553
+ }
596
554
 
597
- // 4. 前後加上 HashKey 和 HashIV
598
- const rawString = `HashKey=${hashKey}&${paramString}&HashIV=${hashIV}`
555
+ export function generateECPayCheckMacValue(params: Record<string, any>, hashKey: string, hashIV: string): string {
556
+ const { CheckMacValue, ...clean } = params
557
+ const keys = Object.keys(clean).sort((a, b) => {
558
+ const x = a.toLowerCase(), y = b.toLowerCase()
559
+ return x < y ? -1 : x > y ? 1 : 0
560
+ })
561
+ const raw = `HashKey=${hashKey}&${keys.map(k => `${k}=${clean[k]}`).join('&')}&HashIV=${hashIV}`
562
+ return sha256Upper(ecpayUrlEncode(raw))
563
+ }
599
564
 
600
- // 5. URL Encode (lowercase)
601
- const encoded = encodeURIComponent(rawString).toLowerCase()
565
+ export function verifyECPayCallback(posted: Record<string, string>, hashKey: string, hashIV: string): boolean {
566
+ return !!posted.CheckMacValue && safeEqual(generateECPayCheckMacValue(posted, hashKey, hashIV), posted.CheckMacValue)
567
+ }
602
568
 
603
- // 6. SHA256 雜湊
604
- const hash = crypto.createHash('sha256').update(encoded).digest('hex')
569
+ // ---------------------------------------------------------------------------
570
+ // NewebPay AES-256-CBC + SHA256
571
+ // ---------------------------------------------------------------------------
605
572
 
606
- // 7. 轉大寫
607
- return hash.toUpperCase()
573
+ export function encryptNewebPay(data: Record<string, any>, hashKey: string, hashIV: string) {
574
+ const cipher = crypto.createCipheriv('aes-256-cbc', hashKey, hashIV) // 標準 PKCS#7
575
+ const tradeInfo = cipher.update(new URLSearchParams(data).toString(), 'utf8', 'hex') + cipher.final('hex')
576
+ return { TradeInfo: tradeInfo, TradeSha: sha256Upper(`HashKey=${hashKey}&${tradeInfo}&HashIV=${hashIV}`) }
608
577
  }
609
578
 
610
- /**
611
- * NewebPay AES-256-CBC 加密
612
- */
613
- export function encryptNewebPay(
614
- data: Record<string, any>,
615
- hashKey: string,
616
- hashIV: string
617
- ): { TradeInfo: string; TradeSha: string } {
618
- // 1. 轉換為查詢字串
619
- const queryString = new URLSearchParams(data).toString()
620
-
621
- // 2. AES-256-CBC 加密
622
- const cipher = crypto.createCipheriv('aes-256-cbc', hashKey, hashIV)
623
- cipher.setAutoPadding(true)
624
- let encrypted = cipher.update(queryString, 'utf8', 'hex')
625
- encrypted += cipher.final('hex')
626
-
627
- // 3. 計算 SHA256
628
- const tradeSha = crypto
629
- .createHash('sha256')
630
- .update(`HashKey=${hashKey}&${encrypted}&HashIV=${hashIV}`)
631
- .digest('hex')
632
- .toUpperCase()
633
-
634
- return {
635
- TradeInfo: encrypted,
636
- TradeSha: tradeSha,
579
+ export function decryptNewebPay(tradeInfo: string, hashKey: string, hashIV: string): Record<string, any> {
580
+ const decipher = crypto.createDecipheriv('aes-256-cbc', hashKey, hashIV)
581
+ decipher.setAutoPadding(false) // 官方外掛以 32 bytes 補齊,padding 可能 1–32
582
+ const raw = Buffer.concat([decipher.update(tradeInfo, 'hex'), decipher.final()])
583
+ const n = raw[raw.length - 1]
584
+ if (n < 1 || n > 32 || !raw.subarray(raw.length - n).every(b => b === n)) {
585
+ throw new Error('padding 錯誤(HashKey / HashIV 可能不正確)')
637
586
  }
587
+ const text = raw.subarray(0, raw.length - n).toString('utf8')
588
+ return text.startsWith('{') ? JSON.parse(text) : Object.fromEntries(new URLSearchParams(text))
638
589
  }
639
590
 
640
- /**
641
- * NewebPay AES-256-CBC 解密
642
- */
643
- export function decryptNewebPay(
644
- encryptedData: string,
645
- hashKey: string,
646
- hashIV: string
647
- ): Record<string, any> {
648
- const decipher = crypto.createDecipheriv('aes-256-cbc', hashKey, hashIV)
649
- decipher.setAutoPadding(true)
650
- let decrypted = decipher.update(encryptedData, 'hex', 'utf8')
651
- decrypted += decipher.final('utf8')
652
-
653
- return Object.fromEntries(new URLSearchParams(decrypted))
591
+ /** 驗證回呼:比對收到的 TradeInfo 的雜湊,不是把參數重新加密 */
592
+ export function verifyNewebPayCallback(tradeInfo: string, tradeSha: string, hashKey: string, hashIV: string): boolean {
593
+ return safeEqual(sha256Upper(`HashKey=${hashKey}&${tradeInfo}&HashIV=${hashIV}`), tradeSha)
654
594
  }
655
595
 
656
- /**
657
- * PAYUNi AES-256-GCM 加密
658
- */
659
- export function encryptPAYUNi(
660
- data: Record<string, any>,
661
- hashKey: string,
662
- hashIV: string
663
- ): { EncryptInfo: string; HashInfo: string } {
664
- // 1. JSON 字串化
665
- const jsonString = JSON.stringify(data)
666
-
667
- // 2. AES-256-GCM 加密
668
- const cipher = crypto.createCipheriv('aes-256-gcm', hashKey, hashIV)
669
- let encrypted = cipher.update(jsonString, 'utf8', 'hex')
670
- encrypted += cipher.final('hex')
671
-
672
- // 3. 取得 Auth Tag (16 bytes)
673
- const authTag = cipher.getAuthTag().toString('hex')
674
-
675
- // 4. 組合加密資料
676
- const encryptInfo = encrypted + authTag
677
-
678
- // 5. SHA256 簽章
679
- const hashInfo = crypto
680
- .createHash('sha256')
681
- .update(`HashKey=${hashKey}&${encryptInfo}&HashIV=${hashIV}`)
682
- .digest('hex')
683
- .toUpperCase()
684
-
685
- return {
686
- EncryptInfo: encryptInfo,
687
- HashInfo: hashInfo,
688
- }
596
+ // ---------------------------------------------------------------------------
597
+ // PAYUNi AES-256-GCM + SHA256
598
+ // ---------------------------------------------------------------------------
599
+
600
+ export function encryptPAYUNi(data: Record<string, any>, hashKey: string, hashIV: string) {
601
+ const cipher = crypto.createCipheriv('aes-256-gcm', hashKey, hashIV) // HashIV 直接當 nonce(16 bytes)
602
+ const encrypted = Buffer.concat([cipher.update(new URLSearchParams(data).toString(), 'utf8'), cipher.final()])
603
+ const encryptInfo = Buffer.from(`${encrypted.toString('base64')}:::${cipher.getAuthTag().toString('base64')}`).toString('hex')
604
+ return { EncryptInfo: encryptInfo, HashInfo: sha256Upper(hashKey + encryptInfo + hashIV) }
689
605
  }
690
606
 
691
- /**
692
- * PAYUNi AES-256-GCM 解密
693
- */
694
- export function decryptPAYUNi(
695
- encryptedData: string,
696
- hashKey: string,
697
- hashIV: string
698
- ): Record<string, any> {
699
- // 1. 分離加密內容和 Auth Tag(最後 32 個字元)
700
- const encryptedContent = encryptedData.slice(0, -32)
701
- const authTag = Buffer.from(encryptedData.slice(-32), 'hex')
702
-
703
- // 2. AES-256-GCM 解密
607
+ export function decryptPAYUNi(encryptInfo: string, hashKey: string, hashIV: string): Record<string, any> {
608
+ const [data, tag] = Buffer.from(encryptInfo, 'hex').toString('utf8').split(':::')
704
609
  const decipher = crypto.createDecipheriv('aes-256-gcm', hashKey, hashIV)
705
- decipher.setAuthTag(authTag)
706
- let decrypted = decipher.update(encryptedContent, 'hex', 'utf8')
707
- decrypted += decipher.final('utf8')
708
-
709
- return JSON.parse(decrypted)
610
+ decipher.setAuthTag(Buffer.from(tag, 'base64'))
611
+ const text = Buffer.concat([decipher.update(Buffer.from(data, 'base64')), decipher.final()]).toString('utf8')
612
+ return Object.fromEntries(new URLSearchParams(text))
710
613
  }
711
614
 
712
- /**
713
- * 驗證簽章
714
- */
715
- export function verifySignature(
716
- params: Record<string, any>,
717
- signature: string,
718
- hashKey: string,
719
- hashIV: string,
720
- provider: 'ECPAY' | 'NEWEBPAY' | 'PAYUNI'
721
- ): boolean {
722
- switch (provider) {
723
- case 'ECPAY':
724
- const calculatedECPay = generateECPayCheckMacValue(params, hashKey, hashIV)
725
- return calculatedECPay === signature
726
- case 'NEWEBPAY':
727
- const { TradeSha } = encryptNewebPay(params, hashKey, hashIV)
728
- return TradeSha === signature
729
- case 'PAYUNI':
730
- const { HashInfo } = encryptPAYUNi(params, hashKey, hashIV)
731
- return HashInfo === signature
732
- default:
733
- return false
734
- }
615
+ /** 驗證回呼:比對收到的 EncryptInfo 的雜湊 */
616
+ export function verifyPAYUNiCallback(encryptInfo: string, hashInfo: string, hashKey: string, hashIV: string): boolean {
617
+ return safeEqual(sha256Upper(hashKey + encryptInfo + hashIV), hashInfo)
735
618
  }
736
619
  ```
737
620
 
@@ -761,22 +644,23 @@ const newebpayData = {
761
644
  }
762
645
  const { TradeInfo, TradeSha } = encryptNewebPay(
763
646
  newebpayData,
764
- 'your32BytesHashKeyHere123456',
765
- 'your16BytesIV123'
647
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345', // HashKey 必須 32 bytes
648
+ 'ABCDEFGHIJKLMNOP' // HashIV 必須 16 bytes
766
649
  )
767
650
  console.log('NewebPay TradeInfo:', TradeInfo.substring(0, 50) + '...')
768
651
  console.log('NewebPay TradeSha:', TradeSha)
769
652
 
770
- // PAYUNi 加密
653
+ // PAYUNi 加密(欄位名稱是 MerID / MerTradeNo / TradeAmt,不是藍新的 MerchantID / Amt)
771
654
  const payuniData = {
772
- MerchantID: 'UNI12345',
773
- MerchantOrderNo: 'UNI123456',
774
- Amount: 3000,
655
+ MerID: 'S01234567',
656
+ MerTradeNo: 'UNI123456',
657
+ TradeAmt: 3000,
658
+ Timestamp: Math.floor(Date.now() / 1000),
775
659
  }
776
660
  const { EncryptInfo, HashInfo } = encryptPAYUNi(
777
661
  payuniData,
778
- 'your32BytesHashKey',
779
- 'your16BytesIV'
662
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345', // HashKey 必須 32 bytes
663
+ 'ABCDEFGHIJKLMNOP' // HashIV 必須 16 bytes
780
664
  )
781
665
  console.log('PAYUNi EncryptInfo:', EncryptInfo.substring(0, 50) + '...')
782
666
  console.log('PAYUNi HashInfo:', HashInfo)
@@ -1236,188 +1120,81 @@ export async function POST(request: Request) {
1236
1120
 
1237
1121
  ## 常見錯誤與修正
1238
1122
 
1123
+ 以下錯誤的正確寫法皆為「範例 5: 加密輔助函數」的模組(已由 CI 以官方實作產生的標準答案驗證)。
1124
+
1239
1125
  ### 錯誤 1: CheckMacValue 計算錯誤
1240
1126
 
1241
- **錯誤訊息:** ECPay 回傳 `10100058: 請確認檢查碼是否正確`
1127
+ **錯誤訊息:** ECPay 回傳 `10200073`(CheckMacValue 驗證失敗)
1242
1128
 
1243
- **原因:** 參數排序錯誤或 URL Encode 不正確
1129
+ > `10100058` 是「ATM 繳費期限已過」,不是檢查碼錯誤。
1244
1130
 
1245
- **修正前:**
1246
- ```typescript
1247
- // * 錯誤:未排序參數
1248
- function generateCheckMacValue(params: Record<string, any>, hashKey: string, hashIV: string) {
1249
- const paramString = Object.entries(params)
1250
- .map(([k, v]) => `${k}=${v}`)
1251
- .join('&')
1252
-
1253
- const rawString = `HashKey=${hashKey}&${paramString}&HashIV=${hashIV}`
1254
- const hash = crypto.createHash('sha256').update(rawString).digest('hex')
1255
- return hash.toUpperCase()
1256
- }
1257
- ```
1131
+ **常見的錯誤寫法:**
1258
1132
 
1259
- **修正後:**
1260
1133
  ```typescript
1261
- // *! 正確:排序 + URL Encode (lowercase)
1262
- function generateCheckMacValue(params: Record<string, any>, hashKey: string, hashIV: string) {
1263
- // 1. 移除 CheckMacValue 本身
1264
- const { CheckMacValue, ...cleanParams } = params
1265
-
1266
- // 2. 排序 keys
1267
- const sortedKeys = Object.keys(cleanParams).sort()
1268
-
1269
- // 3. 組合參數字串
1270
- const paramString = sortedKeys
1271
- .map(key => `${key}=${cleanParams[key]}`)
1272
- .join('&')
1134
+ // * 錯誤 1:區分大小寫排序(綠界 SDK 用 strcasecmp,不分大小寫)
1135
+ Object.keys(params).sort()
1273
1136
 
1274
- // 4. 前後加上 HashKey/HashIV
1275
- const rawString = `HashKey=${hashKey}&${paramString}&HashIV=${hashIV}`
1137
+ // * 錯誤 2:encodeURIComponent 把空白編成 %20,綠界要的是 +;
1138
+ // MerchantTradeDate 一定含空白,所以這個寫法「每一筆」都會失敗
1139
+ encodeURIComponent(rawString).toLowerCase()
1276
1140
 
1277
- // 5. URL Encode (lowercase)
1278
- const encoded = encodeURIComponent(rawString).toLowerCase()
1279
-
1280
- // 6. SHA256 + 大寫
1281
- const hash = crypto.createHash('sha256').update(encoded).digest('hex')
1282
- return hash.toUpperCase()
1283
- }
1141
+ // * 錯誤 3:物流 API 用了 SHA256(國內物流是 MD5)
1284
1142
  ```
1285
1143
 
1286
- **驗證方法:**
1144
+ **用已知答案自我檢查:** 以下輸入與預期值由綠界官方 PHP SDK 算出(`tests/vectors/ecpay.json` 的 `aio_basic`),
1145
+ 你的實作算出的值必須完全相同:
1146
+
1287
1147
  ```typescript
1288
- // 測試範例
1289
1148
  const params = {
1290
1149
  MerchantID: '3002607',
1291
- MerchantTradeNo: 'ORD123456',
1292
- MerchantTradeDate: '2024/01/29 12:00:00',
1293
- TotalAmount: 1050,
1150
+ MerchantTradeNo: 'ORD20260923001',
1151
+ MerchantTradeDate: '2026/09/23 12:00:00',
1152
+ PaymentType: 'aio',
1153
+ TotalAmount: '1280',
1154
+ TradeDesc: '測試交易',
1155
+ ItemName: '測試商品',
1156
+ ReturnURL: 'https://shop.example.com/ecpay/notify',
1157
+ ChoosePayment: 'ALL',
1158
+ EncryptType: '1',
1294
1159
  }
1295
-
1296
- const checkMacValue = generateCheckMacValue(
1297
- params,
1298
- 'pwFHCqoQZGmho4w6',
1299
- 'EkRm7iFT261dpevs'
1300
- )
1301
-
1302
- console.log('計算結果:', checkMacValue)
1303
- // 應該與 ECPay 要求的值一致
1160
+ const got = generateECPayCheckMacValue(params, 'pwFHCqoQZGmho4w6', 'EkRm7iFT261dpevs')
1161
+ console.assert(got === 'D5499ADD6F1D331B09D196D56C672A3A6E0D4FE31C1B19E10378B67AD1249DC8', got)
1304
1162
  ```
1305
1163
 
1306
1164
  ---
1307
1165
 
1308
- ### 錯誤 2: AES 加密錯誤
1309
-
1310
- **錯誤訊息:** NewebPay 回傳 `TradeSha 錯誤` 或 PAYUNi 回傳 `HashInfo 錯誤`
1166
+ ### 錯誤 2: AES 加解密錯誤
1311
1167
 
1312
- **原因:** Key/IV 長度錯誤或未附加 Auth Tag
1168
+ **錯誤訊息:** NewebPay 回傳 `MPG02001`(檢查碼錯誤);PAYUNi 解密失敗或 HashInfo 不符
1313
1169
 
1314
- **修正前 (NewebPay):**
1315
- ```typescript
1316
- // * 錯誤:Key/IV 長度不正確
1317
- function encryptNewebPay(data: Record<string, any>, hashKey: string, hashIV: string) {
1318
- const queryString = new URLSearchParams(data).toString()
1170
+ **NewebPay 常見錯誤:**
1319
1171
 
1320
- // 錯誤:未檢查 Key/IV 長度
1321
- const cipher = crypto.createCipheriv('aes-256-cbc', hashKey, hashIV)
1322
- let encrypted = cipher.update(queryString, 'utf8', 'hex')
1323
- encrypted += cipher.final('hex')
1172
+ - HashKey 不是 32 bytes、HashIV 不是 16 bytes
1173
+ - 解密時用 `setAutoPadding(true)`:官方外掛以 32 bytes 補齊,padding 17–32 的密文會直接拋錯
1174
+ - `RespondType=JSON` 時解出來是 JSON,用 `URLSearchParams` 解析會得到錯誤結果
1324
1175
 
1325
- return encrypted
1326
- }
1327
- ```
1176
+ **PAYUNi 常見錯誤:**
1328
1177
 
1329
- **修正後 (NewebPay):**
1330
1178
  ```typescript
1331
- // *! 正確:確認 Key/IV 長度 + 計算 TradeSha
1332
- function encryptNewebPay(data: Record<string, any>, hashKey: string, hashIV: string) {
1333
- // 確認長度
1334
- if (hashKey.length !== 32) throw new Error('HashKey 必須 32 bytes')
1335
- if (hashIV.length !== 16) throw new Error('HashIV 必須 16 bytes')
1336
-
1337
- const queryString = new URLSearchParams(data).toString()
1338
-
1339
- // AES-256-CBC 加密
1340
- const cipher = crypto.createCipheriv('aes-256-cbc', hashKey, hashIV)
1341
- cipher.setAutoPadding(true)
1342
- let encrypted = cipher.update(queryString, 'utf8', 'hex')
1343
- encrypted += cipher.final('hex')
1344
-
1345
- // 計算 TradeSha
1346
- const tradeSha = crypto
1347
- .createHash('sha256')
1348
- .update(`HashKey=${hashKey}&${encrypted}&HashIV=${hashIV}`)
1349
- .digest('hex')
1350
- .toUpperCase()
1351
-
1352
- return {
1353
- TradeInfo: encrypted,
1354
- TradeSha: tradeSha
1355
- }
1356
- }
1357
- ```
1358
-
1359
- **修正前 (PAYUNi):**
1360
- ```typescript
1361
- // * 錯誤:忘記附加 Auth Tag
1362
- function encryptPAYUNi(data: Record<string, any>, hashKey: string, hashIV: string) {
1363
- const jsonString = JSON.stringify(data)
1179
+ // * 錯誤:加密內容用 JSON(應為 query string)
1180
+ cipher.update(JSON.stringify(data), 'utf8', 'hex')
1364
1181
 
1365
- const cipher = crypto.createCipheriv('aes-256-gcm', hashKey, hashIV)
1366
- let encrypted = cipher.update(jsonString, 'utf8', 'hex')
1367
- encrypted += cipher.final('hex')
1182
+ // * 錯誤:hex(密文 + tag)(應為 hex( base64(密文) + ":::" + base64(tag) ))
1183
+ const encryptInfo = encrypted + authTag
1368
1184
 
1369
- // 錯誤:忘記取得 Auth Tag
1370
- return encrypted
1371
- }
1185
+ // * 錯誤:HashInfo 加了 "HashKey=" 前綴(應為 sha256(HashKey + EncryptInfo + HashIV))
1186
+ `HashKey=${hashKey}&${encryptInfo}&HashIV=${hashIV}`
1372
1187
  ```
1373
1188
 
1374
- **修正後 (PAYUNi):**
1375
- ```typescript
1376
- // *! 正確:附加 Auth Tag
1377
- function encryptPAYUNi(data: Record<string, any>, hashKey: string, hashIV: string) {
1378
- const jsonString = JSON.stringify(data)
1379
-
1380
- // AES-256-GCM 加密
1381
- const cipher = crypto.createCipheriv('aes-256-gcm', hashKey, hashIV)
1382
- let encrypted = cipher.update(jsonString, 'utf8', 'hex')
1383
- encrypted += cipher.final('hex')
1384
-
1385
- // 取得 Auth Tag(16 bytes = 32 hex chars)
1386
- const authTag = cipher.getAuthTag().toString('hex')
1387
-
1388
- // 組合:encrypted + authTag
1389
- const encryptInfo = encrypted + authTag
1390
-
1391
- // 計算 HashInfo
1392
- const hashInfo = crypto
1393
- .createHash('sha256')
1394
- .update(`HashKey=${hashKey}&${encryptInfo}&HashIV=${hashIV}`)
1395
- .digest('hex')
1396
- .toUpperCase()
1397
-
1398
- return {
1399
- EncryptInfo: encryptInfo,
1400
- HashInfo: hashInfo
1401
- }
1402
- }
1403
- ```
1189
+ **用已知答案自我檢查:** 以下由統一金流官方外掛與官方 PHP SDK 算出(`tests/vectors/payuni.json` 的 `minimal`):
1404
1190
 
1405
- **測試工具:**
1406
1191
  ```typescript
1407
- // 測試 NewebPay 加密/解密
1408
- const testData = { test: 'hello', amount: 1000 }
1409
- const { TradeInfo, TradeSha } = encryptNewebPay(testData, hashKey, hashIV)
1410
- const decrypted = decryptNewebPay(TradeInfo, hashKey, hashIV)
1411
- console.log('原始:', testData)
1412
- console.log('解密:', decrypted)
1413
- console.log('一致:', JSON.stringify(testData) === JSON.stringify(decrypted))
1414
-
1415
- // 測試 PAYUNi 加密/解密
1416
- const { EncryptInfo, HashInfo } = encryptPAYUNi(testData, hashKey, hashIV)
1417
- const decryptedPAYUNi = decryptPAYUNi(EncryptInfo, hashKey, hashIV)
1418
- console.log('原始:', testData)
1419
- console.log('解密:', decryptedPAYUNi)
1420
- console.log('一致:', JSON.stringify(testData) === JSON.stringify(decryptedPAYUNi))
1192
+ const { HashInfo } = encryptPAYUNi(
1193
+ { MerID: 'S01234567', MerTradeNo: 'T20260923001', TradeAmt: '100', Timestamp: '1758600000' },
1194
+ '12345678901234567890123456789012',
1195
+ '1234567890123456',
1196
+ )
1197
+ console.assert(HashInfo === '6563710212EB74701B34AB4D510DC05AC0775CFCEEB1FBE44CFD031F01760BA9', HashInfo)
1421
1198
  ```
1422
1199
 
1423
1200
  ---
@@ -1457,16 +1234,21 @@ PChomePay 採用 **HTTP Basic Auth → pcpay-token** 兩階段認證:先用 AP
1457
1234
 
1458
1235
  ## ezPay 簡單付範例
1459
1236
 
1460
- ezPay 是藍新 NewebPay 集團的小型商家品牌,金流 API **與 NewebPay MPG 完全相同**(TradeInfo / TradeSha / AES-256-CBC + SHA256),只在 MerchantID、HashKey、URL 與部分付款方式上有差異。
1237
+ ezPay 簡單付是**電子支付機構**,官方提供兩組 API(演算法相同、欄位與網址不同):
1238
+
1239
+ - **電子支付平台(境內)**:`https://(c)payment.ezpay.com.tw/API/Twqr/{APIID}`,外層 `APIID` + `Version=1.0` + `UID` + `EncryptData` + `HashData`;
1240
+ 收 ezPay 帳戶、約定連結存款帳戶、ezPay 約定信用卡與 **TWQR**(台灣 Pay、街口、全支付…掃碼)。
1241
+ - **跨境(支付寶 / 微信)**:`https://(c)payment.ezpay.com.tw/MPG/mpg_gateway`,`TradeInfo` / `TradeSha`,Version 1.0。
1461
1242
 
1462
1243
  ### 完整 Python 範例
1463
- 請見 [`examples/ezpay-payment-example.py`](examples/ezpay-payment-example.py) — 由 `newebpay-payment-example.py` 衍生,凸顯差異點。
1244
+ 請見 [`examples/ezpay-payment-example.py`](examples/ezpay-payment-example.py):`EzPayWalletService`(7 支境內 API)與
1245
+ `EzPayCrossBorderService`(跨境 MPG、查詢、退款),內建官方手冊的已知答案測試。
1464
1246
 
1465
1247
  ### 三大要點
1466
1248
 
1467
- 1. **加密邏輯完全照抄 NewebPay**:可直接複用同一份加解密 helper。
1468
- 2. **URL 不同**:ezPay 沙箱 `https://ccore.spgateway.com/MPG/mpg_gateway`(spgateway.com 是舊網域,仍可用)。
1469
- 3. **付款方式受限**:分期、部分電子錢包在 ezPay 計劃下不可用;以後台啟用為準。
1249
+ 1. **AES 以 32 bytes 補齊**:`EncryptData = hex(AES-256-CBC(urlencode(參數)))`,PKCS#7 區塊大小 32;用 16 bytes 補齊會與官方範例不符。
1250
+ 2. **回應是 urlencoded,不是 JSON**:電子支付平台的 EncryptData 解密後是 `Status=SUCCESS&...&Result%5BTradeNo%5D=...`,要自行把 `Result[...]` 還原成巢狀;跨境才是 JSON。
1251
+ 3. **不是藍新 NewebPay**:網域、外層欄位、Version、支付工具都不同。舊版本文件說「與 NewebPay MPG 完全相同」並指向 `spgateway.com`,是錯的。
1470
1252
 
1471
1253
  ---
1472
1254
 
@@ -1502,7 +1284,7 @@ Shopline Payments (SLP) 採 **HTTP Header `merchantId` + `apiKey`** 認證,所
1502
1284
 
1503
1285
  1. **金額是分(cents)**:NT$1,050 要傳 `value: 105000`,弄錯會差 100 倍。
1504
1286
  2. **僅支援 TWD**:`currency` 固定為 `TWD`;其他幣別不支援。
1505
- 3. **Webhook 驗章**:`x-slp-signature: sha256=<hex>` header,HMAC-SHA256 用 `webhookSecret` 對 raw body 簽。**用 raw bytes,不要 parse JSON 後再 stringify**(會差換行/空白)。
1287
+ 3. **Webhook 驗章**:header 帶 `timestamp`(毫秒)與 `sign`;`sign = HMAC-SHA256(signKey, f"{timestamp}.{rawBody}")` 的 hex。**用原始 body,不要 parse JSON 後再 stringify**(會差換行/空白),並檢查 timestamp 防重放。
1506
1288
 
1507
1289
  ---
1508
1290
 
@@ -1515,9 +1297,9 @@ LINE Pay 採 **兩段式流程**:`Request → Confirm`。每次請求需產生
1515
1297
 
1516
1298
  ### 五大要點
1517
1299
 
1518
- 1. **HMAC string-to-sign 公式(v3 慣例)**:`ChannelSecret + ApiPath + Body + Nonce` (POST) / `ChannelSecret + ApiPath + QueryString + Nonce` (GET)。⚠️ v4 公式與 v3 是否完全一致需以官方 PDF 驗證。
1300
+ 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」)。
1519
1301
  2. **transactionId 是 19 位數字**:在 JS 直接用 number 會被 IEEE-754 截斷,**永遠用字串處理**。
1520
- 3. **Confirm 的 amount/currency 必須與 Request 完全一致**:差一塊錢就 1183 錯誤。
1302
+ 3. **Confirm 的 amount/currency 必須與 Request 完全一致**:官方 v4 Confirm 的相關錯誤碼含 `1124`(金額資訊錯誤);`1183` 是「低於最低金額」,不在 Confirm 的錯誤清單。
1521
1303
  4. **Capture 兩階段授權**:建立時 `options.payment.capture=false` 只授權;之後手動呼叫 `/capture` 請款,可分批請款多次。
1522
1304
  5. **Preapproved Pay 自動扣款**:建立時帶 `payType=PREAPPROVED` 取得 `regKey`,之後用 `/preapprovedPay/{regKey}/payment` 直接扣款,免使用者再次確認。
1523
1305