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.
- package/README.md +8 -4
- package/assets/taiwan-payment/CLAUDE.md +4 -1
- package/assets/taiwan-payment/EXAMPLES.md +48 -0
- package/assets/taiwan-payment/README.md +23 -7
- package/assets/taiwan-payment/SKILL.md +29 -2
- package/assets/taiwan-payment/data/error-codes.csv +60 -32
- package/assets/taiwan-payment/data/operations.csv +9 -0
- package/assets/taiwan-payment/data/providers.csv +3 -0
- package/assets/taiwan-payment/examples/ezpay-payment-example.py +690 -690
- package/assets/taiwan-payment/examples/linepay-payment-example.py +305 -0
- package/assets/taiwan-payment/examples/paynow-payment-example.py +767 -767
- package/assets/taiwan-payment/examples/pchomepay-payment-example.py +556 -556
- package/assets/taiwan-payment/examples/shopline-payment-example.py +291 -0
- package/assets/taiwan-payment/examples/smilepay-payment-example.py +673 -673
- package/assets/taiwan-payment/examples/tappay-payment-example.py +337 -0
- package/assets/taiwan-payment/references/ezpay-payment-api.md +660 -660
- package/assets/taiwan-payment/references/linepay-payment-api.md +940 -0
- package/assets/taiwan-payment/references/paynow-payment-api.md +1654 -1654
- package/assets/taiwan-payment/references/pchomepay-payment-api.md +1431 -1431
- package/assets/taiwan-payment/references/shopline-payment-api.md +1523 -0
- package/assets/taiwan-payment/references/smilepay-payment-api.md +919 -919
- package/assets/taiwan-payment/references/tappay-payment-api.md +1245 -0
- package/assets/templates/base/skill-content.md +27 -0
- package/assets/templates/platforms/agent.json +2 -2
- package/assets/templates/platforms/antigravity.json +1 -1
- package/assets/templates/platforms/claude.json +2 -2
- package/assets/templates/platforms/codebuddy.json +2 -2
- package/assets/templates/platforms/codex.json +2 -2
- package/assets/templates/platforms/continue.json +2 -2
- package/assets/templates/platforms/copilot.json +2 -2
- package/assets/templates/platforms/cursor.json +2 -2
- package/assets/templates/platforms/gemini.json +2 -2
- package/assets/templates/platforms/kiro.json +2 -2
- package/assets/templates/platforms/opencode.json +2 -2
- package/assets/templates/platforms/qoder.json +2 -2
- package/assets/templates/platforms/roocode.json +2 -2
- package/assets/templates/platforms/trae.json +2 -2
- package/assets/templates/platforms/windsurf.json +2 -2
- package/package.json +5 -2
|
@@ -1,690 +1,690 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""
|
|
3
|
-
ezPay 簡單付 Python 完整範例
|
|
4
|
-
|
|
5
|
-
依照 taiwan-payment-skill 最高規範撰寫
|
|
6
|
-
支援: MPG 整合支付 (信用卡、ATM、超商代碼、TWQR、LINE Pay 等)、訂單查詢、退款
|
|
7
|
-
|
|
8
|
-
API 文件: https://www.ezpay.com.tw/info/Service_intro/api_document/member
|
|
9
|
-
參考文件: taiwan-payment/references/ezpay-payment-api.md
|
|
10
|
-
|
|
11
|
-
ezPay 與 Newebpay 關係:
|
|
12
|
-
ezPay 簡單付 為藍新金流 Newebpay 集團小型商家品牌;
|
|
13
|
-
金流 API 完全相同 (TradeInfo AES-256-CBC + TradeSha SHA256),
|
|
14
|
-
主要差異為 MerchantID/HashKey 為 ezPay 獨立簽發、部分付款方式受限
|
|
15
|
-
(例如分期付款、特定電子錢包),且 URL 改用 spgateway / ezpay 域名。
|
|
16
|
-
|
|
17
|
-
URL 差異:
|
|
18
|
-
Newebpay 沙箱: https://ccore.newebpay.com/MPG/mpg_gateway
|
|
19
|
-
Newebpay 正式: https://core.newebpay.com/MPG/mpg_gateway
|
|
20
|
-
ezPay 沙箱: https://ccore.spgateway.com/MPG/mpg_gateway (本範例採用)
|
|
21
|
-
ezPay 正式: https://core.spgateway.com/MPG/mpg_gateway
|
|
22
|
-
|
|
23
|
-
版本差異:
|
|
24
|
-
Newebpay 主推 Version=2.3 (含 GCM 加密選項)
|
|
25
|
-
ezPay 老商家多數仍維持 Version=2.0 (本範例預設 2.0)
|
|
26
|
-
|
|
27
|
-
依賴:
|
|
28
|
-
pip install pycryptodome requests
|
|
29
|
-
"""
|
|
30
|
-
|
|
31
|
-
import hashlib
|
|
32
|
-
import json
|
|
33
|
-
import time
|
|
34
|
-
import urllib.parse
|
|
35
|
-
from dataclasses import dataclass, field
|
|
36
|
-
from datetime import datetime
|
|
37
|
-
from typing import Any, Dict, Literal, Optional
|
|
38
|
-
|
|
39
|
-
try:
|
|
40
|
-
from Crypto.Cipher import AES
|
|
41
|
-
from Crypto.Util.Padding import pad, unpad
|
|
42
|
-
HAS_CRYPTO = True
|
|
43
|
-
except ImportError:
|
|
44
|
-
HAS_CRYPTO = False
|
|
45
|
-
|
|
46
|
-
try:
|
|
47
|
-
import requests
|
|
48
|
-
HAS_REQUESTS = True
|
|
49
|
-
except ImportError:
|
|
50
|
-
HAS_REQUESTS = False
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
# ----------------------------------------------------------------------------
|
|
54
|
-
# Dataclasses
|
|
55
|
-
# ----------------------------------------------------------------------------
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
@dataclass
|
|
59
|
-
class EzPayMPGOrder:
|
|
60
|
-
"""
|
|
61
|
-
ezPay MPG 付款訂單資料 (送進 mpg_gateway 加密前)
|
|
62
|
-
|
|
63
|
-
對應 Newebpay TradeInfo 內含欄位;ezPay 強制 Email 必填。
|
|
64
|
-
"""
|
|
65
|
-
merchant_order_no: str # MerchantOrderNo (<=30,唯一)
|
|
66
|
-
amt: int # Amt (TWD 整數)
|
|
67
|
-
item_desc: str # ItemDesc (<=50)
|
|
68
|
-
email: str # Email (ezPay 強制必填)
|
|
69
|
-
return_url: str # ReturnURL 付款完成前景轉跳
|
|
70
|
-
notify_url: Optional[str] = None
|
|
71
|
-
client_back_url: Optional[str] = None
|
|
72
|
-
enable_credit: bool = True
|
|
73
|
-
enable_credit_installment: bool = False
|
|
74
|
-
installment_periods: Optional[str] = None # InstFlag, e.g. "3,6,12"
|
|
75
|
-
enable_unionpay: bool = False
|
|
76
|
-
enable_webatm: bool = False
|
|
77
|
-
enable_vacc: bool = False
|
|
78
|
-
enable_cvs: bool = False
|
|
79
|
-
enable_barcode: bool = False
|
|
80
|
-
enable_linepay: bool = False
|
|
81
|
-
enable_applepay: bool = False
|
|
82
|
-
enable_androidpay: bool = False
|
|
83
|
-
enable_twqr: bool = False
|
|
84
|
-
enable_esunwallet: bool = False
|
|
85
|
-
enable_taiwanpay: bool = False
|
|
86
|
-
login_type: int = 0
|
|
87
|
-
order_comment: Optional[str] = None
|
|
88
|
-
trade_limit: int = 900
|
|
89
|
-
expire_date: Optional[str] = None # ATM/CVS 繳費期限 Ymd
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
@dataclass
|
|
93
|
-
class EzPayMPGResponse:
|
|
94
|
-
"""ezPay MPG 訂單建立回應 (供前端 form POST)"""
|
|
95
|
-
success: bool
|
|
96
|
-
merchant_order_no: str
|
|
97
|
-
form_action: str = ''
|
|
98
|
-
trade_info: str = ''
|
|
99
|
-
trade_sha: str = ''
|
|
100
|
-
merchant_id: str = ''
|
|
101
|
-
version: str = ''
|
|
102
|
-
error_message: str = ''
|
|
103
|
-
raw: Dict[str, str] = field(default_factory=dict)
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
@dataclass
|
|
107
|
-
class EzPayMPGCallback:
|
|
108
|
-
"""ezPay MPG NotifyURL / ReturnURL 解密後資料"""
|
|
109
|
-
status: str # SUCCESS / 失敗碼
|
|
110
|
-
message: str
|
|
111
|
-
merchant_order_no: str
|
|
112
|
-
amt: int
|
|
113
|
-
trade_no: str
|
|
114
|
-
merchant_id: str
|
|
115
|
-
payment_type: str
|
|
116
|
-
pay_time: str
|
|
117
|
-
ip: str
|
|
118
|
-
check_code_valid: bool = False # CheckCode 是否通過
|
|
119
|
-
code_no: Optional[str] = None
|
|
120
|
-
barcode_1: Optional[str] = None
|
|
121
|
-
barcode_2: Optional[str] = None
|
|
122
|
-
barcode_3: Optional[str] = None
|
|
123
|
-
expire_date: Optional[str] = None
|
|
124
|
-
raw: Dict[str, Any] = field(default_factory=dict)
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
@dataclass
|
|
128
|
-
class EzPayQueryResult:
|
|
129
|
-
"""訂單查詢結果 (POST /API/QueryTradeInfo)"""
|
|
130
|
-
success: bool
|
|
131
|
-
trade_status: str # 0/1/2/3/6/9
|
|
132
|
-
payment_type: str = ''
|
|
133
|
-
amt: int = 0
|
|
134
|
-
trade_no: str = ''
|
|
135
|
-
merchant_order_no: str = ''
|
|
136
|
-
create_time: str = ''
|
|
137
|
-
pay_time: str = ''
|
|
138
|
-
raw: Dict[str, Any] = field(default_factory=dict)
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
@dataclass
|
|
142
|
-
class EzPayRefundResult:
|
|
143
|
-
"""信用卡請款 / 退款結果 (POST /API/CreditCard/Close)"""
|
|
144
|
-
success: bool
|
|
145
|
-
status: str # SUCCESS / 失敗碼
|
|
146
|
-
message: str = ''
|
|
147
|
-
raw: Dict[str, Any] = field(default_factory=dict)
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
# ----------------------------------------------------------------------------
|
|
151
|
-
# Service
|
|
152
|
-
# ----------------------------------------------------------------------------
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
class EzPayPaymentService:
|
|
156
|
-
"""
|
|
157
|
-
ezPay 簡單付金流服務
|
|
158
|
-
|
|
159
|
-
認證方式: AES-256-CBC + SHA256 (與 Newebpay 完全相同)
|
|
160
|
-
加密欄位:
|
|
161
|
-
TradeInfo = AES-256-CBC(query_string(params), key=HashKey, iv=HashIV).hex()
|
|
162
|
-
TradeSha = SHA256("HashKey={HashKey}&{TradeInfo}&HashIV={HashIV}").upper()
|
|
163
|
-
CheckCode = SHA256("HashIV={IV}&Amt&MerchantID&MerchantOrderNo&TradeNo&HashKey={Key}").upper()
|
|
164
|
-
(key 順序: Amt -> MerchantID -> MerchantOrderNo -> TradeNo)
|
|
165
|
-
|
|
166
|
-
支援付款方式 (依商家方案啟用):
|
|
167
|
-
CREDIT / InstFlag / UNIONPAY / APPLEPAY / ANDROIDPAY / WEBATM / VACC /
|
|
168
|
-
CVS / BARCODE / LINEPAY / ESUNWALLET / TAIWANPAY / TWQR ...
|
|
169
|
-
|
|
170
|
-
測試環境:
|
|
171
|
-
商店代號 / HashKey / HashIV 需自行於 ezPay 後台申請;
|
|
172
|
-
ezPay 不公開共用測試 Merchant。
|
|
173
|
-
測試卡號: 4000-2211-1111-1111
|
|
174
|
-
"""
|
|
175
|
-
|
|
176
|
-
# 沙箱 / 正式環境 (採 spgateway 域名;ezpay.com.tw 域名亦可)
|
|
177
|
-
TEST_API_URL = 'https://ccore.spgateway.com/MPG/mpg_gateway'
|
|
178
|
-
TEST_QUERY_URL = 'https://ccore.spgateway.com/API/QueryTradeInfo'
|
|
179
|
-
TEST_CLOSE_URL = 'https://ccore.spgateway.com/API/CreditCard/Close'
|
|
180
|
-
TEST_EWALLET_REFUND_URL = 'https://ccore.spgateway.com/API/EWallet/refund'
|
|
181
|
-
|
|
182
|
-
PROD_API_URL = 'https://core.spgateway.com/MPG/mpg_gateway'
|
|
183
|
-
PROD_QUERY_URL = 'https://core.spgateway.com/API/QueryTradeInfo'
|
|
184
|
-
PROD_CLOSE_URL = 'https://core.spgateway.com/API/CreditCard/Close'
|
|
185
|
-
PROD_EWALLET_REFUND_URL = 'https://core.spgateway.com/API/EWallet/refund'
|
|
186
|
-
|
|
187
|
-
# ezPay 慣用版本 (Newebpay 主推 2.3,ezPay 多數老商家仍 2.0)
|
|
188
|
-
DEFAULT_VERSION = '2.0'
|
|
189
|
-
|
|
190
|
-
def __init__(
|
|
191
|
-
self,
|
|
192
|
-
merchant_id: str,
|
|
193
|
-
hash_key: str,
|
|
194
|
-
hash_iv: str,
|
|
195
|
-
is_production: bool = False,
|
|
196
|
-
version: Optional[str] = None,
|
|
197
|
-
timeout: int = 30,
|
|
198
|
-
):
|
|
199
|
-
"""
|
|
200
|
-
初始化 ezPay 金流服務
|
|
201
|
-
|
|
202
|
-
Args:
|
|
203
|
-
merchant_id: ezPay 商店代號 (通常以 EZ 系列前綴開頭)
|
|
204
|
-
hash_key: 32 字元 HashKey
|
|
205
|
-
hash_iv: 16 字元 HashIV
|
|
206
|
-
is_production: 是否為正式環境 (預設 False)
|
|
207
|
-
version: 串接版本 (預設 2.0);可改 2.3 對齊 Newebpay
|
|
208
|
-
"""
|
|
209
|
-
if not HAS_CRYPTO:
|
|
210
|
-
raise ImportError('需要安裝 pycryptodome: pip install pycryptodome')
|
|
211
|
-
|
|
212
|
-
self.merchant_id = merchant_id
|
|
213
|
-
self.hash_key = hash_key.encode('utf-8')
|
|
214
|
-
self.hash_iv = hash_iv.encode('utf-8')
|
|
215
|
-
self.version = version or self.DEFAULT_VERSION
|
|
216
|
-
|
|
217
|
-
if is_production:
|
|
218
|
-
self.api_url = self.PROD_API_URL
|
|
219
|
-
self.query_url = self.PROD_QUERY_URL
|
|
220
|
-
self.close_url = self.PROD_CLOSE_URL
|
|
221
|
-
self.ewallet_refund_url = self.PROD_EWALLET_REFUND_URL
|
|
222
|
-
else:
|
|
223
|
-
self.api_url = self.TEST_API_URL
|
|
224
|
-
self.query_url = self.TEST_QUERY_URL
|
|
225
|
-
self.close_url = self.TEST_CLOSE_URL
|
|
226
|
-
self.ewallet_refund_url = self.TEST_EWALLET_REFUND_URL
|
|
227
|
-
|
|
228
|
-
self.timeout = timeout
|
|
229
|
-
|
|
230
|
-
# ------------------------------------------------------------------
|
|
231
|
-
# Encryption helpers (與 Newebpay 共用實作)
|
|
232
|
-
# ------------------------------------------------------------------
|
|
233
|
-
|
|
234
|
-
def encrypt_trade_info(self, data: Dict[str, Any]) -> str:
|
|
235
|
-
"""AES-256-CBC + PKCS#7 padding -> hex 字串"""
|
|
236
|
-
query_string = urllib.parse.urlencode(data)
|
|
237
|
-
cipher = AES.new(self.hash_key, AES.MODE_CBC, self.hash_iv)
|
|
238
|
-
padded = pad(query_string.encode('utf-8'), AES.block_size)
|
|
239
|
-
return cipher.encrypt(padded).hex()
|
|
240
|
-
|
|
241
|
-
def decrypt_trade_info(self, encrypted_data: str) -> Dict[str, Any]:
|
|
242
|
-
"""AES-256-CBC 解密 -> dict"""
|
|
243
|
-
try:
|
|
244
|
-
encrypted_bytes = bytes.fromhex(encrypted_data)
|
|
245
|
-
cipher = AES.new(self.hash_key, AES.MODE_CBC, self.hash_iv)
|
|
246
|
-
decrypted = unpad(cipher.decrypt(encrypted_bytes), AES.block_size)
|
|
247
|
-
params = urllib.parse.parse_qs(decrypted.decode('utf-8'))
|
|
248
|
-
return {k: v[0] if len(v) == 1 else v for k, v in params.items()}
|
|
249
|
-
except Exception as exc:
|
|
250
|
-
raise ValueError(f'TradeInfo 解密失敗: {exc}')
|
|
251
|
-
|
|
252
|
-
def generate_trade_sha(self, trade_info: str) -> str:
|
|
253
|
-
"""TradeSha = SHA256("HashKey=...&TradeInfo&HashIV=...").upper()"""
|
|
254
|
-
raw = (
|
|
255
|
-
f'HashKey={self.hash_key.decode("utf-8")}'
|
|
256
|
-
f'&{trade_info}'
|
|
257
|
-
f'&HashIV={self.hash_iv.decode("utf-8")}'
|
|
258
|
-
)
|
|
259
|
-
return hashlib.sha256(raw.encode('utf-8')).hexdigest().upper()
|
|
260
|
-
|
|
261
|
-
def verify_trade_sha(self, trade_info: str, trade_sha: str) -> bool:
|
|
262
|
-
return self.generate_trade_sha(trade_info) == trade_sha.upper()
|
|
263
|
-
|
|
264
|
-
def generate_check_code(
|
|
265
|
-
self,
|
|
266
|
-
amt: int | str,
|
|
267
|
-
merchant_id: str,
|
|
268
|
-
merchant_order_no: str,
|
|
269
|
-
trade_no: str,
|
|
270
|
-
) -> str:
|
|
271
|
-
"""
|
|
272
|
-
CheckCode (防金額竄改) - 使用「HashIV=...&[排序後 querystring]&HashKey=...」格式
|
|
273
|
-
|
|
274
|
-
欄位順序固定為 Amt -> MerchantID -> MerchantOrderNo -> TradeNo (字典序)
|
|
275
|
-
"""
|
|
276
|
-
check_params = {
|
|
277
|
-
'Amt': amt,
|
|
278
|
-
'MerchantID': merchant_id,
|
|
279
|
-
'MerchantOrderNo': merchant_order_no,
|
|
280
|
-
'TradeNo': trade_no,
|
|
281
|
-
}
|
|
282
|
-
ordered = {k: check_params[k] for k in sorted(check_params)}
|
|
283
|
-
param_str = urllib.parse.urlencode(ordered)
|
|
284
|
-
raw = (
|
|
285
|
-
f'HashIV={self.hash_iv.decode("utf-8")}'
|
|
286
|
-
f'&{param_str}'
|
|
287
|
-
f'&HashKey={self.hash_key.decode("utf-8")}'
|
|
288
|
-
)
|
|
289
|
-
return hashlib.sha256(raw.encode('utf-8')).hexdigest().upper()
|
|
290
|
-
|
|
291
|
-
# ------------------------------------------------------------------
|
|
292
|
-
# MPG order
|
|
293
|
-
# ------------------------------------------------------------------
|
|
294
|
-
|
|
295
|
-
def create_order(self, data: EzPayMPGOrder) -> EzPayMPGResponse:
|
|
296
|
-
"""
|
|
297
|
-
建立 ezPay MPG 整合支付訂單
|
|
298
|
-
|
|
299
|
-
Returns:
|
|
300
|
-
EzPayMPGResponse: 含 trade_info / trade_sha,前端以 form POST 至 form_action
|
|
301
|
-
"""
|
|
302
|
-
if data.amt < 1:
|
|
303
|
-
raise ValueError('金額必須大於 0')
|
|
304
|
-
if len(data.merchant_order_no) > 30:
|
|
305
|
-
raise ValueError('訂單編號不可超過 30 字元')
|
|
306
|
-
if not data.email:
|
|
307
|
-
raise ValueError('ezPay 強制需要 Email 欄位')
|
|
308
|
-
|
|
309
|
-
params: Dict[str, Any] = {
|
|
310
|
-
'MerchantID': self.merchant_id,
|
|
311
|
-
'RespondType': 'JSON',
|
|
312
|
-
'TimeStamp': str(int(datetime.now().timestamp())),
|
|
313
|
-
'Version': self.version,
|
|
314
|
-
'MerchantOrderNo': data.merchant_order_no,
|
|
315
|
-
'Amt': data.amt,
|
|
316
|
-
'ItemDesc': data.item_desc,
|
|
317
|
-
'Email': data.email,
|
|
318
|
-
'ReturnURL': data.return_url,
|
|
319
|
-
'LoginType': data.login_type,
|
|
320
|
-
'TradeLimit': data.trade_limit,
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
# 支付方式啟用旗標 (與 Newebpay 共用,但 ezPay 多數方案不支援分期)
|
|
324
|
-
if data.enable_credit:
|
|
325
|
-
params['CREDIT'] = 1
|
|
326
|
-
if data.enable_credit_installment:
|
|
327
|
-
# ezPay 多數方案不支援;需先在後台啟用
|
|
328
|
-
params['InstFlag'] = data.installment_periods or '3,6,12'
|
|
329
|
-
if data.enable_unionpay:
|
|
330
|
-
params['UNIONPAY'] = 1
|
|
331
|
-
if data.enable_webatm:
|
|
332
|
-
params['WEBATM'] = 1
|
|
333
|
-
if data.enable_vacc:
|
|
334
|
-
params['VACC'] = 1
|
|
335
|
-
if data.enable_cvs:
|
|
336
|
-
params['CVS'] = 1
|
|
337
|
-
if data.enable_barcode:
|
|
338
|
-
params['BARCODE'] = 1
|
|
339
|
-
if data.enable_linepay:
|
|
340
|
-
params['LINEPAY'] = 1
|
|
341
|
-
if data.enable_applepay:
|
|
342
|
-
params['APPLEPAY'] = 1
|
|
343
|
-
if data.enable_androidpay:
|
|
344
|
-
params['ANDROIDPAY'] = 1
|
|
345
|
-
if data.enable_twqr:
|
|
346
|
-
params['TWQR'] = 1 # ezPay 主打方式之一
|
|
347
|
-
if data.enable_esunwallet:
|
|
348
|
-
params['ESUNWALLET'] = 1
|
|
349
|
-
if data.enable_taiwanpay:
|
|
350
|
-
params['TAIWANPAY'] = 1
|
|
351
|
-
|
|
352
|
-
if data.notify_url:
|
|
353
|
-
params['NotifyURL'] = data.notify_url
|
|
354
|
-
if data.client_back_url:
|
|
355
|
-
params['ClientBackURL'] = data.client_back_url
|
|
356
|
-
if data.order_comment:
|
|
357
|
-
params['OrderComment'] = data.order_comment
|
|
358
|
-
if data.expire_date:
|
|
359
|
-
params['ExpireDate'] = data.expire_date
|
|
360
|
-
|
|
361
|
-
trade_info = self.encrypt_trade_info(params)
|
|
362
|
-
trade_sha = self.generate_trade_sha(trade_info)
|
|
363
|
-
|
|
364
|
-
return EzPayMPGResponse(
|
|
365
|
-
success=True,
|
|
366
|
-
merchant_order_no=data.merchant_order_no,
|
|
367
|
-
form_action=self.api_url,
|
|
368
|
-
trade_info=trade_info,
|
|
369
|
-
trade_sha=trade_sha,
|
|
370
|
-
merchant_id=self.merchant_id,
|
|
371
|
-
version=self.version,
|
|
372
|
-
raw={
|
|
373
|
-
'MerchantID': self.merchant_id,
|
|
374
|
-
'TradeInfo': trade_info,
|
|
375
|
-
'TradeSha': trade_sha,
|
|
376
|
-
'Version': self.version,
|
|
377
|
-
},
|
|
378
|
-
)
|
|
379
|
-
|
|
380
|
-
def verify_notification(self, callback_data: Dict[str, str]) -> EzPayMPGCallback:
|
|
381
|
-
"""
|
|
382
|
-
驗證並解析 ezPay NotifyURL / ReturnURL POST 進來的資料
|
|
383
|
-
|
|
384
|
-
步驟:
|
|
385
|
-
1. 比對 TradeSha
|
|
386
|
-
2. AES 解密 TradeInfo -> { Status, Message, Result }
|
|
387
|
-
3. Result 為 JSON 字串,解析後再驗 CheckCode (防金額竄改)
|
|
388
|
-
"""
|
|
389
|
-
trade_info = callback_data.get('TradeInfo', '')
|
|
390
|
-
trade_sha = callback_data.get('TradeSha', '')
|
|
391
|
-
|
|
392
|
-
if not self.verify_trade_sha(trade_info, trade_sha):
|
|
393
|
-
raise ValueError('TradeSha 驗證失敗')
|
|
394
|
-
|
|
395
|
-
decrypted = self.decrypt_trade_info(trade_info)
|
|
396
|
-
result_field = decrypted.get('Result', '{}')
|
|
397
|
-
try:
|
|
398
|
-
result = json.loads(result_field) if isinstance(result_field, str) else result_field
|
|
399
|
-
except json.JSONDecodeError:
|
|
400
|
-
result = {}
|
|
401
|
-
|
|
402
|
-
# 驗 CheckCode (僅成功訂單才會帶)
|
|
403
|
-
check_code_valid = False
|
|
404
|
-
received_check_code = result.get('CheckCode', '')
|
|
405
|
-
if received_check_code and result.get('TradeNo'):
|
|
406
|
-
expected = self.generate_check_code(
|
|
407
|
-
amt=result.get('Amt', 0),
|
|
408
|
-
merchant_id=result.get('MerchantID', ''),
|
|
409
|
-
merchant_order_no=result.get('MerchantOrderNo', ''),
|
|
410
|
-
trade_no=result.get('TradeNo', ''),
|
|
411
|
-
)
|
|
412
|
-
check_code_valid = expected == received_check_code.upper()
|
|
413
|
-
|
|
414
|
-
return EzPayMPGCallback(
|
|
415
|
-
status=decrypted.get('Status', ''),
|
|
416
|
-
message=decrypted.get('Message', ''),
|
|
417
|
-
merchant_order_no=result.get('MerchantOrderNo', ''),
|
|
418
|
-
amt=int(result.get('Amt', 0)),
|
|
419
|
-
trade_no=result.get('TradeNo', ''),
|
|
420
|
-
merchant_id=result.get('MerchantID', ''),
|
|
421
|
-
payment_type=result.get('PaymentType', ''),
|
|
422
|
-
pay_time=result.get('PayTime', ''),
|
|
423
|
-
ip=result.get('IP', ''),
|
|
424
|
-
check_code_valid=check_code_valid,
|
|
425
|
-
code_no=result.get('CodeNo'),
|
|
426
|
-
barcode_1=result.get('Barcode_1'),
|
|
427
|
-
barcode_2=result.get('Barcode_2'),
|
|
428
|
-
barcode_3=result.get('Barcode_3'),
|
|
429
|
-
expire_date=result.get('ExpireDate'),
|
|
430
|
-
raw=decrypted,
|
|
431
|
-
)
|
|
432
|
-
|
|
433
|
-
# ------------------------------------------------------------------
|
|
434
|
-
# Order query POST /API/QueryTradeInfo
|
|
435
|
-
# ------------------------------------------------------------------
|
|
436
|
-
|
|
437
|
-
def query_order(self, merchant_order_no: str, amt: int) -> EzPayQueryResult:
|
|
438
|
-
"""
|
|
439
|
-
訂單查詢 (走 CheckValue 而非 TradeInfo)
|
|
440
|
-
|
|
441
|
-
CheckValue = SHA256("IV=xxx&Amt=...&MerchantID=...&MerchantOrderNo=...&Key=xxx").upper()
|
|
442
|
-
"""
|
|
443
|
-
if not HAS_REQUESTS:
|
|
444
|
-
raise ImportError('需要安裝 requests: pip install requests')
|
|
445
|
-
|
|
446
|
-
param_str = (
|
|
447
|
-
f'Amt={amt}&MerchantID={self.merchant_id}'
|
|
448
|
-
f'&MerchantOrderNo={merchant_order_no}'
|
|
449
|
-
)
|
|
450
|
-
raw = (
|
|
451
|
-
f'IV={self.hash_iv.decode("utf-8")}'
|
|
452
|
-
f'&{param_str}'
|
|
453
|
-
f'&Key={self.hash_key.decode("utf-8")}'
|
|
454
|
-
)
|
|
455
|
-
check_value = hashlib.sha256(raw.encode('utf-8')).hexdigest().upper()
|
|
456
|
-
|
|
457
|
-
body = {
|
|
458
|
-
'MerchantID': self.merchant_id,
|
|
459
|
-
'Version': '1.3',
|
|
460
|
-
'RespondType': 'JSON',
|
|
461
|
-
'CheckValue': check_value,
|
|
462
|
-
'TimeStamp': str(int(datetime.now().timestamp())),
|
|
463
|
-
'MerchantOrderNo': merchant_order_no,
|
|
464
|
-
'Amt': amt,
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
resp = requests.post(self.query_url, data=body, timeout=self.timeout)
|
|
468
|
-
resp.raise_for_status()
|
|
469
|
-
try:
|
|
470
|
-
data = resp.json()
|
|
471
|
-
except ValueError:
|
|
472
|
-
data = {'raw': resp.text}
|
|
473
|
-
|
|
474
|
-
result = data.get('Result', {}) if isinstance(data.get('Result'), dict) else {}
|
|
475
|
-
return EzPayQueryResult(
|
|
476
|
-
success=(data.get('Status') == 'SUCCESS'),
|
|
477
|
-
trade_status=str(result.get('TradeStatus', '')),
|
|
478
|
-
payment_type=result.get('PaymentType', ''),
|
|
479
|
-
amt=int(result.get('Amt', 0)),
|
|
480
|
-
trade_no=result.get('TradeNo', ''),
|
|
481
|
-
merchant_order_no=result.get('MerchantOrderNo', ''),
|
|
482
|
-
create_time=result.get('CreateTime', ''),
|
|
483
|
-
pay_time=result.get('PayTime', ''),
|
|
484
|
-
raw=data,
|
|
485
|
-
)
|
|
486
|
-
|
|
487
|
-
# ------------------------------------------------------------------
|
|
488
|
-
# Credit card refund / capture POST /API/CreditCard/Close
|
|
489
|
-
# ------------------------------------------------------------------
|
|
490
|
-
|
|
491
|
-
def refund_credit(
|
|
492
|
-
self,
|
|
493
|
-
merchant_order_no: str,
|
|
494
|
-
trade_no: str,
|
|
495
|
-
amt: int,
|
|
496
|
-
close_type: Literal[1, 2] = 2, # 1 請款 / 2 退款
|
|
497
|
-
cancel: bool = False, # True -> 取消請款 / 取消退款
|
|
498
|
-
index_type: Literal[1, 2] = 1, # 1 訂單編號 / 2 交易序號
|
|
499
|
-
) -> EzPayRefundResult:
|
|
500
|
-
"""
|
|
501
|
-
信用卡請款 / 退款 / 取消
|
|
502
|
-
|
|
503
|
-
ezPay 特別注意:
|
|
504
|
-
- 分期付款在 ezPay 通常受限,許多方案不支援
|
|
505
|
-
- 一次付清 / 銀聯卡 支援部分退款
|
|
506
|
-
"""
|
|
507
|
-
if not HAS_REQUESTS:
|
|
508
|
-
raise ImportError('需要安裝 requests: pip install requests')
|
|
509
|
-
|
|
510
|
-
post_data: Dict[str, Any] = {
|
|
511
|
-
'RespondType': 'JSON',
|
|
512
|
-
'Version': '1.1',
|
|
513
|
-
'Amt': amt,
|
|
514
|
-
'MerchantOrderNo': merchant_order_no,
|
|
515
|
-
'TimeStamp': str(int(datetime.now().timestamp())),
|
|
516
|
-
'IndexType': index_type,
|
|
517
|
-
'TradeNo': trade_no,
|
|
518
|
-
'CloseType': close_type,
|
|
519
|
-
}
|
|
520
|
-
if cancel:
|
|
521
|
-
post_data['Cancel'] = 1
|
|
522
|
-
|
|
523
|
-
# PostData_ = AES 加密後 hex
|
|
524
|
-
post_data_encrypted = self.encrypt_trade_info(post_data)
|
|
525
|
-
|
|
526
|
-
body = {
|
|
527
|
-
'MerchantID_': self.merchant_id,
|
|
528
|
-
'PostData_': post_data_encrypted,
|
|
529
|
-
}
|
|
530
|
-
resp = requests.post(self.close_url, data=body, timeout=self.timeout)
|
|
531
|
-
resp.raise_for_status()
|
|
532
|
-
try:
|
|
533
|
-
data = resp.json()
|
|
534
|
-
except ValueError:
|
|
535
|
-
data = {'raw': resp.text}
|
|
536
|
-
|
|
537
|
-
return EzPayRefundResult(
|
|
538
|
-
success=(data.get('Status') == 'SUCCESS'),
|
|
539
|
-
status=data.get('Status', ''),
|
|
540
|
-
message=data.get('Message', ''),
|
|
541
|
-
raw=data,
|
|
542
|
-
)
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
# ----------------------------------------------------------------------------
|
|
546
|
-
# Examples
|
|
547
|
-
# ----------------------------------------------------------------------------
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
def example_create_order(service: EzPayPaymentService) -> None:
|
|
551
|
-
print('[範例 1] 建立 ezPay MPG 整合支付訂單')
|
|
552
|
-
print('-' * 60)
|
|
553
|
-
|
|
554
|
-
order_data = EzPayMPGOrder(
|
|
555
|
-
merchant_order_no=f'EZ{int(time.time())}',
|
|
556
|
-
amt=1500,
|
|
557
|
-
item_desc='ezPay 測試商品 * 1',
|
|
558
|
-
email='buyer@example.com',
|
|
559
|
-
return_url='https://shop.example.com/api/ezpay/return',
|
|
560
|
-
notify_url='https://shop.example.com/api/ezpay/notify',
|
|
561
|
-
client_back_url='https://shop.example.com/cart',
|
|
562
|
-
enable_credit=True,
|
|
563
|
-
enable_vacc=True,
|
|
564
|
-
enable_cvs=True,
|
|
565
|
-
enable_twqr=True, # ezPay 主打 TWQR
|
|
566
|
-
)
|
|
567
|
-
|
|
568
|
-
try:
|
|
569
|
-
result = service.create_order(order_data)
|
|
570
|
-
if result.success:
|
|
571
|
-
print(f' 訂單編號: {result.merchant_order_no}')
|
|
572
|
-
print(f' Form Action: {result.form_action}')
|
|
573
|
-
print(f' Version: {result.version}')
|
|
574
|
-
print(f' TradeInfo: {result.trade_info[:60]}...')
|
|
575
|
-
print(f' TradeSha: {result.trade_sha[:32]}...')
|
|
576
|
-
print()
|
|
577
|
-
print(' 將以下欄位 form POST 至 form_action:')
|
|
578
|
-
for key in ('MerchantID', 'TradeInfo', 'TradeSha', 'Version'):
|
|
579
|
-
value = result.raw.get(key, '')
|
|
580
|
-
preview = value if len(str(value)) < 40 else f'{str(value)[:40]}...'
|
|
581
|
-
print(f' {key}: {preview}')
|
|
582
|
-
except Exception as exc:
|
|
583
|
-
print(f' ✗ 例外: {exc}')
|
|
584
|
-
print()
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
def example_verify_notification(service: EzPayPaymentService) -> None:
|
|
588
|
-
print('[範例 2] 驗證 NotifyURL 通知 (TradeSha + CheckCode)')
|
|
589
|
-
print('-' * 60)
|
|
590
|
-
|
|
591
|
-
# 模擬一筆 ezPay 成功通知 (信用卡)
|
|
592
|
-
result_dict = {
|
|
593
|
-
'Status': 'SUCCESS',
|
|
594
|
-
'Message': '授權成功',
|
|
595
|
-
'MerchantID': service.merchant_id,
|
|
596
|
-
'Amt': 1500,
|
|
597
|
-
'TradeNo': '24050714300012345678',
|
|
598
|
-
'MerchantOrderNo': 'EZ1715000000',
|
|
599
|
-
'PaymentType': 'CREDIT',
|
|
600
|
-
'PayTime': '2026-05-07 14:30:00',
|
|
601
|
-
'IP': '203.0.113.7',
|
|
602
|
-
'EscrowBank': 'KGI',
|
|
603
|
-
}
|
|
604
|
-
# CheckCode 用 service 的 generate_check_code 算出再放回去
|
|
605
|
-
result_dict['CheckCode'] = service.generate_check_code(
|
|
606
|
-
amt=result_dict['Amt'],
|
|
607
|
-
merchant_id=result_dict['MerchantID'],
|
|
608
|
-
merchant_order_no=result_dict['MerchantOrderNo'],
|
|
609
|
-
trade_no=result_dict['TradeNo'],
|
|
610
|
-
)
|
|
611
|
-
|
|
612
|
-
plaintext = {
|
|
613
|
-
'Status': 'SUCCESS',
|
|
614
|
-
'Message': '授權成功',
|
|
615
|
-
'Result': json.dumps(result_dict, ensure_ascii=False),
|
|
616
|
-
}
|
|
617
|
-
trade_info = service.encrypt_trade_info(plaintext)
|
|
618
|
-
trade_sha = service.generate_trade_sha(trade_info)
|
|
619
|
-
|
|
620
|
-
try:
|
|
621
|
-
callback = service.verify_notification(
|
|
622
|
-
{'TradeInfo': trade_info, 'TradeSha': trade_sha}
|
|
623
|
-
)
|
|
624
|
-
print(f' Status: {callback.status}')
|
|
625
|
-
print(f' TradeNo: {callback.trade_no}')
|
|
626
|
-
print(f' MerchantOrder: {callback.merchant_order_no}')
|
|
627
|
-
print(f' Amt: {callback.amt}')
|
|
628
|
-
print(f' PaymentType: {callback.payment_type}')
|
|
629
|
-
print(f' CheckCode 通過: {callback.check_code_valid}')
|
|
630
|
-
except ValueError as exc:
|
|
631
|
-
print(f' ✗ 驗證失敗: {exc}')
|
|
632
|
-
print()
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
def example_query_order(service: EzPayPaymentService) -> None:
|
|
636
|
-
print('[範例 3] 訂單查詢 POST /API/QueryTradeInfo')
|
|
637
|
-
print('-' * 60)
|
|
638
|
-
print(' service.query_order(merchant_order_no="EZ1715000000", amt=1500)')
|
|
639
|
-
print(' -> 回傳 trade_status: 0 未付款 / 1 成功 / 2 失敗 / 3 取消 / 6 退款 / 9 付款中')
|
|
640
|
-
print(' (示範僅展示 API 呼叫;正式呼叫需要實際 sandbox 帳號)')
|
|
641
|
-
print()
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
def example_refund_credit(service: EzPayPaymentService) -> None:
|
|
645
|
-
print('[範例 4] 信用卡退款 POST /API/CreditCard/Close')
|
|
646
|
-
print('-' * 60)
|
|
647
|
-
print(' service.refund_credit(')
|
|
648
|
-
print(' merchant_order_no="EZ1715000000",')
|
|
649
|
-
print(' trade_no="24050714300012345678",')
|
|
650
|
-
print(' amt=1500,')
|
|
651
|
-
print(' close_type=2, # 1 請款 / 2 退款')
|
|
652
|
-
print(' cancel=False, # True 則為取消請款/取消退款')
|
|
653
|
-
print(' )')
|
|
654
|
-
print(' 注意:')
|
|
655
|
-
print(' - 分期付款在 ezPay 多數方案不支援,需後台另行啟用')
|
|
656
|
-
print(' - 一次付清 / 銀聯卡 支援整筆 / 部分退款')
|
|
657
|
-
print()
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
if __name__ == '__main__':
|
|
661
|
-
print('=' * 60)
|
|
662
|
-
print('ezPay 簡單付金流 - Python 範例')
|
|
663
|
-
print('=' * 60)
|
|
664
|
-
print()
|
|
665
|
-
|
|
666
|
-
if not HAS_CRYPTO:
|
|
667
|
-
print('✗ 缺少 pycryptodome,請執行: pip install pycryptodome')
|
|
668
|
-
exit(1)
|
|
669
|
-
|
|
670
|
-
print('[注意] ezPay 不公開共用測試 Merchant,請先至 ezPay 後台申請測試帳號')
|
|
671
|
-
print(' 將以下 MerchantID / HashKey / HashIV 替換為您的測試環境參數')
|
|
672
|
-
print()
|
|
673
|
-
|
|
674
|
-
# ⚠ 測試 / Demo 用:請替換為實際 ezPay 後台核發之 sandbox 參數
|
|
675
|
-
service = EzPayPaymentService(
|
|
676
|
-
merchant_id='YOUR_EZPAY_MERCHANT_ID', # ezPay 商店代號 (通常 EZ 開頭)
|
|
677
|
-
hash_key='YOUR_EZPAY_HASH_KEY_32_CHARACTERS_', # 32 字元
|
|
678
|
-
hash_iv='YOUR_EZPAY_HIV_', # 16 字元
|
|
679
|
-
is_production=False,
|
|
680
|
-
version='2.0', # ezPay 慣用版本
|
|
681
|
-
)
|
|
682
|
-
|
|
683
|
-
example_create_order(service)
|
|
684
|
-
example_verify_notification(service)
|
|
685
|
-
example_query_order(service)
|
|
686
|
-
example_refund_credit(service)
|
|
687
|
-
|
|
688
|
-
print('=' * 60)
|
|
689
|
-
print('範例執行完成')
|
|
690
|
-
print('=' * 60)
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
ezPay 簡單付 Python 完整範例
|
|
4
|
+
|
|
5
|
+
依照 taiwan-payment-skill 最高規範撰寫
|
|
6
|
+
支援: MPG 整合支付 (信用卡、ATM、超商代碼、TWQR、LINE Pay 等)、訂單查詢、退款
|
|
7
|
+
|
|
8
|
+
API 文件: https://www.ezpay.com.tw/info/Service_intro/api_document/member
|
|
9
|
+
參考文件: taiwan-payment/references/ezpay-payment-api.md
|
|
10
|
+
|
|
11
|
+
ezPay 與 Newebpay 關係:
|
|
12
|
+
ezPay 簡單付 為藍新金流 Newebpay 集團小型商家品牌;
|
|
13
|
+
金流 API 完全相同 (TradeInfo AES-256-CBC + TradeSha SHA256),
|
|
14
|
+
主要差異為 MerchantID/HashKey 為 ezPay 獨立簽發、部分付款方式受限
|
|
15
|
+
(例如分期付款、特定電子錢包),且 URL 改用 spgateway / ezpay 域名。
|
|
16
|
+
|
|
17
|
+
URL 差異:
|
|
18
|
+
Newebpay 沙箱: https://ccore.newebpay.com/MPG/mpg_gateway
|
|
19
|
+
Newebpay 正式: https://core.newebpay.com/MPG/mpg_gateway
|
|
20
|
+
ezPay 沙箱: https://ccore.spgateway.com/MPG/mpg_gateway (本範例採用)
|
|
21
|
+
ezPay 正式: https://core.spgateway.com/MPG/mpg_gateway
|
|
22
|
+
|
|
23
|
+
版本差異:
|
|
24
|
+
Newebpay 主推 Version=2.3 (含 GCM 加密選項)
|
|
25
|
+
ezPay 老商家多數仍維持 Version=2.0 (本範例預設 2.0)
|
|
26
|
+
|
|
27
|
+
依賴:
|
|
28
|
+
pip install pycryptodome requests
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
import hashlib
|
|
32
|
+
import json
|
|
33
|
+
import time
|
|
34
|
+
import urllib.parse
|
|
35
|
+
from dataclasses import dataclass, field
|
|
36
|
+
from datetime import datetime
|
|
37
|
+
from typing import Any, Dict, Literal, Optional
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
from Crypto.Cipher import AES
|
|
41
|
+
from Crypto.Util.Padding import pad, unpad
|
|
42
|
+
HAS_CRYPTO = True
|
|
43
|
+
except ImportError:
|
|
44
|
+
HAS_CRYPTO = False
|
|
45
|
+
|
|
46
|
+
try:
|
|
47
|
+
import requests
|
|
48
|
+
HAS_REQUESTS = True
|
|
49
|
+
except ImportError:
|
|
50
|
+
HAS_REQUESTS = False
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ----------------------------------------------------------------------------
|
|
54
|
+
# Dataclasses
|
|
55
|
+
# ----------------------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class EzPayMPGOrder:
|
|
60
|
+
"""
|
|
61
|
+
ezPay MPG 付款訂單資料 (送進 mpg_gateway 加密前)
|
|
62
|
+
|
|
63
|
+
對應 Newebpay TradeInfo 內含欄位;ezPay 強制 Email 必填。
|
|
64
|
+
"""
|
|
65
|
+
merchant_order_no: str # MerchantOrderNo (<=30,唯一)
|
|
66
|
+
amt: int # Amt (TWD 整數)
|
|
67
|
+
item_desc: str # ItemDesc (<=50)
|
|
68
|
+
email: str # Email (ezPay 強制必填)
|
|
69
|
+
return_url: str # ReturnURL 付款完成前景轉跳
|
|
70
|
+
notify_url: Optional[str] = None
|
|
71
|
+
client_back_url: Optional[str] = None
|
|
72
|
+
enable_credit: bool = True
|
|
73
|
+
enable_credit_installment: bool = False
|
|
74
|
+
installment_periods: Optional[str] = None # InstFlag, e.g. "3,6,12"
|
|
75
|
+
enable_unionpay: bool = False
|
|
76
|
+
enable_webatm: bool = False
|
|
77
|
+
enable_vacc: bool = False
|
|
78
|
+
enable_cvs: bool = False
|
|
79
|
+
enable_barcode: bool = False
|
|
80
|
+
enable_linepay: bool = False
|
|
81
|
+
enable_applepay: bool = False
|
|
82
|
+
enable_androidpay: bool = False
|
|
83
|
+
enable_twqr: bool = False
|
|
84
|
+
enable_esunwallet: bool = False
|
|
85
|
+
enable_taiwanpay: bool = False
|
|
86
|
+
login_type: int = 0
|
|
87
|
+
order_comment: Optional[str] = None
|
|
88
|
+
trade_limit: int = 900
|
|
89
|
+
expire_date: Optional[str] = None # ATM/CVS 繳費期限 Ymd
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class EzPayMPGResponse:
|
|
94
|
+
"""ezPay MPG 訂單建立回應 (供前端 form POST)"""
|
|
95
|
+
success: bool
|
|
96
|
+
merchant_order_no: str
|
|
97
|
+
form_action: str = ''
|
|
98
|
+
trade_info: str = ''
|
|
99
|
+
trade_sha: str = ''
|
|
100
|
+
merchant_id: str = ''
|
|
101
|
+
version: str = ''
|
|
102
|
+
error_message: str = ''
|
|
103
|
+
raw: Dict[str, str] = field(default_factory=dict)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass
|
|
107
|
+
class EzPayMPGCallback:
|
|
108
|
+
"""ezPay MPG NotifyURL / ReturnURL 解密後資料"""
|
|
109
|
+
status: str # SUCCESS / 失敗碼
|
|
110
|
+
message: str
|
|
111
|
+
merchant_order_no: str
|
|
112
|
+
amt: int
|
|
113
|
+
trade_no: str
|
|
114
|
+
merchant_id: str
|
|
115
|
+
payment_type: str
|
|
116
|
+
pay_time: str
|
|
117
|
+
ip: str
|
|
118
|
+
check_code_valid: bool = False # CheckCode 是否通過
|
|
119
|
+
code_no: Optional[str] = None
|
|
120
|
+
barcode_1: Optional[str] = None
|
|
121
|
+
barcode_2: Optional[str] = None
|
|
122
|
+
barcode_3: Optional[str] = None
|
|
123
|
+
expire_date: Optional[str] = None
|
|
124
|
+
raw: Dict[str, Any] = field(default_factory=dict)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass
|
|
128
|
+
class EzPayQueryResult:
|
|
129
|
+
"""訂單查詢結果 (POST /API/QueryTradeInfo)"""
|
|
130
|
+
success: bool
|
|
131
|
+
trade_status: str # 0/1/2/3/6/9
|
|
132
|
+
payment_type: str = ''
|
|
133
|
+
amt: int = 0
|
|
134
|
+
trade_no: str = ''
|
|
135
|
+
merchant_order_no: str = ''
|
|
136
|
+
create_time: str = ''
|
|
137
|
+
pay_time: str = ''
|
|
138
|
+
raw: Dict[str, Any] = field(default_factory=dict)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass
|
|
142
|
+
class EzPayRefundResult:
|
|
143
|
+
"""信用卡請款 / 退款結果 (POST /API/CreditCard/Close)"""
|
|
144
|
+
success: bool
|
|
145
|
+
status: str # SUCCESS / 失敗碼
|
|
146
|
+
message: str = ''
|
|
147
|
+
raw: Dict[str, Any] = field(default_factory=dict)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# ----------------------------------------------------------------------------
|
|
151
|
+
# Service
|
|
152
|
+
# ----------------------------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class EzPayPaymentService:
|
|
156
|
+
"""
|
|
157
|
+
ezPay 簡單付金流服務
|
|
158
|
+
|
|
159
|
+
認證方式: AES-256-CBC + SHA256 (與 Newebpay 完全相同)
|
|
160
|
+
加密欄位:
|
|
161
|
+
TradeInfo = AES-256-CBC(query_string(params), key=HashKey, iv=HashIV).hex()
|
|
162
|
+
TradeSha = SHA256("HashKey={HashKey}&{TradeInfo}&HashIV={HashIV}").upper()
|
|
163
|
+
CheckCode = SHA256("HashIV={IV}&Amt&MerchantID&MerchantOrderNo&TradeNo&HashKey={Key}").upper()
|
|
164
|
+
(key 順序: Amt -> MerchantID -> MerchantOrderNo -> TradeNo)
|
|
165
|
+
|
|
166
|
+
支援付款方式 (依商家方案啟用):
|
|
167
|
+
CREDIT / InstFlag / UNIONPAY / APPLEPAY / ANDROIDPAY / WEBATM / VACC /
|
|
168
|
+
CVS / BARCODE / LINEPAY / ESUNWALLET / TAIWANPAY / TWQR ...
|
|
169
|
+
|
|
170
|
+
測試環境:
|
|
171
|
+
商店代號 / HashKey / HashIV 需自行於 ezPay 後台申請;
|
|
172
|
+
ezPay 不公開共用測試 Merchant。
|
|
173
|
+
測試卡號: 4000-2211-1111-1111
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
# 沙箱 / 正式環境 (採 spgateway 域名;ezpay.com.tw 域名亦可)
|
|
177
|
+
TEST_API_URL = 'https://ccore.spgateway.com/MPG/mpg_gateway'
|
|
178
|
+
TEST_QUERY_URL = 'https://ccore.spgateway.com/API/QueryTradeInfo'
|
|
179
|
+
TEST_CLOSE_URL = 'https://ccore.spgateway.com/API/CreditCard/Close'
|
|
180
|
+
TEST_EWALLET_REFUND_URL = 'https://ccore.spgateway.com/API/EWallet/refund'
|
|
181
|
+
|
|
182
|
+
PROD_API_URL = 'https://core.spgateway.com/MPG/mpg_gateway'
|
|
183
|
+
PROD_QUERY_URL = 'https://core.spgateway.com/API/QueryTradeInfo'
|
|
184
|
+
PROD_CLOSE_URL = 'https://core.spgateway.com/API/CreditCard/Close'
|
|
185
|
+
PROD_EWALLET_REFUND_URL = 'https://core.spgateway.com/API/EWallet/refund'
|
|
186
|
+
|
|
187
|
+
# ezPay 慣用版本 (Newebpay 主推 2.3,ezPay 多數老商家仍 2.0)
|
|
188
|
+
DEFAULT_VERSION = '2.0'
|
|
189
|
+
|
|
190
|
+
def __init__(
|
|
191
|
+
self,
|
|
192
|
+
merchant_id: str,
|
|
193
|
+
hash_key: str,
|
|
194
|
+
hash_iv: str,
|
|
195
|
+
is_production: bool = False,
|
|
196
|
+
version: Optional[str] = None,
|
|
197
|
+
timeout: int = 30,
|
|
198
|
+
):
|
|
199
|
+
"""
|
|
200
|
+
初始化 ezPay 金流服務
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
merchant_id: ezPay 商店代號 (通常以 EZ 系列前綴開頭)
|
|
204
|
+
hash_key: 32 字元 HashKey
|
|
205
|
+
hash_iv: 16 字元 HashIV
|
|
206
|
+
is_production: 是否為正式環境 (預設 False)
|
|
207
|
+
version: 串接版本 (預設 2.0);可改 2.3 對齊 Newebpay
|
|
208
|
+
"""
|
|
209
|
+
if not HAS_CRYPTO:
|
|
210
|
+
raise ImportError('需要安裝 pycryptodome: pip install pycryptodome')
|
|
211
|
+
|
|
212
|
+
self.merchant_id = merchant_id
|
|
213
|
+
self.hash_key = hash_key.encode('utf-8')
|
|
214
|
+
self.hash_iv = hash_iv.encode('utf-8')
|
|
215
|
+
self.version = version or self.DEFAULT_VERSION
|
|
216
|
+
|
|
217
|
+
if is_production:
|
|
218
|
+
self.api_url = self.PROD_API_URL
|
|
219
|
+
self.query_url = self.PROD_QUERY_URL
|
|
220
|
+
self.close_url = self.PROD_CLOSE_URL
|
|
221
|
+
self.ewallet_refund_url = self.PROD_EWALLET_REFUND_URL
|
|
222
|
+
else:
|
|
223
|
+
self.api_url = self.TEST_API_URL
|
|
224
|
+
self.query_url = self.TEST_QUERY_URL
|
|
225
|
+
self.close_url = self.TEST_CLOSE_URL
|
|
226
|
+
self.ewallet_refund_url = self.TEST_EWALLET_REFUND_URL
|
|
227
|
+
|
|
228
|
+
self.timeout = timeout
|
|
229
|
+
|
|
230
|
+
# ------------------------------------------------------------------
|
|
231
|
+
# Encryption helpers (與 Newebpay 共用實作)
|
|
232
|
+
# ------------------------------------------------------------------
|
|
233
|
+
|
|
234
|
+
def encrypt_trade_info(self, data: Dict[str, Any]) -> str:
|
|
235
|
+
"""AES-256-CBC + PKCS#7 padding -> hex 字串"""
|
|
236
|
+
query_string = urllib.parse.urlencode(data)
|
|
237
|
+
cipher = AES.new(self.hash_key, AES.MODE_CBC, self.hash_iv)
|
|
238
|
+
padded = pad(query_string.encode('utf-8'), AES.block_size)
|
|
239
|
+
return cipher.encrypt(padded).hex()
|
|
240
|
+
|
|
241
|
+
def decrypt_trade_info(self, encrypted_data: str) -> Dict[str, Any]:
|
|
242
|
+
"""AES-256-CBC 解密 -> dict"""
|
|
243
|
+
try:
|
|
244
|
+
encrypted_bytes = bytes.fromhex(encrypted_data)
|
|
245
|
+
cipher = AES.new(self.hash_key, AES.MODE_CBC, self.hash_iv)
|
|
246
|
+
decrypted = unpad(cipher.decrypt(encrypted_bytes), AES.block_size)
|
|
247
|
+
params = urllib.parse.parse_qs(decrypted.decode('utf-8'))
|
|
248
|
+
return {k: v[0] if len(v) == 1 else v for k, v in params.items()}
|
|
249
|
+
except Exception as exc:
|
|
250
|
+
raise ValueError(f'TradeInfo 解密失敗: {exc}')
|
|
251
|
+
|
|
252
|
+
def generate_trade_sha(self, trade_info: str) -> str:
|
|
253
|
+
"""TradeSha = SHA256("HashKey=...&TradeInfo&HashIV=...").upper()"""
|
|
254
|
+
raw = (
|
|
255
|
+
f'HashKey={self.hash_key.decode("utf-8")}'
|
|
256
|
+
f'&{trade_info}'
|
|
257
|
+
f'&HashIV={self.hash_iv.decode("utf-8")}'
|
|
258
|
+
)
|
|
259
|
+
return hashlib.sha256(raw.encode('utf-8')).hexdigest().upper()
|
|
260
|
+
|
|
261
|
+
def verify_trade_sha(self, trade_info: str, trade_sha: str) -> bool:
|
|
262
|
+
return self.generate_trade_sha(trade_info) == trade_sha.upper()
|
|
263
|
+
|
|
264
|
+
def generate_check_code(
|
|
265
|
+
self,
|
|
266
|
+
amt: int | str,
|
|
267
|
+
merchant_id: str,
|
|
268
|
+
merchant_order_no: str,
|
|
269
|
+
trade_no: str,
|
|
270
|
+
) -> str:
|
|
271
|
+
"""
|
|
272
|
+
CheckCode (防金額竄改) - 使用「HashIV=...&[排序後 querystring]&HashKey=...」格式
|
|
273
|
+
|
|
274
|
+
欄位順序固定為 Amt -> MerchantID -> MerchantOrderNo -> TradeNo (字典序)
|
|
275
|
+
"""
|
|
276
|
+
check_params = {
|
|
277
|
+
'Amt': amt,
|
|
278
|
+
'MerchantID': merchant_id,
|
|
279
|
+
'MerchantOrderNo': merchant_order_no,
|
|
280
|
+
'TradeNo': trade_no,
|
|
281
|
+
}
|
|
282
|
+
ordered = {k: check_params[k] for k in sorted(check_params)}
|
|
283
|
+
param_str = urllib.parse.urlencode(ordered)
|
|
284
|
+
raw = (
|
|
285
|
+
f'HashIV={self.hash_iv.decode("utf-8")}'
|
|
286
|
+
f'&{param_str}'
|
|
287
|
+
f'&HashKey={self.hash_key.decode("utf-8")}'
|
|
288
|
+
)
|
|
289
|
+
return hashlib.sha256(raw.encode('utf-8')).hexdigest().upper()
|
|
290
|
+
|
|
291
|
+
# ------------------------------------------------------------------
|
|
292
|
+
# MPG order
|
|
293
|
+
# ------------------------------------------------------------------
|
|
294
|
+
|
|
295
|
+
def create_order(self, data: EzPayMPGOrder) -> EzPayMPGResponse:
|
|
296
|
+
"""
|
|
297
|
+
建立 ezPay MPG 整合支付訂單
|
|
298
|
+
|
|
299
|
+
Returns:
|
|
300
|
+
EzPayMPGResponse: 含 trade_info / trade_sha,前端以 form POST 至 form_action
|
|
301
|
+
"""
|
|
302
|
+
if data.amt < 1:
|
|
303
|
+
raise ValueError('金額必須大於 0')
|
|
304
|
+
if len(data.merchant_order_no) > 30:
|
|
305
|
+
raise ValueError('訂單編號不可超過 30 字元')
|
|
306
|
+
if not data.email:
|
|
307
|
+
raise ValueError('ezPay 強制需要 Email 欄位')
|
|
308
|
+
|
|
309
|
+
params: Dict[str, Any] = {
|
|
310
|
+
'MerchantID': self.merchant_id,
|
|
311
|
+
'RespondType': 'JSON',
|
|
312
|
+
'TimeStamp': str(int(datetime.now().timestamp())),
|
|
313
|
+
'Version': self.version,
|
|
314
|
+
'MerchantOrderNo': data.merchant_order_no,
|
|
315
|
+
'Amt': data.amt,
|
|
316
|
+
'ItemDesc': data.item_desc,
|
|
317
|
+
'Email': data.email,
|
|
318
|
+
'ReturnURL': data.return_url,
|
|
319
|
+
'LoginType': data.login_type,
|
|
320
|
+
'TradeLimit': data.trade_limit,
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
# 支付方式啟用旗標 (與 Newebpay 共用,但 ezPay 多數方案不支援分期)
|
|
324
|
+
if data.enable_credit:
|
|
325
|
+
params['CREDIT'] = 1
|
|
326
|
+
if data.enable_credit_installment:
|
|
327
|
+
# ezPay 多數方案不支援;需先在後台啟用
|
|
328
|
+
params['InstFlag'] = data.installment_periods or '3,6,12'
|
|
329
|
+
if data.enable_unionpay:
|
|
330
|
+
params['UNIONPAY'] = 1
|
|
331
|
+
if data.enable_webatm:
|
|
332
|
+
params['WEBATM'] = 1
|
|
333
|
+
if data.enable_vacc:
|
|
334
|
+
params['VACC'] = 1
|
|
335
|
+
if data.enable_cvs:
|
|
336
|
+
params['CVS'] = 1
|
|
337
|
+
if data.enable_barcode:
|
|
338
|
+
params['BARCODE'] = 1
|
|
339
|
+
if data.enable_linepay:
|
|
340
|
+
params['LINEPAY'] = 1
|
|
341
|
+
if data.enable_applepay:
|
|
342
|
+
params['APPLEPAY'] = 1
|
|
343
|
+
if data.enable_androidpay:
|
|
344
|
+
params['ANDROIDPAY'] = 1
|
|
345
|
+
if data.enable_twqr:
|
|
346
|
+
params['TWQR'] = 1 # ezPay 主打方式之一
|
|
347
|
+
if data.enable_esunwallet:
|
|
348
|
+
params['ESUNWALLET'] = 1
|
|
349
|
+
if data.enable_taiwanpay:
|
|
350
|
+
params['TAIWANPAY'] = 1
|
|
351
|
+
|
|
352
|
+
if data.notify_url:
|
|
353
|
+
params['NotifyURL'] = data.notify_url
|
|
354
|
+
if data.client_back_url:
|
|
355
|
+
params['ClientBackURL'] = data.client_back_url
|
|
356
|
+
if data.order_comment:
|
|
357
|
+
params['OrderComment'] = data.order_comment
|
|
358
|
+
if data.expire_date:
|
|
359
|
+
params['ExpireDate'] = data.expire_date
|
|
360
|
+
|
|
361
|
+
trade_info = self.encrypt_trade_info(params)
|
|
362
|
+
trade_sha = self.generate_trade_sha(trade_info)
|
|
363
|
+
|
|
364
|
+
return EzPayMPGResponse(
|
|
365
|
+
success=True,
|
|
366
|
+
merchant_order_no=data.merchant_order_no,
|
|
367
|
+
form_action=self.api_url,
|
|
368
|
+
trade_info=trade_info,
|
|
369
|
+
trade_sha=trade_sha,
|
|
370
|
+
merchant_id=self.merchant_id,
|
|
371
|
+
version=self.version,
|
|
372
|
+
raw={
|
|
373
|
+
'MerchantID': self.merchant_id,
|
|
374
|
+
'TradeInfo': trade_info,
|
|
375
|
+
'TradeSha': trade_sha,
|
|
376
|
+
'Version': self.version,
|
|
377
|
+
},
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
def verify_notification(self, callback_data: Dict[str, str]) -> EzPayMPGCallback:
|
|
381
|
+
"""
|
|
382
|
+
驗證並解析 ezPay NotifyURL / ReturnURL POST 進來的資料
|
|
383
|
+
|
|
384
|
+
步驟:
|
|
385
|
+
1. 比對 TradeSha
|
|
386
|
+
2. AES 解密 TradeInfo -> { Status, Message, Result }
|
|
387
|
+
3. Result 為 JSON 字串,解析後再驗 CheckCode (防金額竄改)
|
|
388
|
+
"""
|
|
389
|
+
trade_info = callback_data.get('TradeInfo', '')
|
|
390
|
+
trade_sha = callback_data.get('TradeSha', '')
|
|
391
|
+
|
|
392
|
+
if not self.verify_trade_sha(trade_info, trade_sha):
|
|
393
|
+
raise ValueError('TradeSha 驗證失敗')
|
|
394
|
+
|
|
395
|
+
decrypted = self.decrypt_trade_info(trade_info)
|
|
396
|
+
result_field = decrypted.get('Result', '{}')
|
|
397
|
+
try:
|
|
398
|
+
result = json.loads(result_field) if isinstance(result_field, str) else result_field
|
|
399
|
+
except json.JSONDecodeError:
|
|
400
|
+
result = {}
|
|
401
|
+
|
|
402
|
+
# 驗 CheckCode (僅成功訂單才會帶)
|
|
403
|
+
check_code_valid = False
|
|
404
|
+
received_check_code = result.get('CheckCode', '')
|
|
405
|
+
if received_check_code and result.get('TradeNo'):
|
|
406
|
+
expected = self.generate_check_code(
|
|
407
|
+
amt=result.get('Amt', 0),
|
|
408
|
+
merchant_id=result.get('MerchantID', ''),
|
|
409
|
+
merchant_order_no=result.get('MerchantOrderNo', ''),
|
|
410
|
+
trade_no=result.get('TradeNo', ''),
|
|
411
|
+
)
|
|
412
|
+
check_code_valid = expected == received_check_code.upper()
|
|
413
|
+
|
|
414
|
+
return EzPayMPGCallback(
|
|
415
|
+
status=decrypted.get('Status', ''),
|
|
416
|
+
message=decrypted.get('Message', ''),
|
|
417
|
+
merchant_order_no=result.get('MerchantOrderNo', ''),
|
|
418
|
+
amt=int(result.get('Amt', 0)),
|
|
419
|
+
trade_no=result.get('TradeNo', ''),
|
|
420
|
+
merchant_id=result.get('MerchantID', ''),
|
|
421
|
+
payment_type=result.get('PaymentType', ''),
|
|
422
|
+
pay_time=result.get('PayTime', ''),
|
|
423
|
+
ip=result.get('IP', ''),
|
|
424
|
+
check_code_valid=check_code_valid,
|
|
425
|
+
code_no=result.get('CodeNo'),
|
|
426
|
+
barcode_1=result.get('Barcode_1'),
|
|
427
|
+
barcode_2=result.get('Barcode_2'),
|
|
428
|
+
barcode_3=result.get('Barcode_3'),
|
|
429
|
+
expire_date=result.get('ExpireDate'),
|
|
430
|
+
raw=decrypted,
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
# ------------------------------------------------------------------
|
|
434
|
+
# Order query POST /API/QueryTradeInfo
|
|
435
|
+
# ------------------------------------------------------------------
|
|
436
|
+
|
|
437
|
+
def query_order(self, merchant_order_no: str, amt: int) -> EzPayQueryResult:
|
|
438
|
+
"""
|
|
439
|
+
訂單查詢 (走 CheckValue 而非 TradeInfo)
|
|
440
|
+
|
|
441
|
+
CheckValue = SHA256("IV=xxx&Amt=...&MerchantID=...&MerchantOrderNo=...&Key=xxx").upper()
|
|
442
|
+
"""
|
|
443
|
+
if not HAS_REQUESTS:
|
|
444
|
+
raise ImportError('需要安裝 requests: pip install requests')
|
|
445
|
+
|
|
446
|
+
param_str = (
|
|
447
|
+
f'Amt={amt}&MerchantID={self.merchant_id}'
|
|
448
|
+
f'&MerchantOrderNo={merchant_order_no}'
|
|
449
|
+
)
|
|
450
|
+
raw = (
|
|
451
|
+
f'IV={self.hash_iv.decode("utf-8")}'
|
|
452
|
+
f'&{param_str}'
|
|
453
|
+
f'&Key={self.hash_key.decode("utf-8")}'
|
|
454
|
+
)
|
|
455
|
+
check_value = hashlib.sha256(raw.encode('utf-8')).hexdigest().upper()
|
|
456
|
+
|
|
457
|
+
body = {
|
|
458
|
+
'MerchantID': self.merchant_id,
|
|
459
|
+
'Version': '1.3',
|
|
460
|
+
'RespondType': 'JSON',
|
|
461
|
+
'CheckValue': check_value,
|
|
462
|
+
'TimeStamp': str(int(datetime.now().timestamp())),
|
|
463
|
+
'MerchantOrderNo': merchant_order_no,
|
|
464
|
+
'Amt': amt,
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
resp = requests.post(self.query_url, data=body, timeout=self.timeout)
|
|
468
|
+
resp.raise_for_status()
|
|
469
|
+
try:
|
|
470
|
+
data = resp.json()
|
|
471
|
+
except ValueError:
|
|
472
|
+
data = {'raw': resp.text}
|
|
473
|
+
|
|
474
|
+
result = data.get('Result', {}) if isinstance(data.get('Result'), dict) else {}
|
|
475
|
+
return EzPayQueryResult(
|
|
476
|
+
success=(data.get('Status') == 'SUCCESS'),
|
|
477
|
+
trade_status=str(result.get('TradeStatus', '')),
|
|
478
|
+
payment_type=result.get('PaymentType', ''),
|
|
479
|
+
amt=int(result.get('Amt', 0)),
|
|
480
|
+
trade_no=result.get('TradeNo', ''),
|
|
481
|
+
merchant_order_no=result.get('MerchantOrderNo', ''),
|
|
482
|
+
create_time=result.get('CreateTime', ''),
|
|
483
|
+
pay_time=result.get('PayTime', ''),
|
|
484
|
+
raw=data,
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
# ------------------------------------------------------------------
|
|
488
|
+
# Credit card refund / capture POST /API/CreditCard/Close
|
|
489
|
+
# ------------------------------------------------------------------
|
|
490
|
+
|
|
491
|
+
def refund_credit(
|
|
492
|
+
self,
|
|
493
|
+
merchant_order_no: str,
|
|
494
|
+
trade_no: str,
|
|
495
|
+
amt: int,
|
|
496
|
+
close_type: Literal[1, 2] = 2, # 1 請款 / 2 退款
|
|
497
|
+
cancel: bool = False, # True -> 取消請款 / 取消退款
|
|
498
|
+
index_type: Literal[1, 2] = 1, # 1 訂單編號 / 2 交易序號
|
|
499
|
+
) -> EzPayRefundResult:
|
|
500
|
+
"""
|
|
501
|
+
信用卡請款 / 退款 / 取消
|
|
502
|
+
|
|
503
|
+
ezPay 特別注意:
|
|
504
|
+
- 分期付款在 ezPay 通常受限,許多方案不支援
|
|
505
|
+
- 一次付清 / 銀聯卡 支援部分退款
|
|
506
|
+
"""
|
|
507
|
+
if not HAS_REQUESTS:
|
|
508
|
+
raise ImportError('需要安裝 requests: pip install requests')
|
|
509
|
+
|
|
510
|
+
post_data: Dict[str, Any] = {
|
|
511
|
+
'RespondType': 'JSON',
|
|
512
|
+
'Version': '1.1',
|
|
513
|
+
'Amt': amt,
|
|
514
|
+
'MerchantOrderNo': merchant_order_no,
|
|
515
|
+
'TimeStamp': str(int(datetime.now().timestamp())),
|
|
516
|
+
'IndexType': index_type,
|
|
517
|
+
'TradeNo': trade_no,
|
|
518
|
+
'CloseType': close_type,
|
|
519
|
+
}
|
|
520
|
+
if cancel:
|
|
521
|
+
post_data['Cancel'] = 1
|
|
522
|
+
|
|
523
|
+
# PostData_ = AES 加密後 hex
|
|
524
|
+
post_data_encrypted = self.encrypt_trade_info(post_data)
|
|
525
|
+
|
|
526
|
+
body = {
|
|
527
|
+
'MerchantID_': self.merchant_id,
|
|
528
|
+
'PostData_': post_data_encrypted,
|
|
529
|
+
}
|
|
530
|
+
resp = requests.post(self.close_url, data=body, timeout=self.timeout)
|
|
531
|
+
resp.raise_for_status()
|
|
532
|
+
try:
|
|
533
|
+
data = resp.json()
|
|
534
|
+
except ValueError:
|
|
535
|
+
data = {'raw': resp.text}
|
|
536
|
+
|
|
537
|
+
return EzPayRefundResult(
|
|
538
|
+
success=(data.get('Status') == 'SUCCESS'),
|
|
539
|
+
status=data.get('Status', ''),
|
|
540
|
+
message=data.get('Message', ''),
|
|
541
|
+
raw=data,
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
# ----------------------------------------------------------------------------
|
|
546
|
+
# Examples
|
|
547
|
+
# ----------------------------------------------------------------------------
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def example_create_order(service: EzPayPaymentService) -> None:
|
|
551
|
+
print('[範例 1] 建立 ezPay MPG 整合支付訂單')
|
|
552
|
+
print('-' * 60)
|
|
553
|
+
|
|
554
|
+
order_data = EzPayMPGOrder(
|
|
555
|
+
merchant_order_no=f'EZ{int(time.time())}',
|
|
556
|
+
amt=1500,
|
|
557
|
+
item_desc='ezPay 測試商品 * 1',
|
|
558
|
+
email='buyer@example.com',
|
|
559
|
+
return_url='https://shop.example.com/api/ezpay/return',
|
|
560
|
+
notify_url='https://shop.example.com/api/ezpay/notify',
|
|
561
|
+
client_back_url='https://shop.example.com/cart',
|
|
562
|
+
enable_credit=True,
|
|
563
|
+
enable_vacc=True,
|
|
564
|
+
enable_cvs=True,
|
|
565
|
+
enable_twqr=True, # ezPay 主打 TWQR
|
|
566
|
+
)
|
|
567
|
+
|
|
568
|
+
try:
|
|
569
|
+
result = service.create_order(order_data)
|
|
570
|
+
if result.success:
|
|
571
|
+
print(f' 訂單編號: {result.merchant_order_no}')
|
|
572
|
+
print(f' Form Action: {result.form_action}')
|
|
573
|
+
print(f' Version: {result.version}')
|
|
574
|
+
print(f' TradeInfo: {result.trade_info[:60]}...')
|
|
575
|
+
print(f' TradeSha: {result.trade_sha[:32]}...')
|
|
576
|
+
print()
|
|
577
|
+
print(' 將以下欄位 form POST 至 form_action:')
|
|
578
|
+
for key in ('MerchantID', 'TradeInfo', 'TradeSha', 'Version'):
|
|
579
|
+
value = result.raw.get(key, '')
|
|
580
|
+
preview = value if len(str(value)) < 40 else f'{str(value)[:40]}...'
|
|
581
|
+
print(f' {key}: {preview}')
|
|
582
|
+
except Exception as exc:
|
|
583
|
+
print(f' ✗ 例外: {exc}')
|
|
584
|
+
print()
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def example_verify_notification(service: EzPayPaymentService) -> None:
|
|
588
|
+
print('[範例 2] 驗證 NotifyURL 通知 (TradeSha + CheckCode)')
|
|
589
|
+
print('-' * 60)
|
|
590
|
+
|
|
591
|
+
# 模擬一筆 ezPay 成功通知 (信用卡)
|
|
592
|
+
result_dict = {
|
|
593
|
+
'Status': 'SUCCESS',
|
|
594
|
+
'Message': '授權成功',
|
|
595
|
+
'MerchantID': service.merchant_id,
|
|
596
|
+
'Amt': 1500,
|
|
597
|
+
'TradeNo': '24050714300012345678',
|
|
598
|
+
'MerchantOrderNo': 'EZ1715000000',
|
|
599
|
+
'PaymentType': 'CREDIT',
|
|
600
|
+
'PayTime': '2026-05-07 14:30:00',
|
|
601
|
+
'IP': '203.0.113.7',
|
|
602
|
+
'EscrowBank': 'KGI',
|
|
603
|
+
}
|
|
604
|
+
# CheckCode 用 service 的 generate_check_code 算出再放回去
|
|
605
|
+
result_dict['CheckCode'] = service.generate_check_code(
|
|
606
|
+
amt=result_dict['Amt'],
|
|
607
|
+
merchant_id=result_dict['MerchantID'],
|
|
608
|
+
merchant_order_no=result_dict['MerchantOrderNo'],
|
|
609
|
+
trade_no=result_dict['TradeNo'],
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
plaintext = {
|
|
613
|
+
'Status': 'SUCCESS',
|
|
614
|
+
'Message': '授權成功',
|
|
615
|
+
'Result': json.dumps(result_dict, ensure_ascii=False),
|
|
616
|
+
}
|
|
617
|
+
trade_info = service.encrypt_trade_info(plaintext)
|
|
618
|
+
trade_sha = service.generate_trade_sha(trade_info)
|
|
619
|
+
|
|
620
|
+
try:
|
|
621
|
+
callback = service.verify_notification(
|
|
622
|
+
{'TradeInfo': trade_info, 'TradeSha': trade_sha}
|
|
623
|
+
)
|
|
624
|
+
print(f' Status: {callback.status}')
|
|
625
|
+
print(f' TradeNo: {callback.trade_no}')
|
|
626
|
+
print(f' MerchantOrder: {callback.merchant_order_no}')
|
|
627
|
+
print(f' Amt: {callback.amt}')
|
|
628
|
+
print(f' PaymentType: {callback.payment_type}')
|
|
629
|
+
print(f' CheckCode 通過: {callback.check_code_valid}')
|
|
630
|
+
except ValueError as exc:
|
|
631
|
+
print(f' ✗ 驗證失敗: {exc}')
|
|
632
|
+
print()
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def example_query_order(service: EzPayPaymentService) -> None:
|
|
636
|
+
print('[範例 3] 訂單查詢 POST /API/QueryTradeInfo')
|
|
637
|
+
print('-' * 60)
|
|
638
|
+
print(' service.query_order(merchant_order_no="EZ1715000000", amt=1500)')
|
|
639
|
+
print(' -> 回傳 trade_status: 0 未付款 / 1 成功 / 2 失敗 / 3 取消 / 6 退款 / 9 付款中')
|
|
640
|
+
print(' (示範僅展示 API 呼叫;正式呼叫需要實際 sandbox 帳號)')
|
|
641
|
+
print()
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def example_refund_credit(service: EzPayPaymentService) -> None:
|
|
645
|
+
print('[範例 4] 信用卡退款 POST /API/CreditCard/Close')
|
|
646
|
+
print('-' * 60)
|
|
647
|
+
print(' service.refund_credit(')
|
|
648
|
+
print(' merchant_order_no="EZ1715000000",')
|
|
649
|
+
print(' trade_no="24050714300012345678",')
|
|
650
|
+
print(' amt=1500,')
|
|
651
|
+
print(' close_type=2, # 1 請款 / 2 退款')
|
|
652
|
+
print(' cancel=False, # True 則為取消請款/取消退款')
|
|
653
|
+
print(' )')
|
|
654
|
+
print(' 注意:')
|
|
655
|
+
print(' - 分期付款在 ezPay 多數方案不支援,需後台另行啟用')
|
|
656
|
+
print(' - 一次付清 / 銀聯卡 支援整筆 / 部分退款')
|
|
657
|
+
print()
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
if __name__ == '__main__':
|
|
661
|
+
print('=' * 60)
|
|
662
|
+
print('ezPay 簡單付金流 - Python 範例')
|
|
663
|
+
print('=' * 60)
|
|
664
|
+
print()
|
|
665
|
+
|
|
666
|
+
if not HAS_CRYPTO:
|
|
667
|
+
print('✗ 缺少 pycryptodome,請執行: pip install pycryptodome')
|
|
668
|
+
exit(1)
|
|
669
|
+
|
|
670
|
+
print('[注意] ezPay 不公開共用測試 Merchant,請先至 ezPay 後台申請測試帳號')
|
|
671
|
+
print(' 將以下 MerchantID / HashKey / HashIV 替換為您的測試環境參數')
|
|
672
|
+
print()
|
|
673
|
+
|
|
674
|
+
# ⚠ 測試 / Demo 用:請替換為實際 ezPay 後台核發之 sandbox 參數
|
|
675
|
+
service = EzPayPaymentService(
|
|
676
|
+
merchant_id='YOUR_EZPAY_MERCHANT_ID', # ezPay 商店代號 (通常 EZ 開頭)
|
|
677
|
+
hash_key='YOUR_EZPAY_HASH_KEY_32_CHARACTERS_', # 32 字元
|
|
678
|
+
hash_iv='YOUR_EZPAY_HIV_', # 16 字元
|
|
679
|
+
is_production=False,
|
|
680
|
+
version='2.0', # ezPay 慣用版本
|
|
681
|
+
)
|
|
682
|
+
|
|
683
|
+
example_create_order(service)
|
|
684
|
+
example_verify_notification(service)
|
|
685
|
+
example_query_order(service)
|
|
686
|
+
example_refund_credit(service)
|
|
687
|
+
|
|
688
|
+
print('=' * 60)
|
|
689
|
+
print('範例執行完成')
|
|
690
|
+
print('=' * 60)
|