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,673 +1,673 @@
1
- #!/usr/bin/env python3
2
- """
3
- SmilePay 速買配 Python 完整範例
4
-
5
- 依照 taiwan-payment-skill 最高規範撰寫
6
- 支援: ATM 虛擬帳號、信用卡 (一次付清/分期)、超商條碼、ibon、FamiPort
7
-
8
- API 文件: https://www.smilepay.net/
9
- 參考文件: taiwan-payment/references/smilepay-payment-api.md
10
-
11
- 特色:
12
- - 一支 SPPayment.asp 端點涵蓋多種非同步取號類付款 (ATM / 條碼 / ibon / FamiPort)
13
- - 信用卡 / 銀聯卡走另一支 mtmk_utf.asp 結帳頁
14
- - 回應為 XML 格式 (使用 Python stdlib xml.etree.ElementTree 解析)
15
- - 通知驗章採 Mid_smilepay 加權校驗碼 (非 SHA256)
16
- - 部分中文欄位 (Errdesc / Process_time / Address) 可能以 BIG-5 編碼
17
-
18
- 依賴:
19
- pip install requests
20
- (本範例不需 pycryptodome,SmilePay 沒有 AES 加密流程)
21
- """
22
-
23
- import hashlib
24
- import time
25
- from dataclasses import dataclass, field
26
- from datetime import datetime, timedelta
27
- from typing import Dict, Literal, Optional
28
- from urllib.parse import urlencode
29
- import xml.etree.ElementTree as ET
30
-
31
- try:
32
- import requests
33
- HAS_REQUESTS = True
34
- except ImportError:
35
- HAS_REQUESTS = False
36
-
37
-
38
- # ----------------------------------------------------------------------------
39
- # Dataclasses (Inputs / Responses)
40
- # ----------------------------------------------------------------------------
41
-
42
-
43
- @dataclass
44
- class SmilePayBuyer:
45
- """SmilePay 訂購人 / 付款人資訊 (UTF-8 編碼)"""
46
- name: str # Pur_name 訂購人姓名
47
- mobile: str # Mobile_number 手機
48
- email: str # Email
49
- tel: Optional[str] = None # Tel_number 市話 (常以手機帶入)
50
- address: Optional[str] = None # Address 收件 / 帳單地址
51
-
52
-
53
- @dataclass
54
- class SmilePayAtmOrder:
55
- """SmilePay ATM 虛擬帳號 (Pay_zg=2) 訂單資料"""
56
- data_id: str # 商店訂單編號 (英數,唯一,<=20)
57
- amount: int # 金額 (TWD 整數)
58
- item_name: str # od_sob 商品摘要 (<=45 字)
59
- buyer: SmilePayBuyer
60
- deadline_date: Optional[str] = None # YYYY/MM/DD,預設下單日 +7 天
61
- roturl: Optional[str] = None # 付款結果通知網址
62
- roturl_status: Optional[str] = None # 通知識別字串
63
- remark: Optional[str] = None
64
- invoice_num: Optional[str] = None # 統編 / 載具
65
-
66
-
67
- @dataclass
68
- class SmilePayCreditOrder:
69
- """SmilePay 信用卡 (Pay_zg=1) 一次付清訂單"""
70
- data_id: str
71
- amount: int
72
- item_name: str # od_sob (<=49 字)
73
- buyer: SmilePayBuyer
74
- roturl: Optional[str] = None
75
- roturl_status: Optional[str] = None
76
- remark: Optional[str] = None
77
- invoice_num: Optional[str] = None
78
-
79
-
80
- @dataclass
81
- class SmilePayInstallmentOrder:
82
- """SmilePay 信用卡分期訂單 (Pay_zg=1 + Stage)"""
83
- data_id: str
84
- amount: int
85
- item_name: str
86
- buyer: SmilePayBuyer
87
- stage: Literal[3, 6, 12, 18, 24] = 3 # 分期期數
88
- roturl: Optional[str] = None
89
- roturl_status: Optional[str] = None
90
- remark: Optional[str] = None
91
-
92
-
93
- @dataclass
94
- class SmilePayBarcodeOrder:
95
- """SmilePay 超商條碼 (Pay_zg=3) 訂單資料"""
96
- data_id: str
97
- amount: int
98
- item_name: str
99
- buyer: SmilePayBuyer
100
- deadline_date: Optional[str] = None # < 50 天
101
- roturl: Optional[str] = None
102
- roturl_status: Optional[str] = None
103
- remark: Optional[str] = None
104
-
105
-
106
- @dataclass
107
- class SmilePayAtmResponse:
108
- """ATM 取號成功回應"""
109
- success: bool
110
- status: str
111
- desc: str
112
- data_id: str
113
- smilepay_no: str = ''
114
- atm_bank_no: str = '' # 3 碼財金代碼
115
- atm_no: str = '' # 14~16 碼虛擬帳號
116
- amount: int = 0
117
- pay_end_date: str = ''
118
- raw_xml: str = ''
119
-
120
-
121
- @dataclass
122
- class SmilePayBarcodeResponse:
123
- """條碼取號成功回應"""
124
- success: bool
125
- status: str
126
- desc: str
127
- data_id: str
128
- smilepay_no: str = ''
129
- barcode1: str = ''
130
- barcode2: str = ''
131
- barcode3: str = ''
132
- amount: int = 0
133
- pay_end_date: str = ''
134
- raw_xml: str = ''
135
-
136
-
137
- @dataclass
138
- class SmilePayCreditRedirect:
139
- """信用卡 / 銀聯 / 分期:回傳 redirect URL,給前端跳轉"""
140
- success: bool
141
- redirect_url: str
142
- data_id: str
143
- params: Dict[str, str] = field(default_factory=dict)
144
-
145
-
146
- @dataclass
147
- class SmilePayNotification:
148
- """Roturl 通知解析結果 (取號類 / 信用卡共用)"""
149
- classif: str # A/B/C/T/O
150
- data_id: str
151
- smseid: str
152
- amount: int
153
- process_date: str
154
- process_time: str
155
- response_id: Optional[str] = None # 信用卡有,1=成功
156
- payment_title: Optional[str] = None
157
- errdesc: Optional[str] = None
158
- mid_smilepay: Optional[str] = None
159
- verified: bool = False # Mid_smilepay 是否通過
160
- raw: Dict[str, str] = field(default_factory=dict)
161
-
162
-
163
- # ----------------------------------------------------------------------------
164
- # Service
165
- # ----------------------------------------------------------------------------
166
-
167
-
168
- class SmilePayPaymentService:
169
- """
170
- SmilePay 速買配金流服務
171
-
172
- 認證方式: 帳號參數三件組 (Dcvc / Rvg2c / Verify_key) + Mid_smilepay 通知驗章
173
- 加密方式: 不使用 AES / SHA256;僅有 Mid_smilepay 加權校驗碼
174
-
175
- 支援付款方式:
176
- - Pay_zg=1 信用卡 (一次付清 / 分期 + Stage)
177
- - Pay_zg=2 ATM 虛擬帳號
178
- - Pay_zg=3 超商條碼
179
- - Pay_zg=4 7-11 ibon
180
- - Pay_zg=6 全家 FamiPort
181
- - Pay_zg=11 銀聯 / 國際信用卡
182
-
183
- 測試環境 (官方公開測試參數):
184
- Dcvc: 107
185
- Rvg2c: 1
186
- Verify_key: 174A02F97A95F72CE301137B3F98D128
187
- mid: 1111
188
-
189
- 測試 / 正式環境同網域 (ssl.smse.com.tw);差異僅在帳號參數。
190
- """
191
-
192
- # 測試帳號 (官方公開)
193
- TEST_DCVC = '107'
194
- TEST_RVG2C = '1'
195
- TEST_VERIFY_KEY = '174A02F97A95F72CE301137B3F98D128'
196
- TEST_MID = '1111'
197
-
198
- # API 端點
199
- PAYMENT_URL = 'https://ssl.smse.com.tw/api/SPPayment.asp' # 取號類
200
- CHECKOUT_URL = 'https://ssl.smse.com.tw/ezpos/mtmk_utf.asp' # 信用卡 / 銀聯
201
- MODIFY_URL = 'https://ssl.smse.com.tw/api/SPPayment_Modify.asp' # 訂單修改 / 退款
202
-
203
- def __init__(
204
- self,
205
- dcvc: str,
206
- rvg2c: str,
207
- verify_key: str,
208
- mid: str = '',
209
- timeout: int = 30,
210
- ):
211
- """
212
- 初始化 SmilePay 金流服務
213
-
214
- Args:
215
- dcvc: 商店代號
216
- rvg2c: 收款銀行 / 路由碼 (預設 1)
217
- verify_key: 驗證金鑰 (32 碼大寫 hex)
218
- mid: 金流 mid (Mid_smilepay 簽章用,正式環境必填)
219
- timeout: HTTP 逾時 (秒)
220
- """
221
- if not HAS_REQUESTS:
222
- raise ImportError('需要安裝 requests: pip install requests')
223
-
224
- self.dcvc = dcvc
225
- self.rvg2c = rvg2c
226
- self.verify_key = verify_key
227
- self.mid = mid
228
- self.timeout = timeout
229
-
230
- # ------------------------------------------------------------------
231
- # Helpers
232
- # ------------------------------------------------------------------
233
-
234
- def _account_params(self) -> Dict[str, str]:
235
- """三件組帳號驗證參數"""
236
- return {
237
- 'Dcvc': self.dcvc,
238
- 'Rvg2c': self.rvg2c,
239
- 'Verify_key': self.verify_key,
240
- }
241
-
242
- def _buyer_params(self, buyer: SmilePayBuyer) -> Dict[str, str]:
243
- """訂購人欄位"""
244
- params = {
245
- 'Pur_name': buyer.name,
246
- 'Mobile_number': buyer.mobile,
247
- 'Email': buyer.email,
248
- }
249
- if buyer.tel:
250
- params['Tel_number'] = buyer.tel
251
- else:
252
- params['Tel_number'] = buyer.mobile
253
- if buyer.address:
254
- params['Address'] = buyer.address
255
- return params
256
-
257
- def _post_payment(self, payload: Dict[str, str]) -> ET.Element:
258
- """POST 至 SPPayment.asp 並解析 XML"""
259
- resp = requests.post(self.PAYMENT_URL, data=payload, timeout=self.timeout)
260
- resp.raise_for_status()
261
- # 速買配回傳的內容通常是 UTF-8;少數欄位 (Errdesc 等) 可能 BIG-5
262
- # 但根層 XML 本體為 UTF-8,可直接以 fromstring 解析
263
- try:
264
- return ET.fromstring(resp.text)
265
- except ET.ParseError as exc:
266
- raise RuntimeError(
267
- f'SmilePay XML 解析失敗: {exc} | body={resp.text[:200]}'
268
- )
269
-
270
- def _xml_text(self, root: ET.Element, tag: str, default: str = '') -> str:
271
- node = root.findtext(tag)
272
- return node if node is not None else default
273
-
274
- @staticmethod
275
- def _default_deadline(days: int = 7) -> str:
276
- return (datetime.now() + timedelta(days=days)).strftime('%Y/%m/%d')
277
-
278
- # ------------------------------------------------------------------
279
- # Order creation
280
- # ------------------------------------------------------------------
281
-
282
- def create_atm_order(self, order: SmilePayAtmOrder) -> SmilePayAtmResponse:
283
- """
284
- 建立 ATM 虛擬帳號訂單 (Pay_zg=2)
285
-
286
- Returns:
287
- SmilePayAtmResponse: 含 atm_bank_no / atm_no / pay_end_date
288
- """
289
- if order.amount < 8 or order.amount > 20000:
290
- raise ValueError('ATM 金額需介於 8 ~ 20,000 元')
291
- if len(order.data_id) > 20:
292
- raise ValueError('Data_id 不可超過 20 字元')
293
-
294
- payload = {
295
- **self._account_params(),
296
- **self._buyer_params(order.buyer),
297
- 'Pay_zg': '2',
298
- 'Data_id': order.data_id,
299
- 'Amount': str(order.amount),
300
- 'od_sob': order.item_name[:45],
301
- 'Deadline_date': order.deadline_date or self._default_deadline(7),
302
- }
303
- if order.roturl:
304
- payload['Roturl'] = order.roturl
305
- if order.roturl_status:
306
- payload['Roturl_status'] = order.roturl_status
307
- if order.remark:
308
- payload['Remark'] = order.remark
309
- if order.invoice_num:
310
- payload['Invoice_num'] = order.invoice_num
311
-
312
- root = self._post_payment(payload)
313
- status = self._xml_text(root, 'Status')
314
- desc = self._xml_text(root, 'Desc')
315
-
316
- return SmilePayAtmResponse(
317
- success=(status == '1'),
318
- status=status,
319
- desc=desc,
320
- data_id=self._xml_text(root, 'Data_id', order.data_id),
321
- smilepay_no=self._xml_text(root, 'SmilePayNO'),
322
- atm_bank_no=self._xml_text(root, 'AtmBankNo'),
323
- atm_no=self._xml_text(root, 'AtmNo'),
324
- amount=int(self._xml_text(root, 'Amount', '0') or 0),
325
- pay_end_date=self._xml_text(root, 'PayEndDate'),
326
- raw_xml=ET.tostring(root, encoding='unicode'),
327
- )
328
-
329
- def create_barcode_order(self, order: SmilePayBarcodeOrder) -> SmilePayBarcodeResponse:
330
- """
331
- 建立超商條碼訂單 (Pay_zg=3)
332
-
333
- Returns:
334
- SmilePayBarcodeResponse: 含三段條碼 + pay_end_date
335
- """
336
- if order.amount < 8 or order.amount > 20000:
337
- raise ValueError('條碼金額需介於 8 ~ 20,000 元')
338
-
339
- payload = {
340
- **self._account_params(),
341
- **self._buyer_params(order.buyer),
342
- 'Pay_zg': '3',
343
- 'Data_id': order.data_id,
344
- 'Amount': str(order.amount),
345
- 'od_sob': order.item_name[:45],
346
- 'Deadline_date': order.deadline_date or self._default_deadline(30),
347
- }
348
- if order.roturl:
349
- payload['Roturl'] = order.roturl
350
- if order.roturl_status:
351
- payload['Roturl_status'] = order.roturl_status
352
- if order.remark:
353
- payload['Remark'] = order.remark
354
-
355
- root = self._post_payment(payload)
356
- status = self._xml_text(root, 'Status')
357
-
358
- return SmilePayBarcodeResponse(
359
- success=(status == '1'),
360
- status=status,
361
- desc=self._xml_text(root, 'Desc'),
362
- data_id=self._xml_text(root, 'Data_id', order.data_id),
363
- smilepay_no=self._xml_text(root, 'SmilePayNO'),
364
- barcode1=self._xml_text(root, 'Barcode1'),
365
- barcode2=self._xml_text(root, 'Barcode2'),
366
- barcode3=self._xml_text(root, 'Barcode3'),
367
- amount=int(self._xml_text(root, 'Amount', '0') or 0),
368
- pay_end_date=self._xml_text(root, 'PayEndDate'),
369
- raw_xml=ET.tostring(root, encoding='unicode'),
370
- )
371
-
372
- def create_credit_order(self, order: SmilePayCreditOrder) -> SmilePayCreditRedirect:
373
- """
374
- 建立信用卡 (一次付清) 結帳頁 redirect URL (Pay_zg=1)
375
-
376
- Note: 此方法不發 HTTP 請求,僅組好 querystring 給商店端 redirect。
377
- 消費者進入結帳頁後輸入卡號、3D 驗證,結束後 SmilePay 以
378
- querystring 帶結果到 Roturl。
379
- """
380
- params = {
381
- **self._account_params(),
382
- **self._buyer_params(order.buyer),
383
- 'Pay_zg': '1',
384
- 'Data_id': order.data_id,
385
- 'Amount': str(order.amount),
386
- 'od_sob': order.item_name[:49],
387
- }
388
- if order.roturl:
389
- params['Roturl'] = order.roturl
390
- if order.roturl_status:
391
- params['Roturl_status'] = order.roturl_status
392
- if order.remark:
393
- params['Remark'] = order.remark
394
- if order.invoice_num:
395
- params['Invoice_num'] = order.invoice_num
396
-
397
- return SmilePayCreditRedirect(
398
- success=True,
399
- redirect_url=f'{self.CHECKOUT_URL}?{urlencode(params)}',
400
- data_id=order.data_id,
401
- params=params,
402
- )
403
-
404
- def create_credit_installment_order(
405
- self, order: SmilePayInstallmentOrder
406
- ) -> SmilePayCreditRedirect:
407
- """
408
- 建立信用卡分期 (Pay_zg=1 + Stage) 結帳頁 redirect URL
409
-
410
- 模組預設支援期數: 3 / 6 / 12 / 18 / 24
411
- """
412
- if order.stage not in (3, 6, 12, 18, 24):
413
- raise ValueError('Stage 僅支援 3 / 6 / 12 / 18 / 24 期')
414
-
415
- params = {
416
- **self._account_params(),
417
- **self._buyer_params(order.buyer),
418
- 'Pay_zg': '1',
419
- 'Stage': str(order.stage),
420
- 'Data_id': order.data_id,
421
- 'Amount': str(order.amount),
422
- 'od_sob': order.item_name[:49],
423
- }
424
- if order.roturl:
425
- params['Roturl'] = order.roturl
426
- if order.roturl_status:
427
- params['Roturl_status'] = order.roturl_status
428
- if order.remark:
429
- params['Remark'] = order.remark
430
-
431
- return SmilePayCreditRedirect(
432
- success=True,
433
- redirect_url=f'{self.CHECKOUT_URL}?{urlencode(params)}',
434
- data_id=order.data_id,
435
- params=params,
436
- )
437
-
438
- # ------------------------------------------------------------------
439
- # Mid_smilepay verification
440
- # ------------------------------------------------------------------
441
-
442
- @staticmethod
443
- def calc_mid_smilepay(mid: str, amount: int, smseid: str) -> int:
444
- """
445
- 計算 Mid_smilepay 通知校驗碼
446
-
447
- 演算法 (摘自 WooCommerce 模組推導,見 references/smilepay-payment-api.md)
448
-
449
- 步驟:
450
- 1. 取 Smseid 末 4 碼 r1 r2 r3 r4,非數字以 9 取代
451
- 2. Amount 補零至 8 碼 (左補) -> str1
452
- 3. 串接 s = mid + str1 + r1 r2 r3 r4 (16 碼)
453
- 4. even = s 偶數位 (0,2,4...) 加總;odd = 奇數位加總
454
- 5. Mid_smilepay = even * 9 + odd * 3
455
- """
456
- r_all = (smseid or '')[-4:].rjust(4, '9')
457
- r = [c if c.isdigit() else '9' for c in r_all]
458
- str1 = str(amount).zfill(8)
459
- s = f'{mid}{str1}{r[0]}{r[1]}{r[2]}{r[3]}'
460
- if len(s) != 16:
461
- raise ValueError(
462
- f'Mid_smilepay 長度錯誤: {len(s)} (應為 16, mid={mid})'
463
- )
464
- even = sum(int(s[i]) for i in range(16) if i % 2 == 0)
465
- odd = sum(int(s[i]) for i in range(16) if i % 2 == 1)
466
- return even * 9 + odd * 3
467
-
468
- def verify_notification(self, callback: Dict[str, str]) -> SmilePayNotification:
469
- """
470
- 驗證 SmilePay Roturl 通知
471
-
472
- Args:
473
- callback: 速買配 POST/GET 進來的所有 querystring 參數
474
-
475
- Returns:
476
- SmilePayNotification: verified=True 表示 Mid_smilepay 校驗通過
477
-
478
- Raises:
479
- ValueError: 缺必要欄位 (Data_id / Smseid / Amount / Mid_smilepay)
480
- """
481
- for key in ('Data_id', 'Smseid', 'Amount', 'Mid_smilepay'):
482
- if key not in callback:
483
- raise ValueError(f'通知缺少必要欄位: {key}')
484
-
485
- amount_str = str(callback.get('Amount', '')).strip()
486
- if '.' in amount_str:
487
- raise ValueError(f'Amount 含小數點: {amount_str}')
488
- try:
489
- amount = int(amount_str)
490
- except ValueError as exc:
491
- raise ValueError(f'Amount 非整數: {amount_str}') from exc
492
-
493
- verified = False
494
- if self.mid:
495
- try:
496
- expected = self.calc_mid_smilepay(
497
- self.mid, amount, callback.get('Smseid', '')
498
- )
499
- verified = str(expected) == str(callback.get('Mid_smilepay', ''))
500
- except ValueError:
501
- verified = False
502
-
503
- return SmilePayNotification(
504
- classif=callback.get('Classif', ''),
505
- data_id=callback.get('Data_id', ''),
506
- smseid=callback.get('Smseid', ''),
507
- amount=amount,
508
- process_date=callback.get('Process_date', ''),
509
- process_time=callback.get('Process_time', ''),
510
- response_id=callback.get('Response_id'),
511
- payment_title=callback.get('Payment_title'),
512
- errdesc=callback.get('Errdesc'),
513
- mid_smilepay=callback.get('Mid_smilepay'),
514
- verified=verified,
515
- raw=dict(callback),
516
- )
517
-
518
- @staticmethod
519
- def build_notification_response(roturl_status: str = 'OK') -> str:
520
- """產生回給 SmilePay 的 Roturlstatus 字串"""
521
- return f'<Roturlstatus>{roturl_status}</Roturlstatus>'
522
-
523
-
524
- # ----------------------------------------------------------------------------
525
- # Examples
526
- # ----------------------------------------------------------------------------
527
-
528
-
529
- def example_create_atm_order(service: SmilePayPaymentService) -> None:
530
- print('[範例 1] 建立 ATM 虛擬帳號訂單 (Pay_zg=2)')
531
- print('-' * 60)
532
- order = SmilePayAtmOrder(
533
- data_id=f'ORD{int(time.time())}',
534
- amount=1500,
535
- item_name='測試商品 A * 1',
536
- buyer=SmilePayBuyer(
537
- name='王小明',
538
- mobile='0912345678',
539
- email='test@example.com',
540
- ),
541
- roturl='https://shop.example.com/api/smilepay/roturl',
542
- roturl_status='ok',
543
- )
544
- print(f'訂單編號: {order.data_id}')
545
- print(f'金額: {order.amount}')
546
- print('(範例不實際 POST,避免在 sandbox 留下測試訂單;如要真打,移除 demo guard)')
547
- print()
548
-
549
-
550
- def example_create_credit_redirect(service: SmilePayPaymentService) -> None:
551
- print('[範例 2] 信用卡一次付清結帳頁 redirect URL (Pay_zg=1)')
552
- print('-' * 60)
553
- order = SmilePayCreditOrder(
554
- data_id=f'ORDCC{int(time.time())}',
555
- amount=2500,
556
- item_name='測試商品 B * 1',
557
- buyer=SmilePayBuyer(
558
- name='李小華',
559
- mobile='0922333444',
560
- email='hua@example.com',
561
- ),
562
- roturl='https://shop.example.com/api/smilepay/credit_roturl?Payment_title=信用卡',
563
- roturl_status='ok',
564
- )
565
- result = service.create_credit_order(order)
566
- print(f'訂單編號: {result.data_id}')
567
- print(f'Redirect URL: {result.redirect_url[:120]}...')
568
- print(f'參數數: {len(result.params)}')
569
- print()
570
-
571
-
572
- def example_create_installment(service: SmilePayPaymentService) -> None:
573
- print('[範例 3] 信用卡分期 (Pay_zg=1, Stage=6) 結帳頁 redirect URL')
574
- print('-' * 60)
575
- order = SmilePayInstallmentOrder(
576
- data_id=f'ORDINST{int(time.time())}',
577
- amount=12000,
578
- item_name='高單價商品 * 1',
579
- buyer=SmilePayBuyer(
580
- name='陳大文',
581
- mobile='0933555777',
582
- email='dawen@example.com',
583
- ),
584
- stage=6,
585
- roturl='https://shop.example.com/api/smilepay/credit_roturl',
586
- roturl_status='ok',
587
- )
588
- result = service.create_credit_installment_order(order)
589
- print(f'訂單編號: {result.data_id}')
590
- print(f'Stage: 6 期')
591
- print(f'Redirect URL: {result.redirect_url[:120]}...')
592
- print()
593
-
594
-
595
- def example_create_barcode_order(service: SmilePayPaymentService) -> None:
596
- print('[範例 4] 建立超商條碼訂單 (Pay_zg=3)')
597
- print('-' * 60)
598
- order = SmilePayBarcodeOrder(
599
- data_id=f'ORDBAR{int(time.time())}',
600
- amount=600,
601
- item_name='測試商品 C * 1',
602
- buyer=SmilePayBuyer(
603
- name='張小美',
604
- mobile='0955666888',
605
- email='mei@example.com',
606
- ),
607
- )
608
- print(f'訂單編號: {order.data_id}')
609
- print('(範例不實際 POST,避免在 sandbox 留下測試訂單;如要真打,移除 demo guard)')
610
- print()
611
-
612
-
613
- def example_verify_notification(service: SmilePayPaymentService) -> None:
614
- print('[範例 5] 驗證 Roturl 通知 (Mid_smilepay 校驗)')
615
- print('-' * 60)
616
-
617
- # 模擬一筆 ATM 入帳通知。先依 mid=1111 計算 Mid_smilepay 再放回去
618
- amount = 1500
619
- smseid = '2410287654'
620
- mid_value = service.calc_mid_smilepay(service.mid, amount, smseid)
621
-
622
- callback = {
623
- 'Classif': 'B', # B = ATM 入帳
624
- 'Data_id': 'ORD20260507001',
625
- 'Smseid': smseid,
626
- 'Amount': str(amount),
627
- 'Process_date': '2026/05/07',
628
- 'Process_time': '14:30:00',
629
- 'Mid_smilepay': str(mid_value),
630
- }
631
-
632
- try:
633
- result = service.verify_notification(callback)
634
- print(f'Classif: {result.classif} (B=ATM 入帳)')
635
- print(f'Data_id: {result.data_id}')
636
- print(f'Smseid: {result.smseid}')
637
- print(f'Amount: {result.amount}')
638
- print(f'Mid_smilepay: {result.mid_smilepay}')
639
- print(f'驗章結果: {"通過" if result.verified else "失敗"}')
640
- print()
641
- print('回給 SmilePay:', service.build_notification_response('ok'))
642
- except ValueError as exc:
643
- print(f'通知格式錯誤: {exc}')
644
- print()
645
-
646
-
647
- if __name__ == '__main__':
648
- print('=' * 60)
649
- print('SmilePay 速買配金流 - Python 範例')
650
- print('=' * 60)
651
- print()
652
-
653
- if not HAS_REQUESTS:
654
- print('(缺 requests 套件,僅執行不需 HTTP 的範例)')
655
- print('安裝指令: pip install requests')
656
- print()
657
-
658
- service = SmilePayPaymentService(
659
- dcvc=SmilePayPaymentService.TEST_DCVC,
660
- rvg2c=SmilePayPaymentService.TEST_RVG2C,
661
- verify_key=SmilePayPaymentService.TEST_VERIFY_KEY,
662
- mid=SmilePayPaymentService.TEST_MID,
663
- )
664
-
665
- example_create_atm_order(service)
666
- example_create_credit_redirect(service)
667
- example_create_installment(service)
668
- example_create_barcode_order(service)
669
- example_verify_notification(service)
670
-
671
- print('=' * 60)
672
- print('範例執行完成')
673
- print('=' * 60)
1
+ #!/usr/bin/env python3
2
+ """
3
+ SmilePay 速買配 Python 完整範例
4
+
5
+ 依照 taiwan-payment-skill 最高規範撰寫
6
+ 支援: ATM 虛擬帳號、信用卡 (一次付清/分期)、超商條碼、ibon、FamiPort
7
+
8
+ API 文件: https://www.smilepay.net/
9
+ 參考文件: taiwan-payment/references/smilepay-payment-api.md
10
+
11
+ 特色:
12
+ - 一支 SPPayment.asp 端點涵蓋多種非同步取號類付款 (ATM / 條碼 / ibon / FamiPort)
13
+ - 信用卡 / 銀聯卡走另一支 mtmk_utf.asp 結帳頁
14
+ - 回應為 XML 格式 (使用 Python stdlib xml.etree.ElementTree 解析)
15
+ - 通知驗章採 Mid_smilepay 加權校驗碼 (非 SHA256)
16
+ - 部分中文欄位 (Errdesc / Process_time / Address) 可能以 BIG-5 編碼
17
+
18
+ 依賴:
19
+ pip install requests
20
+ (本範例不需 pycryptodome,SmilePay 沒有 AES 加密流程)
21
+ """
22
+
23
+ import hashlib
24
+ import time
25
+ from dataclasses import dataclass, field
26
+ from datetime import datetime, timedelta
27
+ from typing import Dict, Literal, Optional
28
+ from urllib.parse import urlencode
29
+ import xml.etree.ElementTree as ET
30
+
31
+ try:
32
+ import requests
33
+ HAS_REQUESTS = True
34
+ except ImportError:
35
+ HAS_REQUESTS = False
36
+
37
+
38
+ # ----------------------------------------------------------------------------
39
+ # Dataclasses (Inputs / Responses)
40
+ # ----------------------------------------------------------------------------
41
+
42
+
43
+ @dataclass
44
+ class SmilePayBuyer:
45
+ """SmilePay 訂購人 / 付款人資訊 (UTF-8 編碼)"""
46
+ name: str # Pur_name 訂購人姓名
47
+ mobile: str # Mobile_number 手機
48
+ email: str # Email
49
+ tel: Optional[str] = None # Tel_number 市話 (常以手機帶入)
50
+ address: Optional[str] = None # Address 收件 / 帳單地址
51
+
52
+
53
+ @dataclass
54
+ class SmilePayAtmOrder:
55
+ """SmilePay ATM 虛擬帳號 (Pay_zg=2) 訂單資料"""
56
+ data_id: str # 商店訂單編號 (英數,唯一,<=20)
57
+ amount: int # 金額 (TWD 整數)
58
+ item_name: str # od_sob 商品摘要 (<=45 字)
59
+ buyer: SmilePayBuyer
60
+ deadline_date: Optional[str] = None # YYYY/MM/DD,預設下單日 +7 天
61
+ roturl: Optional[str] = None # 付款結果通知網址
62
+ roturl_status: Optional[str] = None # 通知識別字串
63
+ remark: Optional[str] = None
64
+ invoice_num: Optional[str] = None # 統編 / 載具
65
+
66
+
67
+ @dataclass
68
+ class SmilePayCreditOrder:
69
+ """SmilePay 信用卡 (Pay_zg=1) 一次付清訂單"""
70
+ data_id: str
71
+ amount: int
72
+ item_name: str # od_sob (<=49 字)
73
+ buyer: SmilePayBuyer
74
+ roturl: Optional[str] = None
75
+ roturl_status: Optional[str] = None
76
+ remark: Optional[str] = None
77
+ invoice_num: Optional[str] = None
78
+
79
+
80
+ @dataclass
81
+ class SmilePayInstallmentOrder:
82
+ """SmilePay 信用卡分期訂單 (Pay_zg=1 + Stage)"""
83
+ data_id: str
84
+ amount: int
85
+ item_name: str
86
+ buyer: SmilePayBuyer
87
+ stage: Literal[3, 6, 12, 18, 24] = 3 # 分期期數
88
+ roturl: Optional[str] = None
89
+ roturl_status: Optional[str] = None
90
+ remark: Optional[str] = None
91
+
92
+
93
+ @dataclass
94
+ class SmilePayBarcodeOrder:
95
+ """SmilePay 超商條碼 (Pay_zg=3) 訂單資料"""
96
+ data_id: str
97
+ amount: int
98
+ item_name: str
99
+ buyer: SmilePayBuyer
100
+ deadline_date: Optional[str] = None # < 50 天
101
+ roturl: Optional[str] = None
102
+ roturl_status: Optional[str] = None
103
+ remark: Optional[str] = None
104
+
105
+
106
+ @dataclass
107
+ class SmilePayAtmResponse:
108
+ """ATM 取號成功回應"""
109
+ success: bool
110
+ status: str
111
+ desc: str
112
+ data_id: str
113
+ smilepay_no: str = ''
114
+ atm_bank_no: str = '' # 3 碼財金代碼
115
+ atm_no: str = '' # 14~16 碼虛擬帳號
116
+ amount: int = 0
117
+ pay_end_date: str = ''
118
+ raw_xml: str = ''
119
+
120
+
121
+ @dataclass
122
+ class SmilePayBarcodeResponse:
123
+ """條碼取號成功回應"""
124
+ success: bool
125
+ status: str
126
+ desc: str
127
+ data_id: str
128
+ smilepay_no: str = ''
129
+ barcode1: str = ''
130
+ barcode2: str = ''
131
+ barcode3: str = ''
132
+ amount: int = 0
133
+ pay_end_date: str = ''
134
+ raw_xml: str = ''
135
+
136
+
137
+ @dataclass
138
+ class SmilePayCreditRedirect:
139
+ """信用卡 / 銀聯 / 分期:回傳 redirect URL,給前端跳轉"""
140
+ success: bool
141
+ redirect_url: str
142
+ data_id: str
143
+ params: Dict[str, str] = field(default_factory=dict)
144
+
145
+
146
+ @dataclass
147
+ class SmilePayNotification:
148
+ """Roturl 通知解析結果 (取號類 / 信用卡共用)"""
149
+ classif: str # A/B/C/T/O
150
+ data_id: str
151
+ smseid: str
152
+ amount: int
153
+ process_date: str
154
+ process_time: str
155
+ response_id: Optional[str] = None # 信用卡有,1=成功
156
+ payment_title: Optional[str] = None
157
+ errdesc: Optional[str] = None
158
+ mid_smilepay: Optional[str] = None
159
+ verified: bool = False # Mid_smilepay 是否通過
160
+ raw: Dict[str, str] = field(default_factory=dict)
161
+
162
+
163
+ # ----------------------------------------------------------------------------
164
+ # Service
165
+ # ----------------------------------------------------------------------------
166
+
167
+
168
+ class SmilePayPaymentService:
169
+ """
170
+ SmilePay 速買配金流服務
171
+
172
+ 認證方式: 帳號參數三件組 (Dcvc / Rvg2c / Verify_key) + Mid_smilepay 通知驗章
173
+ 加密方式: 不使用 AES / SHA256;僅有 Mid_smilepay 加權校驗碼
174
+
175
+ 支援付款方式:
176
+ - Pay_zg=1 信用卡 (一次付清 / 分期 + Stage)
177
+ - Pay_zg=2 ATM 虛擬帳號
178
+ - Pay_zg=3 超商條碼
179
+ - Pay_zg=4 7-11 ibon
180
+ - Pay_zg=6 全家 FamiPort
181
+ - Pay_zg=11 銀聯 / 國際信用卡
182
+
183
+ 測試環境 (官方公開測試參數):
184
+ Dcvc: 107
185
+ Rvg2c: 1
186
+ Verify_key: 174A02F97A95F72CE301137B3F98D128
187
+ mid: 1111
188
+
189
+ 測試 / 正式環境同網域 (ssl.smse.com.tw);差異僅在帳號參數。
190
+ """
191
+
192
+ # 測試帳號 (官方公開)
193
+ TEST_DCVC = '107'
194
+ TEST_RVG2C = '1'
195
+ TEST_VERIFY_KEY = '174A02F97A95F72CE301137B3F98D128'
196
+ TEST_MID = '1111'
197
+
198
+ # API 端點
199
+ PAYMENT_URL = 'https://ssl.smse.com.tw/api/SPPayment.asp' # 取號類
200
+ CHECKOUT_URL = 'https://ssl.smse.com.tw/ezpos/mtmk_utf.asp' # 信用卡 / 銀聯
201
+ MODIFY_URL = 'https://ssl.smse.com.tw/api/SPPayment_Modify.asp' # 訂單修改 / 退款
202
+
203
+ def __init__(
204
+ self,
205
+ dcvc: str,
206
+ rvg2c: str,
207
+ verify_key: str,
208
+ mid: str = '',
209
+ timeout: int = 30,
210
+ ):
211
+ """
212
+ 初始化 SmilePay 金流服務
213
+
214
+ Args:
215
+ dcvc: 商店代號
216
+ rvg2c: 收款銀行 / 路由碼 (預設 1)
217
+ verify_key: 驗證金鑰 (32 碼大寫 hex)
218
+ mid: 金流 mid (Mid_smilepay 簽章用,正式環境必填)
219
+ timeout: HTTP 逾時 (秒)
220
+ """
221
+ if not HAS_REQUESTS:
222
+ raise ImportError('需要安裝 requests: pip install requests')
223
+
224
+ self.dcvc = dcvc
225
+ self.rvg2c = rvg2c
226
+ self.verify_key = verify_key
227
+ self.mid = mid
228
+ self.timeout = timeout
229
+
230
+ # ------------------------------------------------------------------
231
+ # Helpers
232
+ # ------------------------------------------------------------------
233
+
234
+ def _account_params(self) -> Dict[str, str]:
235
+ """三件組帳號驗證參數"""
236
+ return {
237
+ 'Dcvc': self.dcvc,
238
+ 'Rvg2c': self.rvg2c,
239
+ 'Verify_key': self.verify_key,
240
+ }
241
+
242
+ def _buyer_params(self, buyer: SmilePayBuyer) -> Dict[str, str]:
243
+ """訂購人欄位"""
244
+ params = {
245
+ 'Pur_name': buyer.name,
246
+ 'Mobile_number': buyer.mobile,
247
+ 'Email': buyer.email,
248
+ }
249
+ if buyer.tel:
250
+ params['Tel_number'] = buyer.tel
251
+ else:
252
+ params['Tel_number'] = buyer.mobile
253
+ if buyer.address:
254
+ params['Address'] = buyer.address
255
+ return params
256
+
257
+ def _post_payment(self, payload: Dict[str, str]) -> ET.Element:
258
+ """POST 至 SPPayment.asp 並解析 XML"""
259
+ resp = requests.post(self.PAYMENT_URL, data=payload, timeout=self.timeout)
260
+ resp.raise_for_status()
261
+ # 速買配回傳的內容通常是 UTF-8;少數欄位 (Errdesc 等) 可能 BIG-5
262
+ # 但根層 XML 本體為 UTF-8,可直接以 fromstring 解析
263
+ try:
264
+ return ET.fromstring(resp.text)
265
+ except ET.ParseError as exc:
266
+ raise RuntimeError(
267
+ f'SmilePay XML 解析失敗: {exc} | body={resp.text[:200]}'
268
+ )
269
+
270
+ def _xml_text(self, root: ET.Element, tag: str, default: str = '') -> str:
271
+ node = root.findtext(tag)
272
+ return node if node is not None else default
273
+
274
+ @staticmethod
275
+ def _default_deadline(days: int = 7) -> str:
276
+ return (datetime.now() + timedelta(days=days)).strftime('%Y/%m/%d')
277
+
278
+ # ------------------------------------------------------------------
279
+ # Order creation
280
+ # ------------------------------------------------------------------
281
+
282
+ def create_atm_order(self, order: SmilePayAtmOrder) -> SmilePayAtmResponse:
283
+ """
284
+ 建立 ATM 虛擬帳號訂單 (Pay_zg=2)
285
+
286
+ Returns:
287
+ SmilePayAtmResponse: 含 atm_bank_no / atm_no / pay_end_date
288
+ """
289
+ if order.amount < 8 or order.amount > 20000:
290
+ raise ValueError('ATM 金額需介於 8 ~ 20,000 元')
291
+ if len(order.data_id) > 20:
292
+ raise ValueError('Data_id 不可超過 20 字元')
293
+
294
+ payload = {
295
+ **self._account_params(),
296
+ **self._buyer_params(order.buyer),
297
+ 'Pay_zg': '2',
298
+ 'Data_id': order.data_id,
299
+ 'Amount': str(order.amount),
300
+ 'od_sob': order.item_name[:45],
301
+ 'Deadline_date': order.deadline_date or self._default_deadline(7),
302
+ }
303
+ if order.roturl:
304
+ payload['Roturl'] = order.roturl
305
+ if order.roturl_status:
306
+ payload['Roturl_status'] = order.roturl_status
307
+ if order.remark:
308
+ payload['Remark'] = order.remark
309
+ if order.invoice_num:
310
+ payload['Invoice_num'] = order.invoice_num
311
+
312
+ root = self._post_payment(payload)
313
+ status = self._xml_text(root, 'Status')
314
+ desc = self._xml_text(root, 'Desc')
315
+
316
+ return SmilePayAtmResponse(
317
+ success=(status == '1'),
318
+ status=status,
319
+ desc=desc,
320
+ data_id=self._xml_text(root, 'Data_id', order.data_id),
321
+ smilepay_no=self._xml_text(root, 'SmilePayNO'),
322
+ atm_bank_no=self._xml_text(root, 'AtmBankNo'),
323
+ atm_no=self._xml_text(root, 'AtmNo'),
324
+ amount=int(self._xml_text(root, 'Amount', '0') or 0),
325
+ pay_end_date=self._xml_text(root, 'PayEndDate'),
326
+ raw_xml=ET.tostring(root, encoding='unicode'),
327
+ )
328
+
329
+ def create_barcode_order(self, order: SmilePayBarcodeOrder) -> SmilePayBarcodeResponse:
330
+ """
331
+ 建立超商條碼訂單 (Pay_zg=3)
332
+
333
+ Returns:
334
+ SmilePayBarcodeResponse: 含三段條碼 + pay_end_date
335
+ """
336
+ if order.amount < 8 or order.amount > 20000:
337
+ raise ValueError('條碼金額需介於 8 ~ 20,000 元')
338
+
339
+ payload = {
340
+ **self._account_params(),
341
+ **self._buyer_params(order.buyer),
342
+ 'Pay_zg': '3',
343
+ 'Data_id': order.data_id,
344
+ 'Amount': str(order.amount),
345
+ 'od_sob': order.item_name[:45],
346
+ 'Deadline_date': order.deadline_date or self._default_deadline(30),
347
+ }
348
+ if order.roturl:
349
+ payload['Roturl'] = order.roturl
350
+ if order.roturl_status:
351
+ payload['Roturl_status'] = order.roturl_status
352
+ if order.remark:
353
+ payload['Remark'] = order.remark
354
+
355
+ root = self._post_payment(payload)
356
+ status = self._xml_text(root, 'Status')
357
+
358
+ return SmilePayBarcodeResponse(
359
+ success=(status == '1'),
360
+ status=status,
361
+ desc=self._xml_text(root, 'Desc'),
362
+ data_id=self._xml_text(root, 'Data_id', order.data_id),
363
+ smilepay_no=self._xml_text(root, 'SmilePayNO'),
364
+ barcode1=self._xml_text(root, 'Barcode1'),
365
+ barcode2=self._xml_text(root, 'Barcode2'),
366
+ barcode3=self._xml_text(root, 'Barcode3'),
367
+ amount=int(self._xml_text(root, 'Amount', '0') or 0),
368
+ pay_end_date=self._xml_text(root, 'PayEndDate'),
369
+ raw_xml=ET.tostring(root, encoding='unicode'),
370
+ )
371
+
372
+ def create_credit_order(self, order: SmilePayCreditOrder) -> SmilePayCreditRedirect:
373
+ """
374
+ 建立信用卡 (一次付清) 結帳頁 redirect URL (Pay_zg=1)
375
+
376
+ Note: 此方法不發 HTTP 請求,僅組好 querystring 給商店端 redirect。
377
+ 消費者進入結帳頁後輸入卡號、3D 驗證,結束後 SmilePay 以
378
+ querystring 帶結果到 Roturl。
379
+ """
380
+ params = {
381
+ **self._account_params(),
382
+ **self._buyer_params(order.buyer),
383
+ 'Pay_zg': '1',
384
+ 'Data_id': order.data_id,
385
+ 'Amount': str(order.amount),
386
+ 'od_sob': order.item_name[:49],
387
+ }
388
+ if order.roturl:
389
+ params['Roturl'] = order.roturl
390
+ if order.roturl_status:
391
+ params['Roturl_status'] = order.roturl_status
392
+ if order.remark:
393
+ params['Remark'] = order.remark
394
+ if order.invoice_num:
395
+ params['Invoice_num'] = order.invoice_num
396
+
397
+ return SmilePayCreditRedirect(
398
+ success=True,
399
+ redirect_url=f'{self.CHECKOUT_URL}?{urlencode(params)}',
400
+ data_id=order.data_id,
401
+ params=params,
402
+ )
403
+
404
+ def create_credit_installment_order(
405
+ self, order: SmilePayInstallmentOrder
406
+ ) -> SmilePayCreditRedirect:
407
+ """
408
+ 建立信用卡分期 (Pay_zg=1 + Stage) 結帳頁 redirect URL
409
+
410
+ 模組預設支援期數: 3 / 6 / 12 / 18 / 24
411
+ """
412
+ if order.stage not in (3, 6, 12, 18, 24):
413
+ raise ValueError('Stage 僅支援 3 / 6 / 12 / 18 / 24 期')
414
+
415
+ params = {
416
+ **self._account_params(),
417
+ **self._buyer_params(order.buyer),
418
+ 'Pay_zg': '1',
419
+ 'Stage': str(order.stage),
420
+ 'Data_id': order.data_id,
421
+ 'Amount': str(order.amount),
422
+ 'od_sob': order.item_name[:49],
423
+ }
424
+ if order.roturl:
425
+ params['Roturl'] = order.roturl
426
+ if order.roturl_status:
427
+ params['Roturl_status'] = order.roturl_status
428
+ if order.remark:
429
+ params['Remark'] = order.remark
430
+
431
+ return SmilePayCreditRedirect(
432
+ success=True,
433
+ redirect_url=f'{self.CHECKOUT_URL}?{urlencode(params)}',
434
+ data_id=order.data_id,
435
+ params=params,
436
+ )
437
+
438
+ # ------------------------------------------------------------------
439
+ # Mid_smilepay verification
440
+ # ------------------------------------------------------------------
441
+
442
+ @staticmethod
443
+ def calc_mid_smilepay(mid: str, amount: int, smseid: str) -> int:
444
+ """
445
+ 計算 Mid_smilepay 通知校驗碼
446
+
447
+ 演算法 (摘自 WooCommerce 模組推導,見 references/smilepay-payment-api.md)
448
+
449
+ 步驟:
450
+ 1. 取 Smseid 末 4 碼 r1 r2 r3 r4,非數字以 9 取代
451
+ 2. Amount 補零至 8 碼 (左補) -> str1
452
+ 3. 串接 s = mid + str1 + r1 r2 r3 r4 (16 碼)
453
+ 4. even = s 偶數位 (0,2,4...) 加總;odd = 奇數位加總
454
+ 5. Mid_smilepay = even * 9 + odd * 3
455
+ """
456
+ r_all = (smseid or '')[-4:].rjust(4, '9')
457
+ r = [c if c.isdigit() else '9' for c in r_all]
458
+ str1 = str(amount).zfill(8)
459
+ s = f'{mid}{str1}{r[0]}{r[1]}{r[2]}{r[3]}'
460
+ if len(s) != 16:
461
+ raise ValueError(
462
+ f'Mid_smilepay 長度錯誤: {len(s)} (應為 16, mid={mid})'
463
+ )
464
+ even = sum(int(s[i]) for i in range(16) if i % 2 == 0)
465
+ odd = sum(int(s[i]) for i in range(16) if i % 2 == 1)
466
+ return even * 9 + odd * 3
467
+
468
+ def verify_notification(self, callback: Dict[str, str]) -> SmilePayNotification:
469
+ """
470
+ 驗證 SmilePay Roturl 通知
471
+
472
+ Args:
473
+ callback: 速買配 POST/GET 進來的所有 querystring 參數
474
+
475
+ Returns:
476
+ SmilePayNotification: verified=True 表示 Mid_smilepay 校驗通過
477
+
478
+ Raises:
479
+ ValueError: 缺必要欄位 (Data_id / Smseid / Amount / Mid_smilepay)
480
+ """
481
+ for key in ('Data_id', 'Smseid', 'Amount', 'Mid_smilepay'):
482
+ if key not in callback:
483
+ raise ValueError(f'通知缺少必要欄位: {key}')
484
+
485
+ amount_str = str(callback.get('Amount', '')).strip()
486
+ if '.' in amount_str:
487
+ raise ValueError(f'Amount 含小數點: {amount_str}')
488
+ try:
489
+ amount = int(amount_str)
490
+ except ValueError as exc:
491
+ raise ValueError(f'Amount 非整數: {amount_str}') from exc
492
+
493
+ verified = False
494
+ if self.mid:
495
+ try:
496
+ expected = self.calc_mid_smilepay(
497
+ self.mid, amount, callback.get('Smseid', '')
498
+ )
499
+ verified = str(expected) == str(callback.get('Mid_smilepay', ''))
500
+ except ValueError:
501
+ verified = False
502
+
503
+ return SmilePayNotification(
504
+ classif=callback.get('Classif', ''),
505
+ data_id=callback.get('Data_id', ''),
506
+ smseid=callback.get('Smseid', ''),
507
+ amount=amount,
508
+ process_date=callback.get('Process_date', ''),
509
+ process_time=callback.get('Process_time', ''),
510
+ response_id=callback.get('Response_id'),
511
+ payment_title=callback.get('Payment_title'),
512
+ errdesc=callback.get('Errdesc'),
513
+ mid_smilepay=callback.get('Mid_smilepay'),
514
+ verified=verified,
515
+ raw=dict(callback),
516
+ )
517
+
518
+ @staticmethod
519
+ def build_notification_response(roturl_status: str = 'OK') -> str:
520
+ """產生回給 SmilePay 的 Roturlstatus 字串"""
521
+ return f'<Roturlstatus>{roturl_status}</Roturlstatus>'
522
+
523
+
524
+ # ----------------------------------------------------------------------------
525
+ # Examples
526
+ # ----------------------------------------------------------------------------
527
+
528
+
529
+ def example_create_atm_order(service: SmilePayPaymentService) -> None:
530
+ print('[範例 1] 建立 ATM 虛擬帳號訂單 (Pay_zg=2)')
531
+ print('-' * 60)
532
+ order = SmilePayAtmOrder(
533
+ data_id=f'ORD{int(time.time())}',
534
+ amount=1500,
535
+ item_name='測試商品 A * 1',
536
+ buyer=SmilePayBuyer(
537
+ name='王小明',
538
+ mobile='0912345678',
539
+ email='test@example.com',
540
+ ),
541
+ roturl='https://shop.example.com/api/smilepay/roturl',
542
+ roturl_status='ok',
543
+ )
544
+ print(f'訂單編號: {order.data_id}')
545
+ print(f'金額: {order.amount}')
546
+ print('(範例不實際 POST,避免在 sandbox 留下測試訂單;如要真打,移除 demo guard)')
547
+ print()
548
+
549
+
550
+ def example_create_credit_redirect(service: SmilePayPaymentService) -> None:
551
+ print('[範例 2] 信用卡一次付清結帳頁 redirect URL (Pay_zg=1)')
552
+ print('-' * 60)
553
+ order = SmilePayCreditOrder(
554
+ data_id=f'ORDCC{int(time.time())}',
555
+ amount=2500,
556
+ item_name='測試商品 B * 1',
557
+ buyer=SmilePayBuyer(
558
+ name='李小華',
559
+ mobile='0922333444',
560
+ email='hua@example.com',
561
+ ),
562
+ roturl='https://shop.example.com/api/smilepay/credit_roturl?Payment_title=信用卡',
563
+ roturl_status='ok',
564
+ )
565
+ result = service.create_credit_order(order)
566
+ print(f'訂單編號: {result.data_id}')
567
+ print(f'Redirect URL: {result.redirect_url[:120]}...')
568
+ print(f'參數數: {len(result.params)}')
569
+ print()
570
+
571
+
572
+ def example_create_installment(service: SmilePayPaymentService) -> None:
573
+ print('[範例 3] 信用卡分期 (Pay_zg=1, Stage=6) 結帳頁 redirect URL')
574
+ print('-' * 60)
575
+ order = SmilePayInstallmentOrder(
576
+ data_id=f'ORDINST{int(time.time())}',
577
+ amount=12000,
578
+ item_name='高單價商品 * 1',
579
+ buyer=SmilePayBuyer(
580
+ name='陳大文',
581
+ mobile='0933555777',
582
+ email='dawen@example.com',
583
+ ),
584
+ stage=6,
585
+ roturl='https://shop.example.com/api/smilepay/credit_roturl',
586
+ roturl_status='ok',
587
+ )
588
+ result = service.create_credit_installment_order(order)
589
+ print(f'訂單編號: {result.data_id}')
590
+ print(f'Stage: 6 期')
591
+ print(f'Redirect URL: {result.redirect_url[:120]}...')
592
+ print()
593
+
594
+
595
+ def example_create_barcode_order(service: SmilePayPaymentService) -> None:
596
+ print('[範例 4] 建立超商條碼訂單 (Pay_zg=3)')
597
+ print('-' * 60)
598
+ order = SmilePayBarcodeOrder(
599
+ data_id=f'ORDBAR{int(time.time())}',
600
+ amount=600,
601
+ item_name='測試商品 C * 1',
602
+ buyer=SmilePayBuyer(
603
+ name='張小美',
604
+ mobile='0955666888',
605
+ email='mei@example.com',
606
+ ),
607
+ )
608
+ print(f'訂單編號: {order.data_id}')
609
+ print('(範例不實際 POST,避免在 sandbox 留下測試訂單;如要真打,移除 demo guard)')
610
+ print()
611
+
612
+
613
+ def example_verify_notification(service: SmilePayPaymentService) -> None:
614
+ print('[範例 5] 驗證 Roturl 通知 (Mid_smilepay 校驗)')
615
+ print('-' * 60)
616
+
617
+ # 模擬一筆 ATM 入帳通知。先依 mid=1111 計算 Mid_smilepay 再放回去
618
+ amount = 1500
619
+ smseid = '2410287654'
620
+ mid_value = service.calc_mid_smilepay(service.mid, amount, smseid)
621
+
622
+ callback = {
623
+ 'Classif': 'B', # B = ATM 入帳
624
+ 'Data_id': 'ORD20260507001',
625
+ 'Smseid': smseid,
626
+ 'Amount': str(amount),
627
+ 'Process_date': '2026/05/07',
628
+ 'Process_time': '14:30:00',
629
+ 'Mid_smilepay': str(mid_value),
630
+ }
631
+
632
+ try:
633
+ result = service.verify_notification(callback)
634
+ print(f'Classif: {result.classif} (B=ATM 入帳)')
635
+ print(f'Data_id: {result.data_id}')
636
+ print(f'Smseid: {result.smseid}')
637
+ print(f'Amount: {result.amount}')
638
+ print(f'Mid_smilepay: {result.mid_smilepay}')
639
+ print(f'驗章結果: {"通過" if result.verified else "失敗"}')
640
+ print()
641
+ print('回給 SmilePay:', service.build_notification_response('ok'))
642
+ except ValueError as exc:
643
+ print(f'通知格式錯誤: {exc}')
644
+ print()
645
+
646
+
647
+ if __name__ == '__main__':
648
+ print('=' * 60)
649
+ print('SmilePay 速買配金流 - Python 範例')
650
+ print('=' * 60)
651
+ print()
652
+
653
+ if not HAS_REQUESTS:
654
+ print('(缺 requests 套件,僅執行不需 HTTP 的範例)')
655
+ print('安裝指令: pip install requests')
656
+ print()
657
+
658
+ service = SmilePayPaymentService(
659
+ dcvc=SmilePayPaymentService.TEST_DCVC,
660
+ rvg2c=SmilePayPaymentService.TEST_RVG2C,
661
+ verify_key=SmilePayPaymentService.TEST_VERIFY_KEY,
662
+ mid=SmilePayPaymentService.TEST_MID,
663
+ )
664
+
665
+ example_create_atm_order(service)
666
+ example_create_credit_redirect(service)
667
+ example_create_installment(service)
668
+ example_create_barcode_order(service)
669
+ example_verify_notification(service)
670
+
671
+ print('=' * 60)
672
+ print('範例執行完成')
673
+ print('=' * 60)