taiwan-payment-skill 1.2.0 → 1.3.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 (39) hide show
  1. package/README.md +8 -4
  2. package/assets/taiwan-payment/CLAUDE.md +4 -1
  3. package/assets/taiwan-payment/EXAMPLES.md +48 -0
  4. package/assets/taiwan-payment/README.md +23 -7
  5. package/assets/taiwan-payment/SKILL.md +29 -2
  6. package/assets/taiwan-payment/data/error-codes.csv +60 -32
  7. package/assets/taiwan-payment/data/operations.csv +9 -0
  8. package/assets/taiwan-payment/data/providers.csv +3 -0
  9. package/assets/taiwan-payment/examples/ezpay-payment-example.py +690 -690
  10. package/assets/taiwan-payment/examples/linepay-payment-example.py +305 -0
  11. package/assets/taiwan-payment/examples/paynow-payment-example.py +767 -767
  12. package/assets/taiwan-payment/examples/pchomepay-payment-example.py +556 -556
  13. package/assets/taiwan-payment/examples/shopline-payment-example.py +291 -0
  14. package/assets/taiwan-payment/examples/smilepay-payment-example.py +673 -673
  15. package/assets/taiwan-payment/examples/tappay-payment-example.py +337 -0
  16. package/assets/taiwan-payment/references/ezpay-payment-api.md +660 -660
  17. package/assets/taiwan-payment/references/linepay-payment-api.md +940 -0
  18. package/assets/taiwan-payment/references/paynow-payment-api.md +1654 -1654
  19. package/assets/taiwan-payment/references/pchomepay-payment-api.md +1431 -1431
  20. package/assets/taiwan-payment/references/shopline-payment-api.md +1523 -0
  21. package/assets/taiwan-payment/references/smilepay-payment-api.md +919 -919
  22. package/assets/taiwan-payment/references/tappay-payment-api.md +1245 -0
  23. package/assets/templates/base/skill-content.md +27 -0
  24. package/assets/templates/platforms/agent.json +2 -2
  25. package/assets/templates/platforms/antigravity.json +1 -1
  26. package/assets/templates/platforms/claude.json +2 -2
  27. package/assets/templates/platforms/codebuddy.json +2 -2
  28. package/assets/templates/platforms/codex.json +2 -2
  29. package/assets/templates/platforms/continue.json +2 -2
  30. package/assets/templates/platforms/copilot.json +2 -2
  31. package/assets/templates/platforms/cursor.json +2 -2
  32. package/assets/templates/platforms/gemini.json +2 -2
  33. package/assets/templates/platforms/kiro.json +2 -2
  34. package/assets/templates/platforms/opencode.json +2 -2
  35. package/assets/templates/platforms/qoder.json +2 -2
  36. package/assets/templates/platforms/roocode.json +2 -2
  37. package/assets/templates/platforms/trae.json +2 -2
  38. package/assets/templates/platforms/windsurf.json +2 -2
  39. package/package.json +5 -2
