taiwan-payment-skill 1.3.0 → 1.3.1

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,305 +1,305 @@
1
- #!/usr/bin/env python3
2
- """
3
- LINE Pay v4 Online API Python 範例
4
-
5
- 依照 taiwan-payment-skill 規範撰寫。
6
- LINE Pay 兩段式流程: Request -> Confirm。
7
-
8
- 支援:
9
- - Request / Confirm
10
- - Capture / Void (autoCapture=false 模式)
11
- - Refund
12
- - Preapproved Pay (自動扣款)
13
-
14
- ⚠️ HMAC string-to-sign 公式為依 v3 慣例推測
15
- (POST: ChannelSecret + ApiPath + Body + Nonce
16
- GET: ChannelSecret + ApiPath + QueryString + Nonce)
17
- 串接前請以官方 v4 PDF 驗證。
18
-
19
- API 文件: 參見 references/linepay-payment-api.md
20
-
21
- 依賴:
22
- pip install requests
23
- """
24
-
25
- import base64
26
- import hashlib
27
- import hmac
28
- import json
29
- import time
30
- import uuid
31
- from dataclasses import dataclass, field
32
- from typing import Dict, List, Literal, Optional
33
-
34
- import requests
35
-
36
-
37
- # ============================================================================
38
- # Data classes
39
- # ============================================================================
40
-
41
- @dataclass
42
- class PaymentRequestData:
43
- """LINE Pay 建立交易資料"""
44
- amount: int # 金額(整數,TWD 不含小數)
45
- currency: str = 'TWD' # TWD / JPY / USD / THB
46
- order_id: str = '' # 商家訂單編號(唯一)
47
- packages: List[Dict[str, any]] = field(default_factory=list)
48
- redirect_confirm_url: str = ''
49
- redirect_cancel_url: str = ''
50
- capture: bool = True # False = 授權 + 後續手動 Capture
51
- product_name: str = ''
52
- options_extra: Optional[Dict[str, any]] = None
53
-
54
-
55
- @dataclass
56
- class LinePayResponse:
57
- success: bool
58
- return_code: str = ''
59
- return_message: str = ''
60
- transaction_id: str = '' # 19 digits — 用字串避免 JS 精度遺失
61
- payment_url_web: str = ''
62
- payment_url_app: str = ''
63
- raw: Dict[str, any] = field(default_factory=dict)
64
-
65
-
66
- # ============================================================================
67
- # Service
68
- # ============================================================================
69
-
70
- class LinePayService:
71
- """
72
- LINE Pay v4 Online API.
73
-
74
- 認證:
75
- - Channel ID + Channel Secret (LINE Pay Merchant Center 申請)
76
- - 每次請求需產生 Nonce (UUID4)
77
- - HMAC-SHA256 簽章放在 X-LINE-Authorization header
78
- - X-LINE-ChannelId / X-LINE-Authorization-Nonce 也是必帶
79
-
80
- 端點:
81
- - POST /v3/payments/request 建立交易
82
- - POST /v3/payments/{transactionId}/confirm 確認付款
83
- - POST /v3/payments/authorizations/{transactionId}/capture 手動請款
84
- - POST /v3/payments/authorizations/{transactionId}/void 取消授權
85
- - POST /v3/payments/{transactionId}/refund 退款
86
- - GET /v3/payments?transactionId=xxx 查詢交易
87
- - POST /v3/payments/preapprovedPay/{regKey}/payment 自動扣款
88
- """
89
-
90
- SANDBOX_BASE = 'https://sandbox-api-pay.line.me'
91
- PROD_BASE = 'https://api-pay.line.me'
92
-
93
- def __init__(self, channel_id: str, channel_secret: str, is_test: bool = True):
94
- if not channel_id or not channel_secret:
95
- raise ValueError('LINE Pay 需要 ChannelId 與 ChannelSecret')
96
- self.channel_id = channel_id
97
- self.channel_secret = channel_secret
98
- self.base_url = self.SANDBOX_BASE if is_test else self.PROD_BASE
99
- self.is_test = is_test
100
-
101
- # -- Signing --------------------------------------------------------------
102
-
103
- def _sign(self, api_path: str, body_or_query: str, nonce: str) -> str:
104
- """
105
- HMAC-SHA256 簽章.
106
-
107
- ⚠️ 公式依 v3 慣例推測:
108
- - POST: ChannelSecret + ApiPath + RequestBody + Nonce
109
- - GET: ChannelSecret + ApiPath + QueryString + Nonce
110
- 輸出 base64.
111
- """
112
- message = self.channel_secret + api_path + body_or_query + nonce
113
- digest = hmac.new(
114
- self.channel_secret.encode('utf-8'),
115
- message.encode('utf-8'),
116
- hashlib.sha256,
117
- ).digest()
118
- return base64.b64encode(digest).decode('utf-8')
119
-
120
- def _headers(self, signature: str, nonce: str) -> Dict[str, str]:
121
- return {
122
- 'Content-Type': 'application/json',
123
- 'X-LINE-ChannelId': self.channel_id,
124
- 'X-LINE-Authorization-Nonce': nonce,
125
- 'X-LINE-Authorization': signature,
126
- }
127
-
128
- # -- Operations -----------------------------------------------------------
129
-
130
- def request_payment(self, data: PaymentRequestData) -> LinePayResponse:
131
- """建立 LINE Pay 交易"""
132
- api_path = '/v3/payments/request'
133
- body = {
134
- 'amount': data.amount,
135
- 'currency': data.currency,
136
- 'orderId': data.order_id or f'ORD{int(time.time())}',
137
- 'packages': data.packages or [{
138
- 'id': 'package-1',
139
- 'amount': data.amount,
140
- 'name': data.product_name or 'Order',
141
- 'products': [{
142
- 'name': data.product_name or 'Item',
143
- 'quantity': 1,
144
- 'price': data.amount,
145
- }],
146
- }],
147
- 'redirectUrls': {
148
- 'confirmUrl': data.redirect_confirm_url,
149
- 'cancelUrl': data.redirect_cancel_url,
150
- },
151
- 'options': {
152
- 'payment': {'capture': data.capture},
153
- **(data.options_extra or {}),
154
- },
155
- }
156
- return self._post(api_path, body)
157
-
158
- def confirm_payment(self, transaction_id: str, amount: int, currency: str = 'TWD') -> LinePayResponse:
159
- """確認付款 (Confirm) — amount/currency 必須與 Request 一致"""
160
- api_path = f'/v3/payments/{transaction_id}/confirm'
161
- body = {'amount': amount, 'currency': currency}
162
- return self._post(api_path, body)
163
-
164
- def capture(self, transaction_id: str, amount: int, currency: str = 'TWD') -> LinePayResponse:
165
- """手動請款 (autoCapture=false 模式)"""
166
- api_path = f'/v3/payments/authorizations/{transaction_id}/capture'
167
- body = {'amount': amount, 'currency': currency}
168
- return self._post(api_path, body)
169
-
170
- def void_auth(self, transaction_id: str) -> LinePayResponse:
171
- """取消授權"""
172
- api_path = f'/v3/payments/authorizations/{transaction_id}/void'
173
- return self._post(api_path, {})
174
-
175
- def refund(self, transaction_id: str, refund_amount: Optional[int] = None) -> LinePayResponse:
176
- """退款 (refund_amount 不填則全額退)"""
177
- api_path = f'/v3/payments/{transaction_id}/refund'
178
- body = {}
179
- if refund_amount is not None:
180
- body['refundAmount'] = refund_amount
181
- return self._post(api_path, body)
182
-
183
- def query_transaction(self, transaction_id: str) -> LinePayResponse:
184
- """查詢交易狀態"""
185
- api_path = '/v3/payments'
186
- query_string = f'transactionId={transaction_id}'
187
- return self._get(api_path, query_string)
188
-
189
- def preapproved_pay(self, reg_key: str, product_name: str, amount: int, order_id: str = '') -> LinePayResponse:
190
- """自動扣款 (Preapproved Pay)"""
191
- api_path = f'/v3/payments/preapprovedPay/{reg_key}/payment'
192
- body = {
193
- 'amount': amount,
194
- 'currency': 'TWD',
195
- 'orderId': order_id or f'AUTO{int(time.time())}',
196
- 'productName': product_name,
197
- }
198
- return self._post(api_path, body)
199
-
200
- # -- HTTP submit ----------------------------------------------------------
201
-
202
- def _post(self, api_path: str, body: Dict[str, any]) -> LinePayResponse:
203
- nonce = str(uuid.uuid4())
204
- body_str = json.dumps(body, ensure_ascii=False, separators=(',', ':'))
205
- signature = self._sign(api_path, body_str, nonce)
206
- url = self.base_url + api_path
207
- try:
208
- r = requests.post(url, headers=self._headers(signature, nonce), data=body_str.encode('utf-8'), timeout=30)
209
- except requests.exceptions.RequestException as e:
210
- raise ConnectionError(f'LINE Pay API 連線失敗: {e}')
211
- return self._parse_response(r)
212
-
213
- def _get(self, api_path: str, query_string: str) -> LinePayResponse:
214
- nonce = str(uuid.uuid4())
215
- signature = self._sign(api_path, query_string, nonce)
216
- url = self.base_url + api_path + '?' + query_string
217
- try:
218
- r = requests.get(url, headers=self._headers(signature, nonce), timeout=30)
219
- except requests.exceptions.RequestException as e:
220
- raise ConnectionError(f'LINE Pay API 連線失敗: {e}')
221
- return self._parse_response(r)
222
-
223
- def _parse_response(self, r: requests.Response) -> LinePayResponse:
224
- try:
225
- resp = r.json()
226
- except ValueError:
227
- return LinePayResponse(success=False, return_code=str(r.status_code), return_message=r.text[:200])
228
-
229
- return_code = resp.get('returnCode', '')
230
- is_success = (return_code == '0000') and r.status_code < 400
231
-
232
- info = resp.get('info', {}) or {}
233
- payment_url = info.get('paymentUrl', {}) or {}
234
-
235
- return LinePayResponse(
236
- success=is_success,
237
- return_code=return_code,
238
- return_message=resp.get('returnMessage', ''),
239
- transaction_id=str(info.get('transactionId', '')), # 19-digit, keep as string
240
- payment_url_web=payment_url.get('web', ''),
241
- payment_url_app=payment_url.get('app', ''),
242
- raw=resp,
243
- )
244
-
245
-
246
- # ============================================================================
247
- # Examples
248
- # ============================================================================
249
-
250
- def example_payment_request():
251
- print('=== LINE Pay 建立交易 ===\n')
252
- svc = LinePayService(channel_id='YOUR_CHANNEL_ID', channel_secret='YOUR_CHANNEL_SECRET', is_test=True)
253
- resp = svc.request_payment(PaymentRequestData(
254
- amount=1050,
255
- currency='TWD',
256
- order_id=f'ORD{int(time.time())}',
257
- product_name='測試商品',
258
- redirect_confirm_url='https://your-shop.com/linepay/confirm',
259
- redirect_cancel_url='https://your-shop.com/linepay/cancel',
260
- ))
261
- if resp.success:
262
- print(f'[OK] transactionId: {resp.transaction_id}')
263
- print(f'web URL: {resp.payment_url_web}')
264
- print(f'app URL: {resp.payment_url_app}')
265
- else:
266
- print(f'[FAIL] {resp.return_code}: {resp.return_message}')
267
-
268
-
269
- def example_payment_confirm():
270
- print('\n=== LINE Pay 確認交易 ===\n')
271
- svc = LinePayService('YOUR_CHANNEL_ID', 'YOUR_CHANNEL_SECRET', is_test=True)
272
- # transactionId 來自 redirectUrls.confirmUrl 的 query param
273
- resp = svc.confirm_payment(transaction_id='2024010100000000001', amount=1050, currency='TWD')
274
- if resp.success:
275
- print(f'[OK] 付款成功: {json.dumps(resp.raw, ensure_ascii=False)}')
276
- else:
277
- print(f'[FAIL] {resp.return_code}: {resp.return_message}')
278
-
279
-
280
- def example_refund():
281
- print('\n=== LINE Pay 退款 ===\n')
282
- svc = LinePayService('YOUR_CHANNEL_ID', 'YOUR_CHANNEL_SECRET', is_test=True)
283
- resp = svc.refund(transaction_id='2024010100000000001', refund_amount=500) # 部分退款 NT$500
284
- if resp.success:
285
- print('[OK] 退款成功')
286
- else:
287
- print(f'[FAIL] {resp.return_code}: {resp.return_message}')
288
-
289
-
290
- def example_preapproved_pay():
291
- print('\n=== LINE Pay 自動扣款 ===\n')
292
- svc = LinePayService('YOUR_CHANNEL_ID', 'YOUR_CHANNEL_SECRET', is_test=True)
293
- # regKey 是當初 Request 時帶 options.payment.payType=PREAPPROVED 取得
294
- resp = svc.preapproved_pay(reg_key='regkey-abc', product_name='月費訂閱', amount=199)
295
- if resp.success:
296
- print(f'[OK] 自動扣款成功: transactionId={resp.transaction_id}')
297
- else:
298
- print(f'[FAIL] {resp.return_code}: {resp.return_message}')
299
-
300
-
301
- if __name__ == '__main__':
302
- example_payment_request()
303
- example_payment_confirm()
304
- example_refund()
305
- example_preapproved_pay()
1
+ #!/usr/bin/env python3
2
+ """
3
+ LINE Pay v4 Online API Python 範例
4
+
5
+ 依照 taiwan-payment-skill 規範撰寫。
6
+ LINE Pay 兩段式流程: Request -> Confirm。
7
+
8
+ 支援:
9
+ - Request / Confirm
10
+ - Capture / Void (autoCapture=false 模式)
11
+ - Refund
12
+ - Preapproved Pay (自動扣款)
13
+
14
+ ⚠️ HMAC string-to-sign 公式為依 v3 慣例推測
15
+ (POST: ChannelSecret + ApiPath + Body + Nonce
16
+ GET: ChannelSecret + ApiPath + QueryString + Nonce)
17
+ 串接前請以官方 v4 PDF 驗證。
18
+
19
+ API 文件: 參見 references/linepay-payment-api.md
20
+
21
+ 依賴:
22
+ pip install requests
23
+ """
24
+
25
+ import base64
26
+ import hashlib
27
+ import hmac
28
+ import json
29
+ import time
30
+ import uuid
31
+ from dataclasses import dataclass, field
32
+ from typing import Dict, List, Literal, Optional
33
+
34
+ import requests
35
+
36
+
37
+ # ============================================================================
38
+ # Data classes
39
+ # ============================================================================
40
+
41
+ @dataclass
42
+ class PaymentRequestData:
43
+ """LINE Pay 建立交易資料"""
44
+ amount: int # 金額(整數,TWD 不含小數)
45
+ currency: str = 'TWD' # TWD / JPY / USD / THB
46
+ order_id: str = '' # 商家訂單編號(唯一)
47
+ packages: List[Dict[str, any]] = field(default_factory=list)
48
+ redirect_confirm_url: str = ''
49
+ redirect_cancel_url: str = ''
50
+ capture: bool = True # False = 授權 + 後續手動 Capture
51
+ product_name: str = ''
52
+ options_extra: Optional[Dict[str, any]] = None
53
+
54
+
55
+ @dataclass
56
+ class LinePayResponse:
57
+ success: bool
58
+ return_code: str = ''
59
+ return_message: str = ''
60
+ transaction_id: str = '' # 19 digits — 用字串避免 JS 精度遺失
61
+ payment_url_web: str = ''
62
+ payment_url_app: str = ''
63
+ raw: Dict[str, any] = field(default_factory=dict)
64
+
65
+
66
+ # ============================================================================
67
+ # Service
68
+ # ============================================================================
69
+
70
+ class LinePayService:
71
+ """
72
+ LINE Pay v4 Online API.
73
+
74
+ 認證:
75
+ - Channel ID + Channel Secret (LINE Pay Merchant Center 申請)
76
+ - 每次請求需產生 Nonce (UUID4)
77
+ - HMAC-SHA256 簽章放在 X-LINE-Authorization header
78
+ - X-LINE-ChannelId / X-LINE-Authorization-Nonce 也是必帶
79
+
80
+ 端點:
81
+ - POST /v3/payments/request 建立交易
82
+ - POST /v3/payments/{transactionId}/confirm 確認付款
83
+ - POST /v3/payments/authorizations/{transactionId}/capture 手動請款
84
+ - POST /v3/payments/authorizations/{transactionId}/void 取消授權
85
+ - POST /v3/payments/{transactionId}/refund 退款
86
+ - GET /v3/payments?transactionId=xxx 查詢交易
87
+ - POST /v3/payments/preapprovedPay/{regKey}/payment 自動扣款
88
+ """
89
+
90
+ SANDBOX_BASE = 'https://sandbox-api-pay.line.me'
91
+ PROD_BASE = 'https://api-pay.line.me'
92
+
93
+ def __init__(self, channel_id: str, channel_secret: str, is_test: bool = True):
94
+ if not channel_id or not channel_secret:
95
+ raise ValueError('LINE Pay 需要 ChannelId 與 ChannelSecret')
96
+ self.channel_id = channel_id
97
+ self.channel_secret = channel_secret
98
+ self.base_url = self.SANDBOX_BASE if is_test else self.PROD_BASE
99
+ self.is_test = is_test
100
+
101
+ # -- Signing --------------------------------------------------------------
102
+
103
+ def _sign(self, api_path: str, body_or_query: str, nonce: str) -> str:
104
+ """
105
+ HMAC-SHA256 簽章.
106
+
107
+ ⚠️ 公式依 v3 慣例推測:
108
+ - POST: ChannelSecret + ApiPath + RequestBody + Nonce
109
+ - GET: ChannelSecret + ApiPath + QueryString + Nonce
110
+ 輸出 base64.
111
+ """
112
+ message = self.channel_secret + api_path + body_or_query + nonce
113
+ digest = hmac.new(
114
+ self.channel_secret.encode('utf-8'),
115
+ message.encode('utf-8'),
116
+ hashlib.sha256,
117
+ ).digest()
118
+ return base64.b64encode(digest).decode('utf-8')
119
+
120
+ def _headers(self, signature: str, nonce: str) -> Dict[str, str]:
121
+ return {
122
+ 'Content-Type': 'application/json',
123
+ 'X-LINE-ChannelId': self.channel_id,
124
+ 'X-LINE-Authorization-Nonce': nonce,
125
+ 'X-LINE-Authorization': signature,
126
+ }
127
+
128
+ # -- Operations -----------------------------------------------------------
129
+
130
+ def request_payment(self, data: PaymentRequestData) -> LinePayResponse:
131
+ """建立 LINE Pay 交易"""
132
+ api_path = '/v3/payments/request'
133
+ body = {
134
+ 'amount': data.amount,
135
+ 'currency': data.currency,
136
+ 'orderId': data.order_id or f'ORD{int(time.time())}',
137
+ 'packages': data.packages or [{
138
+ 'id': 'package-1',
139
+ 'amount': data.amount,
140
+ 'name': data.product_name or 'Order',
141
+ 'products': [{
142
+ 'name': data.product_name or 'Item',
143
+ 'quantity': 1,
144
+ 'price': data.amount,
145
+ }],
146
+ }],
147
+ 'redirectUrls': {
148
+ 'confirmUrl': data.redirect_confirm_url,
149
+ 'cancelUrl': data.redirect_cancel_url,
150
+ },
151
+ 'options': {
152
+ 'payment': {'capture': data.capture},
153
+ **(data.options_extra or {}),
154
+ },
155
+ }
156
+ return self._post(api_path, body)
157
+
158
+ def confirm_payment(self, transaction_id: str, amount: int, currency: str = 'TWD') -> LinePayResponse:
159
+ """確認付款 (Confirm) — amount/currency 必須與 Request 一致"""
160
+ api_path = f'/v3/payments/{transaction_id}/confirm'
161
+ body = {'amount': amount, 'currency': currency}
162
+ return self._post(api_path, body)
163
+
164
+ def capture(self, transaction_id: str, amount: int, currency: str = 'TWD') -> LinePayResponse:
165
+ """手動請款 (autoCapture=false 模式)"""
166
+ api_path = f'/v3/payments/authorizations/{transaction_id}/capture'
167
+ body = {'amount': amount, 'currency': currency}
168
+ return self._post(api_path, body)
169
+
170
+ def void_auth(self, transaction_id: str) -> LinePayResponse:
171
+ """取消授權"""
172
+ api_path = f'/v3/payments/authorizations/{transaction_id}/void'
173
+ return self._post(api_path, {})
174
+
175
+ def refund(self, transaction_id: str, refund_amount: Optional[int] = None) -> LinePayResponse:
176
+ """退款 (refund_amount 不填則全額退)"""
177
+ api_path = f'/v3/payments/{transaction_id}/refund'
178
+ body = {}
179
+ if refund_amount is not None:
180
+ body['refundAmount'] = refund_amount
181
+ return self._post(api_path, body)
182
+
183
+ def query_transaction(self, transaction_id: str) -> LinePayResponse:
184
+ """查詢交易狀態"""
185
+ api_path = '/v3/payments'
186
+ query_string = f'transactionId={transaction_id}'
187
+ return self._get(api_path, query_string)
188
+
189
+ def preapproved_pay(self, reg_key: str, product_name: str, amount: int, order_id: str = '') -> LinePayResponse:
190
+ """自動扣款 (Preapproved Pay)"""
191
+ api_path = f'/v3/payments/preapprovedPay/{reg_key}/payment'
192
+ body = {
193
+ 'amount': amount,
194
+ 'currency': 'TWD',
195
+ 'orderId': order_id or f'AUTO{int(time.time())}',
196
+ 'productName': product_name,
197
+ }
198
+ return self._post(api_path, body)
199
+
200
+ # -- HTTP submit ----------------------------------------------------------
201
+
202
+ def _post(self, api_path: str, body: Dict[str, any]) -> LinePayResponse:
203
+ nonce = str(uuid.uuid4())
204
+ body_str = json.dumps(body, ensure_ascii=False, separators=(',', ':'))
205
+ signature = self._sign(api_path, body_str, nonce)
206
+ url = self.base_url + api_path
207
+ try:
208
+ r = requests.post(url, headers=self._headers(signature, nonce), data=body_str.encode('utf-8'), timeout=30)
209
+ except requests.exceptions.RequestException as e:
210
+ raise ConnectionError(f'LINE Pay API 連線失敗: {e}')
211
+ return self._parse_response(r)
212
+
213
+ def _get(self, api_path: str, query_string: str) -> LinePayResponse:
214
+ nonce = str(uuid.uuid4())
215
+ signature = self._sign(api_path, query_string, nonce)
216
+ url = self.base_url + api_path + '?' + query_string
217
+ try:
218
+ r = requests.get(url, headers=self._headers(signature, nonce), timeout=30)
219
+ except requests.exceptions.RequestException as e:
220
+ raise ConnectionError(f'LINE Pay API 連線失敗: {e}')
221
+ return self._parse_response(r)
222
+
223
+ def _parse_response(self, r: requests.Response) -> LinePayResponse:
224
+ try:
225
+ resp = r.json()
226
+ except ValueError:
227
+ return LinePayResponse(success=False, return_code=str(r.status_code), return_message=r.text[:200])
228
+
229
+ return_code = resp.get('returnCode', '')
230
+ is_success = (return_code == '0000') and r.status_code < 400
231
+
232
+ info = resp.get('info', {}) or {}
233
+ payment_url = info.get('paymentUrl', {}) or {}
234
+
235
+ return LinePayResponse(
236
+ success=is_success,
237
+ return_code=return_code,
238
+ return_message=resp.get('returnMessage', ''),
239
+ transaction_id=str(info.get('transactionId', '')), # 19-digit, keep as string
240
+ payment_url_web=payment_url.get('web', ''),
241
+ payment_url_app=payment_url.get('app', ''),
242
+ raw=resp,
243
+ )
244
+
245
+
246
+ # ============================================================================
247
+ # Examples
248
+ # ============================================================================
249
+
250
+ def example_payment_request():
251
+ print('=== LINE Pay 建立交易 ===\n')
252
+ svc = LinePayService(channel_id='YOUR_CHANNEL_ID', channel_secret='YOUR_CHANNEL_SECRET', is_test=True)
253
+ resp = svc.request_payment(PaymentRequestData(
254
+ amount=1050,
255
+ currency='TWD',
256
+ order_id=f'ORD{int(time.time())}',
257
+ product_name='測試商品',
258
+ redirect_confirm_url='https://your-shop.com/linepay/confirm',
259
+ redirect_cancel_url='https://your-shop.com/linepay/cancel',
260
+ ))
261
+ if resp.success:
262
+ print(f'[OK] transactionId: {resp.transaction_id}')
263
+ print(f'web URL: {resp.payment_url_web}')
264
+ print(f'app URL: {resp.payment_url_app}')
265
+ else:
266
+ print(f'[FAIL] {resp.return_code}: {resp.return_message}')
267
+
268
+
269
+ def example_payment_confirm():
270
+ print('\n=== LINE Pay 確認交易 ===\n')
271
+ svc = LinePayService('YOUR_CHANNEL_ID', 'YOUR_CHANNEL_SECRET', is_test=True)
272
+ # transactionId 來自 redirectUrls.confirmUrl 的 query param
273
+ resp = svc.confirm_payment(transaction_id='2024010100000000001', amount=1050, currency='TWD')
274
+ if resp.success:
275
+ print(f'[OK] 付款成功: {json.dumps(resp.raw, ensure_ascii=False)}')
276
+ else:
277
+ print(f'[FAIL] {resp.return_code}: {resp.return_message}')
278
+
279
+
280
+ def example_refund():
281
+ print('\n=== LINE Pay 退款 ===\n')
282
+ svc = LinePayService('YOUR_CHANNEL_ID', 'YOUR_CHANNEL_SECRET', is_test=True)
283
+ resp = svc.refund(transaction_id='2024010100000000001', refund_amount=500) # 部分退款 NT$500
284
+ if resp.success:
285
+ print('[OK] 退款成功')
286
+ else:
287
+ print(f'[FAIL] {resp.return_code}: {resp.return_message}')
288
+
289
+
290
+ def example_preapproved_pay():
291
+ print('\n=== LINE Pay 自動扣款 ===\n')
292
+ svc = LinePayService('YOUR_CHANNEL_ID', 'YOUR_CHANNEL_SECRET', is_test=True)
293
+ # regKey 是當初 Request 時帶 options.payment.payType=PREAPPROVED 取得
294
+ resp = svc.preapproved_pay(reg_key='regkey-abc', product_name='月費訂閱', amount=199)
295
+ if resp.success:
296
+ print(f'[OK] 自動扣款成功: transactionId={resp.transaction_id}')
297
+ else:
298
+ print(f'[FAIL] {resp.return_code}: {resp.return_message}')
299
+
300
+
301
+ if __name__ == '__main__':
302
+ example_payment_request()
303
+ example_payment_confirm()
304
+ example_refund()
305
+ example_preapproved_pay()