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,556 +1,556 @@
1
- #!/usr/bin/env python3
2
- """
3
- PChomePay 拍錢包 Python 完整範例
4
-
5
- 依照 taiwan-payment-skill 最高規範撰寫
6
- 支援: 信用卡 (一次付清 / 分期)、ATM 虛擬帳號、超商代碼繳費、訂單查詢、退款
7
-
8
- API 文件: https://web.pchomepay.com.tw/api-setting/environment-setting
9
- 參考文件: taiwan-payment/references/pchomepay-payment-api.md
10
-
11
- 特色:
12
- - REST + JSON:所有請求 / 回應皆為 JSON
13
- - 兩階段認證:HTTP Basic Auth(APP_ID:SECRET) -> /v1/token -> pcpay-token Header
14
- - Token 預設 8 小時 (28,800 秒):本範例會自動快取並在到期前自動 refresh
15
- - 手續費內扣:訂單金額 - 手續費 = 實際入帳
16
-
17
- 防火牆白名單:
18
- PChomePay Notify 來源 IP = 113.196.231.190
19
- 請務必加入合作方 firewall 白名單,否則收不到付款 / 退款 / 物流通知。
20
-
21
- 依賴:
22
- pip install requests
23
- """
24
-
25
- import base64
26
- import time
27
- from dataclasses import dataclass, field
28
- from typing import Any, Dict, List, Literal, Optional
29
-
30
- try:
31
- import requests
32
- HAS_REQUESTS = True
33
- except ImportError:
34
- HAS_REQUESTS = False
35
-
36
-
37
- # ----------------------------------------------------------------------------
38
- # Dataclasses
39
- # ----------------------------------------------------------------------------
40
-
41
-
42
- PayType = Literal['CARD', 'PI', 'ATM', 'IPL7', 'IPLFM', 'IPLHL', 'BCODE']
43
-
44
-
45
- @dataclass
46
- class PChomePayItem:
47
- """商品資訊 (items[*])"""
48
- name: str
49
- url: str # 必須以 http:// 或 https:// 開頭
50
-
51
-
52
- @dataclass
53
- class PChomePayCreditOrder:
54
- """跳轉付款頁訂單 (POST /v1/payment) — 信用卡情境"""
55
- order_id: str # <=50, 英數 + - _
56
- amount: int # CARD: 30 ~ 199,999
57
- items: List[PChomePayItem]
58
- return_url: Optional[str] = None
59
- fail_return_url: Optional[str] = None
60
- notify_url: Optional[str] = None
61
- buyer_email: Optional[str] = None
62
- card_installment: Optional[str] = None # "1,3,6,12,18,24"
63
- member_key: Optional[str] = None # 平台會員 ID (記憶卡用)
64
- platform_code: Optional[str] = None
65
- return_timer: Optional[Literal['Y', 'N']] = None # Y: 倒數 10 秒;N: 立即跳轉
66
-
67
-
68
- @dataclass
69
- class PChomePayAtmOrder:
70
- """幕後取號 ATM 虛擬帳號 (POST /v1/payment/atmva)"""
71
- order_id: str
72
- amount: int # 1 ~ 49,999
73
- item_name: str
74
- item_url: str
75
- buyer_name: str
76
- buyer_mobile: str
77
- expire_days: int = 5 # 1 ~ 5
78
- atm_bank: str = '011' # 預設上海商銀
79
- notify_url: Optional[str] = None
80
- buyer_email: Optional[str] = None
81
- platform_code: Optional[str] = None
82
-
83
-
84
- @dataclass
85
- class PChomePayBarcodeOrder:
86
- """幕後取號 超商代碼繳費 (POST /v1/payment/barcode)"""
87
- order_id: str
88
- amount: int # 25 ~ 20,000
89
- items: List[PChomePayItem]
90
- buyer_name: str # <=50
91
- buyer_mobile: str # 09 開頭 10 碼
92
- expire_days: int = 7 # 1 ~ 7
93
- notify_url: Optional[str] = None
94
- buyer_email: Optional[str] = None
95
- platform_code: Optional[str] = None
96
-
97
-
98
- @dataclass
99
- class PChomePayRefundRequest:
100
- """退款請求 (POST /v1/refund)"""
101
- order_id: str
102
- refund_id: str # <=50, 不可重複
103
- trade_amount: int
104
-
105
-
106
- @dataclass
107
- class PChomePayResponse:
108
- """通用回應 wrapper"""
109
- success: bool
110
- status_code: int
111
- data: Dict[str, Any] = field(default_factory=dict)
112
- error_type: Optional[str] = None
113
- error_code: Optional[int] = None
114
- error_message: Optional[str] = None
115
-
116
-
117
- # ----------------------------------------------------------------------------
118
- # Service
119
- # ----------------------------------------------------------------------------
120
-
121
-
122
- class PChomePayService:
123
- """
124
- PChomePay 拍錢包金流服務 (REST + JSON)
125
-
126
- 認證流程:
127
- 1. POST /v1/token + Authorization: Basic base64(APP_ID:SECRET)
128
- -> { "token": "...", "expired_in": 28800, "expired_timestamp": ... }
129
- 2. 後續請求帶 Header: pcpay-token: <token>
130
-
131
- 本範例會自動快取 token,在到期前 (預留 60 秒緩衝) 自動 refresh。
132
-
133
- 環境:
134
- sandbox = "https://sandbox-api.pchomepay.com.tw"
135
- prod = "https://api.pchomepay.com.tw"
136
-
137
- Notify 來源 IP (firewall 白名單):
138
- 113.196.231.190
139
- """
140
-
141
- SANDBOX_BASE = 'https://sandbox-api.pchomepay.com.tw'
142
- PROD_BASE = 'https://api.pchomepay.com.tw'
143
-
144
- NOTIFY_SOURCE_IP = '113.196.231.190'
145
- TOKEN_REFRESH_BUFFER_SECONDS = 60
146
-
147
- def __init__(
148
- self,
149
- app_id: str,
150
- secret: str,
151
- is_production: bool = False,
152
- timeout: int = 30,
153
- ):
154
- if not HAS_REQUESTS:
155
- raise ImportError('需要安裝 requests: pip install requests')
156
-
157
- self.app_id = app_id
158
- self.secret = secret
159
- self.base_url = self.PROD_BASE if is_production else self.SANDBOX_BASE
160
- self.timeout = timeout
161
-
162
- # token cache
163
- self._token: Optional[str] = None
164
- self._token_expired_at: float = 0.0
165
-
166
- self._session = requests.Session()
167
-
168
- # ------------------------------------------------------------------
169
- # Token management
170
- # ------------------------------------------------------------------
171
-
172
- def _basic_auth_header(self) -> str:
173
- """Authorization: Basic base64(APP_ID:SECRET)"""
174
- raw = f'{self.app_id}:{self.secret}'.encode('utf-8')
175
- return 'Basic ' + base64.b64encode(raw).decode('ascii')
176
-
177
- def get_token(self, force_refresh: bool = False) -> str:
178
- """
179
- 取得 pcpay-token,會自動 cache。Token 預設 8 小時,到期前
180
- TOKEN_REFRESH_BUFFER_SECONDS 秒會自動 refresh。
181
-
182
- Args:
183
- force_refresh: True 則忽略 cache 直接重打 /v1/token
184
-
185
- Returns:
186
- str: 有效的 pcpay-token
187
- """
188
- now = time.time()
189
- if (
190
- not force_refresh
191
- and self._token
192
- and now < self._token_expired_at - self.TOKEN_REFRESH_BUFFER_SECONDS
193
- ):
194
- return self._token
195
-
196
- url = f'{self.base_url}/v1/token'
197
- headers = {
198
- 'Authorization': self._basic_auth_header(),
199
- 'Content-Type': 'application/json',
200
- }
201
- resp = self._session.post(url, headers=headers, timeout=self.timeout)
202
- resp.raise_for_status()
203
- body = resp.json()
204
-
205
- token = body.get('token')
206
- if not token:
207
- raise RuntimeError(f'PChomePay token 取得失敗: {body}')
208
-
209
- self._token = token
210
- # 優先用 expired_timestamp,若無再以 expired_in + now 計算
211
- if body.get('expired_timestamp'):
212
- self._token_expired_at = float(body['expired_timestamp'])
213
- else:
214
- self._token_expired_at = now + float(body.get('expired_in', 28800))
215
-
216
- return token
217
-
218
- def _auth_headers(self) -> Dict[str, str]:
219
- return {
220
- 'pcpay-token': self.get_token(),
221
- 'Content-Type': 'application/json',
222
- 'Accept': 'application/json',
223
- }
224
-
225
- # ------------------------------------------------------------------
226
- # HTTP wrapper
227
- # ------------------------------------------------------------------
228
-
229
- def _request(
230
- self,
231
- method: Literal['GET', 'POST'],
232
- path: str,
233
- json: Optional[Dict[str, Any]] = None,
234
- ) -> PChomePayResponse:
235
- url = f'{self.base_url}{path}'
236
- try:
237
- resp = self._session.request(
238
- method,
239
- url,
240
- headers=self._auth_headers(),
241
- json=json,
242
- timeout=self.timeout,
243
- )
244
- except requests.RequestException as exc:
245
- return PChomePayResponse(
246
- success=False,
247
- status_code=0,
248
- error_message=str(exc),
249
- )
250
-
251
- try:
252
- body = resp.json()
253
- except ValueError:
254
- body = {'raw': resp.text}
255
-
256
- if resp.ok and 'error_type' not in body:
257
- return PChomePayResponse(success=True, status_code=resp.status_code, data=body)
258
-
259
- return PChomePayResponse(
260
- success=False,
261
- status_code=resp.status_code,
262
- data=body,
263
- error_type=body.get('error_type'),
264
- error_code=body.get('code'),
265
- error_message=body.get('message'),
266
- )
267
-
268
- # ------------------------------------------------------------------
269
- # Order creation
270
- # ------------------------------------------------------------------
271
-
272
- def create_credit_order(self, order: PChomePayCreditOrder) -> PChomePayResponse:
273
- """
274
- 建立信用卡 (跳轉付款頁) 訂單 POST /v1/payment
275
-
276
- Returns:
277
- PChomePayResponse.data 內含 order_id / payment_url
278
- -> 將消費者導頁至 payment_url 完成付款
279
- """
280
- if order.amount < 30 or order.amount > 199_999:
281
- raise ValueError('CARD 金額需介於 30 ~ 199,999')
282
-
283
- body: Dict[str, Any] = {
284
- 'order_id': order.order_id,
285
- 'pay_type': ['CARD'],
286
- 'amount': order.amount,
287
- 'items': [{'name': i.name, 'url': i.url} for i in order.items],
288
- }
289
- if order.return_url:
290
- body['return_url'] = order.return_url
291
- if order.fail_return_url:
292
- body['fail_return_url'] = order.fail_return_url
293
- if order.notify_url:
294
- body['notify_url'] = order.notify_url
295
- if order.buyer_email:
296
- body['buyer_email'] = order.buyer_email
297
- if order.card_installment:
298
- body['card_installment'] = order.card_installment
299
- if order.member_key:
300
- body['member_key'] = order.member_key
301
- if order.platform_code:
302
- body['platform_code'] = order.platform_code
303
- if order.return_timer:
304
- body['return_timer'] = order.return_timer
305
-
306
- return self._request('POST', '/v1/payment', body)
307
-
308
- def create_atm_order(self, order: PChomePayAtmOrder) -> PChomePayResponse:
309
- """
310
- 建立 ATM 幕後取號訂單 POST /v1/payment/atmva
311
-
312
- Returns:
313
- PChomePayResponse.data 內含 order_id / virtual_account / bank_id / expire_date
314
- """
315
- if order.amount < 1 or order.amount > 49_999:
316
- raise ValueError('ATM 金額需介於 1 ~ 49,999')
317
- if not (1 <= order.expire_days <= 5):
318
- raise ValueError('expire_days 需介於 1 ~ 5 天')
319
-
320
- body: Dict[str, Any] = {
321
- 'order_id': order.order_id,
322
- 'amount': order.amount,
323
- 'expire_days': order.expire_days,
324
- 'item_name': order.item_name,
325
- 'item_url': order.item_url,
326
- 'atm_bank': order.atm_bank,
327
- 'buyer_name': order.buyer_name,
328
- 'buyer_mobile': order.buyer_mobile,
329
- }
330
- if order.notify_url:
331
- body['notify_url'] = order.notify_url
332
- if order.buyer_email:
333
- body['buyer_email'] = order.buyer_email
334
- if order.platform_code:
335
- body['platform_code'] = order.platform_code
336
-
337
- return self._request('POST', '/v1/payment/atmva', body)
338
-
339
- def create_barcode_order(self, order: PChomePayBarcodeOrder) -> PChomePayResponse:
340
- """
341
- 建立超商代碼繳費 幕後取號訂單 POST /v1/payment/barcode
342
-
343
- Returns:
344
- PChomePayResponse.data 內含 pincode / barcode1~3 / expire_date
345
- """
346
- if order.amount < 25 or order.amount > 20_000:
347
- raise ValueError('BCODE 金額需介於 25 ~ 20,000')
348
- if not (1 <= order.expire_days <= 7):
349
- raise ValueError('expire_days 需介於 1 ~ 7 天')
350
-
351
- body: Dict[str, Any] = {
352
- 'order_id': order.order_id,
353
- 'amount': order.amount,
354
- 'expire_days': order.expire_days,
355
- 'items': [{'name': i.name, 'url': i.url} for i in order.items],
356
- 'buyer_name': order.buyer_name,
357
- 'buyer_mobile': order.buyer_mobile,
358
- }
359
- if order.notify_url:
360
- body['notify_url'] = order.notify_url
361
- if order.buyer_email:
362
- body['buyer_email'] = order.buyer_email
363
- if order.platform_code:
364
- body['platform_code'] = order.platform_code
365
-
366
- return self._request('POST', '/v1/payment/barcode', body)
367
-
368
- # ------------------------------------------------------------------
369
- # Order query / refund
370
- # ------------------------------------------------------------------
371
-
372
- def query_order(self, order_id: str) -> PChomePayResponse:
373
- """訂單查詢 GET /v1/payment/{order_id}"""
374
- return self._request('GET', f'/v1/payment/{order_id}')
375
-
376
- def refund(self, refund_req: PChomePayRefundRequest) -> PChomePayResponse:
377
- """
378
- 建立退款 POST /v1/refund
379
-
380
- 退款規則摘要:
381
- - 信用卡分期 / 超商取貨 / 代碼繳費 → 僅支援全額退款
382
- - 信用卡一次付清 / 拍錢包 / ATM → 支援部分退款
383
- - 退款手續費: ATM / 超商取貨 / 代碼繳費 每筆 15 元
384
- - 帳戶餘額需 >= 退款金額 + 退款手續費
385
- """
386
- if refund_req.trade_amount <= 0:
387
- raise ValueError('退款金額需 > 0')
388
-
389
- body = {
390
- 'order_id': refund_req.order_id,
391
- 'refund_id': refund_req.refund_id,
392
- 'trade_amount': refund_req.trade_amount,
393
- }
394
- return self._request('POST', '/v1/refund', body)
395
-
396
- def query_refund(self, refund_id: str) -> PChomePayResponse:
397
- """退款查詢 GET /v1/refund/{refund_id}"""
398
- return self._request('GET', f'/v1/refund/{refund_id}')
399
-
400
- def query_balance(self) -> PChomePayResponse:
401
- """帳戶餘額查詢 GET /v1/balance"""
402
- return self._request('GET', '/v1/balance')
403
-
404
- def list_atm_banks(self) -> PChomePayResponse:
405
- """ATM 支援銀行清單 GET /v1/payment/atm/banks"""
406
- return self._request('GET', '/v1/payment/atm/banks')
407
-
408
- def list_card_banks(self) -> PChomePayResponse:
409
- """信用卡分期支援銀行 GET /v1/payment/card/banks"""
410
- return self._request('GET', '/v1/payment/card/banks')
411
-
412
-
413
- # ----------------------------------------------------------------------------
414
- # Examples
415
- # ----------------------------------------------------------------------------
416
-
417
-
418
- def example_token_refresh(service: PChomePayService) -> None:
419
- print('[範例 1] Token auto-refresh 機制 (不實際打 API)')
420
- print('-' * 60)
421
- print(f' Base URL: {service.base_url}')
422
- print(f' APP_ID: {service.app_id[:8]}...')
423
- print(f' Refresh buffer: {service.TOKEN_REFRESH_BUFFER_SECONDS} 秒')
424
- print(f' Notify 來源 IP (記得加 firewall 白名單): {service.NOTIFY_SOURCE_IP}')
425
- print()
426
-
427
-
428
- def example_create_credit_order(service: PChomePayService) -> None:
429
- print('[範例 2] 建立信用卡跳轉付款頁訂單 POST /v1/payment')
430
- print('-' * 60)
431
- order = PChomePayCreditOrder(
432
- order_id=f'B2C{int(time.time())}',
433
- amount=2675,
434
- items=[
435
- PChomePayItem(
436
- name='Chrome Dino Camp Shirt',
437
- url='https://shop.example.com/items/chrome-dino-shirt',
438
- ),
439
- ],
440
- return_url='https://shop.example.com/success',
441
- fail_return_url='https://shop.example.com/failed',
442
- notify_url='https://shop.example.com/api/pchomepay/notify',
443
- card_installment='1,3,6,12',
444
- )
445
- print(f' order_id: {order.order_id}')
446
- print(f' amount: {order.amount}')
447
- print(f' 分期: {order.card_installment}')
448
- print(' (示範僅組 payload,未實際呼叫 API;正式 sandbox 需先取得 APP_ID/SECRET)')
449
- print()
450
-
451
-
452
- def example_create_atm_order(service: PChomePayService) -> None:
453
- print('[範例 3] 建立 ATM 幕後取號訂單 POST /v1/payment/atmva')
454
- print('-' * 60)
455
- order = PChomePayAtmOrder(
456
- order_id=f'B2CATM{int(time.time())}',
457
- amount=500,
458
- item_name='休閒褲',
459
- item_url='https://www.example.com.tw',
460
- buyer_name='王大明',
461
- buyer_mobile='0912345678',
462
- expire_days=3,
463
- atm_bank='812', # 台新
464
- notify_url='https://shop.example.com/api/pchomepay/notify',
465
- )
466
- print(f' order_id: {order.order_id}')
467
- print(f' ATM 銀行: {order.atm_bank}')
468
- print(f' 繳費期限: {order.expire_days} 天')
469
- print(' (示範僅組 payload,未實際呼叫 API)')
470
- print()
471
-
472
-
473
- def example_create_barcode_order(service: PChomePayService) -> None:
474
- print('[範例 4] 建立超商代碼繳費訂單 POST /v1/payment/barcode')
475
- print('-' * 60)
476
- order = PChomePayBarcodeOrder(
477
- order_id=f'B2CBARCODE{int(time.time())}',
478
- amount=500,
479
- items=[
480
- PChomePayItem(name='Chrome Dino Camp Shirt', url='https://shop.example.com'),
481
- ],
482
- buyer_name='John Doe',
483
- buyer_mobile='0912345678',
484
- expire_days=7,
485
- notify_url='https://shop.example.com/api/pchomepay/notify',
486
- )
487
- print(f' order_id: {order.order_id}')
488
- print(f' amount: {order.amount}')
489
- print(f' expire: {order.expire_days} 天')
490
- print(' (示範僅組 payload,未實際呼叫 API)')
491
- print()
492
-
493
-
494
- def example_query_order(service: PChomePayService) -> None:
495
- print('[範例 5] 訂單查詢 GET /v1/payment/{order_id}')
496
- print('-' * 60)
497
- print(' service.query_order("B2C1695210352")')
498
- print(' -> response.data 含 status (S/W/F) / pay_type / payment_info / amount ...')
499
- print()
500
-
501
-
502
- def example_refund(service: PChomePayService) -> None:
503
- print('[範例 6] 建立退款 POST /v1/refund')
504
- print('-' * 60)
505
- refund = PChomePayRefundRequest(
506
- order_id='B2C1695210352',
507
- refund_id='B2C1695210352-Refund',
508
- trade_amount=100,
509
- )
510
- print(f' order_id: {refund.order_id}')
511
- print(f' refund_id: {refund.refund_id}')
512
- print(f' trade_amount: {refund.trade_amount}')
513
- print(' 注意:')
514
- print(' - 信用卡分期 / 超商取貨 / 代碼繳費 → 僅支援全額退款')
515
- print(' - ATM / 超商取貨 / 代碼繳費 每筆退款手續費 15 元')
516
- print(' - 帳戶餘額須 >= 退款金額 + 退款手續費')
517
- print()
518
-
519
-
520
- if __name__ == '__main__':
521
- print('=' * 60)
522
- print('PChomePay 拍錢包金流 - Python 範例')
523
- print('=' * 60)
524
- print()
525
-
526
- if not HAS_REQUESTS:
527
- print('(缺 requests 套件,僅展示資料結構)')
528
- print('安裝指令: pip install requests')
529
- print()
530
-
531
- # 建立 service 物件會 raise ImportError;改示範資料結構
532
- order = PChomePayCreditOrder(
533
- order_id='B2C0000000001',
534
- amount=1000,
535
- items=[PChomePayItem(name='範例', url='https://example.com')],
536
- )
537
- print(f'CreditOrder dataclass: order_id={order.order_id} amount={order.amount}')
538
- exit(0)
539
-
540
- # 注意: 請替換為您的測試 APP_ID / SECRET
541
- service = PChomePayService(
542
- app_id='YOUR_SANDBOX_APP_ID',
543
- secret='YOUR_SANDBOX_SECRET',
544
- is_production=False,
545
- )
546
-
547
- example_token_refresh(service)
548
- example_create_credit_order(service)
549
- example_create_atm_order(service)
550
- example_create_barcode_order(service)
551
- example_query_order(service)
552
- example_refund(service)
553
-
554
- print('=' * 60)
555
- print('範例執行完成')
556
- print('=' * 60)
1
+ #!/usr/bin/env python3
2
+ """
3
+ PChomePay 拍錢包 Python 完整範例
4
+
5
+ 依照 taiwan-payment-skill 最高規範撰寫
6
+ 支援: 信用卡 (一次付清 / 分期)、ATM 虛擬帳號、超商代碼繳費、訂單查詢、退款
7
+
8
+ API 文件: https://web.pchomepay.com.tw/api-setting/environment-setting
9
+ 參考文件: taiwan-payment/references/pchomepay-payment-api.md
10
+
11
+ 特色:
12
+ - REST + JSON:所有請求 / 回應皆為 JSON
13
+ - 兩階段認證:HTTP Basic Auth(APP_ID:SECRET) -> /v1/token -> pcpay-token Header
14
+ - Token 預設 8 小時 (28,800 秒):本範例會自動快取並在到期前自動 refresh
15
+ - 手續費內扣:訂單金額 - 手續費 = 實際入帳
16
+
17
+ 防火牆白名單:
18
+ PChomePay Notify 來源 IP = 113.196.231.190
19
+ 請務必加入合作方 firewall 白名單,否則收不到付款 / 退款 / 物流通知。
20
+
21
+ 依賴:
22
+ pip install requests
23
+ """
24
+
25
+ import base64
26
+ import time
27
+ from dataclasses import dataclass, field
28
+ from typing import Any, Dict, List, Literal, Optional
29
+
30
+ try:
31
+ import requests
32
+ HAS_REQUESTS = True
33
+ except ImportError:
34
+ HAS_REQUESTS = False
35
+
36
+
37
+ # ----------------------------------------------------------------------------
38
+ # Dataclasses
39
+ # ----------------------------------------------------------------------------
40
+
41
+
42
+ PayType = Literal['CARD', 'PI', 'ATM', 'IPL7', 'IPLFM', 'IPLHL', 'BCODE']
43
+
44
+
45
+ @dataclass
46
+ class PChomePayItem:
47
+ """商品資訊 (items[*])"""
48
+ name: str
49
+ url: str # 必須以 http:// 或 https:// 開頭
50
+
51
+
52
+ @dataclass
53
+ class PChomePayCreditOrder:
54
+ """跳轉付款頁訂單 (POST /v1/payment) — 信用卡情境"""
55
+ order_id: str # <=50, 英數 + - _
56
+ amount: int # CARD: 30 ~ 199,999
57
+ items: List[PChomePayItem]
58
+ return_url: Optional[str] = None
59
+ fail_return_url: Optional[str] = None
60
+ notify_url: Optional[str] = None
61
+ buyer_email: Optional[str] = None
62
+ card_installment: Optional[str] = None # "1,3,6,12,18,24"
63
+ member_key: Optional[str] = None # 平台會員 ID (記憶卡用)
64
+ platform_code: Optional[str] = None
65
+ return_timer: Optional[Literal['Y', 'N']] = None # Y: 倒數 10 秒;N: 立即跳轉
66
+
67
+
68
+ @dataclass
69
+ class PChomePayAtmOrder:
70
+ """幕後取號 ATM 虛擬帳號 (POST /v1/payment/atmva)"""
71
+ order_id: str
72
+ amount: int # 1 ~ 49,999
73
+ item_name: str
74
+ item_url: str
75
+ buyer_name: str
76
+ buyer_mobile: str
77
+ expire_days: int = 5 # 1 ~ 5
78
+ atm_bank: str = '011' # 預設上海商銀
79
+ notify_url: Optional[str] = None
80
+ buyer_email: Optional[str] = None
81
+ platform_code: Optional[str] = None
82
+
83
+
84
+ @dataclass
85
+ class PChomePayBarcodeOrder:
86
+ """幕後取號 超商代碼繳費 (POST /v1/payment/barcode)"""
87
+ order_id: str
88
+ amount: int # 25 ~ 20,000
89
+ items: List[PChomePayItem]
90
+ buyer_name: str # <=50
91
+ buyer_mobile: str # 09 開頭 10 碼
92
+ expire_days: int = 7 # 1 ~ 7
93
+ notify_url: Optional[str] = None
94
+ buyer_email: Optional[str] = None
95
+ platform_code: Optional[str] = None
96
+
97
+
98
+ @dataclass
99
+ class PChomePayRefundRequest:
100
+ """退款請求 (POST /v1/refund)"""
101
+ order_id: str
102
+ refund_id: str # <=50, 不可重複
103
+ trade_amount: int
104
+
105
+
106
+ @dataclass
107
+ class PChomePayResponse:
108
+ """通用回應 wrapper"""
109
+ success: bool
110
+ status_code: int
111
+ data: Dict[str, Any] = field(default_factory=dict)
112
+ error_type: Optional[str] = None
113
+ error_code: Optional[int] = None
114
+ error_message: Optional[str] = None
115
+
116
+
117
+ # ----------------------------------------------------------------------------
118
+ # Service
119
+ # ----------------------------------------------------------------------------
120
+
121
+
122
+ class PChomePayService:
123
+ """
124
+ PChomePay 拍錢包金流服務 (REST + JSON)
125
+
126
+ 認證流程:
127
+ 1. POST /v1/token + Authorization: Basic base64(APP_ID:SECRET)
128
+ -> { "token": "...", "expired_in": 28800, "expired_timestamp": ... }
129
+ 2. 後續請求帶 Header: pcpay-token: <token>
130
+
131
+ 本範例會自動快取 token,在到期前 (預留 60 秒緩衝) 自動 refresh。
132
+
133
+ 環境:
134
+ sandbox = "https://sandbox-api.pchomepay.com.tw"
135
+ prod = "https://api.pchomepay.com.tw"
136
+
137
+ Notify 來源 IP (firewall 白名單):
138
+ 113.196.231.190
139
+ """
140
+
141
+ SANDBOX_BASE = 'https://sandbox-api.pchomepay.com.tw'
142
+ PROD_BASE = 'https://api.pchomepay.com.tw'
143
+
144
+ NOTIFY_SOURCE_IP = '113.196.231.190'
145
+ TOKEN_REFRESH_BUFFER_SECONDS = 60
146
+
147
+ def __init__(
148
+ self,
149
+ app_id: str,
150
+ secret: str,
151
+ is_production: bool = False,
152
+ timeout: int = 30,
153
+ ):
154
+ if not HAS_REQUESTS:
155
+ raise ImportError('需要安裝 requests: pip install requests')
156
+
157
+ self.app_id = app_id
158
+ self.secret = secret
159
+ self.base_url = self.PROD_BASE if is_production else self.SANDBOX_BASE
160
+ self.timeout = timeout
161
+
162
+ # token cache
163
+ self._token: Optional[str] = None
164
+ self._token_expired_at: float = 0.0
165
+
166
+ self._session = requests.Session()
167
+
168
+ # ------------------------------------------------------------------
169
+ # Token management
170
+ # ------------------------------------------------------------------
171
+
172
+ def _basic_auth_header(self) -> str:
173
+ """Authorization: Basic base64(APP_ID:SECRET)"""
174
+ raw = f'{self.app_id}:{self.secret}'.encode('utf-8')
175
+ return 'Basic ' + base64.b64encode(raw).decode('ascii')
176
+
177
+ def get_token(self, force_refresh: bool = False) -> str:
178
+ """
179
+ 取得 pcpay-token,會自動 cache。Token 預設 8 小時,到期前
180
+ TOKEN_REFRESH_BUFFER_SECONDS 秒會自動 refresh。
181
+
182
+ Args:
183
+ force_refresh: True 則忽略 cache 直接重打 /v1/token
184
+
185
+ Returns:
186
+ str: 有效的 pcpay-token
187
+ """
188
+ now = time.time()
189
+ if (
190
+ not force_refresh
191
+ and self._token
192
+ and now < self._token_expired_at - self.TOKEN_REFRESH_BUFFER_SECONDS
193
+ ):
194
+ return self._token
195
+
196
+ url = f'{self.base_url}/v1/token'
197
+ headers = {
198
+ 'Authorization': self._basic_auth_header(),
199
+ 'Content-Type': 'application/json',
200
+ }
201
+ resp = self._session.post(url, headers=headers, timeout=self.timeout)
202
+ resp.raise_for_status()
203
+ body = resp.json()
204
+
205
+ token = body.get('token')
206
+ if not token:
207
+ raise RuntimeError(f'PChomePay token 取得失敗: {body}')
208
+
209
+ self._token = token
210
+ # 優先用 expired_timestamp,若無再以 expired_in + now 計算
211
+ if body.get('expired_timestamp'):
212
+ self._token_expired_at = float(body['expired_timestamp'])
213
+ else:
214
+ self._token_expired_at = now + float(body.get('expired_in', 28800))
215
+
216
+ return token
217
+
218
+ def _auth_headers(self) -> Dict[str, str]:
219
+ return {
220
+ 'pcpay-token': self.get_token(),
221
+ 'Content-Type': 'application/json',
222
+ 'Accept': 'application/json',
223
+ }
224
+
225
+ # ------------------------------------------------------------------
226
+ # HTTP wrapper
227
+ # ------------------------------------------------------------------
228
+
229
+ def _request(
230
+ self,
231
+ method: Literal['GET', 'POST'],
232
+ path: str,
233
+ json: Optional[Dict[str, Any]] = None,
234
+ ) -> PChomePayResponse:
235
+ url = f'{self.base_url}{path}'
236
+ try:
237
+ resp = self._session.request(
238
+ method,
239
+ url,
240
+ headers=self._auth_headers(),
241
+ json=json,
242
+ timeout=self.timeout,
243
+ )
244
+ except requests.RequestException as exc:
245
+ return PChomePayResponse(
246
+ success=False,
247
+ status_code=0,
248
+ error_message=str(exc),
249
+ )
250
+
251
+ try:
252
+ body = resp.json()
253
+ except ValueError:
254
+ body = {'raw': resp.text}
255
+
256
+ if resp.ok and 'error_type' not in body:
257
+ return PChomePayResponse(success=True, status_code=resp.status_code, data=body)
258
+
259
+ return PChomePayResponse(
260
+ success=False,
261
+ status_code=resp.status_code,
262
+ data=body,
263
+ error_type=body.get('error_type'),
264
+ error_code=body.get('code'),
265
+ error_message=body.get('message'),
266
+ )
267
+
268
+ # ------------------------------------------------------------------
269
+ # Order creation
270
+ # ------------------------------------------------------------------
271
+
272
+ def create_credit_order(self, order: PChomePayCreditOrder) -> PChomePayResponse:
273
+ """
274
+ 建立信用卡 (跳轉付款頁) 訂單 POST /v1/payment
275
+
276
+ Returns:
277
+ PChomePayResponse.data 內含 order_id / payment_url
278
+ -> 將消費者導頁至 payment_url 完成付款
279
+ """
280
+ if order.amount < 30 or order.amount > 199_999:
281
+ raise ValueError('CARD 金額需介於 30 ~ 199,999')
282
+
283
+ body: Dict[str, Any] = {
284
+ 'order_id': order.order_id,
285
+ 'pay_type': ['CARD'],
286
+ 'amount': order.amount,
287
+ 'items': [{'name': i.name, 'url': i.url} for i in order.items],
288
+ }
289
+ if order.return_url:
290
+ body['return_url'] = order.return_url
291
+ if order.fail_return_url:
292
+ body['fail_return_url'] = order.fail_return_url
293
+ if order.notify_url:
294
+ body['notify_url'] = order.notify_url
295
+ if order.buyer_email:
296
+ body['buyer_email'] = order.buyer_email
297
+ if order.card_installment:
298
+ body['card_installment'] = order.card_installment
299
+ if order.member_key:
300
+ body['member_key'] = order.member_key
301
+ if order.platform_code:
302
+ body['platform_code'] = order.platform_code
303
+ if order.return_timer:
304
+ body['return_timer'] = order.return_timer
305
+
306
+ return self._request('POST', '/v1/payment', body)
307
+
308
+ def create_atm_order(self, order: PChomePayAtmOrder) -> PChomePayResponse:
309
+ """
310
+ 建立 ATM 幕後取號訂單 POST /v1/payment/atmva
311
+
312
+ Returns:
313
+ PChomePayResponse.data 內含 order_id / virtual_account / bank_id / expire_date
314
+ """
315
+ if order.amount < 1 or order.amount > 49_999:
316
+ raise ValueError('ATM 金額需介於 1 ~ 49,999')
317
+ if not (1 <= order.expire_days <= 5):
318
+ raise ValueError('expire_days 需介於 1 ~ 5 天')
319
+
320
+ body: Dict[str, Any] = {
321
+ 'order_id': order.order_id,
322
+ 'amount': order.amount,
323
+ 'expire_days': order.expire_days,
324
+ 'item_name': order.item_name,
325
+ 'item_url': order.item_url,
326
+ 'atm_bank': order.atm_bank,
327
+ 'buyer_name': order.buyer_name,
328
+ 'buyer_mobile': order.buyer_mobile,
329
+ }
330
+ if order.notify_url:
331
+ body['notify_url'] = order.notify_url
332
+ if order.buyer_email:
333
+ body['buyer_email'] = order.buyer_email
334
+ if order.platform_code:
335
+ body['platform_code'] = order.platform_code
336
+
337
+ return self._request('POST', '/v1/payment/atmva', body)
338
+
339
+ def create_barcode_order(self, order: PChomePayBarcodeOrder) -> PChomePayResponse:
340
+ """
341
+ 建立超商代碼繳費 幕後取號訂單 POST /v1/payment/barcode
342
+
343
+ Returns:
344
+ PChomePayResponse.data 內含 pincode / barcode1~3 / expire_date
345
+ """
346
+ if order.amount < 25 or order.amount > 20_000:
347
+ raise ValueError('BCODE 金額需介於 25 ~ 20,000')
348
+ if not (1 <= order.expire_days <= 7):
349
+ raise ValueError('expire_days 需介於 1 ~ 7 天')
350
+
351
+ body: Dict[str, Any] = {
352
+ 'order_id': order.order_id,
353
+ 'amount': order.amount,
354
+ 'expire_days': order.expire_days,
355
+ 'items': [{'name': i.name, 'url': i.url} for i in order.items],
356
+ 'buyer_name': order.buyer_name,
357
+ 'buyer_mobile': order.buyer_mobile,
358
+ }
359
+ if order.notify_url:
360
+ body['notify_url'] = order.notify_url
361
+ if order.buyer_email:
362
+ body['buyer_email'] = order.buyer_email
363
+ if order.platform_code:
364
+ body['platform_code'] = order.platform_code
365
+
366
+ return self._request('POST', '/v1/payment/barcode', body)
367
+
368
+ # ------------------------------------------------------------------
369
+ # Order query / refund
370
+ # ------------------------------------------------------------------
371
+
372
+ def query_order(self, order_id: str) -> PChomePayResponse:
373
+ """訂單查詢 GET /v1/payment/{order_id}"""
374
+ return self._request('GET', f'/v1/payment/{order_id}')
375
+
376
+ def refund(self, refund_req: PChomePayRefundRequest) -> PChomePayResponse:
377
+ """
378
+ 建立退款 POST /v1/refund
379
+
380
+ 退款規則摘要:
381
+ - 信用卡分期 / 超商取貨 / 代碼繳費 → 僅支援全額退款
382
+ - 信用卡一次付清 / 拍錢包 / ATM → 支援部分退款
383
+ - 退款手續費: ATM / 超商取貨 / 代碼繳費 每筆 15 元
384
+ - 帳戶餘額需 >= 退款金額 + 退款手續費
385
+ """
386
+ if refund_req.trade_amount <= 0:
387
+ raise ValueError('退款金額需 > 0')
388
+
389
+ body = {
390
+ 'order_id': refund_req.order_id,
391
+ 'refund_id': refund_req.refund_id,
392
+ 'trade_amount': refund_req.trade_amount,
393
+ }
394
+ return self._request('POST', '/v1/refund', body)
395
+
396
+ def query_refund(self, refund_id: str) -> PChomePayResponse:
397
+ """退款查詢 GET /v1/refund/{refund_id}"""
398
+ return self._request('GET', f'/v1/refund/{refund_id}')
399
+
400
+ def query_balance(self) -> PChomePayResponse:
401
+ """帳戶餘額查詢 GET /v1/balance"""
402
+ return self._request('GET', '/v1/balance')
403
+
404
+ def list_atm_banks(self) -> PChomePayResponse:
405
+ """ATM 支援銀行清單 GET /v1/payment/atm/banks"""
406
+ return self._request('GET', '/v1/payment/atm/banks')
407
+
408
+ def list_card_banks(self) -> PChomePayResponse:
409
+ """信用卡分期支援銀行 GET /v1/payment/card/banks"""
410
+ return self._request('GET', '/v1/payment/card/banks')
411
+
412
+
413
+ # ----------------------------------------------------------------------------
414
+ # Examples
415
+ # ----------------------------------------------------------------------------
416
+
417
+
418
+ def example_token_refresh(service: PChomePayService) -> None:
419
+ print('[範例 1] Token auto-refresh 機制 (不實際打 API)')
420
+ print('-' * 60)
421
+ print(f' Base URL: {service.base_url}')
422
+ print(f' APP_ID: {service.app_id[:8]}...')
423
+ print(f' Refresh buffer: {service.TOKEN_REFRESH_BUFFER_SECONDS} 秒')
424
+ print(f' Notify 來源 IP (記得加 firewall 白名單): {service.NOTIFY_SOURCE_IP}')
425
+ print()
426
+
427
+
428
+ def example_create_credit_order(service: PChomePayService) -> None:
429
+ print('[範例 2] 建立信用卡跳轉付款頁訂單 POST /v1/payment')
430
+ print('-' * 60)
431
+ order = PChomePayCreditOrder(
432
+ order_id=f'B2C{int(time.time())}',
433
+ amount=2675,
434
+ items=[
435
+ PChomePayItem(
436
+ name='Chrome Dino Camp Shirt',
437
+ url='https://shop.example.com/items/chrome-dino-shirt',
438
+ ),
439
+ ],
440
+ return_url='https://shop.example.com/success',
441
+ fail_return_url='https://shop.example.com/failed',
442
+ notify_url='https://shop.example.com/api/pchomepay/notify',
443
+ card_installment='1,3,6,12',
444
+ )
445
+ print(f' order_id: {order.order_id}')
446
+ print(f' amount: {order.amount}')
447
+ print(f' 分期: {order.card_installment}')
448
+ print(' (示範僅組 payload,未實際呼叫 API;正式 sandbox 需先取得 APP_ID/SECRET)')
449
+ print()
450
+
451
+
452
+ def example_create_atm_order(service: PChomePayService) -> None:
453
+ print('[範例 3] 建立 ATM 幕後取號訂單 POST /v1/payment/atmva')
454
+ print('-' * 60)
455
+ order = PChomePayAtmOrder(
456
+ order_id=f'B2CATM{int(time.time())}',
457
+ amount=500,
458
+ item_name='休閒褲',
459
+ item_url='https://www.example.com.tw',
460
+ buyer_name='王大明',
461
+ buyer_mobile='0912345678',
462
+ expire_days=3,
463
+ atm_bank='812', # 台新
464
+ notify_url='https://shop.example.com/api/pchomepay/notify',
465
+ )
466
+ print(f' order_id: {order.order_id}')
467
+ print(f' ATM 銀行: {order.atm_bank}')
468
+ print(f' 繳費期限: {order.expire_days} 天')
469
+ print(' (示範僅組 payload,未實際呼叫 API)')
470
+ print()
471
+
472
+
473
+ def example_create_barcode_order(service: PChomePayService) -> None:
474
+ print('[範例 4] 建立超商代碼繳費訂單 POST /v1/payment/barcode')
475
+ print('-' * 60)
476
+ order = PChomePayBarcodeOrder(
477
+ order_id=f'B2CBARCODE{int(time.time())}',
478
+ amount=500,
479
+ items=[
480
+ PChomePayItem(name='Chrome Dino Camp Shirt', url='https://shop.example.com'),
481
+ ],
482
+ buyer_name='John Doe',
483
+ buyer_mobile='0912345678',
484
+ expire_days=7,
485
+ notify_url='https://shop.example.com/api/pchomepay/notify',
486
+ )
487
+ print(f' order_id: {order.order_id}')
488
+ print(f' amount: {order.amount}')
489
+ print(f' expire: {order.expire_days} 天')
490
+ print(' (示範僅組 payload,未實際呼叫 API)')
491
+ print()
492
+
493
+
494
+ def example_query_order(service: PChomePayService) -> None:
495
+ print('[範例 5] 訂單查詢 GET /v1/payment/{order_id}')
496
+ print('-' * 60)
497
+ print(' service.query_order("B2C1695210352")')
498
+ print(' -> response.data 含 status (S/W/F) / pay_type / payment_info / amount ...')
499
+ print()
500
+
501
+
502
+ def example_refund(service: PChomePayService) -> None:
503
+ print('[範例 6] 建立退款 POST /v1/refund')
504
+ print('-' * 60)
505
+ refund = PChomePayRefundRequest(
506
+ order_id='B2C1695210352',
507
+ refund_id='B2C1695210352-Refund',
508
+ trade_amount=100,
509
+ )
510
+ print(f' order_id: {refund.order_id}')
511
+ print(f' refund_id: {refund.refund_id}')
512
+ print(f' trade_amount: {refund.trade_amount}')
513
+ print(' 注意:')
514
+ print(' - 信用卡分期 / 超商取貨 / 代碼繳費 → 僅支援全額退款')
515
+ print(' - ATM / 超商取貨 / 代碼繳費 每筆退款手續費 15 元')
516
+ print(' - 帳戶餘額須 >= 退款金額 + 退款手續費')
517
+ print()
518
+
519
+
520
+ if __name__ == '__main__':
521
+ print('=' * 60)
522
+ print('PChomePay 拍錢包金流 - Python 範例')
523
+ print('=' * 60)
524
+ print()
525
+
526
+ if not HAS_REQUESTS:
527
+ print('(缺 requests 套件,僅展示資料結構)')
528
+ print('安裝指令: pip install requests')
529
+ print()
530
+
531
+ # 建立 service 物件會 raise ImportError;改示範資料結構
532
+ order = PChomePayCreditOrder(
533
+ order_id='B2C0000000001',
534
+ amount=1000,
535
+ items=[PChomePayItem(name='範例', url='https://example.com')],
536
+ )
537
+ print(f'CreditOrder dataclass: order_id={order.order_id} amount={order.amount}')
538
+ exit(0)
539
+
540
+ # 注意: 請替換為您的測試 APP_ID / SECRET
541
+ service = PChomePayService(
542
+ app_id='YOUR_SANDBOX_APP_ID',
543
+ secret='YOUR_SANDBOX_SECRET',
544
+ is_production=False,
545
+ )
546
+
547
+ example_token_refresh(service)
548
+ example_create_credit_order(service)
549
+ example_create_atm_order(service)
550
+ example_create_barcode_order(service)
551
+ example_query_order(service)
552
+ example_refund(service)
553
+
554
+ print('=' * 60)
555
+ print('範例執行完成')
556
+ print('=' * 60)