@@ -1,767 +1,767 @@
1
- #!/usr/bin/env python3
2
- """
3
- PayNow 立吉富 Python 完整範例 (現代版 PaymentIntent API)
4
-
5
- 依照 taiwan-payment-skill 最高規範撰寫
6
- 聚焦現代版 PaymentIntent / Customer / Refund REST API;
7
- 傳統版 (cashflow) 提供 stub 供既有商家對照。
8
-
9
- API 文件: https://docs.paynow.com.tw/
10
- 參考文件: taiwan-payment/references/paynow-payment-api.md
11
-
12
- ⚠ 重要提醒 (請於上線前確認):
13
- PayNow 現代版 API 文件聚焦於 request schemas,部分回應的 result 欄位
14
- 僅以 "依場景變化" 描述,並未列出完整鍵名。本檔 dataclass / 解析邏輯
15
- 中的 result_xxx 欄位係依文件示意推導 (例如 auth_code / last4 /
16
- payment_code / virtual_account / redirect_url / tokenized_card_id /
17
- deferred_payment_id 等),**正式上線前請以 PayNow 業務窗口提供之
18
- 完整回應規格為準,並依需要調整本範例的欄位名稱。**
19
-
20
- API Base URL:
21
- PayNow 現代版的實際 API 主機由 PayNow 業務窗口提供 (常見候選網域:
22
- https://api.paynow.com.tw 或 https://gateway.paynow.com.tw);
23
- PayNow 文件範例顯示為 docs.paynow.com.tw,那是文件站,非實際 API host。
24
- 本範例採用 https://api.paynow.com.tw 作為預設,**請依實際開通信件確認**。
25
-
26
- 依賴:
27
- pip install requests
28
- """
29
-
30
- import time
31
- from dataclasses import dataclass, field
32
- from typing import Any, Dict, List, Literal, Optional
33
-
34
- try:
35
- import requests
36
- HAS_REQUESTS = True
37
- except ImportError:
38
- HAS_REQUESTS = False
39
-
40
-
41
- # ----------------------------------------------------------------------------
42
- # Dataclasses (PaymentIntent API)
43
- # ----------------------------------------------------------------------------
44
-
45
-
46
- PayMethod = Literal[
47
- 'CreditCard',
48
- 'CreditCardInstallment',
49
- 'ATM',
50
- 'ConvenienceStore',
51
- 'LINEPayOnline',
52
- 'LINEPayOffline',
53
- 'ApplePay',
54
- 'ApplePayDeferred',
55
- ]
56
-
57
-
58
- @dataclass
59
- class PayNowAddress:
60
- country: str = 'TW'
61
- locality: str = ''
62
- address1: str = ''
63
- address2: str = ''
64
- administrative_area: str = ''
65
- postal_code: str = ''
66
-
67
-
68
- @dataclass
69
- class PayNowCustomerData:
70
- """POST /api/v1/customers"""
71
- first_name: Optional[str] = None
72
- last_name: Optional[str] = None
73
- email: Optional[str] = None
74
- phone_code: Optional[str] = None # 例: "886"
75
- phone_number: Optional[str] = None
76
- address: Optional[PayNowAddress] = None
77
- metadata: Optional[Dict[str, Any]] = None
78
-
79
-
80
- @dataclass
81
- class PayNowPaymentIntentData:
82
- """POST /api/v1/payment-intents"""
83
- amount: float # < 1_000_000_000_000
84
- currency: str = 'TWD'
85
- payment_no: Optional[str] = None # 不指定則系統自動產生
86
- description: Optional[str] = None
87
- result_url: Optional[str] = None # 前景轉跳
88
- webhook_url: Optional[str] = None # 後端通知
89
- allowed_payment_methods: Optional[List[PayMethod]] = None
90
- allow_installments: Optional[List[int]] = None # subset of [3,6,9,12,18,24]
91
- expire_days: Optional[int] = None # 僅 ATM / ConvenienceStore 有效
92
- customer: Optional[str] = None # customer_uuid
93
- line_pay_online_info: Optional[Dict[str, Any]] = None
94
- line_pay_offline_info: Optional[Dict[str, Any]] = None
95
- apple_pay_deferred_info: Optional[Dict[str, Any]] = None
96
-
97
-
98
- @dataclass
99
- class PayNowCheckoutData:
100
- """POST /api/v1/payment-intents/{id}/checkout"""
101
- payment_intent_id: str
102
- key: str # 公鑰
103
- secret: str # PaymentIntent secret
104
- payment_method_type: PayMethod
105
- payment_method_data: Dict[str, Any] = field(default_factory=dict)
106
- use_paynow_sdk: bool = False
107
- payment_no: Optional[str] = None
108
- session_id: Optional[str] = None
109
- otp_flag: Optional[bool] = None
110
- meta: Optional[Dict[str, Any]] = None
111
-
112
-
113
- @dataclass
114
- class PayNowRefundData:
115
- """POST /api/v1/payment-intents/{id}/refunds"""
116
- payment_intent_id: str
117
- amount: float
118
- reason: str # <=255
119
- bank_code: Optional[str] = None # ATM 退款必填
120
- bank_branch_code: Optional[str] = None
121
- bank_account: Optional[str] = None
122
-
123
-
124
- @dataclass
125
- class PayNowApplePaySessionData:
126
- """POST /api/v2/apple-pay-session"""
127
- merchant_identifier: str # merchant.xxx.xxx
128
- display_name: str # <=64 UTF-8
129
- initiative: str = 'web'
130
- initiative_context: str = ''
131
-
132
-
133
- @dataclass
134
- class PayNowApplePayConfirmData:
135
- """POST /api/v1/apple-pay-session"""
136
- merchant_identifier: str
137
- validation_url: str # event.validationURL
138
- domain_name: str
139
- display_name: str
140
-
141
-
142
- @dataclass
143
- class PayNowAPIResponse:
144
- """
145
- PaymentIntent API 通用 wrapper
146
-
147
- 依文件範例:
148
- {
149
- "status": 200,
150
- "type": "success",
151
- "message": "Success",
152
- "result": { ... },
153
- "requestId": "uuid",
154
- "paginate": null
155
- }
156
- """
157
- success: bool
158
- status: int
159
- type_: str = ''
160
- message: str = ''
161
- result: Any = None
162
- request_id: str = ''
163
- paginate: Any = None
164
- error: Optional[str] = None
165
- raw: Dict[str, Any] = field(default_factory=dict)
166
-
167
-
168
- # ----------------------------------------------------------------------------
169
- # Modern Service
170
- # ----------------------------------------------------------------------------
171
-
172
-
173
- class PayNowModernService:
174
- """
175
- PayNow 現代版 PaymentIntent / Customer / Refund REST API
176
-
177
- 認證: Authorization: Bearer <API_KEY>
178
- 請求 / 回應均為 JSON,UTF-8。
179
-
180
- 支援付款方式 (透過 allowedPaymentMethods 或 paymentMethodType):
181
- CreditCard / CreditCardInstallment / ATM / ConvenienceStore /
182
- LINEPayOnline / LINEPayOffline / ApplePay / ApplePayDeferred
183
-
184
- ⚠ Apple Pay session 端點: 新整合請優先使用 v2 (request_apple_pay_session);
185
- v1 (confirm_apple_pay) 用於 ApplePaySession.onvalidatemerchant 階段。
186
-
187
- ⚠ 文件 caveat:
188
- PayNow 提供完整 request schema,但 result 欄位以 "依場景變化" 描述。
189
- 本範例對 result 採 raw dict 透傳,請依實測回應再封裝專屬 dataclass。
190
- """
191
-
192
- # PayNow 業務窗口會提供實際 production base URL;以下為文件展示用網域。
193
- # 文件 base URL 為 https://docs.paynow.com.tw/api/v1,那是文件站。
194
- DEFAULT_BASE_URL = 'https://api.paynow.com.tw' # 待 PayNow 確認
195
- ALTERNATE_BASE_URL = 'https://gateway.paynow.com.tw' # 傳統版 cashflow 主域
196
-
197
- def __init__(
198
- self,
199
- api_key: str,
200
- base_url: Optional[str] = None,
201
- timeout: int = 30,
202
- ):
203
- if not HAS_REQUESTS:
204
- raise ImportError('需要安裝 requests: pip install requests')
205
-
206
- self.api_key = api_key
207
- self.base_url = (base_url or self.DEFAULT_BASE_URL).rstrip('/')
208
- self.timeout = timeout
209
- self._session = requests.Session()
210
-
211
- # ------------------------------------------------------------------
212
- # Helpers
213
- # ------------------------------------------------------------------
214
-
215
- def _headers(self) -> Dict[str, str]:
216
- return {
217
- 'Authorization': f'Bearer {self.api_key}',
218
- 'Content-Type': 'application/json',
219
- 'Accept': 'application/json',
220
- }
221
-
222
- def _request(
223
- self,
224
- method: Literal['GET', 'POST', 'DELETE'],
225
- path: str,
226
- json: Optional[Dict[str, Any]] = None,
227
- params: Optional[Dict[str, Any]] = None,
228
- ) -> PayNowAPIResponse:
229
- url = f'{self.base_url}{path}'
230
- try:
231
- resp = self._session.request(
232
- method,
233
- url,
234
- headers=self._headers(),
235
- json=json,
236
- params=params,
237
- timeout=self.timeout,
238
- )
239
- except requests.RequestException as exc:
240
- return PayNowAPIResponse(success=False, status=0, error=str(exc))
241
-
242
- try:
243
- body = resp.json()
244
- except ValueError:
245
- return PayNowAPIResponse(
246
- success=False,
247
- status=resp.status_code,
248
- error='Non-JSON response',
249
- raw={'text': resp.text},
250
- )
251
-
252
- type_ = body.get('type', '')
253
- success = resp.ok and type_ != 'error'
254
-
255
- return PayNowAPIResponse(
256
- success=success,
257
- status=body.get('status', resp.status_code),
258
- type_=type_,
259
- message=body.get('message', ''),
260
- result=body.get('result'),
261
- request_id=body.get('requestId', ''),
262
- paginate=body.get('paginate'),
263
- error=body.get('message') if not success else None,
264
- raw=body,
265
- )
266
-
267
- # ------------------------------------------------------------------
268
- # PaymentIntent
269
- # ------------------------------------------------------------------
270
-
271
- def create_payment_intent(
272
- self, data: PayNowPaymentIntentData
273
- ) -> PayNowAPIResponse:
274
- """
275
- 建立 PaymentIntent POST /api/v1/payment-intents
276
-
277
- result 預期含 (依文件示意):
278
- id, paymentNo, status, checkout_url, ...
279
- """
280
- if data.amount <= 0:
281
- raise ValueError('amount 需大於 0')
282
- if data.amount >= 1_000_000_000_000:
283
- raise ValueError('amount 限制 < 1,000,000,000,000')
284
-
285
- body: Dict[str, Any] = {
286
- 'amount': data.amount,
287
- 'currency': data.currency,
288
- }
289
- if data.payment_no is not None:
290
- body['paymentNo'] = data.payment_no
291
- if data.description:
292
- body['description'] = data.description
293
- if data.result_url:
294
- body['resultUrl'] = data.result_url
295
- if data.webhook_url:
296
- body['webhookUrl'] = data.webhook_url
297
- if data.allowed_payment_methods:
298
- body['allowedPaymentMethods'] = data.allowed_payment_methods
299
- if data.allow_installments:
300
- body['allowInstallments'] = data.allow_installments
301
- if data.expire_days is not None:
302
- body['expireDays'] = data.expire_days
303
- if data.customer:
304
- body['customer'] = data.customer
305
- if data.line_pay_online_info:
306
- body['linePayOnlineInfo'] = data.line_pay_online_info
307
- if data.line_pay_offline_info:
308
- body['linePayOfflineInfo'] = data.line_pay_offline_info
309
- if data.apple_pay_deferred_info:
310
- body['applePayDeferredInfo'] = data.apple_pay_deferred_info
311
-
312
- return self._request('POST', '/api/v1/payment-intents', body)
313
-
314
- def checkout(self, data: PayNowCheckoutData) -> PayNowAPIResponse:
315
- """
316
- 付款執行 POST /api/v1/payment-intents/{id}/checkout
317
-
318
- ⚠ 此 API 需另行向 PayNow 業務申請開通;通常用於商家自建表單流程。
319
-
320
- result 依 paymentMethodType 不同會帶不同欄位 (依文件示意):
321
- CreditCard 成功: result.auth_code, result.last4
322
- CreditCard With Token: result.tokenized_card_id (後續可重複使用)
323
- CreditCard 3D Secure: result.redirect_url (需轉址完成 3DS)
324
- ATM Pending Review: result.bank_code, result.virtual_account, result.expire_at
325
- ConvenienceStore Ibon: result.payment_code, result.expire_at
326
- LINE Pay Online: result.redirect_url
327
- ApplePay 成功: result.auth_code, result.last4
328
- ApplePay Deferred: result.deferred_payment_id
329
- """
330
- body: Dict[str, Any] = {
331
- 'key': data.key,
332
- 'secret': data.secret,
333
- 'paymentMethodType': data.payment_method_type,
334
- 'paymentMethodData': data.payment_method_data,
335
- 'usePayNowSdk': data.use_paynow_sdk,
336
- }
337
- if data.payment_no is not None:
338
- body['paymentNo'] = data.payment_no
339
- if data.session_id:
340
- body['sessionId'] = data.session_id
341
- if data.otp_flag is not None:
342
- body['otpFlag'] = data.otp_flag
343
- if data.meta:
344
- body['meta'] = data.meta
345
-
346
- return self._request(
347
- 'POST',
348
- f'/api/v1/payment-intents/{data.payment_intent_id}/checkout',
349
- body,
350
- )
351
-
352
- def retrieve_payment_intent(self, payment_intent_id: str) -> PayNowAPIResponse:
353
- """訂單查詢 GET /api/v1/payment-intents/{id}"""
354
- return self._request('GET', f'/api/v1/payment-intents/{payment_intent_id}')
355
-
356
- # ------------------------------------------------------------------
357
- # Refund
358
- # ------------------------------------------------------------------
359
-
360
- def refund(self, data: PayNowRefundData) -> PayNowAPIResponse:
361
- """
362
- 建立退款 POST /api/v1/payment-intents/{id}/refunds
363
-
364
- ATM 退款需帶 bank_code / bank_branch_code / bank_account;
365
- 信用卡 / Apple Pay / LINE Pay 直接走原通路退款,免帶銀行欄位。
366
-
367
- result.status 可能值: success / failed / rejected / processing / validation_error
368
- """
369
- if data.amount <= 0:
370
- raise ValueError('退款金額需 > 0')
371
- if len(data.reason) > 255:
372
- raise ValueError('reason 限 255 字元')
373
-
374
- body: Dict[str, Any] = {
375
- 'amount': data.amount,
376
- 'reason': data.reason,
377
- }
378
- if data.bank_code:
379
- body['bankCode'] = data.bank_code
380
- if data.bank_branch_code:
381
- body['bankBranchCode'] = data.bank_branch_code
382
- if data.bank_account:
383
- body['bankAccount'] = data.bank_account
384
-
385
- return self._request(
386
- 'POST',
387
- f'/api/v1/payment-intents/{data.payment_intent_id}/refunds',
388
- body,
389
- )
390
-
391
- def list_refunds(
392
- self, page: int = 1, limit: int = 10
393
- ) -> PayNowAPIResponse:
394
- """退款列表 GET /api/v1/refunds"""
395
- return self._request(
396
- 'GET', '/api/v1/refunds', params={'Page': page, 'Limit': limit}
397
- )
398
-
399
- def retrieve_refund(self, refund_uuid: str) -> PayNowAPIResponse:
400
- """退款查詢 GET /api/v1/refunds/{uuid}"""
401
- return self._request('GET', f'/api/v1/refunds/{refund_uuid}')
402
-
403
- # ------------------------------------------------------------------
404
- # Apple Pay
405
- # ------------------------------------------------------------------
406
-
407
- def request_apple_pay_session(
408
- self, data: PayNowApplePaySessionData
409
- ) -> PayNowAPIResponse:
410
- """
411
- Request Apple Pay session (v2) POST /api/v2/apple-pay-session
412
-
413
- 新整合請優先使用 v2。
414
- """
415
- body = {
416
- 'merchant_identifier': data.merchant_identifier,
417
- 'display_name': data.display_name,
418
- 'initiative': data.initiative,
419
- 'initiative_context': data.initiative_context,
420
- }
421
- return self._request('POST', '/api/v2/apple-pay-session', body)
422
-
423
- def confirm_apple_pay(
424
- self, data: PayNowApplePayConfirmData
425
- ) -> PayNowAPIResponse:
426
- """
427
- Confirm Apple Pay session (v1) POST /api/v1/apple-pay-session
428
-
429
- 於 ApplePaySession.onvalidatemerchant 收到 event.validationURL 時呼叫。
430
- """
431
- body = {
432
- 'merchant_identifier': data.merchant_identifier,
433
- 'validation_url': data.validation_url,
434
- 'domain_name': data.domain_name,
435
- 'display_name': data.display_name,
436
- }
437
- return self._request('POST', '/api/v1/apple-pay-session', body)
438
-
439
- def cancel_apple_pay_deferred(
440
- self, payment_intent_uuid: str, reason: str
441
- ) -> PayNowAPIResponse:
442
- """
443
- Apple Pay Deferred Cancel
444
- POST /api/v1/payment-intents/apple-pay-deferreds/{uuid}/cancel
445
- """
446
- if len(reason) > 500:
447
- raise ValueError('reason 限 500 字元')
448
- return self._request(
449
- 'POST',
450
- f'/api/v1/payment-intents/apple-pay-deferreds/{payment_intent_uuid}/cancel',
451
- {'reason': reason},
452
- )
453
-
454
- # ------------------------------------------------------------------
455
- # Customer / Card Token
456
- # ------------------------------------------------------------------
457
-
458
- def create_customer(self, data: PayNowCustomerData) -> PayNowAPIResponse:
459
- """建立 Customer POST /api/v1/customers"""
460
- body: Dict[str, Any] = {}
461
- if data.first_name:
462
- body['first_name'] = data.first_name
463
- if data.last_name:
464
- body['last_name'] = data.last_name
465
- if data.email:
466
- body['email'] = data.email
467
- if data.phone_code:
468
- body['phone_code'] = data.phone_code
469
- if data.phone_number:
470
- body['phone_number'] = data.phone_number
471
- if data.address:
472
- body['address'] = {
473
- 'country': data.address.country,
474
- 'locality': data.address.locality,
475
- 'address1': data.address.address1,
476
- 'address2': data.address.address2,
477
- 'administrative_area': data.address.administrative_area,
478
- 'postal_code': data.address.postal_code,
479
- }
480
- if data.metadata:
481
- body['metadata'] = data.metadata
482
-
483
- return self._request('POST', '/api/v1/customers', body)
484
-
485
- def retrieve_customer(self, customer_uuid: str) -> PayNowAPIResponse:
486
- """Customer 查詢 GET /api/v1/customers/{customer_uuid}"""
487
- return self._request('GET', f'/api/v1/customers/{customer_uuid}')
488
-
489
- def retrieve_card_token(self, customer_uuid: str) -> PayNowAPIResponse:
490
- """
491
- 查詢 Customer 名下的記憶卡片 GET /api/v1/customers/{uuid}/card-tokens
492
-
493
- result 為 array,每個元素含 id / last4 / bin / brand / expire_month / expire_year
494
- """
495
- return self._request(
496
- 'GET', f'/api/v1/customers/{customer_uuid}/card-tokens'
497
- )
498
-
499
-
500
- # ----------------------------------------------------------------------------
501
- # Legacy Service (stub for existing 商家)
502
- # ----------------------------------------------------------------------------
503
-
504
-
505
- class PayNowLegacyService:
506
- """
507
- PayNow 傳統版 (cashflow / etopm.aspx) 簡要 stub
508
-
509
- ⚠ 新接商家請改用 PayNowModernService;此 class 僅供既有整合維護參考。
510
- 傳統版採:
511
- - SHA-1 PassCode + 動態 AES-256 (Bootstrap Key/IV → GP/GK 取單次 Key/IV)
512
- - TimeStr 10 碼自訂格式
513
- - Form POST + URL Encoded
514
- 完整實作建議直接參考 references/paynow-payment-api.md 中的演算法章節。
515
- """
516
-
517
- LEGACY_PROD_URL = 'https://www.paynow.com.tw/service/etopm.aspx'
518
- LEGACY_TEST_URL = 'https://test.paynow.com.tw/service/etopm.aspx'
519
-
520
- BOOTSTRAP_KEY = 'paynowencryptpaynowcomtw28229955' # 32 bytes
521
- BOOTSTRAP_IV = 'encrypt282299550' # 16 bytes
522
-
523
- def __init__(self, web_no: str, apicode: str, merchant_password: str,
524
- is_production: bool = False) -> None:
525
- self.web_no = web_no
526
- self.apicode = apicode
527
- self.merchant_password = merchant_password
528
- self.url = self.LEGACY_PROD_URL if is_production else self.LEGACY_TEST_URL
529
-
530
- @staticmethod
531
- def generate_passcode_request(
532
- web_no: str, order_no: str, total_price: int, apicode: str
533
- ) -> str:
534
- """訂單建立 PassCode = SHA1(WebNo + OrderNo + TotalPrice + apicode)"""
535
- import hashlib as _hashlib
536
- raw = f'{web_no}{order_no}{total_price}{apicode}'
537
- return _hashlib.sha1(raw.encode('utf-8')).hexdigest().upper()
538
-
539
- @staticmethod
540
- def verify_passcode_response(
541
- web_no: str,
542
- order_no: str,
543
- total_price: int,
544
- merchant_password: str,
545
- tran_status: str,
546
- received: str,
547
- ) -> bool:
548
- """付款回傳 PassCode = SHA1(WebNo+OrderNo+TotalPrice+賣場交易密碼+TranStatus)"""
549
- import hashlib as _hashlib
550
- raw = f'{web_no}{order_no}{total_price}{merchant_password}{tran_status}'
551
- expected = _hashlib.sha1(raw.encode('utf-8')).hexdigest().upper()
552
- return expected == received.upper()
553
-
554
- @staticmethod
555
- def generate_timestr(now=None) -> str:
556
- """
557
- TimeStr = (西元年最後 1 碼) + (一年中第幾天 3 碼 zfill) + HH + MM + SS
558
- 範例: 2019-11-24 00:50:18 -> 9328005018
559
- """
560
- from datetime import datetime as _dt
561
- now = now or _dt.now()
562
- year_last = str(now.year)[-1]
563
- day_of_year = str(now.timetuple().tm_yday).zfill(3)
564
- return (
565
- f'{year_last}{day_of_year}'
566
- f'{now.hour:02d}{now.minute:02d}{now.second:02d}'
567
- )
568
-
569
-
570
- # ----------------------------------------------------------------------------
571
- # Examples
572
- # ----------------------------------------------------------------------------
573
-
574
-
575
- def example_create_payment_intent(service: PayNowModernService) -> None:
576
- print('[範例 1] 建立 PaymentIntent (信用卡 + 分期)')
577
- print('-' * 60)
578
- intent = PayNowPaymentIntentData(
579
- payment_no=f'ORD{int(time.time())}',
580
- amount=12000,
581
- currency='TWD',
582
- description='Premium membership',
583
- result_url='https://shop.example.com/pay/result',
584
- webhook_url='https://shop.example.com/pay/webhook',
585
- allowed_payment_methods=['CreditCard', 'CreditCardInstallment'],
586
- allow_installments=[3, 6, 12],
587
- )
588
- print(f' paymentNo: {intent.payment_no}')
589
- print(f' amount: {intent.amount}')
590
- print(f' methods: {intent.allowed_payment_methods}')
591
- print(f' installments: {intent.allow_installments}')
592
- print(' -> service.create_payment_intent(intent)')
593
- print(' 回應 result 含 id (PaymentIntent UUID) / paymentNo / checkout_url')
594
- print()
595
-
596
-
597
- def example_checkout(service: PayNowModernService) -> None:
598
- print('[範例 2] PaymentIntent Checkout (信用卡 + PayNow SDK token + 3DS)')
599
- print('-' * 60)
600
- checkout = PayNowCheckoutData(
601
- payment_intent_id='pi_01h8hxxxxxxxxxxxxxxxxx',
602
- key='pk_live_xxxxxxxx',
603
- secret='pi_secret_xxxxxxxxxxxxxxxx',
604
- payment_method_type='CreditCard',
605
- use_paynow_sdk=True, # 由 PayNow Component 蒐集卡號
606
- otp_flag=True,
607
- payment_method_data={
608
- # 卡片資料若 usePayNowSdk=True 由 SDK 回填,這裡示範 billTo
609
- 'billTo': {
610
- 'firstName': 'Hello',
611
- 'lastName': 'World',
612
- 'email': 'buyer@example.com',
613
- },
614
- },
615
- meta={
616
- 'client': {'height': 768, 'width': 1024},
617
- 'iframe': {'height': 600, 'width': 480},
618
- },
619
- )
620
- print(f' payment_intent_id: {checkout.payment_intent_id}')
621
- print(f' paymentMethodType: {checkout.payment_method_type}')
622
- print(f' usePayNowSdk: {checkout.use_paynow_sdk}')
623
- print(' -> service.checkout(checkout)')
624
- print(' 回應 result.auth_code / .last4 (一次扣款成功) 或')
625
- print(' result.redirect_url (3DS 轉址) 或')
626
- print(' result.tokenized_card_id (有開啟 tokenize)')
627
- print()
628
-
629
-
630
- def example_retrieve_payment_intent(service: PayNowModernService) -> None:
631
- print('[範例 3] PaymentIntent Retrieve')
632
- print('-' * 60)
633
- print(' service.retrieve_payment_intent("pi_01h8hxxxxxxxxxxxxxxxxx")')
634
- print(' -> 用於確認消費者是否完成 ATM / 超商 / LINE Pay 取號 -> 繳費的轉態')
635
- print(' -> Webhook 失敗的補單作業也用此 API')
636
- print()
637
-
638
-
639
- def example_refund(service: PayNowModernService) -> None:
640
- print('[範例 4] Refund (信用卡部分退款 + ATM 退款)')
641
- print('-' * 60)
642
- cc_refund = PayNowRefundData(
643
- payment_intent_id='pi_01h8hxxxxxxxxxxxxxxxxx',
644
- amount=500,
645
- reason='Customer requested partial refund',
646
- )
647
- print(' Credit Card partial refund:')
648
- print(f' amount={cc_refund.amount} reason={cc_refund.reason!r}')
649
- print()
650
- atm_refund = PayNowRefundData(
651
- payment_intent_id='pi_01h8hyyyyyyyyyyyyyyyyy',
652
- amount=1500,
653
- reason='Out of stock',
654
- bank_code='812',
655
- bank_branch_code='0017',
656
- bank_account='12345678901234',
657
- )
658
- print(' ATM refund (需帶銀行資訊):')
659
- print(f' amount={atm_refund.amount} bank_code={atm_refund.bank_code}')
660
- print(f' branch={atm_refund.bank_branch_code} account={atm_refund.bank_account}')
661
- print()
662
-
663
-
664
- def example_apple_pay_session(service: PayNowModernService) -> None:
665
- print('[範例 5] Apple Pay session (v2 request + v1 confirm)')
666
- print('-' * 60)
667
- v2 = PayNowApplePaySessionData(
668
- merchant_identifier='merchant.com.example.shop',
669
- display_name='Example Shop',
670
- initiative='web',
671
- initiative_context='shop.example.com',
672
- )
673
- print(' v2 Request (新整合優先):')
674
- print(f' merchant_identifier={v2.merchant_identifier}')
675
- print(f' display_name={v2.display_name}')
676
- print()
677
- v1 = PayNowApplePayConfirmData(
678
- merchant_identifier='merchant.com.example.shop',
679
- validation_url='https://apple-pay-gateway.apple.com/paymentservices/startSession',
680
- domain_name='shop.example.com',
681
- display_name='Example Shop',
682
- )
683
- print(' v1 Confirm (ApplePaySession.onvalidatemerchant 階段):')
684
- print(f' validation_url={v1.validation_url}')
685
- print()
686
-
687
-
688
- def example_customer_and_card_token(service: PayNowModernService) -> None:
689
- print('[範例 6] Customer + Card Token')
690
- print('-' * 60)
691
- customer = PayNowCustomerData(
692
- first_name='Hello',
693
- last_name='World',
694
- email='buyer@example.com',
695
- phone_code='886',
696
- phone_number='0912345678',
697
- address=PayNowAddress(
698
- country='TW',
699
- locality='Taipei',
700
- address1='中山區民生東路三段 19 號',
701
- administrative_area='Taipei City',
702
- postal_code='10478',
703
- ),
704
- )
705
- print(' create_customer(customer)')
706
- print(f' name: {customer.first_name} {customer.last_name}')
707
- print(f' address: {customer.address.address1}')
708
- print()
709
- print(' retrieve_card_token("cus_01h8hxxxxxxxxxxxxxxxxx")')
710
- print(' -> result 為 array,每個元素含 id / last4 / brand / expire_month/year')
711
- print(' -> 將 Card Token id 放到 paymentMethodData 中即可重複扣款')
712
- print()
713
-
714
-
715
- def example_legacy_passcode() -> None:
716
- print('[範例 7] 傳統版 (legacy) PassCode 計算 (僅供既有商家維護)')
717
- print('-' * 60)
718
- passcode = PayNowLegacyService.generate_passcode_request(
719
- web_no='28229955',
720
- order_no='ORD20260507001',
721
- total_price=1500,
722
- apicode='YOUR_API_CODE',
723
- )
724
- print(f' PassCode (送出): {passcode[:40]}...')
725
- timestr = PayNowLegacyService.generate_timestr()
726
- print(f' TimeStr (10 碼自訂格式): {timestr}')
727
- print(' 傳統版完整流程 (GP/GK 取動態 AES Key/IV) 請見 references/paynow-payment-api.md')
728
- print()
729
-
730
-
731
- if __name__ == '__main__':
732
- print('=' * 60)
733
- print('PayNow 立吉富金流 - Python 範例 (現代版 PaymentIntent)')
734
- print('=' * 60)
735
- print()
736
- print('[注意] PayNow 不公開固定測試金鑰;')
737
- print(' 請至 https://test.paynow.com.tw 註冊取得 API Key (現代版)')
738
- print(' 或賣場交易密碼 (傳統版)。')
739
- print()
740
- print('[Caveat] result 欄位名稱 (auth_code / last4 / virtual_account / ...) 為')
741
- print(' 依文件示意推導,正式上線前請以 PayNow 提供之完整回應規格為準。')
742
- print()
743
-
744
- if not HAS_REQUESTS:
745
- print('(缺 requests 套件,僅執行不需 HTTP 的範例)')
746
- print('安裝指令: pip install requests')
747
- print()
748
- example_legacy_passcode()
749
- exit(0)
750
-
751
- # 替換為 PayNow 業務窗口提供之 API Key 與 base URL
752
- service = PayNowModernService(
753
- api_key='YOUR_PAYNOW_API_KEY',
754
- base_url='https://api.paynow.com.tw', # 上線前向 PayNow 確認
755
- )
756
-
757
- example_create_payment_intent(service)
758
- example_checkout(service)
759
- example_retrieve_payment_intent(service)
760
- example_refund(service)
761
- example_apple_pay_session(service)
762
- example_customer_and_card_token(service)
763
- example_legacy_passcode()
764
-
765
- print('=' * 60)
766
- print('範例執行完成')
767
- print('=' * 60)
1
+ #!/usr/bin/env python3
2
+ """
3
+ PayNow 立吉富 Python 完整範例 (現代版 PaymentIntent API)
4
+
5
+ 依照 taiwan-payment-skill 最高規範撰寫
6
+ 聚焦現代版 PaymentIntent / Customer / Refund REST API;
7
+ 傳統版 (cashflow) 提供 stub 供既有商家對照。
8
+
9
+ API 文件: https://docs.paynow.com.tw/
10
+ 參考文件: taiwan-payment/references/paynow-payment-api.md
11
+
12
+ ⚠ 重要提醒 (請於上線前確認):
13
+ PayNow 現代版 API 文件聚焦於 request schemas,部分回應的 result 欄位
14
+ 僅以 "依場景變化" 描述,並未列出完整鍵名。本檔 dataclass / 解析邏輯
15
+ 中的 result_xxx 欄位係依文件示意推導 (例如 auth_code / last4 /
16
+ payment_code / virtual_account / redirect_url / tokenized_card_id /
17
+ deferred_payment_id 等),**正式上線前請以 PayNow 業務窗口提供之
18
+ 完整回應規格為準,並依需要調整本範例的欄位名稱。**
19
+
20
+ API Base URL:
21
+ PayNow 現代版的實際 API 主機由 PayNow 業務窗口提供 (常見候選網域:
22
+ https://api.paynow.com.tw 或 https://gateway.paynow.com.tw);
23
+ PayNow 文件範例顯示為 docs.paynow.com.tw,那是文件站,非實際 API host。
24
+ 本範例採用 https://api.paynow.com.tw 作為預設,**請依實際開通信件確認**。
25
+
26
+ 依賴:
27
+ pip install requests
28
+ """
29
+
30
+ import time
31
+ from dataclasses import dataclass, field
32
+ from typing import Any, Dict, List, Literal, Optional
33
+
34
+ try:
35
+ import requests
36
+ HAS_REQUESTS = True
37
+ except ImportError:
38
+ HAS_REQUESTS = False
39
+
40
+
41
+ # ----------------------------------------------------------------------------
42
+ # Dataclasses (PaymentIntent API)
43
+ # ----------------------------------------------------------------------------
44
+
45
+
46
+ PayMethod = Literal[
47
+ 'CreditCard',
48
+ 'CreditCardInstallment',
49
+ 'ATM',
50
+ 'ConvenienceStore',
51
+ 'LINEPayOnline',
52
+ 'LINEPayOffline',
53
+ 'ApplePay',
54
+ 'ApplePayDeferred',
55
+ ]
56
+
57
+
58
+ @dataclass
59
+ class PayNowAddress:
60
+ country: str = 'TW'
61
+ locality: str = ''
62
+ address1: str = ''
63
+ address2: str = ''
64
+ administrative_area: str = ''
65
+ postal_code: str = ''
66
+
67
+
68
+ @dataclass
69
+ class PayNowCustomerData:
70
+ """POST /api/v1/customers"""
71
+ first_name: Optional[str] = None
72
+ last_name: Optional[str] = None
73
+ email: Optional[str] = None
74
+ phone_code: Optional[str] = None # 例: "886"
75
+ phone_number: Optional[str] = None
76
+ address: Optional[PayNowAddress] = None
77
+ metadata: Optional[Dict[str, Any]] = None
78
+
79
+
80
+ @dataclass
81
+ class PayNowPaymentIntentData:
82
+ """POST /api/v1/payment-intents"""
83
+ amount: float # < 1_000_000_000_000
84
+ currency: str = 'TWD'
85
+ payment_no: Optional[str] = None # 不指定則系統自動產生
86
+ description: Optional[str] = None
87
+ result_url: Optional[str] = None # 前景轉跳
88
+ webhook_url: Optional[str] = None # 後端通知
89
+ allowed_payment_methods: Optional[List[PayMethod]] = None
90
+ allow_installments: Optional[List[int]] = None # subset of [3,6,9,12,18,24]
91
+ expire_days: Optional[int] = None # 僅 ATM / ConvenienceStore 有效
92
+ customer: Optional[str] = None # customer_uuid
93
+ line_pay_online_info: Optional[Dict[str, Any]] = None
94
+ line_pay_offline_info: Optional[Dict[str, Any]] = None
95
+ apple_pay_deferred_info: Optional[Dict[str, Any]] = None
96
+
97
+
98
+ @dataclass
99
+ class PayNowCheckoutData:
100
+ """POST /api/v1/payment-intents/{id}/checkout"""
101
+ payment_intent_id: str
102
+ key: str # 公鑰
103
+ secret: str # PaymentIntent secret
104
+ payment_method_type: PayMethod
105
+ payment_method_data: Dict[str, Any] = field(default_factory=dict)
106
+ use_paynow_sdk: bool = False
107
+ payment_no: Optional[str] = None
108
+ session_id: Optional[str] = None
109
+ otp_flag: Optional[bool] = None
110
+ meta: Optional[Dict[str, Any]] = None
111
+
112
+
113
+ @dataclass
114
+ class PayNowRefundData:
115
+ """POST /api/v1/payment-intents/{id}/refunds"""
116
+ payment_intent_id: str
117
+ amount: float
118
+ reason: str # <=255
119
+ bank_code: Optional[str] = None # ATM 退款必填
120
+ bank_branch_code: Optional[str] = None
121
+ bank_account: Optional[str] = None
122
+
123
+
124
+ @dataclass
125
+ class PayNowApplePaySessionData:
126
+ """POST /api/v2/apple-pay-session"""
127
+ merchant_identifier: str # merchant.xxx.xxx
128
+ display_name: str # <=64 UTF-8
129
+ initiative: str = 'web'
130
+ initiative_context: str = ''
131
+
132
+
133
+ @dataclass
134
+ class PayNowApplePayConfirmData:
135
+ """POST /api/v1/apple-pay-session"""
136
+ merchant_identifier: str
137
+ validation_url: str # event.validationURL
138
+ domain_name: str
139
+ display_name: str
140
+
141
+
142
+ @dataclass
143
+ class PayNowAPIResponse:
144
+ """
145
+ PaymentIntent API 通用 wrapper
146
+
147
+ 依文件範例:
148
+ {
149
+ "status": 200,
150
+ "type": "success",
151
+ "message": "Success",
152
+ "result": { ... },
153
+ "requestId": "uuid",
154
+ "paginate": null
155
+ }
156
+ """
157
+ success: bool
158
+ status: int
159
+ type_: str = ''
160
+ message: str = ''
161
+ result: Any = None
162
+ request_id: str = ''
163
+ paginate: Any = None
164
+ error: Optional[str] = None
165
+ raw: Dict[str, Any] = field(default_factory=dict)
166
+
167
+
168
+ # ----------------------------------------------------------------------------
169
+ # Modern Service
170
+ # ----------------------------------------------------------------------------
171
+
172
+
173
+ class PayNowModernService:
174
+ """
175
+ PayNow 現代版 PaymentIntent / Customer / Refund REST API
176
+
177
+ 認證: Authorization: Bearer <API_KEY>
178
+ 請求 / 回應均為 JSON,UTF-8。
179
+
180
+ 支援付款方式 (透過 allowedPaymentMethods 或 paymentMethodType):
181
+ CreditCard / CreditCardInstallment / ATM / ConvenienceStore /
182
+ LINEPayOnline / LINEPayOffline / ApplePay / ApplePayDeferred
183
+
184
+ ⚠ Apple Pay session 端點: 新整合請優先使用 v2 (request_apple_pay_session);
185
+ v1 (confirm_apple_pay) 用於 ApplePaySession.onvalidatemerchant 階段。
186
+
187
+ ⚠ 文件 caveat:
188
+ PayNow 提供完整 request schema,但 result 欄位以 "依場景變化" 描述。
189
+ 本範例對 result 採 raw dict 透傳,請依實測回應再封裝專屬 dataclass。
190
+ """
191
+
192
+ # PayNow 業務窗口會提供實際 production base URL;以下為文件展示用網域。
193
+ # 文件 base URL 為 https://docs.paynow.com.tw/api/v1,那是文件站。
194
+ DEFAULT_BASE_URL = 'https://api.paynow.com.tw' # 待 PayNow 確認
195
+ ALTERNATE_BASE_URL = 'https://gateway.paynow.com.tw' # 傳統版 cashflow 主域
196
+
197
+ def __init__(
198
+ self,
199
+ api_key: str,
200
+ base_url: Optional[str] = None,
201
+ timeout: int = 30,
202
+ ):
203
+ if not HAS_REQUESTS:
204
+ raise ImportError('需要安裝 requests: pip install requests')
205
+
206
+ self.api_key = api_key
207
+ self.base_url = (base_url or self.DEFAULT_BASE_URL).rstrip('/')
208
+ self.timeout = timeout
209
+ self._session = requests.Session()
210
+
211
+ # ------------------------------------------------------------------
212
+ # Helpers
213
+ # ------------------------------------------------------------------
214
+
215
+ def _headers(self) -> Dict[str, str]:
216
+ return {
217
+ 'Authorization': f'Bearer {self.api_key}',
218
+ 'Content-Type': 'application/json',
219
+ 'Accept': 'application/json',
220
+ }
221
+
222
+ def _request(
223
+ self,
224
+ method: Literal['GET', 'POST', 'DELETE'],
225
+ path: str,
226
+ json: Optional[Dict[str, Any]] = None,
227
+ params: Optional[Dict[str, Any]] = None,
228
+ ) -> PayNowAPIResponse:
229
+ url = f'{self.base_url}{path}'
230
+ try:
231
+ resp = self._session.request(
232
+ method,
233
+ url,
234
+ headers=self._headers(),
235
+ json=json,
236
+ params=params,
237
+ timeout=self.timeout,
238
+ )
239
+ except requests.RequestException as exc:
240
+ return PayNowAPIResponse(success=False, status=0, error=str(exc))
241
+
242
+ try:
243
+ body = resp.json()
244
+ except ValueError:
245
+ return PayNowAPIResponse(
246
+ success=False,
247
+ status=resp.status_code,
248
+ error='Non-JSON response',
249
+ raw={'text': resp.text},
250
+ )
251
+
252
+ type_ = body.get('type', '')
253
+ success = resp.ok and type_ != 'error'
254
+
255
+ return PayNowAPIResponse(
256
+ success=success,
257
+ status=body.get('status', resp.status_code),
258
+ type_=type_,
259
+ message=body.get('message', ''),
260
+ result=body.get('result'),
261
+ request_id=body.get('requestId', ''),
262
+ paginate=body.get('paginate'),
263
+ error=body.get('message') if not success else None,
264
+ raw=body,
265
+ )
266
+
267
+ # ------------------------------------------------------------------
268
+ # PaymentIntent
269
+ # ------------------------------------------------------------------
270
+
271
+ def create_payment_intent(
272
+ self, data: PayNowPaymentIntentData
273
+ ) -> PayNowAPIResponse:
274
+ """
275
+ 建立 PaymentIntent POST /api/v1/payment-intents
276
+
277
+ result 預期含 (依文件示意):
278
+ id, paymentNo, status, checkout_url, ...
279
+ """
280
+ if data.amount <= 0:
281
+ raise ValueError('amount 需大於 0')
282
+ if data.amount >= 1_000_000_000_000:
283
+ raise ValueError('amount 限制 < 1,000,000,000,000')
284
+
285
+ body: Dict[str, Any] = {
286
+ 'amount': data.amount,
287
+ 'currency': data.currency,
288
+ }
289
+ if data.payment_no is not None:
290
+ body['paymentNo'] = data.payment_no
291
+ if data.description:
292
+ body['description'] = data.description
293
+ if data.result_url:
294
+ body['resultUrl'] = data.result_url
295
+ if data.webhook_url:
296
+ body['webhookUrl'] = data.webhook_url
297
+ if data.allowed_payment_methods:
298
+ body['allowedPaymentMethods'] = data.allowed_payment_methods
299
+ if data.allow_installments:
300
+ body['allowInstallments'] = data.allow_installments
301
+ if data.expire_days is not None:
302
+ body['expireDays'] = data.expire_days
303
+ if data.customer:
304
+ body['customer'] = data.customer
305
+ if data.line_pay_online_info:
306
+ body['linePayOnlineInfo'] = data.line_pay_online_info
307
+ if data.line_pay_offline_info:
308
+ body['linePayOfflineInfo'] = data.line_pay_offline_info
309
+ if data.apple_pay_deferred_info:
310
+ body['applePayDeferredInfo'] = data.apple_pay_deferred_info
311
+
312
+ return self._request('POST', '/api/v1/payment-intents', body)
313
+
314
+ def checkout(self, data: PayNowCheckoutData) -> PayNowAPIResponse:
315
+ """
316
+ 付款執行 POST /api/v1/payment-intents/{id}/checkout
317
+
318
+ ⚠ 此 API 需另行向 PayNow 業務申請開通;通常用於商家自建表單流程。
319
+
320
+ result 依 paymentMethodType 不同會帶不同欄位 (依文件示意):
321
+ CreditCard 成功: result.auth_code, result.last4
322
+ CreditCard With Token: result.tokenized_card_id (後續可重複使用)
323
+ CreditCard 3D Secure: result.redirect_url (需轉址完成 3DS)
324
+ ATM Pending Review: result.bank_code, result.virtual_account, result.expire_at
325
+ ConvenienceStore Ibon: result.payment_code, result.expire_at
326
+ LINE Pay Online: result.redirect_url
327
+ ApplePay 成功: result.auth_code, result.last4
328
+ ApplePay Deferred: result.deferred_payment_id
329
+ """
330
+ body: Dict[str, Any] = {
331
+ 'key': data.key,
332
+ 'secret': data.secret,
333
+ 'paymentMethodType': data.payment_method_type,
334
+ 'paymentMethodData': data.payment_method_data,
335
+ 'usePayNowSdk': data.use_paynow_sdk,
336
+ }
337
+ if data.payment_no is not None:
338
+ body['paymentNo'] = data.payment_no
339
+ if data.session_id:
340
+ body['sessionId'] = data.session_id
341
+ if data.otp_flag is not None:
342
+ body['otpFlag'] = data.otp_flag
343
+ if data.meta:
344
+ body['meta'] = data.meta
345
+
346
+ return self._request(
347
+ 'POST',
348
+ f'/api/v1/payment-intents/{data.payment_intent_id}/checkout',
349
+ body,
350
+ )
351
+
352
+ def retrieve_payment_intent(self, payment_intent_id: str) -> PayNowAPIResponse:
353
+ """訂單查詢 GET /api/v1/payment-intents/{id}"""
354
+ return self._request('GET', f'/api/v1/payment-intents/{payment_intent_id}')
355
+
356
+ # ------------------------------------------------------------------
357
+ # Refund
358
+ # ------------------------------------------------------------------
359
+
360
+ def refund(self, data: PayNowRefundData) -> PayNowAPIResponse:
361
+ """
362
+ 建立退款 POST /api/v1/payment-intents/{id}/refunds
363
+
364
+ ATM 退款需帶 bank_code / bank_branch_code / bank_account;
365
+ 信用卡 / Apple Pay / LINE Pay 直接走原通路退款,免帶銀行欄位。
366
+
367
+ result.status 可能值: success / failed / rejected / processing / validation_error
368
+ """
369
+ if data.amount <= 0:
370
+ raise ValueError('退款金額需 > 0')
371
+ if len(data.reason) > 255:
372
+ raise ValueError('reason 限 255 字元')
373
+
374
+ body: Dict[str, Any] = {
375
+ 'amount': data.amount,
376
+ 'reason': data.reason,
377
+ }
378
+ if data.bank_code:
379
+ body['bankCode'] = data.bank_code
380
+ if data.bank_branch_code:
381
+ body['bankBranchCode'] = data.bank_branch_code
382
+ if data.bank_account:
383
+ body['bankAccount'] = data.bank_account
384
+
385
+ return self._request(
386
+ 'POST',
387
+ f'/api/v1/payment-intents/{data.payment_intent_id}/refunds',
388
+ body,
389
+ )
390
+
391
+ def list_refunds(
392
+ self, page: int = 1, limit: int = 10
393
+ ) -> PayNowAPIResponse:
394
+ """退款列表 GET /api/v1/refunds"""
395
+ return self._request(
396
+ 'GET', '/api/v1/refunds', params={'Page': page, 'Limit': limit}
397
+ )
398
+
399
+ def retrieve_refund(self, refund_uuid: str) -> PayNowAPIResponse:
400
+ """退款查詢 GET /api/v1/refunds/{uuid}"""
401
+ return self._request('GET', f'/api/v1/refunds/{refund_uuid}')
402
+
403
+ # ------------------------------------------------------------------
404
+ # Apple Pay
405
+ # ------------------------------------------------------------------
406
+
407
+ def request_apple_pay_session(
408
+ self, data: PayNowApplePaySessionData
409
+ ) -> PayNowAPIResponse:
410
+ """
411
+ Request Apple Pay session (v2) POST /api/v2/apple-pay-session
412
+
413
+ 新整合請優先使用 v2。
414
+ """
415
+ body = {
416
+ 'merchant_identifier': data.merchant_identifier,
417
+ 'display_name': data.display_name,
418
+ 'initiative': data.initiative,
419
+ 'initiative_context': data.initiative_context,
420
+ }
421
+ return self._request('POST', '/api/v2/apple-pay-session', body)
422
+
423
+ def confirm_apple_pay(
424
+ self, data: PayNowApplePayConfirmData
425
+ ) -> PayNowAPIResponse:
426
+ """
427
+ Confirm Apple Pay session (v1) POST /api/v1/apple-pay-session
428
+
429
+ 於 ApplePaySession.onvalidatemerchant 收到 event.validationURL 時呼叫。
430
+ """
431
+ body = {
432
+ 'merchant_identifier': data.merchant_identifier,
433
+ 'validation_url': data.validation_url,
434
+ 'domain_name': data.domain_name,
435
+ 'display_name': data.display_name,
436
+ }
437
+ return self._request('POST', '/api/v1/apple-pay-session', body)
438
+
439
+ def cancel_apple_pay_deferred(
440
+ self, payment_intent_uuid: str, reason: str
441
+ ) -> PayNowAPIResponse:
442
+ """
443
+ Apple Pay Deferred Cancel
444
+ POST /api/v1/payment-intents/apple-pay-deferreds/{uuid}/cancel
445
+ """
446
+ if len(reason) > 500:
447
+ raise ValueError('reason 限 500 字元')
448
+ return self._request(
449
+ 'POST',
450
+ f'/api/v1/payment-intents/apple-pay-deferreds/{payment_intent_uuid}/cancel',
451
+ {'reason': reason},
452
+ )
453
+
454
+ # ------------------------------------------------------------------
455
+ # Customer / Card Token
456
+ # ------------------------------------------------------------------
457
+
458
+ def create_customer(self, data: PayNowCustomerData) -> PayNowAPIResponse:
459
+ """建立 Customer POST /api/v1/customers"""
460
+ body: Dict[str, Any] = {}
461
+ if data.first_name:
462
+ body['first_name'] = data.first_name
463
+ if data.last_name:
464
+ body['last_name'] = data.last_name
465
+ if data.email:
466
+ body['email'] = data.email
467
+ if data.phone_code:
468
+ body['phone_code'] = data.phone_code
469
+ if data.phone_number:
470
+ body['phone_number'] = data.phone_number
471
+ if data.address:
472
+ body['address'] = {
473
+ 'country': data.address.country,
474
+ 'locality': data.address.locality,
475
+ 'address1': data.address.address1,
476
+ 'address2': data.address.address2,
477
+ 'administrative_area': data.address.administrative_area,
478
+ 'postal_code': data.address.postal_code,
479
+ }
480
+ if data.metadata:
481
+ body['metadata'] = data.metadata
482
+
483
+ return self._request('POST', '/api/v1/customers', body)
484
+
485
+ def retrieve_customer(self, customer_uuid: str) -> PayNowAPIResponse:
486
+ """Customer 查詢 GET /api/v1/customers/{customer_uuid}"""
487
+ return self._request('GET', f'/api/v1/customers/{customer_uuid}')
488
+
489
+ def retrieve_card_token(self, customer_uuid: str) -> PayNowAPIResponse:
490
+ """
491
+ 查詢 Customer 名下的記憶卡片 GET /api/v1/customers/{uuid}/card-tokens
492
+
493
+ result 為 array,每個元素含 id / last4 / bin / brand / expire_month / expire_year
494
+ """
495
+ return self._request(
496
+ 'GET', f'/api/v1/customers/{customer_uuid}/card-tokens'
497
+ )
498
+
499
+
500
+ # ----------------------------------------------------------------------------
501
+ # Legacy Service (stub for existing 商家)
502
+ # ----------------------------------------------------------------------------
503
+
504
+
505
+ class PayNowLegacyService:
506
+ """
507
+ PayNow 傳統版 (cashflow / etopm.aspx) 簡要 stub
508
+
509
+ ⚠ 新接商家請改用 PayNowModernService;此 class 僅供既有整合維護參考。
510
+ 傳統版採:
511
+ - SHA-1 PassCode + 動態 AES-256 (Bootstrap Key/IV → GP/GK 取單次 Key/IV)
512
+ - TimeStr 10 碼自訂格式
513
+ - Form POST + URL Encoded
514
+ 完整實作建議直接參考 references/paynow-payment-api.md 中的演算法章節。
515
+ """
516
+
517
+ LEGACY_PROD_URL = 'https://www.paynow.com.tw/service/etopm.aspx'
518
+ LEGACY_TEST_URL = 'https://test.paynow.com.tw/service/etopm.aspx'
519
+
520
+ BOOTSTRAP_KEY = 'paynowencryptpaynowcomtw28229955' # 32 bytes
521
+ BOOTSTRAP_IV = 'encrypt282299550' # 16 bytes
522
+
523
+ def __init__(self, web_no: str, apicode: str, merchant_password: str,
524
+ is_production: bool = False) -> None:
525
+ self.web_no = web_no
526
+ self.apicode = apicode
527
+ self.merchant_password = merchant_password
528
+ self.url = self.LEGACY_PROD_URL if is_production else self.LEGACY_TEST_URL
529
+
530
+ @staticmethod
531
+ def generate_passcode_request(
532
+ web_no: str, order_no: str, total_price: int, apicode: str
533
+ ) -> str:
534
+ """訂單建立 PassCode = SHA1(WebNo + OrderNo + TotalPrice + apicode)"""
535
+ import hashlib as _hashlib
536
+ raw = f'{web_no}{order_no}{total_price}{apicode}'
537
+ return _hashlib.sha1(raw.encode('utf-8')).hexdigest().upper()
538
+
539
+ @staticmethod
540
+ def verify_passcode_response(
541
+ web_no: str,
542
+ order_no: str,
543
+ total_price: int,
544
+ merchant_password: str,
545
+ tran_status: str,
546
+ received: str,
547
+ ) -> bool:
548
+ """付款回傳 PassCode = SHA1(WebNo+OrderNo+TotalPrice+賣場交易密碼+TranStatus)"""
549
+ import hashlib as _hashlib
550
+ raw = f'{web_no}{order_no}{total_price}{merchant_password}{tran_status}'
551
+ expected = _hashlib.sha1(raw.encode('utf-8')).hexdigest().upper()
552
+ return expected == received.upper()
553
+
554
+ @staticmethod
555
+ def generate_timestr(now=None) -> str:
556
+ """
557
+ TimeStr = (西元年最後 1 碼) + (一年中第幾天 3 碼 zfill) + HH + MM + SS
558
+ 範例: 2019-11-24 00:50:18 -> 9328005018
559
+ """
560
+ from datetime import datetime as _dt
561
+ now = now or _dt.now()
562
+ year_last = str(now.year)[-1]
563
+ day_of_year = str(now.timetuple().tm_yday).zfill(3)
564
+ return (
565
+ f'{year_last}{day_of_year}'
566
+ f'{now.hour:02d}{now.minute:02d}{now.second:02d}'
567
+ )
568
+
569
+
570
+ # ----------------------------------------------------------------------------
571
+ # Examples
572
+ # ----------------------------------------------------------------------------
573
+
574
+
575
+ def example_create_payment_intent(service: PayNowModernService) -> None:
576
+ print('[範例 1] 建立 PaymentIntent (信用卡 + 分期)')
577
+ print('-' * 60)
578
+ intent = PayNowPaymentIntentData(
579
+ payment_no=f'ORD{int(time.time())}',
580
+ amount=12000,
581
+ currency='TWD',
582
+ description='Premium membership',
583
+ result_url='https://shop.example.com/pay/result',
584
+ webhook_url='https://shop.example.com/pay/webhook',
585
+ allowed_payment_methods=['CreditCard', 'CreditCardInstallment'],
586
+ allow_installments=[3, 6, 12],
587
+ )
588
+ print(f' paymentNo: {intent.payment_no}')
589
+ print(f' amount: {intent.amount}')
590
+ print(f' methods: {intent.allowed_payment_methods}')
591
+ print(f' installments: {intent.allow_installments}')
592
+ print(' -> service.create_payment_intent(intent)')
593
+ print(' 回應 result 含 id (PaymentIntent UUID) / paymentNo / checkout_url')
594
+ print()
595
+
596
+
597
+ def example_checkout(service: PayNowModernService) -> None:
598
+ print('[範例 2] PaymentIntent Checkout (信用卡 + PayNow SDK token + 3DS)')
599
+ print('-' * 60)
600
+ checkout = PayNowCheckoutData(
601
+ payment_intent_id='pi_01h8hxxxxxxxxxxxxxxxxx',
602
+ key='pk_live_xxxxxxxx',
603
+ secret='pi_secret_xxxxxxxxxxxxxxxx',
604
+ payment_method_type='CreditCard',
605
+ use_paynow_sdk=True, # 由 PayNow Component 蒐集卡號
606
+ otp_flag=True,
607
+ payment_method_data={
608
+ # 卡片資料若 usePayNowSdk=True 由 SDK 回填,這裡示範 billTo
609
+ 'billTo': {
610
+ 'firstName': 'Hello',
611
+ 'lastName': 'World',
612
+ 'email': 'buyer@example.com',
613
+ },
614
+ },
615
+ meta={
616
+ 'client': {'height': 768, 'width': 1024},
617
+ 'iframe': {'height': 600, 'width': 480},
618
+ },
619
+ )
620
+ print(f' payment_intent_id: {checkout.payment_intent_id}')
621
+ print(f' paymentMethodType: {checkout.payment_method_type}')
622
+ print(f' usePayNowSdk: {checkout.use_paynow_sdk}')
623
+ print(' -> service.checkout(checkout)')
624
+ print(' 回應 result.auth_code / .last4 (一次扣款成功) 或')
625
+ print(' result.redirect_url (3DS 轉址) 或')
626
+ print(' result.tokenized_card_id (有開啟 tokenize)')
627
+ print()
628
+
629
+
630
+ def example_retrieve_payment_intent(service: PayNowModernService) -> None:
631
+ print('[範例 3] PaymentIntent Retrieve')
632
+ print('-' * 60)
633
+ print(' service.retrieve_payment_intent("pi_01h8hxxxxxxxxxxxxxxxxx")')
634
+ print(' -> 用於確認消費者是否完成 ATM / 超商 / LINE Pay 取號 -> 繳費的轉態')
635
+ print(' -> Webhook 失敗的補單作業也用此 API')
636
+ print()
637
+
638
+
639
+ def example_refund(service: PayNowModernService) -> None:
640
+ print('[範例 4] Refund (信用卡部分退款 + ATM 退款)')
641
+ print('-' * 60)
642
+ cc_refund = PayNowRefundData(
643
+ payment_intent_id='pi_01h8hxxxxxxxxxxxxxxxxx',
644
+ amount=500,
645
+ reason='Customer requested partial refund',
646
+ )
647
+ print(' Credit Card partial refund:')
648
+ print(f' amount={cc_refund.amount} reason={cc_refund.reason!r}')
649
+ print()
650
+ atm_refund = PayNowRefundData(
651
+ payment_intent_id='pi_01h8hyyyyyyyyyyyyyyyyy',
652
+ amount=1500,
653
+ reason='Out of stock',
654
+ bank_code='812',
655
+ bank_branch_code='0017',
656
+ bank_account='12345678901234',
657
+ )
658
+ print(' ATM refund (需帶銀行資訊):')
659
+ print(f' amount={atm_refund.amount} bank_code={atm_refund.bank_code}')
660
+ print(f' branch={atm_refund.bank_branch_code} account={atm_refund.bank_account}')
661
+ print()
662
+
663
+
664
+ def example_apple_pay_session(service: PayNowModernService) -> None:
665
+ print('[範例 5] Apple Pay session (v2 request + v1 confirm)')
666
+ print('-' * 60)
667
+ v2 = PayNowApplePaySessionData(
668
+ merchant_identifier='merchant.com.example.shop',
669
+ display_name='Example Shop',
670
+ initiative='web',
671
+ initiative_context='shop.example.com',
672
+ )
673
+ print(' v2 Request (新整合優先):')
674
+ print(f' merchant_identifier={v2.merchant_identifier}')
675
+ print(f' display_name={v2.display_name}')
676
+ print()
677
+ v1 = PayNowApplePayConfirmData(
678
+ merchant_identifier='merchant.com.example.shop',
679
+ validation_url='https://apple-pay-gateway.apple.com/paymentservices/startSession',
680
+ domain_name='shop.example.com',
681
+ display_name='Example Shop',
682
+ )
683
+ print(' v1 Confirm (ApplePaySession.onvalidatemerchant 階段):')
684
+ print(f' validation_url={v1.validation_url}')
685
+ print()
686
+
687
+
688
+ def example_customer_and_card_token(service: PayNowModernService) -> None:
689
+ print('[範例 6] Customer + Card Token')
690
+ print('-' * 60)
691
+ customer = PayNowCustomerData(
692
+ first_name='Hello',
693
+ last_name='World',
694
+ email='buyer@example.com',
695
+ phone_code='886',
696
+ phone_number='0912345678',
697
+ address=PayNowAddress(
698
+ country='TW',
699
+ locality='Taipei',
700
+ address1='中山區民生東路三段 19 號',
701
+ administrative_area='Taipei City',
702
+ postal_code='10478',
703
+ ),
704
+ )
705
+ print(' create_customer(customer)')
706
+ print(f' name: {customer.first_name} {customer.last_name}')
707
+ print(f' address: {customer.address.address1}')
708
+ print()
709
+ print(' retrieve_card_token("cus_01h8hxxxxxxxxxxxxxxxxx")')
710
+ print(' -> result 為 array,每個元素含 id / last4 / brand / expire_month/year')
711
+ print(' -> 將 Card Token id 放到 paymentMethodData 中即可重複扣款')
712
+ print()
713
+
714
+
715
+ def example_legacy_passcode() -> None:
716
+ print('[範例 7] 傳統版 (legacy) PassCode 計算 (僅供既有商家維護)')
717
+ print('-' * 60)
718
+ passcode = PayNowLegacyService.generate_passcode_request(
719
+ web_no='28229955',
720
+ order_no='ORD20260507001',
721
+ total_price=1500,
722
+ apicode='YOUR_API_CODE',
723
+ )
724
+ print(f' PassCode (送出): {passcode[:40]}...')
725
+ timestr = PayNowLegacyService.generate_timestr()
726
+ print(f' TimeStr (10 碼自訂格式): {timestr}')
727
+ print(' 傳統版完整流程 (GP/GK 取動態 AES Key/IV) 請見 references/paynow-payment-api.md')
728
+ print()
729
+
730
+
731
+ if __name__ == '__main__':
732
+ print('=' * 60)
733
+ print('PayNow 立吉富金流 - Python 範例 (現代版 PaymentIntent)')
734
+ print('=' * 60)
735
+ print()
736
+ print('[注意] PayNow 不公開固定測試金鑰;')
737
+ print(' 請至 https://test.paynow.com.tw 註冊取得 API Key (現代版)')
738
+ print(' 或賣場交易密碼 (傳統版)。')
739
+ print()
740
+ print('[Caveat] result 欄位名稱 (auth_code / last4 / virtual_account / ...) 為')
741
+ print(' 依文件示意推導,正式上線前請以 PayNow 提供之完整回應規格為準。')
742
+ print()
743
+
744
+ if not HAS_REQUESTS:
745
+ print('(缺 requests 套件,僅執行不需 HTTP 的範例)')
746
+ print('安裝指令: pip install requests')
747
+ print()
748
+ example_legacy_passcode()
749
+ exit(0)
750
+
751
+ # 替換為 PayNow 業務窗口提供之 API Key 與 base URL
752
+ service = PayNowModernService(
753
+ api_key='YOUR_PAYNOW_API_KEY',
754
+ base_url='https://api.paynow.com.tw', # 上線前向 PayNow 確認
755
+ )
756
+
757
+ example_create_payment_intent(service)
758
+ example_checkout(service)
759
+ example_retrieve_payment_intent(service)
760
+ example_refund(service)
761
+ example_apple_pay_session(service)
762
+ example_customer_and_card_token(service)
763
+ example_legacy_passcode()
764
+
765
+ print('=' * 60)
766
+ print('範例執行完成')
767
+ print('=' * 60)