taiwan-logistics-skill 1.4.0 → 1.4.2

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.
@@ -19,9 +19,10 @@ Supporting NewebPay Logistics, ECPay Logistics, and PAYUNi Logistics with compre
19
19
  - [Track Shipment](#8-track-shipment)
20
20
  - [Status Notification](#9-status-notification-callback)
21
21
 
22
- 2. [ECPay Logistics Examples](#ecpay-logistics-examples)
23
- 3. [Real-World Scenarios](#real-world-scenarios)
24
- 4. [Error Handling](#error-handling)
22
+ 2. [PAYUNi Logistics Examples](#payuni-logistics-examples)
23
+ 3. [ECPay Logistics Examples](#ecpay-logistics-examples)
24
+ 4. [Real-World Scenarios](#real-world-scenarios)
25
+ 5. [Error Handling](#error-handling)
25
26
 
26
27
  ---
27
28
 
@@ -31,6 +32,9 @@ Supporting NewebPay Logistics, ECPay Logistics, and PAYUNi Logistics with compre
31
32
 
32
33
  #### TypeScript - Encryption Helper
33
34
 
35
+ > 由 CI 以規格書 NDNS 附錄的 HashData 範例與藍新官方外掛密文驗證(`scripts/verify-examples.py`)。
36
+
37
+ <!-- verify: newebpay-logistics -->
34
38
  ```typescript
35
39
  import crypto from 'crypto';
36
40
 
@@ -57,71 +61,55 @@ class NewebPayLogistics {
57
61
  }
58
62
 
59
63
  /**
60
- * AES-256-CBC Encryption
64
+ * AES-256-CBC Encryption(標準 PKCS#7)
61
65
  */
62
66
  private aesEncrypt(data: string): string {
63
- const cipher = crypto.createCipheriv(
64
- 'aes-256-cbc',
65
- this.config.hashKey,
66
- this.config.hashIV
67
- );
68
-
69
- let encrypted = cipher.update(data, 'utf8', 'hex');
70
- encrypted += cipher.final('hex');
71
-
72
- return encrypted;
67
+ const cipher = crypto.createCipheriv('aes-256-cbc', this.config.hashKey, this.config.hashIV);
68
+ return cipher.update(data, 'utf8', 'hex') + cipher.final('hex');
73
69
  }
74
70
 
75
71
  /**
76
72
  * AES-256-CBC Decryption
73
+ * 藍新官方外掛以 32 bytes 補齊,padding 可能是 1–32,須手動移除
77
74
  */
78
75
  private aesDecrypt(encryptedData: string): string {
79
- const decipher = crypto.createDecipheriv(
80
- 'aes-256-cbc',
81
- this.config.hashKey,
82
- this.config.hashIV
83
- );
84
-
85
- let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
86
- decrypted += decipher.final('utf8');
87
-
88
- return decrypted;
76
+ const decipher = crypto.createDecipheriv('aes-256-cbc', this.config.hashKey, this.config.hashIV);
77
+ decipher.setAutoPadding(false);
78
+ const raw = Buffer.concat([decipher.update(encryptedData, 'hex'), decipher.final()]);
79
+ const n = raw[raw.length - 1];
80
+ if (n < 1 || n > 32 || !raw.subarray(raw.length - n).every(b => b === n)) {
81
+ throw new Error('padding 錯誤(HashKey / HashIV 可能不正確)');
82
+ }
83
+ return raw.subarray(0, raw.length - n).toString('utf8');
89
84
  }
90
85
 
91
86
  /**
92
- * Generate Hash Data (SHA256)
87
+ * Generate Hash Data(規格書 NDNS 附錄(一))
88
+ * SHA256("HashKey={key}&{EncryptData}&HashIV={iv}") 轉大寫
93
89
  */
94
90
  private generateHashData(encryptData: string): string {
95
- const raw = `${this.config.hashKey}${encryptData}${this.config.hashIV}`;
91
+ const raw = `HashKey=${this.config.hashKey}&${encryptData}&HashIV=${this.config.hashIV}`;
96
92
  return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase();
97
93
  }
98
94
 
99
95
  /**
100
- * Encrypt request data
96
+ * Encrypt request data(送出參數名稱後方有底線)
101
97
  */
102
98
  encryptData(data: Record<string, any>): { EncryptData_: string; HashData_: string } {
103
- const jsonStr = JSON.stringify(data);
104
- const encryptData = this.aesEncrypt(jsonStr);
105
- const hashData = this.generateHashData(encryptData);
106
-
107
- return {
108
- EncryptData_: encryptData,
109
- HashData_: hashData,
110
- };
99
+ const encryptData = this.aesEncrypt(JSON.stringify(data));
100
+ return { EncryptData_: encryptData, HashData_: this.generateHashData(encryptData) };
111
101
  }
112
102
 
113
103
  /**
114
- * Decrypt response data
104
+ * Decrypt response data(API 回應欄位為 EncryptData / HashData,沒有底線)
115
105
  */
116
106
  decryptData(encryptData: string, hashData: string): any {
117
- // Verify hash
118
- const calculatedHash = this.generateHashData(encryptData);
119
- if (calculatedHash !== hashData.toUpperCase()) {
107
+ const expected = Buffer.from(this.generateHashData(encryptData));
108
+ const received = Buffer.from(hashData.toUpperCase());
109
+ if (expected.length !== received.length || !crypto.timingSafeEqual(expected, received)) {
120
110
  throw new Error('Hash verification failed');
121
111
  }
122
-
123
- const decrypted = this.aesDecrypt(encryptData);
124
- return JSON.parse(decrypted);
112
+ return JSON.parse(this.aesDecrypt(encryptData));
125
113
  }
126
114
 
127
115
  /**
@@ -137,15 +125,17 @@ export { NewebPayLogistics };
137
125
 
138
126
  #### Python - Encryption Helper
139
127
 
128
+ <!-- verify: newebpay-logistics -->
140
129
  ```python
141
130
  """NewebPay Logistics Encryption Helper - Python"""
142
131
 
143
132
  import json
144
133
  import hashlib
134
+ import hmac
145
135
  import time
146
- from typing import Dict, Any, Tuple
136
+ from typing import Dict, Any
147
137
  from Crypto.Cipher import AES
148
- from Crypto.Util.Padding import pad, unpad
138
+ from Crypto.Util.Padding import pad
149
139
 
150
140
 
151
141
  class NewebPayLogistics:
@@ -169,44 +159,34 @@ class NewebPayLogistics:
169
159
  )
170
160
 
171
161
  def aes_encrypt(self, data: str) -> str:
172
- """AES-256-CBC Encryption"""
162
+ """AES-256-CBC Encryption(標準 PKCS#7)"""
173
163
  cipher = AES.new(self.hash_key, AES.MODE_CBC, self.hash_iv)
174
- padded_data = pad(data.encode('utf-8'), AES.block_size)
175
- encrypted = cipher.encrypt(padded_data)
176
- return encrypted.hex()
164
+ return cipher.encrypt(pad(data.encode('utf-8'), AES.block_size)).hex()
177
165
 
178
166
  def aes_decrypt(self, encrypted_data: str) -> str:
179
- """AES-256-CBC Decryption"""
167
+ """AES-256-CBC Decryption(padding 可能是 1–32,Crypto.Util.Padding.unpad 無法處理)"""
180
168
  cipher = AES.new(self.hash_key, AES.MODE_CBC, self.hash_iv)
181
- decrypted = cipher.decrypt(bytes.fromhex(encrypted_data))
182
- unpadded = unpad(decrypted, AES.block_size)
183
- return unpadded.decode('utf-8')
169
+ data = cipher.decrypt(bytes.fromhex(encrypted_data))
170
+ n = data[-1]
171
+ if not 1 <= n <= 32 or data[-n:] != bytes([n]) * n:
172
+ raise ValueError('padding 錯誤(HashKey / HashIV 可能不正確)')
173
+ return data[:-n].decode('utf-8')
184
174
 
185
175
  def generate_hash_data(self, encrypt_data: str) -> str:
186
- """Generate Hash Data (SHA256)"""
187
- raw = f"{self.hash_key.decode('utf-8')}{encrypt_data}{self.hash_iv.decode('utf-8')}"
176
+ """HashData = SHA256("HashKey={key}&{EncryptData}&HashIV={iv}") 轉大寫(規格書 NDNS 附錄(一))"""
177
+ raw = f"HashKey={self.hash_key.decode('utf-8')}&{encrypt_data}&HashIV={self.hash_iv.decode('utf-8')}"
188
178
  return hashlib.sha256(raw.encode('utf-8')).hexdigest().upper()
189
179
 
190
180
  def encrypt_data(self, data: Dict[str, Any]) -> Dict[str, str]:
191
- """Encrypt request data"""
192
- json_str = json.dumps(data, ensure_ascii=False)
193
- encrypt_data = self.aes_encrypt(json_str)
194
- hash_data = self.generate_hash_data(encrypt_data)
195
-
196
- return {
197
- 'EncryptData_': encrypt_data,
198
- 'HashData_': hash_data,
199
- }
181
+ """Encrypt request data(送出參數名稱後方有底線)"""
182
+ encrypt_data = self.aes_encrypt(json.dumps(data, ensure_ascii=False))
183
+ return {'EncryptData_': encrypt_data, 'HashData_': self.generate_hash_data(encrypt_data)}
200
184
 
201
185
  def decrypt_data(self, encrypt_data: str, hash_data: str) -> Dict[str, Any]:
202
- """Decrypt response data"""
203
- # Verify hash
204
- calculated_hash = self.generate_hash_data(encrypt_data)
205
- if calculated_hash != hash_data.upper():
186
+ """Decrypt response data(API 回應欄位為 EncryptData / HashData,沒有底線)"""
187
+ if not hmac.compare_digest(self.generate_hash_data(encrypt_data), hash_data.upper()):
206
188
  raise ValueError('Hash verification failed')
207
-
208
- decrypted = self.aes_decrypt(encrypt_data)
209
- return json.loads(decrypted)
189
+ return json.loads(self.aes_decrypt(encrypt_data))
210
190
 
211
191
  @staticmethod
212
192
  def get_timestamp() -> str:
@@ -237,7 +217,11 @@ class NewebPayStoreMap extends NewebPayLogistics {
237
217
  /**
238
218
  * Query store map
239
219
  */
240
- async queryStoreMap(params: StoreMapRequest): Promise<string> {
220
+ /**
221
+ * 產生門市地圖表單:門市地圖是給「消費者瀏覽器」操作的頁面,
222
+ * 必須由前端以表單 POST 過去(伺服器端 axios.post 拿不到可用的選店流程)
223
+ */
224
+ queryStoreMap(params: StoreMapRequest): { action: string; fields: Record<string, string> } {
241
225
  const data = {
242
226
  MerchantOrderNo: params.merchantOrderNo,
243
227
  LgsType: params.lgsType,
@@ -257,23 +241,11 @@ class NewebPayStoreMap extends NewebPayLogistics {
257
241
  RespondType_: 'JSON',
258
242
  };
259
243
 
260
- const response = await axios.post(
261
- `${this.baseUrl}/storeMap`,
262
- new URLSearchParams(requestData as any),
263
- {
264
- headers: {
265
- 'Content-Type': 'application/x-www-form-urlencoded',
266
- },
267
- }
268
- );
269
-
270
- // NewebPay will redirect to store selection page
271
- // Return the redirect URL or HTML
272
- return response.data;
244
+ return { action: `${this.baseUrl}/storeMap`, fields: requestData };
273
245
  }
274
246
 
275
247
  /**
276
- * Handle store map callback
248
+ * Handle store map callback(回傳欄位是 EncryptData / HashData,沒有底線)
277
249
  */
278
250
  handleStoreMapCallback(
279
251
  encryptData: string,
@@ -311,8 +283,8 @@ const logistics = new NewebPayStoreMap({
311
283
  isProduction: false,
312
284
  });
313
285
 
314
- // Open store map
315
- await logistics.queryStoreMap({
286
+ // 產生表單,由前端自動送出
287
+ const form = logistics.queryStoreMap({
316
288
  merchantOrderNo: `ORD${Date.now()}`,
317
289
  lgsType: 'C2C',
318
290
  shipType: '1', // 7-ELEVEN
@@ -328,7 +300,7 @@ export { NewebPayStoreMap };
328
300
  ```python
329
301
  """Store Map Query - Python Example"""
330
302
 
331
- import requests
303
+ import time
332
304
  from typing import Dict, Optional
333
305
 
334
306
 
@@ -342,8 +314,8 @@ class NewebPayStoreMap(NewebPayLogistics):
342
314
  ship_type: str, # '1'=7-11, '2'=FamilyMart, '3'=Hi-Life, '4'=OK Mart
343
315
  return_url: str,
344
316
  extra_data: str = '',
345
- ) -> str:
346
- """Query store map"""
317
+ ) -> Dict[str, object]:
318
+ """產生門市地圖表單(瀏覽器 POST)"""
347
319
 
348
320
  data = {
349
321
  'MerchantOrderNo': merchant_order_no,
@@ -364,12 +336,8 @@ class NewebPayStoreMap(NewebPayLogistics):
364
336
  'RespondType_': 'JSON',
365
337
  }
366
338
 
367
- response = requests.post(
368
- f'{self.base_url}/storeMap',
369
- data=request_data,
370
- )
371
-
372
- return response.text
339
+ # 門市地圖須由消費者瀏覽器以表單 POST,這裡只回傳表單內容
340
+ return {'action': f'{self.base_url}/storeMap', 'fields': request_data}
373
341
 
374
342
  def handle_store_map_callback(
375
343
  self,
@@ -400,8 +368,8 @@ logistics = NewebPayStoreMap(
400
368
  is_production=False,
401
369
  )
402
370
 
403
- # Open store map
404
- html = logistics.query_store_map(
371
+ # 產生表單,由前端自動送出
372
+ form = logistics.query_store_map(
405
373
  merchant_order_no=f'ORD{int(time.time())}',
406
374
  lgs_type='C2C',
407
375
  ship_type='1', # 7-ELEVEN
@@ -861,7 +829,7 @@ class NewebPayQueryShipment extends NewebPayLogistics {
861
829
  storeID: decrypted.StoreID,
862
830
  shipType: decrypted.ShipType,
863
831
  storeName: decrypted.StoreName,
864
- retId: decrypted.Retld,
832
+ retId: decrypted.RetId ?? decrypted.Retld, // NDNS 規格書參數表寫 Retld、標題寫 RetId,兩種都接受
865
833
  retString: decrypted.RetString,
866
834
  };
867
835
  }
@@ -1061,7 +1029,7 @@ class NewebPayTrackShipment(NewebPayLogistics):
1061
1029
  'trade_type': decrypted['TradeType'],
1062
1030
  'ship_type': decrypted['ShipType'],
1063
1031
  'history': decrypted.get('History', []),
1064
- 'ret_id': decrypted.get('Retld', ''),
1032
+ 'ret_id': decrypted.get('RetId') or decrypted.get('Retld', ''), # 規格書兩種拼法並存
1065
1033
  'ret_string': decrypted.get('RetString', ''),
1066
1034
  }
1067
1035
 
@@ -1146,7 +1114,7 @@ app.post('/callback/shipment-status', async (req, res) => {
1146
1114
  lgsNo: data.LgsNo,
1147
1115
  tradeType: data.TradeType,
1148
1116
  shipType: data.ShipType,
1149
- retId: data.Retld,
1117
+ retId: data.RetId ?? data.Retld,
1150
1118
  retString: data.RetString,
1151
1119
  eventTime: data.EventTime,
1152
1120
  });
@@ -1260,7 +1228,7 @@ def process_shipment_status_update(data: Dict[str, any]):
1260
1228
  """Process shipment status update"""
1261
1229
 
1262
1230
  merchant_order_no = data['MerchantOrderNo']
1263
- ret_id = data.get('Retld')
1231
+ ret_id = data.get('RetId') or data.get('Retld') # NDNS 規格書兩種拼法並存
1264
1232
  ret_string = data.get('RetString')
1265
1233
 
1266
1234
  app.logger.info(f'Processing status update for order {merchant_order_no}')
@@ -1299,718 +1267,109 @@ if __name__ == '__main__':
1299
1267
 
1300
1268
  ## PAYUNi Logistics Examples
1301
1269
 
1302
- ### 1. Basic Integration (PAYUNi)
1270
+ > 端點、欄位、代碼依 wpbr-payuni-shipping 1.6.4(正式上架外掛);加解密由 CI 以統一金流官方外掛與
1271
+ > 官方 PHP SDK 產生的標準答案驗證。規格細節見 `references/payuni-logistics-api.md`,
1272
+ > 完整 Python 版見 `examples/payuni-logistics-cvs-example.py`。
1273
+ >
1274
+ > 舊版範例中的 `/logistics/create`、`LogisticsType`、`GoodsAmount`、`Receiver*`、`LogisticsID`
1275
+ > 皆不存在於 PAYUNi 物流 API,請勿沿用。
1303
1276
 
1304
- #### TypeScript - AES-256-GCM Encryption Helper
1277
+ ### 1. Encryption Helper (TypeScript)
1305
1278
 
1279
+ <!-- verify: payuni -->
1306
1280
  ```typescript
1307
1281
  import crypto from 'crypto';
1308
1282
 
1309
- interface PAYUNiConfig {
1310
- merchantId: string;
1311
- hashKey: string;
1312
- hashIV: string;
1313
- isProduction?: boolean;
1283
+ // EncryptInfo = hex( base64(AES-256-GCM 密文) + ":::" + base64(tag) ),HashIV 直接當 nonce
1284
+ export function encryptPAYUNi(data: Record<string, any>, hashKey: string, hashIV: string) {
1285
+ const cipher = crypto.createCipheriv('aes-256-gcm', hashKey, hashIV);
1286
+ const encrypted = Buffer.concat([cipher.update(new URLSearchParams(data).toString(), 'utf8'), cipher.final()]);
1287
+ const encryptInfo = Buffer.from(`${encrypted.toString('base64')}:::${cipher.getAuthTag().toString('base64')}`).toString('hex');
1288
+ // HashInfo = SHA256(HashKey + EncryptInfo + HashIV)
1289
+ const hashInfo = crypto.createHash('sha256').update(hashKey + encryptInfo + hashIV).digest('hex').toUpperCase();
1290
+ return { EncryptInfo: encryptInfo, HashInfo: hashInfo };
1314
1291
  }
1315
1292
 
1316
- class PAYUNiLogistics {
1317
- private config: Required<PAYUNiConfig>;
1318
- private baseUrl: string;
1319
-
1320
- constructor(config: PAYUNiConfig) {
1321
- this.config = {
1322
- ...config,
1323
- isProduction: config.isProduction ?? false,
1324
- };
1325
-
1326
- this.baseUrl = this.config.isProduction
1327
- ? 'https://api.payuni.com.tw/api'
1328
- : 'https://sandbox-api.payuni.com.tw/api';
1329
- }
1330
-
1331
- /**
1332
- * AES-256-GCM Encryption
1333
- */
1334
- encrypt(data: Record<string, any>): string {
1335
- // Convert to query string
1336
- const queryString = new URLSearchParams(data).toString();
1337
-
1338
- // Create cipher
1339
- const cipher = crypto.createCipheriv(
1340
- 'aes-256-gcm',
1341
- this.config.hashKey,
1342
- this.config.hashIV
1343
- );
1344
-
1345
- // Encrypt
1346
- let encrypted = cipher.update(queryString, 'utf8', 'hex');
1347
- encrypted += cipher.final('hex');
1348
-
1349
- // Get auth tag
1350
- const authTag = cipher.getAuthTag().toString('hex');
1351
-
1352
- // Combine encrypted + tag
1353
- return encrypted + authTag;
1354
- }
1355
-
1356
- /**
1357
- * AES-256-GCM Decryption
1358
- */
1359
- decrypt(encryptInfo: string): Record<string, any> {
1360
- // Split encrypted data and tag (tag is last 32 hex chars = 16 bytes)
1361
- const encrypted = encryptInfo.slice(0, -32);
1362
- const authTag = encryptInfo.slice(-32);
1363
-
1364
- // Create decipher
1365
- const decipher = crypto.createDecipheriv(
1366
- 'aes-256-gcm',
1367
- this.config.hashKey,
1368
- this.config.hashIV
1369
- );
1370
-
1371
- // Set auth tag
1372
- decipher.setAuthTag(Buffer.from(authTag, 'hex'));
1373
-
1374
- // Decrypt
1375
- let decrypted = decipher.update(encrypted, 'hex', 'utf8');
1376
- decrypted += decipher.final('utf8');
1377
-
1378
- // Parse query string
1379
- const params = new URLSearchParams(decrypted);
1380
- const result: Record<string, any> = {};
1381
- params.forEach((value, key) => {
1382
- result[key] = value;
1383
- });
1384
-
1385
- return result;
1386
- }
1387
-
1388
- /**
1389
- * Generate HashInfo (SHA256)
1390
- */
1391
- generateHashInfo(encryptInfo: string): string {
1392
- const raw = encryptInfo + this.config.hashKey + this.config.hashIV;
1393
- return crypto.createHash('sha256').update(raw).digest('hex').toUpperCase();
1394
- }
1395
-
1396
- /**
1397
- * Get current Unix timestamp
1398
- */
1399
- getTimestamp(): number {
1400
- return Math.floor(Date.now() / 1000);
1401
- }
1293
+ export function decryptPAYUNi(encryptInfo: string, hashKey: string, hashIV: string): Record<string, any> {
1294
+ const [data, tag] = Buffer.from(encryptInfo, 'hex').toString('utf8').split(':::');
1295
+ const decipher = crypto.createDecipheriv('aes-256-gcm', hashKey, hashIV);
1296
+ decipher.setAuthTag(Buffer.from(tag, 'base64'));
1297
+ const text = Buffer.concat([decipher.update(Buffer.from(data, 'base64')), decipher.final()]).toString('utf8');
1298
+ return Object.fromEntries(new URLSearchParams(text));
1402
1299
  }
1403
-
1404
- export { PAYUNiLogistics };
1405
- ```
1406
-
1407
- #### Python - AES-256-GCM Encryption Helper
1408
-
1409
- ```python
1410
- """PAYUNi Logistics Encryption Helper - Python"""
1411
-
1412
- from Crypto.Cipher import AES
1413
- from urllib.parse import urlencode, parse_qs
1414
- import hashlib
1415
- import time
1416
- from typing import Dict, Any
1417
-
1418
-
1419
- class PAYUNiLogistics:
1420
- """PAYUNi Logistics API Client"""
1421
-
1422
- def __init__(
1423
- self,
1424
- merchant_id: str,
1425
- hash_key: str,
1426
- hash_iv: str,
1427
- is_production: bool = False
1428
- ):
1429
- self.merchant_id = merchant_id
1430
- self.hash_key = hash_key.encode('utf-8')
1431
- self.hash_iv = hash_iv.encode('utf-8')
1432
-
1433
- self.base_url = (
1434
- 'https://api.payuni.com.tw/api'
1435
- if is_production
1436
- else 'https://sandbox-api.payuni.com.tw/api'
1437
- )
1438
-
1439
- def encrypt(self, data: Dict[str, Any]) -> str:
1440
- """AES-256-GCM Encryption"""
1441
- # Convert to query string
1442
- query_string = urlencode(data)
1443
-
1444
- # Create cipher
1445
- cipher = AES.new(self.hash_key, AES.MODE_GCM, nonce=self.hash_iv)
1446
-
1447
- # Encrypt and get tag
1448
- encrypted, tag = cipher.encrypt_and_digest(query_string.encode('utf-8'))
1449
-
1450
- # Combine encrypted + tag and convert to hex
1451
- return (encrypted + tag).hex()
1452
-
1453
- def decrypt(self, encrypt_info: str) -> Dict[str, Any]:
1454
- """AES-256-GCM Decryption"""
1455
- # Convert hex to binary
1456
- data = bytes.fromhex(encrypt_info)
1457
-
1458
- # Split encrypted data and tag (last 16 bytes)
1459
- encrypted = data[:-16]
1460
- tag = data[-16:]
1461
-
1462
- # Create cipher
1463
- cipher = AES.new(self.hash_key, AES.MODE_GCM, nonce=self.hash_iv)
1464
-
1465
- # Decrypt and verify
1466
- decrypted = cipher.decrypt_and_verify(encrypted, tag)
1467
-
1468
- # Parse query string
1469
- result = dict(parse_qs(decrypted.decode('utf-8')))
1470
- return {k: v[0] if len(v) == 1 else v for k, v in result.items()}
1471
-
1472
- def generate_hash_info(self, encrypt_info: str) -> str:
1473
- """Generate HashInfo (SHA256)"""
1474
- raw = encrypt_info + self.hash_key.decode('utf-8') + self.hash_iv.decode('utf-8')
1475
- return hashlib.sha256(raw.encode('utf-8')).hexdigest().upper()
1476
-
1477
- @staticmethod
1478
- def get_timestamp() -> int:
1479
- """Get current Unix timestamp"""
1480
- return int(time.time())
1481
- ```
1482
-
1483
- ---
1484
-
1485
- ### 2. Create 7-11 C2C Shipment
1486
-
1487
- #### TypeScript Example
1488
-
1489
- ```typescript
1490
- import axios from 'axios';
1491
-
1492
- interface Create711ShipmentRequest {
1493
- merTradeNo: string;
1494
- goodsType: 1 | 2; // 1=Normal, 2=Frozen
1495
- goodsAmount: number;
1496
- goodsName: string;
1497
- senderName: string;
1498
- senderPhone: string;
1499
- senderStoreID: string;
1500
- receiverName: string;
1501
- receiverPhone: string;
1502
- receiverStoreID: string;
1503
- notifyURL: string;
1504
- }
1505
-
1506
- class PAYUNi711Logistics extends PAYUNiLogistics {
1507
- /**
1508
- * Create 7-11 C2C shipment
1509
- */
1510
- async create711Shipment(params: Create711ShipmentRequest) {
1511
- const data = {
1512
- MerID: this.config.merchantId,
1513
- MerTradeNo: params.merTradeNo,
1514
- LogisticsType: 'PAYUNi_Logistic_711',
1515
- GoodsType: params.goodsType,
1516
- GoodsAmount: params.goodsAmount,
1517
- GoodsName: params.goodsName,
1518
- SenderName: params.senderName,
1519
- SenderPhone: params.senderPhone,
1520
- SenderStoreID: params.senderStoreID,
1521
- ReceiverName: params.receiverName,
1522
- ReceiverPhone: params.receiverPhone,
1523
- ReceiverStoreID: params.receiverStoreID,
1524
- NotifyURL: params.notifyURL,
1525
- Timestamp: this.getTimestamp(),
1526
- };
1527
-
1528
- const encryptInfo = this.encrypt(data);
1529
- const hashInfo = this.generateHashInfo(encryptInfo);
1530
-
1531
- const response = await axios.post(
1532
- `${this.baseUrl}/logistics/create`,
1533
- new URLSearchParams({
1534
- MerID: this.config.merchantId,
1535
- Version: '1.0',
1536
- EncryptInfo: encryptInfo,
1537
- HashInfo: hashInfo,
1538
- }),
1539
- {
1540
- headers: {
1541
- 'Content-Type': 'application/x-www-form-urlencoded',
1542
- },
1543
- }
1544
- );
1545
-
1546
- const result = response.data;
1547
-
1548
- if (result.Status !== 'SUCCESS') {
1549
- throw new Error(`Create shipment failed: ${result.Message}`);
1550
- }
1551
-
1552
- // Decrypt response
1553
- const decrypted = this.decrypt(result.EncryptInfo);
1554
-
1555
- return {
1556
- logisticsID: decrypted.LogisticsID,
1557
- merTradeNo: decrypted.MerTradeNo,
1558
- cvsPaymentNo: decrypted.CVSPaymentNo,
1559
- cvsValidationNo: decrypted.CVSValidationNo,
1560
- expireDate: decrypted.ExpireDate,
1561
- };
1562
- }
1563
- }
1564
-
1565
- // Usage Example
1566
- const logistics = new PAYUNi711Logistics({
1567
- merchantId: 'YOUR_MERCHANT_ID',
1568
- hashKey: 'YOUR_HASH_KEY',
1569
- hashIV: 'YOUR_HASH_IV',
1570
- isProduction: false,
1571
- });
1572
-
1573
- const result = await logistics.create711Shipment({
1574
- merTradeNo: `LOG${Date.now()}`,
1575
- goodsType: 1, // Normal temperature
1576
- goodsAmount: 500,
1577
- goodsName: 'T-shirt',
1578
- senderName: 'John Doe',
1579
- senderPhone: '0912345678',
1580
- senderStoreID: '123456', // 7-11 sender store
1581
- receiverName: 'Jane Doe',
1582
- receiverPhone: '0987654321',
1583
- receiverStoreID: '654321', // 7-11 receiver store
1584
- notifyURL: 'https://your-site.com/callback/payuni-711',
1585
- });
1586
-
1587
- console.log('Logistics ID:', result.logisticsID);
1588
- console.log('Payment Code:', result.cvsPaymentNo);
1589
-
1590
- export { PAYUNi711Logistics };
1591
- ```
1592
-
1593
- #### Python Example
1594
-
1595
- ```python
1596
- """Create 7-11 C2C Shipment - Python Example"""
1597
-
1598
- import requests
1599
- from typing import Dict
1600
-
1601
-
1602
- class PAYUNi711Logistics(PAYUNiLogistics):
1603
- """7-11 C2C Logistics Operations"""
1604
-
1605
- def create_711_shipment(
1606
- self,
1607
- mer_trade_no: str,
1608
- goods_type: int, # 1=Normal, 2=Frozen
1609
- goods_amount: int,
1610
- goods_name: str,
1611
- sender_name: str,
1612
- sender_phone: str,
1613
- sender_store_id: str,
1614
- receiver_name: str,
1615
- receiver_phone: str,
1616
- receiver_store_id: str,
1617
- notify_url: str,
1618
- ) -> Dict[str, any]:
1619
- """Create 7-11 C2C shipment"""
1620
-
1621
- data = {
1622
- 'MerID': self.merchant_id,
1623
- 'MerTradeNo': mer_trade_no,
1624
- 'LogisticsType': 'PAYUNi_Logistic_711',
1625
- 'GoodsType': goods_type,
1626
- 'GoodsAmount': goods_amount,
1627
- 'GoodsName': goods_name,
1628
- 'SenderName': sender_name,
1629
- 'SenderPhone': sender_phone,
1630
- 'SenderStoreID': sender_store_id,
1631
- 'ReceiverName': receiver_name,
1632
- 'ReceiverPhone': receiver_phone,
1633
- 'ReceiverStoreID': receiver_store_id,
1634
- 'NotifyURL': notify_url,
1635
- 'Timestamp': self.get_timestamp(),
1636
- }
1637
-
1638
- encrypt_info = self.encrypt(data)
1639
- hash_info = self.generate_hash_info(encrypt_info)
1640
-
1641
- response = requests.post(
1642
- f'{self.base_url}/logistics/create',
1643
- data={
1644
- 'MerID': self.merchant_id,
1645
- 'Version': '1.0',
1646
- 'EncryptInfo': encrypt_info,
1647
- 'HashInfo': hash_info,
1648
- },
1649
- )
1650
-
1651
- result = response.json()
1652
-
1653
- if result['Status'] != 'SUCCESS':
1654
- raise Exception(f"Create shipment failed: {result['Message']}")
1655
-
1656
- # Decrypt response
1657
- decrypted = self.decrypt(result['EncryptInfo'])
1658
-
1659
- return {
1660
- 'logistics_id': decrypted['LogisticsID'],
1661
- 'mer_trade_no': decrypted['MerTradeNo'],
1662
- 'cvs_payment_no': decrypted['CVSPaymentNo'],
1663
- 'cvs_validation_no': decrypted['CVSValidationNo'],
1664
- 'expire_date': decrypted['ExpireDate'],
1665
- }
1666
-
1667
-
1668
- # Usage Example
1669
- logistics = PAYUNi711Logistics(
1670
- merchant_id='YOUR_MERCHANT_ID',
1671
- hash_key='YOUR_HASH_KEY',
1672
- hash_iv='YOUR_HASH_IV',
1673
- is_production=False,
1674
- )
1675
-
1676
- result = logistics.create_711_shipment(
1677
- mer_trade_no=f'LOG{int(time.time())}',
1678
- goods_type=1, # Normal temperature
1679
- goods_amount=500,
1680
- goods_name='T-shirt',
1681
- sender_name='John Doe',
1682
- sender_phone='0912345678',
1683
- sender_store_id='123456',
1684
- receiver_name='Jane Doe',
1685
- receiver_phone='0987654321',
1686
- receiver_store_id='654321',
1687
- notify_url='https://your-site.com/callback/payuni-711',
1688
- )
1689
-
1690
- print(f"Logistics ID: {result['logistics_id']}")
1691
- print(f"Payment Code: {result['cvs_payment_no']}")
1692
1300
  ```
1693
1301
 
1694
- ---
1695
-
1696
- ### 3. Create T-Cat Home Delivery
1697
-
1698
- #### TypeScript Example
1302
+ ### 2. Create Shipment
1699
1303
 
1700
1304
  ```typescript
1701
- interface CreateTCatShipmentRequest {
1702
- merTradeNo: string;
1703
- goodsType: 1 | 2 | 3; // 1=Normal, 2=Frozen, 3=Refrigerated
1704
- goodsAmount: number;
1705
- goodsName: string;
1706
- goodsWeight?: number;
1707
- senderName: string;
1708
- senderPhone: string;
1709
- senderZipCode: string;
1710
- senderAddress: string;
1711
- receiverName: string;
1712
- receiverPhone: string;
1713
- receiverZipCode: string;
1714
- receiverAddress: string;
1715
- scheduledDeliveryTime?: '01' | '02' | '03';
1716
- notifyURL: string;
1717
- }
1718
-
1719
- class PAYUNiTCatLogistics extends PAYUNiLogistics {
1720
- /**
1721
- * Create T-Cat home delivery shipment
1722
- */
1723
- async createTCatShipment(params: CreateTCatShipmentRequest) {
1724
- const logisticsType =
1725
- params.goodsType === 2 ? 'PAYUNi_Logistic_Tcat_Freeze' :
1726
- params.goodsType === 3 ? 'PAYUNi_Logistic_Tcat_Cold' :
1727
- 'PAYUNi_Logistic_Tcat';
1728
-
1729
- const data: any = {
1730
- MerID: this.config.merchantId,
1731
- MerTradeNo: params.merTradeNo,
1732
- LogisticsType: logisticsType,
1733
- GoodsType: params.goodsType,
1734
- GoodsAmount: params.goodsAmount,
1735
- GoodsName: params.goodsName,
1736
- SenderName: params.senderName,
1737
- SenderPhone: params.senderPhone,
1738
- SenderZipCode: params.senderZipCode,
1739
- SenderAddress: params.senderAddress,
1740
- ReceiverName: params.receiverName,
1741
- ReceiverPhone: params.receiverPhone,
1742
- ReceiverZipCode: params.receiverZipCode,
1743
- ReceiverAddress: params.receiverAddress,
1744
- NotifyURL: params.notifyURL,
1745
- Timestamp: this.getTimestamp(),
1746
- };
1747
-
1748
- if (params.goodsWeight) data.GoodsWeight = params.goodsWeight;
1749
- if (params.scheduledDeliveryTime) data.ScheduledDeliveryTime = params.scheduledDeliveryTime;
1750
-
1751
- const encryptInfo = this.encrypt(data);
1752
- const hashInfo = this.generateHashInfo(encryptInfo);
1753
-
1754
- const response = await axios.post(
1755
- `${this.baseUrl}/logistics/create`,
1756
- new URLSearchParams({
1757
- MerID: this.config.merchantId,
1758
- Version: '1.0',
1759
- EncryptInfo: encryptInfo,
1760
- HashInfo: hashInfo,
1761
- }),
1762
- {
1763
- headers: {
1764
- 'Content-Type': 'application/x-www-form-urlencoded',
1765
- },
1766
- }
1767
- );
1768
-
1769
- const result = response.data;
1770
-
1771
- if (result.Status !== 'SUCCESS') {
1772
- throw new Error(`Create shipment failed: ${result.Message}`);
1773
- }
1774
-
1775
- const decrypted = this.decrypt(result.EncryptInfo);
1776
-
1777
- return {
1778
- logisticsID: decrypted.LogisticsID,
1779
- merTradeNo: decrypted.MerTradeNo,
1780
- shipmentNo: decrypted.ShipmentNo,
1781
- bookingNote: decrypted.BookingNote,
1782
- };
1783
- }
1305
+ const BASE = 'https://sandbox-api.payuni.com.tw/api';
1306
+
1307
+ async function payuniPost(path: string, info: Record<string, any>, version = '1.1') {
1308
+ const { EncryptInfo, HashInfo } = encryptPAYUNi(info, HASH_KEY, HASH_IV);
1309
+ const res = await fetch(`${BASE}${path}`, {
1310
+ method: 'POST',
1311
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1312
+ body: new URLSearchParams({ MerID: MER_ID, Version: version, EncryptInfo, HashInfo }),
1313
+ });
1314
+ const body = await res.json();
1315
+ if (!body.EncryptInfo) return body; // 外層錯誤(例如 API00003)
1316
+ const expected = crypto.createHash('sha256').update(HASH_KEY + body.EncryptInfo + HASH_IV).digest('hex').toUpperCase();
1317
+ if (expected !== body.HashInfo) throw new Error('HashInfo 驗證失敗');
1318
+ return decryptPAYUNi(body.EncryptInfo, HASH_KEY, HASH_IV);
1784
1319
  }
1785
1320
 
1786
- // Usage Example
1787
- const tcat = new PAYUNiTCatLogistics({
1788
- merchantId: 'YOUR_MERCHANT_ID',
1789
- hashKey: 'YOUR_HASH_KEY',
1790
- hashIV: 'YOUR_HASH_IV',
1791
- });
1792
-
1793
- const result = await tcat.createTCatShipment({
1794
- merTradeNo: `TCAT${Date.now()}`,
1795
- goodsType: 1, // Normal temperature
1796
- goodsAmount: 1000,
1797
- goodsName: 'Electronics',
1798
- goodsWeight: 500, // 500g
1799
- senderName: 'Sender Name',
1800
- senderPhone: '0912345678',
1801
- senderZipCode: '100',
1802
- senderAddress: 'Taipei City, Zhongzheng Dist., XXX Road No.1',
1803
- receiverName: 'Receiver Name',
1804
- receiverPhone: '0987654321',
1805
- receiverZipCode: '300',
1806
- receiverAddress: 'Hsinchu City, East Dist., YYY Road No.2',
1807
- scheduledDeliveryTime: '02', // 14:00-18:00
1808
- notifyURL: 'https://your-site.com/callback/payuni-tcat',
1321
+ // 7-11 店到店,取貨不付款(StoreID 來自門市地圖 /logistics/ship_map 的回傳)
1322
+ const created = await payuniPost('/logistics/trade', {
1323
+ MerID: MER_ID,
1324
+ Timestamp: Math.floor(Date.now() / 1000),
1325
+ MerTradeNo: `LOG${Date.now()}`,
1326
+ GoodsType: '1', // 1=常溫 2=冷凍
1327
+ LgsType: 'C2C', // C2C / B2C
1328
+ ShipType: '1', // 1=7-ELEVEN
1329
+ TradeAmt: 500, // 取貨不付款時為報值金額
1330
+ ServiceType: '3', // 1=取貨付款 3=取貨不付款
1331
+ StoreID: '123456',
1332
+ Consignee: '王小明',
1333
+ ConsigneeMail: 'buyer@example.com',
1334
+ ConsigneeMobile: '0987654321',
1335
+ RefundStoreID: '',
1336
+ SenderName: '測試商家',
1337
+ SenderMobile: '0912345678',
1338
+ NotifyURL: 'https://your-site.com/payuni/shipping-notify',
1809
1339
  });
1810
-
1811
- console.log('Tracking No:', result.shipmentNo);
1812
-
1813
- export { PAYUNiTCatLogistics };
1340
+ // 黑貓宅配改呼叫 /home_delivery/trade,ShipType='2'、LgsType='HOME'、StoreID='',
1341
+ // 並加上 ConsigneeAddress、ProdDesc(≤20 字)、DeliveryTimeTag(01 / 02 / 04)
1342
+ console.log(created.Status, created.ShipTradeNo); // ShipTradeNo 是後續查詢、列印、通知的鍵
1814
1343
  ```
1815
1344
 
1816
- ---
1817
-
1818
- ### 4. Query Shipment Status
1819
-
1820
- #### TypeScript Example
1345
+ ### 3. Query Shipment
1821
1346
 
1822
1347
  ```typescript
1823
- class PAYUNiQueryLogistics extends PAYUNiLogistics {
1824
- /**
1825
- * Query shipment status
1826
- */
1827
- async queryShipment(merTradeNo: string) {
1828
- const data = {
1829
- MerID: this.config.merchantId,
1830
- MerTradeNo: merTradeNo,
1831
- Timestamp: this.getTimestamp(),
1832
- };
1833
-
1834
- const encryptInfo = this.encrypt(data);
1835
- const hashInfo = this.generateHashInfo(encryptInfo);
1836
-
1837
- const response = await axios.post(
1838
- `${this.baseUrl}/logistics/query`,
1839
- new URLSearchParams({
1840
- MerID: this.config.merchantId,
1841
- Version: '1.0',
1842
- EncryptInfo: encryptInfo,
1843
- HashInfo: hashInfo,
1844
- }),
1845
- {
1846
- headers: {
1847
- 'Content-Type': 'application/x-www-form-urlencoded',
1848
- },
1849
- }
1850
- );
1851
-
1852
- const result = response.data;
1853
-
1854
- if (result.Status !== 'SUCCESS') {
1855
- throw new Error(`Query shipment failed: ${result.Message}`);
1856
- }
1857
-
1858
- const decrypted = this.decrypt(result.EncryptInfo);
1859
-
1860
- return {
1861
- logisticsID: decrypted.LogisticsID,
1862
- merTradeNo: decrypted.MerTradeNo,
1863
- logisticsType: decrypted.LogisticsType,
1864
- logisticsStatus: decrypted.LogisticsStatus,
1865
- logisticsStatusMsg: decrypted.LogisticsStatusMsg,
1866
- shipmentNo: decrypted.ShipmentNo,
1867
- receiverStoreID: decrypted.ReceiverStoreID,
1868
- updateTime: decrypted.UpdateTime,
1869
- };
1870
- }
1871
-
1872
- /**
1873
- * Get human-readable status
1874
- */
1875
- getStatusDescription(statusCode: string): string {
1876
- const statusMap: Record<string, string> = {
1877
- '11': 'Shipped',
1878
- '21': 'Arrived at store / In delivery',
1879
- '22': 'Picked up / Delivered',
1880
- '31': 'Returning',
1881
- '32': 'Return completed',
1882
- };
1883
-
1884
- return statusMap[statusCode] || 'Unknown status';
1885
- }
1886
- }
1887
-
1888
- // Usage Example
1889
- const query = new PAYUNiQueryLogistics({
1890
- merchantId: 'YOUR_MERCHANT_ID',
1891
- hashKey: 'YOUR_HASH_KEY',
1892
- hashIV: 'YOUR_HASH_IV',
1348
+ const status = await payuniPost('/logistics/query', {
1349
+ MerID: MER_ID,
1350
+ Timestamp: Math.floor(Date.now() / 1000),
1351
+ LgsType: 'C2C',
1352
+ ShipTradeNo: created.ShipTradeNo,
1893
1353
  });
1894
-
1895
- const status = await query.queryShipment('LOG123456');
1896
-
1897
- console.log(`Order: ${status.merTradeNo}`);
1898
- console.log(`Status: ${status.logisticsStatusMsg} (${status.logisticsStatus})`);
1899
- console.log(`Tracking No: ${status.shipmentNo}`);
1900
-
1901
- export { PAYUNiQueryLogistics };
1354
+ // status.ShipStatus: 21 待出貨 / 22 物流中心驗收 / 92 寄件門市已收件 / 31 配送中 / 32 待取貨 / 11 已取貨
1355
+ console.log(status.ShipStatus, status.ShipStatusDesc, status.Odno);
1902
1356
  ```
1903
1357
 
1904
- ---
1905
-
1906
- ### 5. Status Notification Callback
1907
-
1908
- #### Express.js Example
1358
+ ### 4. Status Notification Callback
1909
1359
 
1910
1360
  ```typescript
1911
- import express from 'express';
1912
-
1913
- const app = express();
1914
-
1915
- app.use(express.urlencoded({ extended: true }));
1916
- app.use(express.json());
1917
-
1918
- const logistics = new PAYUNiLogistics({
1919
- merchantId: 'YOUR_MERCHANT_ID',
1920
- hashKey: 'YOUR_HASH_KEY',
1921
- hashIV: 'YOUR_HASH_IV',
1922
- });
1923
-
1924
- /**
1925
- * Handle PAYUNi logistics status notification
1926
- */
1927
- app.post('/callback/payuni-logistics', async (req, res) => {
1928
- try {
1929
- const { MerID, EncryptInfo, HashInfo } = req.body;
1930
-
1931
- console.log('Received notification from PAYUNi');
1932
-
1933
- // Verify HashInfo
1934
- const calculatedHash = logistics.generateHashInfo(EncryptInfo);
1935
- if (calculatedHash !== HashInfo.toUpperCase()) {
1936
- console.error('Hash verification failed');
1937
- return res.send('Hash Error');
1938
- }
1939
-
1940
- // Decrypt data
1941
- const data = logistics.decrypt(EncryptInfo);
1942
-
1943
- console.log('Notification data:', data);
1944
-
1945
- // Process the notification
1946
- await processLogisticsStatusUpdate({
1947
- merTradeNo: data.MerTradeNo,
1948
- logisticsID: data.LogisticsID,
1949
- logisticsType: data.LogisticsType,
1950
- logisticsStatus: data.LogisticsStatus,
1951
- logisticsStatusMsg: data.LogisticsStatusMsg,
1952
- updateTime: data.UpdateTime,
1953
- });
1954
-
1955
- // Return SUCCESS
1956
- res.send('SUCCESS');
1957
- } catch (error) {
1958
- console.error('Callback error:', error);
1959
- res.send('Error');
1361
+ app.post('/payuni/shipping-notify', express.urlencoded({ extended: false }), (req, res) => {
1362
+ const { EncryptInfo, HashInfo } = req.body;
1363
+ // 先驗 HashInfo(官方外掛沒驗,這是疏漏,不要照抄)
1364
+ if (HashInfo !== undefined) {
1365
+ const expected = crypto.createHash('sha256').update(HASH_KEY + EncryptInfo + HASH_IV).digest('hex').toUpperCase();
1366
+ if (expected !== HashInfo) return res.status(400).end();
1960
1367
  }
1961
- });
1962
-
1963
- /**
1964
- * Process logistics status update
1965
- */
1966
- async function processLogisticsStatusUpdate(data: {
1967
- merTradeNo: string;
1968
- logisticsID: string;
1969
- logisticsType: string;
1970
- logisticsStatus: string;
1971
- logisticsStatusMsg: string;
1972
- updateTime: string;
1973
- }) {
1974
- console.log(`Processing status update for order ${data.merTradeNo}`);
1975
-
1976
- // Update database
1977
- // await db.orders.updateOne(
1978
- // { orderNo: data.merTradeNo },
1979
- // {
1980
- // $set: {
1981
- // 'logistics.status': data.logisticsStatus,
1982
- // 'logistics.statusMsg': data.logisticsStatusMsg,
1983
- // 'logistics.logisticsID': data.logisticsID,
1984
- // 'logistics.lastUpdate': new Date(data.updateTime),
1985
- // },
1986
- // }
1987
- // );
1988
-
1989
- // Send notification to customer based on status
1990
- switch (data.logisticsStatus) {
1991
- case '11':
1992
- // Shipped
1993
- console.log('Order shipped');
1994
- break;
1995
- case '21':
1996
- // Arrived
1997
- console.log('Arrived at destination');
1998
- break;
1999
- case '22':
2000
- // Picked up / Delivered
2001
- console.log('Delivery completed');
2002
- // await sendEmail({ ... });
2003
- break;
2004
- case '31':
2005
- case '32':
2006
- // Return
2007
- console.log('Order returned');
2008
- break;
1368
+ const info = decryptPAYUNi(EncryptInfo, HASH_KEY, HASH_IV);
1369
+ if (info.Status === 'SUCCESS' && info.ApiType === 'ShipStatus') {
1370
+ updateShipment(info.ShipTradeNo, info.ShipStatus, info.ShipStatusDesc, info.ShipStatusTime);
2009
1371
  }
2010
- }
2011
-
2012
- app.listen(3000, () => {
2013
- console.log('PAYUNi callback server listening on port 3000');
1372
+ res.status(200).end();
2014
1373
  });
2015
1374
  ```
2016
1375
 
@@ -2022,6 +1381,9 @@ app.listen(3000, () => {
2022
1381
 
2023
1382
  #### TypeScript - MD5 CheckMacValue Helper
2024
1383
 
1384
+ > 由 CI 以綠界官方 PHP SDK 產生的標準答案驗證(`tests/vectors/ecpay.json`)。
1385
+
1386
+ <!-- verify: ecpay-cmv-md5 -->
2025
1387
  ```typescript
2026
1388
  import crypto from 'crypto';
2027
1389
 
@@ -2048,39 +1410,39 @@ class ECPayLogistics {
2048
1410
  }
2049
1411
 
2050
1412
  /**
2051
- * Generate CheckMacValue (MD5)
1413
+ * 與綠界官方 SDK UrlService::ecpayUrlEncode 相同:PHP urlencode → 小寫 → .NET 字元還原
1414
+ * (encodeURIComponent 的空白是 %20,綠界要的是 +;! ' ( ) * ~ 也要先依 PHP 規則編碼)
1415
+ */
1416
+ private ecpayUrlEncode(text: string): string {
1417
+ return encodeURIComponent(text)
1418
+ .replace(/%20/g, '+')
1419
+ .replace(/[!'()*~]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())
1420
+ .toLowerCase()
1421
+ .replace(/%21/g, '!').replace(/%2a/g, '*').replace(/%28/g, '(').replace(/%29/g, ')');
1422
+ }
1423
+
1424
+ /**
1425
+ * Generate CheckMacValue (MD5,國內物流;金流 AIO 才是 SHA256)
2052
1426
  */
2053
1427
  generateCheckMacValue(params: Record<string, any>): string {
2054
- // Sort parameters
2055
- const sorted = Object.keys(params)
2056
- .sort()
2057
- .reduce((acc, key) => {
2058
- acc[key] = params[key];
2059
- return acc;
2060
- }, {} as Record<string, any>);
2061
-
2062
- // Create query string
2063
- const paramStr = Object.entries(sorted)
2064
- .map(([key, value]) => `${key}=${value}`)
2065
- .join('&');
2066
-
2067
- // Add HashKey and HashIV
2068
- const raw = `HashKey=${this.config.hashKey}&${paramStr}&HashIV=${this.config.hashIV}`;
2069
-
2070
- // URL encode and convert to lowercase
2071
- const encoded = encodeURIComponent(raw).toLowerCase();
2072
-
2073
- // MD5 hash and uppercase
2074
- return crypto.createHash('md5').update(encoded).digest('hex').toUpperCase();
1428
+ const { CheckMacValue, ...data } = params;
1429
+ // 不分大小寫排序(SDK 用 strcasecmp)
1430
+ const keys = Object.keys(data).sort((a, b) => {
1431
+ const x = a.toLowerCase(), y = b.toLowerCase();
1432
+ return x < y ? -1 : x > y ? 1 : 0;
1433
+ });
1434
+ const raw = `HashKey=${this.config.hashKey}&${keys.map(k => `${k}=${data[k]}`).join('&')}&HashIV=${this.config.hashIV}`;
1435
+ return crypto.createHash('md5').update(this.ecpayUrlEncode(raw)).digest('hex').toUpperCase();
2075
1436
  }
2076
1437
 
2077
1438
  /**
2078
- * Verify CheckMacValue from callback
1439
+ * Verify CheckMacValue from callback(成功後回應純文字 1|OK)
2079
1440
  */
2080
1441
  verifyCheckMacValue(params: Record<string, any>): boolean {
2081
- const { CheckMacValue, ...data } = params;
2082
- const calculated = this.generateCheckMacValue(data);
2083
- return calculated === CheckMacValue;
1442
+ if (!params.CheckMacValue) return false;
1443
+ const a = Buffer.from(this.generateCheckMacValue(params));
1444
+ const b = Buffer.from(String(params.CheckMacValue).toUpperCase());
1445
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
2084
1446
  }
2085
1447
  }
2086
1448
 
@@ -2089,10 +1451,12 @@ export { ECPayLogistics };
2089
1451
 
2090
1452
  #### Python - MD5 CheckMacValue Helper
2091
1453
 
1454
+ <!-- verify: ecpay-cmv-md5 -->
2092
1455
  ```python
2093
1456
  """ECPay Logistics Encryption Helper - Python"""
2094
1457
 
2095
1458
  import hashlib
1459
+ import hmac
2096
1460
  import urllib.parse
2097
1461
  from typing import Dict, Any
2098
1462
 
@@ -2117,31 +1481,27 @@ class ECPayLogistics:
2117
1481
  else 'https://logistics-stage.ecpay.com.tw'
2118
1482
  )
2119
1483
 
2120
- def generate_check_mac_value(self, params: Dict[str, Any]) -> str:
2121
- """Generate CheckMacValue (MD5)"""
2122
- # Sort parameters
2123
- sorted_params = sorted(params.items())
2124
-
2125
- # Create query string
2126
- param_str = '&'.join(f'{k}={v}' for k, v in sorted_params)
2127
-
2128
- # Add HashKey and HashIV
2129
- raw = f'HashKey={self.hash_key}&{param_str}&HashIV={self.hash_iv}'
2130
-
2131
- # URL encode and convert to lowercase
2132
- encoded = urllib.parse.quote_plus(raw).lower()
1484
+ @staticmethod
1485
+ def ecpay_url_encode(text: str) -> str:
1486
+ """PHP urlencode(~ 也要編碼)→ 小寫 → 還原 .NET 不編碼的 - _ . ! * ( )"""
1487
+ encoded = urllib.parse.quote_plus(text, safe='').replace('~', '%7E').lower()
1488
+ for src, dst in (('%2d', '-'), ('%5f', '_'), ('%2e', '.'), ('%21', '!'),
1489
+ ('%2a', '*'), ('%28', '('), ('%29', ')')):
1490
+ encoded = encoded.replace(src, dst)
1491
+ return encoded
2133
1492
 
2134
- # MD5 hash and uppercase
2135
- return hashlib.md5(encoded.encode('utf-8')).hexdigest().upper()
1493
+ def generate_check_mac_value(self, params: Dict[str, Any]) -> str:
1494
+ """Generate CheckMacValue (MD5,國內物流;金流 AIO 才是 SHA256)"""
1495
+ # 排除 CheckMacValue,不分大小寫排序(SDK 用 strcasecmp)
1496
+ items = sorted(((k, v) for k, v in params.items() if k != 'CheckMacValue'),
1497
+ key=lambda kv: kv[0].lower())
1498
+ raw = f"HashKey={self.hash_key}&{'&'.join(f'{k}={v}' for k, v in items)}&HashIV={self.hash_iv}"
1499
+ return hashlib.md5(self.ecpay_url_encode(raw).encode('utf-8')).hexdigest().upper()
2136
1500
 
2137
1501
  def verify_check_mac_value(self, params: Dict[str, Any]) -> bool:
2138
- """Verify CheckMacValue from callback"""
2139
- check_mac = params.pop('CheckMacValue', None)
2140
- if not check_mac:
2141
- return False
2142
-
2143
- calculated = self.generate_check_mac_value(params)
2144
- return calculated == check_mac
1502
+ """Verify CheckMacValue from callback(不修改傳入的 dict;成功後回應純文字 1|OK)"""
1503
+ received = params.get('CheckMacValue', '')
1504
+ return bool(received) and hmac.compare_digest(self.generate_check_mac_value(params), received.upper())
2145
1505
  ```
2146
1506
 
2147
1507
  ---
@@ -3225,7 +2585,7 @@ SmilePay 透過 `Pay_zg` 矩陣編碼涵蓋 7-11/全家 + 黑貓三大配送:
3225
2585
 
3226
2586
  ## PayNow 立吉富物流範例
3227
2587
 
3228
- ⚠️ **加密用 3DES (TripleDES) / ECB / Zero-Padding**,24-byte Key + 8-byte IV。**不同於金流端的動態 AES-256**。
2588
+ ⚠️ **加密用 3DES (TripleDES) / ECB / Zero-Padding,輸出 Base64**;Key = `1234567890` + Password + `123456`(24 bytes,ECB 不使用 IV)。**不同於金流端的動態 AES-256**。已以文件範例密文逐位元組驗證。
3229
2589
 
3230
2590
  完整範例見 [`examples/paynow-logistics-cvs-example.py`](examples/paynow-logistics-cvs-example.py)。涵蓋 11 條產品線(7-11 大宗 / 冷凍 / 海外、全家 大宗 / 冷凍、4 大超商常溫 C2C、黑貓宅配 / 店到店)。
3231
2591