taiwan-payment-skill 1.3.0 → 1.3.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.
@@ -1,291 +1,291 @@
1
- #!/usr/bin/env python3
2
- """
3
- Shopline Payments Python 範例
4
-
5
- 依照 taiwan-payment-skill 規範撰寫。
6
- SHOPLINE Payments (SLP) 是 SHOPLINE 集團旗下的金流服務,採 RESTful POST + JSON。
7
-
8
- 支援:
9
- - Redirect 模式 (sessions/create -> sessionUrl)
10
- - Embedded SDK 模式 (payment/create)
11
- - HMAC-SHA256 Webhook 驗證
12
-
13
- API 文件: 參見 references/shopline-payment-api.md
14
-
15
- 依賴:
16
- pip install requests
17
- """
18
-
19
- import hashlib
20
- import hmac
21
- import json
22
- import time
23
- import uuid
24
- from dataclasses import dataclass, field
25
- from typing import Dict, List, Literal, Optional
26
-
27
- import requests
28
-
29
-
30
- # ============================================================================
31
- # Data classes
32
- # ============================================================================
33
-
34
- @dataclass
35
- class SessionCreateData:
36
- """Shopline 建立結帳會話(Redirect 模式)"""
37
- reference_number: str # 商家訂單編號 (唯一)
38
- amount_cents: int # 金額(分)— NT$1000 = 100000
39
- currency: str = 'TWD'
40
- return_url: str = '' # 完成後導回網址
41
- cancel_url: str = '' # 取消後導回網址
42
- webhook_url: str = '' # 通知 URL (HTTPS only)
43
- description: str = ''
44
- customer_email: str = ''
45
- customer_phone: str = ''
46
- items: List[Dict[str, any]] = field(default_factory=list)
47
- payment_methods: Optional[List[str]] = None # CARD/APPLEPAY/LINEPAY/JKOPAY/ATM/BNPL
48
-
49
-
50
- @dataclass
51
- class ShoplineResponse:
52
- success: bool
53
- session_id: str = ''
54
- session_url: str = ''
55
- payment_id: str = ''
56
- status: str = ''
57
- error_code: str = ''
58
- error_message: str = ''
59
- raw: Dict[str, any] = field(default_factory=dict)
60
-
61
-
62
- # ============================================================================
63
- # Service
64
- # ============================================================================
65
-
66
- class ShoplinePaymentService:
67
- """
68
- Shopline Payments 服務.
69
-
70
- 認證: HTTP headers `merchantId` + `apiKey`.
71
- 端點:
72
- - POST /sessions/create — Redirect 模式建立會話
73
- - GET /sessions/{sessionId} — 查詢會話
74
- - POST /payment/create — Embedded SDK 提交付款
75
- - POST /refund/create — 退款
76
- - POST /capture — 請款(auth + capture 模式)
77
- - POST /void — 取消授權
78
- """
79
-
80
- SANDBOX_BASE = 'https://sandbox-payments-api.shoplineapp.com'
81
- PROD_BASE = 'https://payments-api.shoplineapp.com'
82
-
83
- def __init__(self, merchant_id: str, api_key: str, webhook_secret: str = '', is_test: bool = True):
84
- if not merchant_id or not api_key:
85
- raise ValueError('Shopline 需要 merchantId 與 apiKey')
86
- self.merchant_id = merchant_id
87
- self.api_key = api_key
88
- self.webhook_secret = webhook_secret
89
- self.base_url = self.SANDBOX_BASE if is_test else self.PROD_BASE
90
- self.is_test = is_test
91
-
92
- @property
93
- def headers(self) -> Dict[str, str]:
94
- return {
95
- 'merchantId': self.merchant_id,
96
- 'apiKey': self.api_key,
97
- 'Content-Type': 'application/json',
98
- 'Accept': 'application/json',
99
- }
100
-
101
- # -- Operations -----------------------------------------------------------
102
-
103
- def create_session(self, data: SessionCreateData) -> ShoplineResponse:
104
- """Redirect 模式:建立結帳會話"""
105
- body = {
106
- 'merchantId': self.merchant_id,
107
- 'referenceNumber': data.reference_number,
108
- 'amount': {
109
- 'value': data.amount_cents, # 已是分
110
- 'currency': data.currency,
111
- },
112
- 'returnUrl': data.return_url,
113
- 'cancelUrl': data.cancel_url,
114
- 'webhookUrl': data.webhook_url,
115
- 'description': data.description,
116
- 'customer': {
117
- 'email': data.customer_email,
118
- 'phone': data.customer_phone,
119
- },
120
- 'items': data.items,
121
- }
122
- if data.payment_methods:
123
- body['paymentMethods'] = data.payment_methods
124
- return self._submit('POST', '/sessions/create', body)
125
-
126
- def query_session(self, session_id: str) -> ShoplineResponse:
127
- """查詢結帳會話狀態"""
128
- return self._submit('GET', f'/sessions/{session_id}', None)
129
-
130
- def refund(self, payment_id: str, amount_cents: int, reason: str = '') -> ShoplineResponse:
131
- """退款"""
132
- body = {
133
- 'paymentId': payment_id,
134
- 'amount': {
135
- 'value': amount_cents,
136
- 'currency': 'TWD',
137
- },
138
- 'reason': reason,
139
- }
140
- return self._submit('POST', '/refund/create', body)
141
-
142
- def capture(self, payment_id: str, amount_cents: int) -> ShoplineResponse:
143
- """請款 (auth + capture 模式專用)"""
144
- body = {
145
- 'paymentId': payment_id,
146
- 'amount': {'value': amount_cents, 'currency': 'TWD'},
147
- }
148
- return self._submit('POST', '/capture', body)
149
-
150
- def void(self, payment_id: str) -> ShoplineResponse:
151
- """取消授權"""
152
- return self._submit('POST', '/void', {'paymentId': payment_id})
153
-
154
- # -- Webhook --------------------------------------------------------------
155
-
156
- def verify_webhook(self, payload: bytes, signature_header: str) -> bool:
157
- """
158
- 驗證 Shopline Webhook 簽章 (HMAC-SHA256).
159
-
160
- Shopline 通知時會在 header 帶 `x-slp-signature: sha256=<hex>`,
161
- 其值為 HMAC-SHA256(secret=webhookSecret, message=raw_body) 的 hex 表示。
162
- """
163
- if not self.webhook_secret:
164
- raise ValueError('未設定 webhookSecret,無法驗章')
165
-
166
- # 提取 signature header 中的 hex 值
167
- if signature_header.startswith('sha256='):
168
- sig_hex = signature_header[7:]
169
- else:
170
- sig_hex = signature_header
171
-
172
- expected = hmac.new(
173
- self.webhook_secret.encode('utf-8'),
174
- payload,
175
- hashlib.sha256,
176
- ).hexdigest()
177
-
178
- return hmac.compare_digest(expected.lower(), sig_hex.lower())
179
-
180
- # -- HTTP submit ----------------------------------------------------------
181
-
182
- def _submit(self, method: str, path: str, body: Optional[Dict[str, any]]) -> ShoplineResponse:
183
- url = self.base_url + path
184
- try:
185
- if method == 'GET':
186
- r = requests.get(url, headers=self.headers, timeout=30)
187
- else:
188
- r = requests.post(url, headers=self.headers, json=body, timeout=30)
189
- except requests.exceptions.RequestException as e:
190
- raise ConnectionError(f'Shopline API 連線失敗: {e}')
191
-
192
- try:
193
- resp = r.json()
194
- except ValueError:
195
- return ShoplineResponse(
196
- success=False,
197
- error_code=str(r.status_code),
198
- error_message=f'回應非 JSON: {r.text[:200]}',
199
- )
200
-
201
- is_success = 200 <= r.status_code < 300
202
-
203
- return ShoplineResponse(
204
- success=is_success,
205
- session_id=resp.get('sessionId', ''),
206
- session_url=resp.get('sessionUrl', ''),
207
- payment_id=resp.get('paymentId', resp.get('id', '')),
208
- status=resp.get('status', ''),
209
- error_code=str(r.status_code) if not is_success else '',
210
- error_message=resp.get('message', resp.get('error', '')),
211
- raw=resp,
212
- )
213
-
214
-
215
- # ============================================================================
216
- # Examples
217
- # ============================================================================
218
-
219
- def example_redirect_create():
220
- print('=== Shopline Redirect 模式建立會話 ===\n')
221
- svc = ShoplinePaymentService(
222
- merchant_id='YOUR_MERCHANT_ID',
223
- api_key='YOUR_API_KEY',
224
- is_test=True,
225
- )
226
- data = SessionCreateData(
227
- reference_number=f'ORD{int(time.time())}',
228
- amount_cents=105000, # NT$1050 -> 105000 分
229
- currency='TWD',
230
- return_url='https://your-shop.com/order/success',
231
- cancel_url='https://your-shop.com/order/cancel',
232
- webhook_url='https://your-shop.com/api/shopline/webhook',
233
- description='測試訂單',
234
- customer_email='test@example.com',
235
- customer_phone='0912345678',
236
- items=[
237
- {'name': '測試商品 A', 'quantity': 1, 'unitPrice': {'value': 105000, 'currency': 'TWD'}},
238
- ],
239
- payment_methods=['CARD', 'APPLEPAY', 'LINEPAY'],
240
- )
241
- resp = svc.create_session(data)
242
- if resp.success:
243
- print(f'[OK] sessionId: {resp.session_id}')
244
- print(f'導轉至: {resp.session_url}')
245
- else:
246
- print(f'[FAIL] {resp.error_code}: {resp.error_message}')
247
-
248
-
249
- def example_query_session():
250
- print('\n=== Shopline 查詢會話 ===\n')
251
- svc = ShoplinePaymentService('YOUR_MERCHANT_ID', 'YOUR_API_KEY', is_test=True)
252
- resp = svc.query_session('session_xxxxxxxx')
253
- print(json.dumps(resp.raw, ensure_ascii=False, indent=2))
254
-
255
-
256
- def example_refund():
257
- print('\n=== Shopline 退款 ===\n')
258
- svc = ShoplinePaymentService('YOUR_MERCHANT_ID', 'YOUR_API_KEY', is_test=True)
259
- resp = svc.refund(payment_id='pay_xxxxxxxx', amount_cents=50000, reason='客戶要求退貨')
260
- if resp.success:
261
- print(f'[OK] 退款 paymentId: {resp.payment_id}')
262
- else:
263
- print(f'[FAIL] {resp.error_code}: {resp.error_message}')
264
-
265
-
266
- def example_verify_webhook():
267
- """範例: 驗證 Shopline Webhook"""
268
- print('\n=== Shopline Webhook 驗章 ===\n')
269
- svc = ShoplinePaymentService(
270
- merchant_id='YOUR_MERCHANT_ID',
271
- api_key='YOUR_API_KEY',
272
- webhook_secret='YOUR_WEBHOOK_SECRET', # 後台取得
273
- is_test=True,
274
- )
275
- # 模擬收到的 Webhook
276
- raw_body = b'{"event":"payment.completed","paymentId":"pay_abc123","amount":{"value":105000,"currency":"TWD"}}'
277
- signature_header = 'sha256=abcdef123456' # 實務上由 Shopline 提供於 x-slp-signature header
278
-
279
- is_valid = svc.verify_webhook(raw_body, signature_header)
280
- if is_valid:
281
- evt = json.loads(raw_body)
282
- print(f'[OK] Webhook 驗章通過: event={evt["event"]} paymentId={evt["paymentId"]}')
283
- else:
284
- print('[FAIL] Webhook 簽章無效,可能是仿冒請求')
285
-
286
-
287
- if __name__ == '__main__':
288
- example_redirect_create()
289
- example_query_session()
290
- example_refund()
291
- example_verify_webhook()
1
+ #!/usr/bin/env python3
2
+ """
3
+ Shopline Payments Python 範例
4
+
5
+ 依照 taiwan-payment-skill 規範撰寫。
6
+ SHOPLINE Payments (SLP) 是 SHOPLINE 集團旗下的金流服務,採 RESTful POST + JSON。
7
+
8
+ 支援:
9
+ - Redirect 模式 (sessions/create -> sessionUrl)
10
+ - Embedded SDK 模式 (payment/create)
11
+ - HMAC-SHA256 Webhook 驗證
12
+
13
+ API 文件: 參見 references/shopline-payment-api.md
14
+
15
+ 依賴:
16
+ pip install requests
17
+ """
18
+
19
+ import hashlib
20
+ import hmac
21
+ import json
22
+ import time
23
+ import uuid
24
+ from dataclasses import dataclass, field
25
+ from typing import Dict, List, Literal, Optional
26
+
27
+ import requests
28
+
29
+
30
+ # ============================================================================
31
+ # Data classes
32
+ # ============================================================================
33
+
34
+ @dataclass
35
+ class SessionCreateData:
36
+ """Shopline 建立結帳會話(Redirect 模式)"""
37
+ reference_number: str # 商家訂單編號 (唯一)
38
+ amount_cents: int # 金額(分)— NT$1000 = 100000
39
+ currency: str = 'TWD'
40
+ return_url: str = '' # 完成後導回網址
41
+ cancel_url: str = '' # 取消後導回網址
42
+ webhook_url: str = '' # 通知 URL (HTTPS only)
43
+ description: str = ''
44
+ customer_email: str = ''
45
+ customer_phone: str = ''
46
+ items: List[Dict[str, any]] = field(default_factory=list)
47
+ payment_methods: Optional[List[str]] = None # CARD/APPLEPAY/LINEPAY/JKOPAY/ATM/BNPL
48
+
49
+
50
+ @dataclass
51
+ class ShoplineResponse:
52
+ success: bool
53
+ session_id: str = ''
54
+ session_url: str = ''
55
+ payment_id: str = ''
56
+ status: str = ''
57
+ error_code: str = ''
58
+ error_message: str = ''
59
+ raw: Dict[str, any] = field(default_factory=dict)
60
+
61
+
62
+ # ============================================================================
63
+ # Service
64
+ # ============================================================================
65
+
66
+ class ShoplinePaymentService:
67
+ """
68
+ Shopline Payments 服務.
69
+
70
+ 認證: HTTP headers `merchantId` + `apiKey`.
71
+ 端點:
72
+ - POST /sessions/create — Redirect 模式建立會話
73
+ - GET /sessions/{sessionId} — 查詢會話
74
+ - POST /payment/create — Embedded SDK 提交付款
75
+ - POST /refund/create — 退款
76
+ - POST /capture — 請款(auth + capture 模式)
77
+ - POST /void — 取消授權
78
+ """
79
+
80
+ SANDBOX_BASE = 'https://sandbox-payments-api.shoplineapp.com'
81
+ PROD_BASE = 'https://payments-api.shoplineapp.com'
82
+
83
+ def __init__(self, merchant_id: str, api_key: str, webhook_secret: str = '', is_test: bool = True):
84
+ if not merchant_id or not api_key:
85
+ raise ValueError('Shopline 需要 merchantId 與 apiKey')
86
+ self.merchant_id = merchant_id
87
+ self.api_key = api_key
88
+ self.webhook_secret = webhook_secret
89
+ self.base_url = self.SANDBOX_BASE if is_test else self.PROD_BASE
90
+ self.is_test = is_test
91
+
92
+ @property
93
+ def headers(self) -> Dict[str, str]:
94
+ return {
95
+ 'merchantId': self.merchant_id,
96
+ 'apiKey': self.api_key,
97
+ 'Content-Type': 'application/json',
98
+ 'Accept': 'application/json',
99
+ }
100
+
101
+ # -- Operations -----------------------------------------------------------
102
+
103
+ def create_session(self, data: SessionCreateData) -> ShoplineResponse:
104
+ """Redirect 模式:建立結帳會話"""
105
+ body = {
106
+ 'merchantId': self.merchant_id,
107
+ 'referenceNumber': data.reference_number,
108
+ 'amount': {
109
+ 'value': data.amount_cents, # 已是分
110
+ 'currency': data.currency,
111
+ },
112
+ 'returnUrl': data.return_url,
113
+ 'cancelUrl': data.cancel_url,
114
+ 'webhookUrl': data.webhook_url,
115
+ 'description': data.description,
116
+ 'customer': {
117
+ 'email': data.customer_email,
118
+ 'phone': data.customer_phone,
119
+ },
120
+ 'items': data.items,
121
+ }
122
+ if data.payment_methods:
123
+ body['paymentMethods'] = data.payment_methods
124
+ return self._submit('POST', '/sessions/create', body)
125
+
126
+ def query_session(self, session_id: str) -> ShoplineResponse:
127
+ """查詢結帳會話狀態"""
128
+ return self._submit('GET', f'/sessions/{session_id}', None)
129
+
130
+ def refund(self, payment_id: str, amount_cents: int, reason: str = '') -> ShoplineResponse:
131
+ """退款"""
132
+ body = {
133
+ 'paymentId': payment_id,
134
+ 'amount': {
135
+ 'value': amount_cents,
136
+ 'currency': 'TWD',
137
+ },
138
+ 'reason': reason,
139
+ }
140
+ return self._submit('POST', '/refund/create', body)
141
+
142
+ def capture(self, payment_id: str, amount_cents: int) -> ShoplineResponse:
143
+ """請款 (auth + capture 模式專用)"""
144
+ body = {
145
+ 'paymentId': payment_id,
146
+ 'amount': {'value': amount_cents, 'currency': 'TWD'},
147
+ }
148
+ return self._submit('POST', '/capture', body)
149
+
150
+ def void(self, payment_id: str) -> ShoplineResponse:
151
+ """取消授權"""
152
+ return self._submit('POST', '/void', {'paymentId': payment_id})
153
+
154
+ # -- Webhook --------------------------------------------------------------
155
+
156
+ def verify_webhook(self, payload: bytes, signature_header: str) -> bool:
157
+ """
158
+ 驗證 Shopline Webhook 簽章 (HMAC-SHA256).
159
+
160
+ Shopline 通知時會在 header 帶 `x-slp-signature: sha256=<hex>`,
161
+ 其值為 HMAC-SHA256(secret=webhookSecret, message=raw_body) 的 hex 表示。
162
+ """
163
+ if not self.webhook_secret:
164
+ raise ValueError('未設定 webhookSecret,無法驗章')
165
+
166
+ # 提取 signature header 中的 hex 值
167
+ if signature_header.startswith('sha256='):
168
+ sig_hex = signature_header[7:]
169
+ else:
170
+ sig_hex = signature_header
171
+
172
+ expected = hmac.new(
173
+ self.webhook_secret.encode('utf-8'),
174
+ payload,
175
+ hashlib.sha256,
176
+ ).hexdigest()
177
+
178
+ return hmac.compare_digest(expected.lower(), sig_hex.lower())
179
+
180
+ # -- HTTP submit ----------------------------------------------------------
181
+
182
+ def _submit(self, method: str, path: str, body: Optional[Dict[str, any]]) -> ShoplineResponse:
183
+ url = self.base_url + path
184
+ try:
185
+ if method == 'GET':
186
+ r = requests.get(url, headers=self.headers, timeout=30)
187
+ else:
188
+ r = requests.post(url, headers=self.headers, json=body, timeout=30)
189
+ except requests.exceptions.RequestException as e:
190
+ raise ConnectionError(f'Shopline API 連線失敗: {e}')
191
+
192
+ try:
193
+ resp = r.json()
194
+ except ValueError:
195
+ return ShoplineResponse(
196
+ success=False,
197
+ error_code=str(r.status_code),
198
+ error_message=f'回應非 JSON: {r.text[:200]}',
199
+ )
200
+
201
+ is_success = 200 <= r.status_code < 300
202
+
203
+ return ShoplineResponse(
204
+ success=is_success,
205
+ session_id=resp.get('sessionId', ''),
206
+ session_url=resp.get('sessionUrl', ''),
207
+ payment_id=resp.get('paymentId', resp.get('id', '')),
208
+ status=resp.get('status', ''),
209
+ error_code=str(r.status_code) if not is_success else '',
210
+ error_message=resp.get('message', resp.get('error', '')),
211
+ raw=resp,
212
+ )
213
+
214
+
215
+ # ============================================================================
216
+ # Examples
217
+ # ============================================================================
218
+
219
+ def example_redirect_create():
220
+ print('=== Shopline Redirect 模式建立會話 ===\n')
221
+ svc = ShoplinePaymentService(
222
+ merchant_id='YOUR_MERCHANT_ID',
223
+ api_key='YOUR_API_KEY',
224
+ is_test=True,
225
+ )
226
+ data = SessionCreateData(
227
+ reference_number=f'ORD{int(time.time())}',
228
+ amount_cents=105000, # NT$1050 -> 105000 分
229
+ currency='TWD',
230
+ return_url='https://your-shop.com/order/success',
231
+ cancel_url='https://your-shop.com/order/cancel',
232
+ webhook_url='https://your-shop.com/api/shopline/webhook',
233
+ description='測試訂單',
234
+ customer_email='test@example.com',
235
+ customer_phone='0912345678',
236
+ items=[
237
+ {'name': '測試商品 A', 'quantity': 1, 'unitPrice': {'value': 105000, 'currency': 'TWD'}},
238
+ ],
239
+ payment_methods=['CARD', 'APPLEPAY', 'LINEPAY'],
240
+ )
241
+ resp = svc.create_session(data)
242
+ if resp.success:
243
+ print(f'[OK] sessionId: {resp.session_id}')
244
+ print(f'導轉至: {resp.session_url}')
245
+ else:
246
+ print(f'[FAIL] {resp.error_code}: {resp.error_message}')
247
+
248
+
249
+ def example_query_session():
250
+ print('\n=== Shopline 查詢會話 ===\n')
251
+ svc = ShoplinePaymentService('YOUR_MERCHANT_ID', 'YOUR_API_KEY', is_test=True)
252
+ resp = svc.query_session('session_xxxxxxxx')
253
+ print(json.dumps(resp.raw, ensure_ascii=False, indent=2))
254
+
255
+
256
+ def example_refund():
257
+ print('\n=== Shopline 退款 ===\n')
258
+ svc = ShoplinePaymentService('YOUR_MERCHANT_ID', 'YOUR_API_KEY', is_test=True)
259
+ resp = svc.refund(payment_id='pay_xxxxxxxx', amount_cents=50000, reason='客戶要求退貨')
260
+ if resp.success:
261
+ print(f'[OK] 退款 paymentId: {resp.payment_id}')
262
+ else:
263
+ print(f'[FAIL] {resp.error_code}: {resp.error_message}')
264
+
265
+
266
+ def example_verify_webhook():
267
+ """範例: 驗證 Shopline Webhook"""
268
+ print('\n=== Shopline Webhook 驗章 ===\n')
269
+ svc = ShoplinePaymentService(
270
+ merchant_id='YOUR_MERCHANT_ID',
271
+ api_key='YOUR_API_KEY',
272
+ webhook_secret='YOUR_WEBHOOK_SECRET', # 後台取得
273
+ is_test=True,
274
+ )
275
+ # 模擬收到的 Webhook
276
+ raw_body = b'{"event":"payment.completed","paymentId":"pay_abc123","amount":{"value":105000,"currency":"TWD"}}'
277
+ signature_header = 'sha256=abcdef123456' # 實務上由 Shopline 提供於 x-slp-signature header
278
+
279
+ is_valid = svc.verify_webhook(raw_body, signature_header)
280
+ if is_valid:
281
+ evt = json.loads(raw_body)
282
+ print(f'[OK] Webhook 驗章通過: event={evt["event"]} paymentId={evt["paymentId"]}')
283
+ else:
284
+ print('[FAIL] Webhook 簽章無效,可能是仿冒請求')
285
+
286
+
287
+ if __name__ == '__main__':
288
+ example_redirect_create()
289
+ example_query_session()
290
+ example_refund()
291
+ example_verify_webhook()