taiwan-logistics-skill 1.2.2 → 1.2.3

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.
@@ -1,255 +1,255 @@
1
- #!/usr/bin/env python3
2
- """
3
- PChomePay 拍錢包物流 Python 範例
4
-
5
- 依 taiwan-logistics-skill 規範撰寫。
6
- PChomePay 物流走 7-11 / 全家 / 萊爾富 / OK 四大超商,金物流二合一設計。
7
-
8
- 支援:
9
- - 取號列印交寄單 (/v1/logistic/batch)
10
- - 物流歷程查詢 (/v1/logistic/query/{order_id}/history)
11
- - 未出貨/未取貨查詢 (/v1/logistic/yet, /v1/logistic/store_return/{date})
12
- - 物流手續費對帳 (/v1/logistic/accounting/{date} - NDJSON 格式)
13
- - 賠款入帳查詢 (/v1/logistic/compensation/{date})
14
-
15
- ⚠️ Notify IP 白名單: 113.196.231.190(必加)
16
-
17
- API 文件: 參見 references/pchomepay-logistics-api.md
18
-
19
- 依賴:
20
- pip install requests
21
- """
22
-
23
- import json
24
- import time
25
- from base64 import b64encode
26
- from dataclasses import dataclass, field
27
- from typing import Dict, List, Literal, Optional
28
-
29
- import requests
30
-
31
-
32
- @dataclass
33
- class LogisticBatchRequest:
34
- """取號列印交寄單"""
35
- order_id: str # 商家訂單編號(與金流訂單關聯)
36
- store_id: str # 取貨門市編號
37
- return_store_id: str = '' # 退貨門市
38
- name: str = '' # 收件人
39
- phone: str = ''
40
- address: str = ''
41
- email: str = ''
42
-
43
-
44
- @dataclass
45
- class PChomePayResponse:
46
- success: bool
47
- code: str = ''
48
- message: str = ''
49
- data: Dict[str, any] = field(default_factory=dict)
50
- raw: Dict[str, any] = field(default_factory=dict)
51
-
52
-
53
- class PChomePayLogisticService:
54
- """
55
- PChomePay 物流服務.
56
-
57
- 認證: 兩段式
58
- 1. HTTP Basic Auth (APP_ID + SECRET) → /v1/token
59
- 2. 後續 API 帶 `pcpay-token` header (8 小時有效)
60
-
61
- Logistic types:
62
- PL711 = 7-11
63
- PLFMI = 全家 (FamilyMart)
64
- PLHIL = 萊爾富 (Hi-Life)
65
- PLOK = OK 超商
66
- """
67
-
68
- SANDBOX_BASE = 'https://sandbox-api.pchomepay.com.tw'
69
- PROD_BASE = 'https://api.pchomepay.com.tw'
70
-
71
- NOTIFY_IP = '113.196.231.190' # 白名單必加
72
-
73
- def __init__(self, app_id: str, secret: str, is_test: bool = True):
74
- self.app_id = app_id
75
- self.secret = secret
76
- self.base_url = self.SANDBOX_BASE if is_test else self.PROD_BASE
77
- self._token = None
78
- self._token_expire = 0
79
-
80
- def _get_token(self) -> str:
81
- """取得 / 刷新 pcpay-token (cache 8h)"""
82
- if self._token and time.time() < self._token_expire - 60:
83
- return self._token
84
-
85
- # Basic Auth 取 token
86
- creds = b64encode(f'{self.app_id}:{self.secret}'.encode()).decode()
87
- try:
88
- r = requests.post(
89
- self.base_url + '/v1/token',
90
- headers={'Authorization': f'Basic {creds}'},
91
- timeout=30,
92
- )
93
- r.raise_for_status()
94
- data = r.json()
95
- self._token = data.get('token', '')
96
- self._token_expire = time.time() + data.get('expires_in', 28800)
97
- return self._token
98
- except Exception as e:
99
- raise ConnectionError(f'PChomePay token 取得失敗: {e}')
100
-
101
- @property
102
- def headers(self) -> Dict[str, str]:
103
- return {
104
- 'pcpay-token': self._get_token(),
105
- 'Content-Type': 'application/json',
106
- 'Accept': 'application/json',
107
- }
108
-
109
- # -- Operations -----------------------------------------------------------
110
-
111
- def create_logistic(self, req: LogisticBatchRequest) -> PChomePayResponse:
112
- """取號列印交寄單"""
113
- body = {
114
- 'order_id': req.order_id,
115
- 'store_id': req.store_id,
116
- 'return_store_id': req.return_store_id,
117
- 'name': req.name,
118
- 'phone': req.phone,
119
- 'address': req.address,
120
- 'email': req.email,
121
- }
122
- return self._submit('POST', '/v1/logistic/batch', body=body)
123
-
124
- def query_history(self, order_id: str) -> PChomePayResponse:
125
- """查詢物流歷程"""
126
- return self._submit('GET', f'/v1/logistic/query/{order_id}/history')
127
-
128
- def get_history_page_url(self, order_id: str) -> str:
129
- """取得物流歷程 HTML 查詢頁 URL(不需 token, 直接給客戶)"""
130
- return f'{self.base_url}/v1/logistic/query/{order_id}/history-page'
131
-
132
- def query_yet_shipped(self) -> PChomePayResponse:
133
- """查詢尚未出貨的訂單"""
134
- return self._submit('GET', '/v1/logistic/yet')
135
-
136
- def query_store_return(self, date_yyyymmdd: str) -> PChomePayResponse:
137
- """查詢未取貨退倉訂單"""
138
- return self._submit('GET', f'/v1/logistic/store_return/{date_yyyymmdd}')
139
-
140
- def query_accounting(self, date_yyyymmdd: str) -> List[Dict[str, any]]:
141
- """
142
- 查詢物流手續費對帳資料(NDJSON 格式).
143
-
144
- 每行為一個獨立 JSON 物件,須逐行 parse。
145
- """
146
- url = self.base_url + f'/v1/logistic/accounting/{date_yyyymmdd}'
147
- try:
148
- r = requests.get(url, headers=self.headers, timeout=30)
149
- r.raise_for_status()
150
- # NDJSON: 每行一個 JSON
151
- records = []
152
- for line in r.text.strip().split('\n'):
153
- if line.strip():
154
- try:
155
- records.append(json.loads(line))
156
- except json.JSONDecodeError:
157
- pass
158
- return records
159
- except requests.exceptions.RequestException as e:
160
- raise ConnectionError(f'PChomePay 對帳 API 連線失敗: {e}')
161
-
162
- def query_compensation(self, date_yyyymm: str) -> PChomePayResponse:
163
- """查詢貨物寄丟之賠款入帳資料"""
164
- return self._submit('GET', f'/v1/logistic/compensation/{date_yyyymm}')
165
-
166
- # -- HTTP submit ----------------------------------------------------------
167
-
168
- def _submit(self, method: str, path: str, body: Optional[Dict[str, any]] = None) -> PChomePayResponse:
169
- url = self.base_url + path
170
- try:
171
- if method == 'GET':
172
- r = requests.get(url, headers=self.headers, timeout=30)
173
- else:
174
- r = requests.post(url, headers=self.headers, json=body, timeout=30)
175
- except requests.exceptions.RequestException as e:
176
- raise ConnectionError(f'PChomePay API 連線失敗: {e}')
177
-
178
- try:
179
- resp = r.json()
180
- except ValueError:
181
- return PChomePayResponse(
182
- success=False,
183
- code=str(r.status_code),
184
- message=f'回應非 JSON: {r.text[:200]}',
185
- )
186
-
187
- is_success = 200 <= r.status_code < 300
188
- return PChomePayResponse(
189
- success=is_success,
190
- code=str(resp.get('code', r.status_code)),
191
- message=resp.get('message', ''),
192
- data=resp.get('data', {}),
193
- raw=resp,
194
- )
195
-
196
-
197
- # ============================================================================
198
- # Examples
199
- # ============================================================================
200
-
201
- def example_create_logistic():
202
- print('=== PChomePay 7-11 取貨付款 取號 ===\n')
203
- svc = PChomePayLogisticService(app_id='YOUR_APP_ID', secret='YOUR_SECRET', is_test=True)
204
- req = LogisticBatchRequest(
205
- order_id=f'ORD{int(time.time())}',
206
- store_id='123456', # 7-11 門市編號
207
- return_store_id='123456',
208
- name='王小明',
209
- phone='0912345678',
210
- email='test@example.com',
211
- )
212
- try:
213
- resp = svc.create_logistic(req)
214
- if resp.success:
215
- print(f'[OK] 取號成功: {json.dumps(resp.data, ensure_ascii=False)}')
216
- else:
217
- print(f'[FAIL] {resp.code}: {resp.message}')
218
- except Exception as e:
219
- print(f'[ERROR] {e}')
220
-
221
-
222
- def example_query_history():
223
- print('\n=== PChomePay 物流歷程查詢 ===\n')
224
- svc = PChomePayLogisticService('YOUR_APP_ID', 'YOUR_SECRET', is_test=True)
225
- try:
226
- resp = svc.query_history(order_id='ORD123456')
227
- print(json.dumps(resp.raw, ensure_ascii=False, indent=2)[:500])
228
- except Exception as e:
229
- print(f'[ERROR] {e}')
230
-
231
-
232
- def example_accounting():
233
- print('\n=== PChomePay 物流手續費對帳(NDJSON)===\n')
234
- svc = PChomePayLogisticService('YOUR_APP_ID', 'YOUR_SECRET', is_test=True)
235
- try:
236
- records = svc.query_accounting(date_yyyymmdd='20260101')
237
- print(f'共 {len(records)} 筆對帳記錄')
238
- for record in records[:3]:
239
- print(f' - {record}')
240
- except Exception as e:
241
- print(f'[ERROR] {e}')
242
-
243
-
244
- def example_history_page():
245
- print('\n=== PChomePay HTML 物流歷程頁(給客戶端)===\n')
246
- svc = PChomePayLogisticService('YOUR_APP_ID', 'YOUR_SECRET', is_test=True)
247
- url = svc.get_history_page_url('ORD123456')
248
- print(f'客戶可開啟: {url}')
249
-
250
-
251
- if __name__ == '__main__':
252
- example_create_logistic()
253
- example_query_history()
254
- example_accounting()
255
- example_history_page()
1
+ #!/usr/bin/env python3
2
+ """
3
+ PChomePay 拍錢包物流 Python 範例
4
+
5
+ 依 taiwan-logistics-skill 規範撰寫。
6
+ PChomePay 物流走 7-11 / 全家 / 萊爾富 / OK 四大超商,金物流二合一設計。
7
+
8
+ 支援:
9
+ - 取號列印交寄單 (/v1/logistic/batch)
10
+ - 物流歷程查詢 (/v1/logistic/query/{order_id}/history)
11
+ - 未出貨/未取貨查詢 (/v1/logistic/yet, /v1/logistic/store_return/{date})
12
+ - 物流手續費對帳 (/v1/logistic/accounting/{date} - NDJSON 格式)
13
+ - 賠款入帳查詢 (/v1/logistic/compensation/{date})
14
+
15
+ ⚠️ Notify IP 白名單: 113.196.231.190(必加)
16
+
17
+ API 文件: 參見 references/pchomepay-logistics-api.md
18
+
19
+ 依賴:
20
+ pip install requests
21
+ """
22
+
23
+ import json
24
+ import time
25
+ from base64 import b64encode
26
+ from dataclasses import dataclass, field
27
+ from typing import Dict, List, Literal, Optional
28
+
29
+ import requests
30
+
31
+
32
+ @dataclass
33
+ class LogisticBatchRequest:
34
+ """取號列印交寄單"""
35
+ order_id: str # 商家訂單編號(與金流訂單關聯)
36
+ store_id: str # 取貨門市編號
37
+ return_store_id: str = '' # 退貨門市
38
+ name: str = '' # 收件人
39
+ phone: str = ''
40
+ address: str = ''
41
+ email: str = ''
42
+
43
+
44
+ @dataclass
45
+ class PChomePayResponse:
46
+ success: bool
47
+ code: str = ''
48
+ message: str = ''
49
+ data: Dict[str, any] = field(default_factory=dict)
50
+ raw: Dict[str, any] = field(default_factory=dict)
51
+
52
+
53
+ class PChomePayLogisticService:
54
+ """
55
+ PChomePay 物流服務.
56
+
57
+ 認證: 兩段式
58
+ 1. HTTP Basic Auth (APP_ID + SECRET) → /v1/token
59
+ 2. 後續 API 帶 `pcpay-token` header (8 小時有效)
60
+
61
+ Logistic types:
62
+ PL711 = 7-11
63
+ PLFMI = 全家 (FamilyMart)
64
+ PLHIL = 萊爾富 (Hi-Life)
65
+ PLOK = OK 超商
66
+ """
67
+
68
+ SANDBOX_BASE = 'https://sandbox-api.pchomepay.com.tw'
69
+ PROD_BASE = 'https://api.pchomepay.com.tw'
70
+
71
+ NOTIFY_IP = '113.196.231.190' # 白名單必加
72
+
73
+ def __init__(self, app_id: str, secret: str, is_test: bool = True):
74
+ self.app_id = app_id
75
+ self.secret = secret
76
+ self.base_url = self.SANDBOX_BASE if is_test else self.PROD_BASE
77
+ self._token = None
78
+ self._token_expire = 0
79
+
80
+ def _get_token(self) -> str:
81
+ """取得 / 刷新 pcpay-token (cache 8h)"""
82
+ if self._token and time.time() < self._token_expire - 60:
83
+ return self._token
84
+
85
+ # Basic Auth 取 token
86
+ creds = b64encode(f'{self.app_id}:{self.secret}'.encode()).decode()
87
+ try:
88
+ r = requests.post(
89
+ self.base_url + '/v1/token',
90
+ headers={'Authorization': f'Basic {creds}'},
91
+ timeout=30,
92
+ )
93
+ r.raise_for_status()
94
+ data = r.json()
95
+ self._token = data.get('token', '')
96
+ self._token_expire = time.time() + data.get('expires_in', 28800)
97
+ return self._token
98
+ except Exception as e:
99
+ raise ConnectionError(f'PChomePay token 取得失敗: {e}')
100
+
101
+ @property
102
+ def headers(self) -> Dict[str, str]:
103
+ return {
104
+ 'pcpay-token': self._get_token(),
105
+ 'Content-Type': 'application/json',
106
+ 'Accept': 'application/json',
107
+ }
108
+
109
+ # -- Operations -----------------------------------------------------------
110
+
111
+ def create_logistic(self, req: LogisticBatchRequest) -> PChomePayResponse:
112
+ """取號列印交寄單"""
113
+ body = {
114
+ 'order_id': req.order_id,
115
+ 'store_id': req.store_id,
116
+ 'return_store_id': req.return_store_id,
117
+ 'name': req.name,
118
+ 'phone': req.phone,
119
+ 'address': req.address,
120
+ 'email': req.email,
121
+ }
122
+ return self._submit('POST', '/v1/logistic/batch', body=body)
123
+
124
+ def query_history(self, order_id: str) -> PChomePayResponse:
125
+ """查詢物流歷程"""
126
+ return self._submit('GET', f'/v1/logistic/query/{order_id}/history')
127
+
128
+ def get_history_page_url(self, order_id: str) -> str:
129
+ """取得物流歷程 HTML 查詢頁 URL(不需 token, 直接給客戶)"""
130
+ return f'{self.base_url}/v1/logistic/query/{order_id}/history-page'
131
+
132
+ def query_yet_shipped(self) -> PChomePayResponse:
133
+ """查詢尚未出貨的訂單"""
134
+ return self._submit('GET', '/v1/logistic/yet')
135
+
136
+ def query_store_return(self, date_yyyymmdd: str) -> PChomePayResponse:
137
+ """查詢未取貨退倉訂單"""
138
+ return self._submit('GET', f'/v1/logistic/store_return/{date_yyyymmdd}')
139
+
140
+ def query_accounting(self, date_yyyymmdd: str) -> List[Dict[str, any]]:
141
+ """
142
+ 查詢物流手續費對帳資料(NDJSON 格式).
143
+
144
+ 每行為一個獨立 JSON 物件,須逐行 parse。
145
+ """
146
+ url = self.base_url + f'/v1/logistic/accounting/{date_yyyymmdd}'
147
+ try:
148
+ r = requests.get(url, headers=self.headers, timeout=30)
149
+ r.raise_for_status()
150
+ # NDJSON: 每行一個 JSON
151
+ records = []
152
+ for line in r.text.strip().split('\n'):
153
+ if line.strip():
154
+ try:
155
+ records.append(json.loads(line))
156
+ except json.JSONDecodeError:
157
+ pass
158
+ return records
159
+ except requests.exceptions.RequestException as e:
160
+ raise ConnectionError(f'PChomePay 對帳 API 連線失敗: {e}')
161
+
162
+ def query_compensation(self, date_yyyymm: str) -> PChomePayResponse:
163
+ """查詢貨物寄丟之賠款入帳資料"""
164
+ return self._submit('GET', f'/v1/logistic/compensation/{date_yyyymm}')
165
+
166
+ # -- HTTP submit ----------------------------------------------------------
167
+
168
+ def _submit(self, method: str, path: str, body: Optional[Dict[str, any]] = None) -> PChomePayResponse:
169
+ url = self.base_url + path
170
+ try:
171
+ if method == 'GET':
172
+ r = requests.get(url, headers=self.headers, timeout=30)
173
+ else:
174
+ r = requests.post(url, headers=self.headers, json=body, timeout=30)
175
+ except requests.exceptions.RequestException as e:
176
+ raise ConnectionError(f'PChomePay API 連線失敗: {e}')
177
+
178
+ try:
179
+ resp = r.json()
180
+ except ValueError:
181
+ return PChomePayResponse(
182
+ success=False,
183
+ code=str(r.status_code),
184
+ message=f'回應非 JSON: {r.text[:200]}',
185
+ )
186
+
187
+ is_success = 200 <= r.status_code < 300
188
+ return PChomePayResponse(
189
+ success=is_success,
190
+ code=str(resp.get('code', r.status_code)),
191
+ message=resp.get('message', ''),
192
+ data=resp.get('data', {}),
193
+ raw=resp,
194
+ )
195
+
196
+
197
+ # ============================================================================
198
+ # Examples
199
+ # ============================================================================
200
+
201
+ def example_create_logistic():
202
+ print('=== PChomePay 7-11 取貨付款 取號 ===\n')
203
+ svc = PChomePayLogisticService(app_id='YOUR_APP_ID', secret='YOUR_SECRET', is_test=True)
204
+ req = LogisticBatchRequest(
205
+ order_id=f'ORD{int(time.time())}',
206
+ store_id='123456', # 7-11 門市編號
207
+ return_store_id='123456',
208
+ name='王小明',
209
+ phone='0912345678',
210
+ email='test@example.com',
211
+ )
212
+ try:
213
+ resp = svc.create_logistic(req)
214
+ if resp.success:
215
+ print(f'[OK] 取號成功: {json.dumps(resp.data, ensure_ascii=False)}')
216
+ else:
217
+ print(f'[FAIL] {resp.code}: {resp.message}')
218
+ except Exception as e:
219
+ print(f'[ERROR] {e}')
220
+
221
+
222
+ def example_query_history():
223
+ print('\n=== PChomePay 物流歷程查詢 ===\n')
224
+ svc = PChomePayLogisticService('YOUR_APP_ID', 'YOUR_SECRET', is_test=True)
225
+ try:
226
+ resp = svc.query_history(order_id='ORD123456')
227
+ print(json.dumps(resp.raw, ensure_ascii=False, indent=2)[:500])
228
+ except Exception as e:
229
+ print(f'[ERROR] {e}')
230
+
231
+
232
+ def example_accounting():
233
+ print('\n=== PChomePay 物流手續費對帳(NDJSON)===\n')
234
+ svc = PChomePayLogisticService('YOUR_APP_ID', 'YOUR_SECRET', is_test=True)
235
+ try:
236
+ records = svc.query_accounting(date_yyyymmdd='20260101')
237
+ print(f'共 {len(records)} 筆對帳記錄')
238
+ for record in records[:3]:
239
+ print(f' - {record}')
240
+ except Exception as e:
241
+ print(f'[ERROR] {e}')
242
+
243
+
244
+ def example_history_page():
245
+ print('\n=== PChomePay HTML 物流歷程頁(給客戶端)===\n')
246
+ svc = PChomePayLogisticService('YOUR_APP_ID', 'YOUR_SECRET', is_test=True)
247
+ url = svc.get_history_page_url('ORD123456')
248
+ print(f'客戶可開啟: {url}')
249
+
250
+
251
+ if __name__ == '__main__':
252
+ example_create_logistic()
253
+ example_query_history()
254
+ example_accounting()
255
+ example_history_page()