bebebus-merchant-openapi-sdk 2.2.0__tar.gz → 2.3.0__tar.gz
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.
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/PKG-INFO +17 -10
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/README.md +12 -5
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/bebebus_merchant_openapi_sdk.egg-info/PKG-INFO +17 -10
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/bebebus_merchant_openapi_sdk.egg-info/SOURCES.txt +2 -1
- bebebus_merchant_openapi_sdk-2.3.0/bebebus_merchant_openapi_sdk.egg-info/requires.txt +3 -0
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/openapi_sdk/__init__.py +4 -2
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/openapi_sdk/client.py +113 -13
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/openapi_sdk/config.py +2 -0
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/openapi_sdk/exceptions.py +14 -3
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/openapi_sdk/payout_precheck.py +2 -0
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/openapi_sdk/signer.py +22 -4
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/pyproject.toml +5 -5
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/tests/test_appendix.py +6 -2
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/tests/test_client.py +80 -3
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/tests/test_payout_precheck.py +2 -0
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/tests/test_signer.py +19 -0
- bebebus_merchant_openapi_sdk-2.3.0/tests/test_transport.py +149 -0
- bebebus_merchant_openapi_sdk-2.2.0/bebebus_merchant_openapi_sdk.egg-info/requires.txt +0 -3
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/LICENSE +0 -0
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/bebebus_merchant_openapi_sdk.egg-info/dependency_links.txt +0 -0
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/bebebus_merchant_openapi_sdk.egg-info/top_level.txt +0 -0
- {bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/setup.cfg +0 -0
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: bebebus-merchant-openapi-sdk
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.0
|
|
4
4
|
Summary: 商户支付 OpenAPI Python SDK(零第三方依赖)
|
|
5
5
|
Author: bebebus
|
|
6
6
|
License: MIT
|
|
7
|
-
Project-URL: Homepage, https://github.com/bebebus/
|
|
8
|
-
Project-URL: Repository, https://github.com/bebebus/
|
|
9
|
-
Project-URL: Issues, https://github.com/bebebus/
|
|
7
|
+
Project-URL: Homepage, https://github.com/bebebus/payment-openapi-sdk/tree/main/python
|
|
8
|
+
Project-URL: Repository, https://github.com/bebebus/payment-openapi-sdk
|
|
9
|
+
Project-URL: Issues, https://github.com/bebebus/payment-openapi-sdk/issues
|
|
10
10
|
Keywords: payment,openapi,merchant,sdk
|
|
11
11
|
Classifier: Programming Language :: Python :: 3
|
|
12
12
|
Classifier: License :: OSI Approved :: MIT License
|
|
@@ -15,7 +15,7 @@ Requires-Python: >=3.8
|
|
|
15
15
|
Description-Content-Type: text/markdown
|
|
16
16
|
License-File: LICENSE
|
|
17
17
|
Provides-Extra: dev
|
|
18
|
-
Requires-Dist: ruff==0.17.
|
|
18
|
+
Requires-Dist: ruff==0.17.4; extra == "dev"
|
|
19
19
|
Dynamic: license-file
|
|
20
20
|
|
|
21
21
|
> 中文 | [English](./README.en.md)
|
|
@@ -91,7 +91,7 @@ config = Config(
|
|
|
91
91
|
)
|
|
92
92
|
```
|
|
93
93
|
|
|
94
|
-
## 全部
|
|
94
|
+
## 全部 15 个端点
|
|
95
95
|
|
|
96
96
|
代收(密钥 `api_secret_pay`,自动选用):
|
|
97
97
|
|
|
@@ -99,7 +99,7 @@ config = Config(
|
|
|
99
99
|
|------|------|
|
|
100
100
|
| `pay_create(...)` | `/merchant/pay/create` |
|
|
101
101
|
| `pay_query(order_no=, out_order_no=)` | `/merchant/pay/query` |
|
|
102
|
-
| `pay_methods_query(country
|
|
102
|
+
| `pay_methods_query(country=)` | `/merchant/pay-methods/query` |
|
|
103
103
|
| `groups_query(biz_type=, currency=, country=)` | `/merchant/groups/query`(兼容别名) |
|
|
104
104
|
| `countries_query()` | `/merchant/countries/query` |
|
|
105
105
|
| `balance_query(currency=)` | `/merchant/balance/query` |
|
|
@@ -116,13 +116,20 @@ config = Config(
|
|
|
116
116
|
| `payout_receipt_query(..., inline=)` | `/merchant/payout/receipt/query` |
|
|
117
117
|
| `payout_test_complete(result=, ...)` | `/merchant/payout/test/complete`(仅测试密钥) |
|
|
118
118
|
|
|
119
|
+
工单(密钥 `api_secret_pay`,自动选用;对应代付单时也用此密钥):
|
|
120
|
+
|
|
121
|
+
| 方法 | 端点 |
|
|
122
|
+
|------|------|
|
|
123
|
+
| `issue_ticket_create(order_no=, ...)` | `/merchant/issue-ticket/create` |
|
|
124
|
+
| `issue_ticket_query(ticket_no=, order_no=)` | `/merchant/issue-ticket/query` |
|
|
125
|
+
|
|
119
126
|
约定:
|
|
120
127
|
|
|
121
128
|
- 每请求自动注入 `merchant_no`/`api_key`/`timestamp`(Unix 秒)/唯一 `nonce` 与 `sign`。
|
|
122
129
|
- 值为 `None` 的参数不放入请求体、也不参与签名。
|
|
123
130
|
- `payout_receipt_query` 的 `inline` 以整数 **1/0** 发送(`True`→1 内联 base64 图片;`False`→0 返回带 token 的 URL)。
|
|
124
131
|
- 金额是最小单位整数(`10000 = 1 元`),用 `int` 类型传入。
|
|
125
|
-
- 成功返回 `data`(dict);`code != 0`
|
|
132
|
+
- 成功返回 `data`(dict);`code != 0`(含 HTTP 503+`300304`、HTTP 500+`300302` 等非 2xx 业务信封)抛 `ApiError`(携带 `code`/`message`/`data`/`status_code`);HTTP/网络错误抛 `TransportError`(附带 `request_sign`)。
|
|
126
133
|
- 需要原始信封时用 `client.call_raw(path, body, secret)`(不因 `code != 0` 抛异常)。
|
|
127
134
|
|
|
128
135
|
## 签名工具(可单独使用)
|
|
@@ -137,11 +144,11 @@ ok = verify_callback(callback, secret) # 时序安全(hmac.compare_digest
|
|
|
137
144
|
|
|
138
145
|
## 回调验签 + 处理
|
|
139
146
|
|
|
140
|
-
见 [`examples/callback_verify.py`](examples/callback_verify.py):解析原始 body → `verify_callback
|
|
147
|
+
见 [`examples/callback_verify.py`](examples/callback_verify.py):解析原始 body → `client.verify_pay_callback` / `client.verify_payout_callback` / `client.verify_issue_ticket_callback`(或顶层 `verify_callback`,时序安全)→ 按 `status` 幂等处理(success/failed)→ 应答 **HTTP 200 + 纯文本 `success`**。代收/退款/工单回复回调用 `api_secret_pay`、代付回调用 `api_secret_payout`,示例各演示一次。验签失败不回成功;同一订单可能再次收到回调。处理务必幂等(同一订单可能多次回调)。
|
|
141
148
|
|
|
142
149
|
## 代付反查
|
|
143
150
|
|
|
144
|
-
平台审核时向商户自己的 HTTPS 地址 POST JSON。`decide_payout_precheck(body, saved)` 的返回值原样作为 HTTP 200 正文,只能是 `approve` 或 `reject`。`saved["sign"]` 用代付下单返回数据上的 `.sign
|
|
151
|
+
平台审核时向商户自己的 HTTPS 地址 POST JSON。`decide_payout_precheck(body, saved)` 的返回值原样作为 HTTP 200 正文,只能是 `approve` 或 `reject`。`saved["sign"]` 用代付下单返回数据上的 `.sign`(若下单遇传输超时,可从 `TransportError.request_sign` 读取本次实际发出的 `sign`)。`payout_no` 必须出现,但不与下单请求比较。
|
|
145
152
|
|
|
146
153
|
```python
|
|
147
154
|
from openapi_sdk import decide_payout_precheck
|
|
@@ -71,7 +71,7 @@ config = Config(
|
|
|
71
71
|
)
|
|
72
72
|
```
|
|
73
73
|
|
|
74
|
-
## 全部
|
|
74
|
+
## 全部 15 个端点
|
|
75
75
|
|
|
76
76
|
代收(密钥 `api_secret_pay`,自动选用):
|
|
77
77
|
|
|
@@ -79,7 +79,7 @@ config = Config(
|
|
|
79
79
|
|------|------|
|
|
80
80
|
| `pay_create(...)` | `/merchant/pay/create` |
|
|
81
81
|
| `pay_query(order_no=, out_order_no=)` | `/merchant/pay/query` |
|
|
82
|
-
| `pay_methods_query(country
|
|
82
|
+
| `pay_methods_query(country=)` | `/merchant/pay-methods/query` |
|
|
83
83
|
| `groups_query(biz_type=, currency=, country=)` | `/merchant/groups/query`(兼容别名) |
|
|
84
84
|
| `countries_query()` | `/merchant/countries/query` |
|
|
85
85
|
| `balance_query(currency=)` | `/merchant/balance/query` |
|
|
@@ -96,13 +96,20 @@ config = Config(
|
|
|
96
96
|
| `payout_receipt_query(..., inline=)` | `/merchant/payout/receipt/query` |
|
|
97
97
|
| `payout_test_complete(result=, ...)` | `/merchant/payout/test/complete`(仅测试密钥) |
|
|
98
98
|
|
|
99
|
+
工单(密钥 `api_secret_pay`,自动选用;对应代付单时也用此密钥):
|
|
100
|
+
|
|
101
|
+
| 方法 | 端点 |
|
|
102
|
+
|------|------|
|
|
103
|
+
| `issue_ticket_create(order_no=, ...)` | `/merchant/issue-ticket/create` |
|
|
104
|
+
| `issue_ticket_query(ticket_no=, order_no=)` | `/merchant/issue-ticket/query` |
|
|
105
|
+
|
|
99
106
|
约定:
|
|
100
107
|
|
|
101
108
|
- 每请求自动注入 `merchant_no`/`api_key`/`timestamp`(Unix 秒)/唯一 `nonce` 与 `sign`。
|
|
102
109
|
- 值为 `None` 的参数不放入请求体、也不参与签名。
|
|
103
110
|
- `payout_receipt_query` 的 `inline` 以整数 **1/0** 发送(`True`→1 内联 base64 图片;`False`→0 返回带 token 的 URL)。
|
|
104
111
|
- 金额是最小单位整数(`10000 = 1 元`),用 `int` 类型传入。
|
|
105
|
-
- 成功返回 `data`(dict);`code != 0`
|
|
112
|
+
- 成功返回 `data`(dict);`code != 0`(含 HTTP 503+`300304`、HTTP 500+`300302` 等非 2xx 业务信封)抛 `ApiError`(携带 `code`/`message`/`data`/`status_code`);HTTP/网络错误抛 `TransportError`(附带 `request_sign`)。
|
|
106
113
|
- 需要原始信封时用 `client.call_raw(path, body, secret)`(不因 `code != 0` 抛异常)。
|
|
107
114
|
|
|
108
115
|
## 签名工具(可单独使用)
|
|
@@ -117,11 +124,11 @@ ok = verify_callback(callback, secret) # 时序安全(hmac.compare_digest
|
|
|
117
124
|
|
|
118
125
|
## 回调验签 + 处理
|
|
119
126
|
|
|
120
|
-
见 [`examples/callback_verify.py`](examples/callback_verify.py):解析原始 body → `verify_callback
|
|
127
|
+
见 [`examples/callback_verify.py`](examples/callback_verify.py):解析原始 body → `client.verify_pay_callback` / `client.verify_payout_callback` / `client.verify_issue_ticket_callback`(或顶层 `verify_callback`,时序安全)→ 按 `status` 幂等处理(success/failed)→ 应答 **HTTP 200 + 纯文本 `success`**。代收/退款/工单回复回调用 `api_secret_pay`、代付回调用 `api_secret_payout`,示例各演示一次。验签失败不回成功;同一订单可能再次收到回调。处理务必幂等(同一订单可能多次回调)。
|
|
121
128
|
|
|
122
129
|
## 代付反查
|
|
123
130
|
|
|
124
|
-
平台审核时向商户自己的 HTTPS 地址 POST JSON。`decide_payout_precheck(body, saved)` 的返回值原样作为 HTTP 200 正文,只能是 `approve` 或 `reject`。`saved["sign"]` 用代付下单返回数据上的 `.sign
|
|
131
|
+
平台审核时向商户自己的 HTTPS 地址 POST JSON。`decide_payout_precheck(body, saved)` 的返回值原样作为 HTTP 200 正文,只能是 `approve` 或 `reject`。`saved["sign"]` 用代付下单返回数据上的 `.sign`(若下单遇传输超时,可从 `TransportError.request_sign` 读取本次实际发出的 `sign`)。`payout_no` 必须出现,但不与下单请求比较。
|
|
125
132
|
|
|
126
133
|
```python
|
|
127
134
|
from openapi_sdk import decide_payout_precheck
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: bebebus-merchant-openapi-sdk
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.0
|
|
4
4
|
Summary: 商户支付 OpenAPI Python SDK(零第三方依赖)
|
|
5
5
|
Author: bebebus
|
|
6
6
|
License: MIT
|
|
7
|
-
Project-URL: Homepage, https://github.com/bebebus/
|
|
8
|
-
Project-URL: Repository, https://github.com/bebebus/
|
|
9
|
-
Project-URL: Issues, https://github.com/bebebus/
|
|
7
|
+
Project-URL: Homepage, https://github.com/bebebus/payment-openapi-sdk/tree/main/python
|
|
8
|
+
Project-URL: Repository, https://github.com/bebebus/payment-openapi-sdk
|
|
9
|
+
Project-URL: Issues, https://github.com/bebebus/payment-openapi-sdk/issues
|
|
10
10
|
Keywords: payment,openapi,merchant,sdk
|
|
11
11
|
Classifier: Programming Language :: Python :: 3
|
|
12
12
|
Classifier: License :: OSI Approved :: MIT License
|
|
@@ -15,7 +15,7 @@ Requires-Python: >=3.8
|
|
|
15
15
|
Description-Content-Type: text/markdown
|
|
16
16
|
License-File: LICENSE
|
|
17
17
|
Provides-Extra: dev
|
|
18
|
-
Requires-Dist: ruff==0.17.
|
|
18
|
+
Requires-Dist: ruff==0.17.4; extra == "dev"
|
|
19
19
|
Dynamic: license-file
|
|
20
20
|
|
|
21
21
|
> 中文 | [English](./README.en.md)
|
|
@@ -91,7 +91,7 @@ config = Config(
|
|
|
91
91
|
)
|
|
92
92
|
```
|
|
93
93
|
|
|
94
|
-
## 全部
|
|
94
|
+
## 全部 15 个端点
|
|
95
95
|
|
|
96
96
|
代收(密钥 `api_secret_pay`,自动选用):
|
|
97
97
|
|
|
@@ -99,7 +99,7 @@ config = Config(
|
|
|
99
99
|
|------|------|
|
|
100
100
|
| `pay_create(...)` | `/merchant/pay/create` |
|
|
101
101
|
| `pay_query(order_no=, out_order_no=)` | `/merchant/pay/query` |
|
|
102
|
-
| `pay_methods_query(country
|
|
102
|
+
| `pay_methods_query(country=)` | `/merchant/pay-methods/query` |
|
|
103
103
|
| `groups_query(biz_type=, currency=, country=)` | `/merchant/groups/query`(兼容别名) |
|
|
104
104
|
| `countries_query()` | `/merchant/countries/query` |
|
|
105
105
|
| `balance_query(currency=)` | `/merchant/balance/query` |
|
|
@@ -116,13 +116,20 @@ config = Config(
|
|
|
116
116
|
| `payout_receipt_query(..., inline=)` | `/merchant/payout/receipt/query` |
|
|
117
117
|
| `payout_test_complete(result=, ...)` | `/merchant/payout/test/complete`(仅测试密钥) |
|
|
118
118
|
|
|
119
|
+
工单(密钥 `api_secret_pay`,自动选用;对应代付单时也用此密钥):
|
|
120
|
+
|
|
121
|
+
| 方法 | 端点 |
|
|
122
|
+
|------|------|
|
|
123
|
+
| `issue_ticket_create(order_no=, ...)` | `/merchant/issue-ticket/create` |
|
|
124
|
+
| `issue_ticket_query(ticket_no=, order_no=)` | `/merchant/issue-ticket/query` |
|
|
125
|
+
|
|
119
126
|
约定:
|
|
120
127
|
|
|
121
128
|
- 每请求自动注入 `merchant_no`/`api_key`/`timestamp`(Unix 秒)/唯一 `nonce` 与 `sign`。
|
|
122
129
|
- 值为 `None` 的参数不放入请求体、也不参与签名。
|
|
123
130
|
- `payout_receipt_query` 的 `inline` 以整数 **1/0** 发送(`True`→1 内联 base64 图片;`False`→0 返回带 token 的 URL)。
|
|
124
131
|
- 金额是最小单位整数(`10000 = 1 元`),用 `int` 类型传入。
|
|
125
|
-
- 成功返回 `data`(dict);`code != 0`
|
|
132
|
+
- 成功返回 `data`(dict);`code != 0`(含 HTTP 503+`300304`、HTTP 500+`300302` 等非 2xx 业务信封)抛 `ApiError`(携带 `code`/`message`/`data`/`status_code`);HTTP/网络错误抛 `TransportError`(附带 `request_sign`)。
|
|
126
133
|
- 需要原始信封时用 `client.call_raw(path, body, secret)`(不因 `code != 0` 抛异常)。
|
|
127
134
|
|
|
128
135
|
## 签名工具(可单独使用)
|
|
@@ -137,11 +144,11 @@ ok = verify_callback(callback, secret) # 时序安全(hmac.compare_digest
|
|
|
137
144
|
|
|
138
145
|
## 回调验签 + 处理
|
|
139
146
|
|
|
140
|
-
见 [`examples/callback_verify.py`](examples/callback_verify.py):解析原始 body → `verify_callback
|
|
147
|
+
见 [`examples/callback_verify.py`](examples/callback_verify.py):解析原始 body → `client.verify_pay_callback` / `client.verify_payout_callback` / `client.verify_issue_ticket_callback`(或顶层 `verify_callback`,时序安全)→ 按 `status` 幂等处理(success/failed)→ 应答 **HTTP 200 + 纯文本 `success`**。代收/退款/工单回复回调用 `api_secret_pay`、代付回调用 `api_secret_payout`,示例各演示一次。验签失败不回成功;同一订单可能再次收到回调。处理务必幂等(同一订单可能多次回调)。
|
|
141
148
|
|
|
142
149
|
## 代付反查
|
|
143
150
|
|
|
144
|
-
平台审核时向商户自己的 HTTPS 地址 POST JSON。`decide_payout_precheck(body, saved)` 的返回值原样作为 HTTP 200 正文,只能是 `approve` 或 `reject`。`saved["sign"]` 用代付下单返回数据上的 `.sign
|
|
151
|
+
平台审核时向商户自己的 HTTPS 地址 POST JSON。`decide_payout_precheck(body, saved)` 的返回值原样作为 HTTP 200 正文,只能是 `approve` 或 `reject`。`saved["sign"]` 用代付下单返回数据上的 `.sign`(若下单遇传输超时,可从 `TransportError.request_sign` 读取本次实际发出的 `sign`)。`payout_no` 必须出现,但不与下单请求比较。
|
|
145
152
|
|
|
146
153
|
```python
|
|
147
154
|
from openapi_sdk import decide_payout_precheck
|
{bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/openapi_sdk/__init__.py
RENAMED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
|
|
1
3
|
"""商户支付 OpenAPI Python SDK(零第三方依赖)。
|
|
2
4
|
|
|
3
5
|
公开 API::
|
|
@@ -48,6 +50,6 @@ try:
|
|
|
48
50
|
try:
|
|
49
51
|
__version__ = _pkg_version("bebebus-merchant-openapi-sdk")
|
|
50
52
|
except PackageNotFoundError:
|
|
51
|
-
__version__ = "2.
|
|
53
|
+
__version__ = "2.3.0"
|
|
52
54
|
except ImportError: # pragma: no cover —— Python <3.8 无 importlib.metadata
|
|
53
|
-
__version__ = "2.
|
|
55
|
+
__version__ = "2.3.0"
|
{bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/openapi_sdk/client.py
RENAMED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
|
|
3
|
+
"""商户支付 OpenAPI 客户端:覆盖代收、代付与工单签名端点。
|
|
2
4
|
|
|
3
5
|
仅用标准库:urllib.request(HTTP)、json、uuid、time、secrets。
|
|
4
6
|
|
|
@@ -41,6 +43,19 @@ class SignedData(dict):
|
|
|
41
43
|
self.sign = sign
|
|
42
44
|
|
|
43
45
|
|
|
46
|
+
class _Envelope(dict):
|
|
47
|
+
"""内部响应信封,附带 HTTP 状态码(仍完全兼容 dict)。"""
|
|
48
|
+
|
|
49
|
+
def __init__(self, data: Mapping[str, Any], status_code: int) -> None:
|
|
50
|
+
super().__init__(data)
|
|
51
|
+
self.status_code = status_code
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _is_int_code(value: Any) -> bool:
|
|
55
|
+
"""判断 code 是否为真正的整数(排除 bool,避免 Python 中 False == 0 误判成功)。"""
|
|
56
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
57
|
+
|
|
58
|
+
|
|
44
59
|
# [L20] User-Agent 版本号单一事实源:从包元数据派生(与 __version__ 同源),
|
|
45
60
|
# 不再硬编码;源码直跑(未安装)取不到则兜底(须随发版同步)。
|
|
46
61
|
try:
|
|
@@ -50,9 +65,9 @@ try:
|
|
|
50
65
|
try:
|
|
51
66
|
_SDK_VERSION = _pkg_version("bebebus-merchant-openapi-sdk")
|
|
52
67
|
except PackageNotFoundError:
|
|
53
|
-
_SDK_VERSION = "2.
|
|
68
|
+
_SDK_VERSION = "2.3.0"
|
|
54
69
|
except ImportError: # pragma: no cover —— Python <3.8 无 importlib.metadata
|
|
55
|
-
_SDK_VERSION = "2.
|
|
70
|
+
_SDK_VERSION = "2.3.0"
|
|
56
71
|
|
|
57
72
|
_JSON_HEADERS = {
|
|
58
73
|
"Content-Type": "application/json",
|
|
@@ -63,6 +78,13 @@ _JSON_HEADERS = {
|
|
|
63
78
|
}
|
|
64
79
|
|
|
65
80
|
|
|
81
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
82
|
+
"""拒绝自动跳转,避免凭证或签名请求转发至非预期地址。"""
|
|
83
|
+
|
|
84
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
|
|
66
88
|
class Client:
|
|
67
89
|
"""商户支付 OpenAPI 客户端。
|
|
68
90
|
|
|
@@ -82,6 +104,7 @@ class Client:
|
|
|
82
104
|
|
|
83
105
|
def __init__(self, config: Config) -> None:
|
|
84
106
|
self._config = config
|
|
107
|
+
self._opener = urllib.request.build_opener(_NoRedirect())
|
|
85
108
|
|
|
86
109
|
# ---- 便捷构造 -----------------------------------------------------------
|
|
87
110
|
|
|
@@ -169,8 +192,6 @@ class Client:
|
|
|
169
192
|
def pay_methods_query(
|
|
170
193
|
self,
|
|
171
194
|
country: Optional[str] = None,
|
|
172
|
-
biz_type: Optional[str] = None,
|
|
173
|
-
currency: Optional[str] = None,
|
|
174
195
|
) -> Dict[str, Any]:
|
|
175
196
|
"""POST /merchant/pay-methods/query — 可用支付方式。
|
|
176
197
|
|
|
@@ -179,7 +200,7 @@ class Client:
|
|
|
179
200
|
"""
|
|
180
201
|
return self._call_pay(
|
|
181
202
|
"/merchant/pay-methods/query",
|
|
182
|
-
{"country": country
|
|
203
|
+
{"country": country},
|
|
183
204
|
)
|
|
184
205
|
|
|
185
206
|
def groups_query(
|
|
@@ -344,6 +365,57 @@ class Client:
|
|
|
344
365
|
},
|
|
345
366
|
)
|
|
346
367
|
|
|
368
|
+
# =====================================================================
|
|
369
|
+
# 工单(密钥:api_secret_pay)
|
|
370
|
+
# =====================================================================
|
|
371
|
+
|
|
372
|
+
def issue_ticket_create(
|
|
373
|
+
self,
|
|
374
|
+
order_no: str,
|
|
375
|
+
content: Optional[str] = None,
|
|
376
|
+
image_base64: Optional[str] = None,
|
|
377
|
+
image_mime: Optional[str] = None,
|
|
378
|
+
notify_url: Optional[str] = None,
|
|
379
|
+
) -> Dict[str, Any]:
|
|
380
|
+
"""POST /merchant/issue-ticket/create — 创建工单。notify_url 为空则不推送回复。"""
|
|
381
|
+
return self._call_pay(
|
|
382
|
+
"/merchant/issue-ticket/create",
|
|
383
|
+
{
|
|
384
|
+
"order_no": order_no,
|
|
385
|
+
"content": content,
|
|
386
|
+
"image_base64": image_base64,
|
|
387
|
+
"image_mime": image_mime,
|
|
388
|
+
"notify_url": notify_url,
|
|
389
|
+
},
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
def issue_ticket_query(
|
|
393
|
+
self,
|
|
394
|
+
ticket_no: Optional[str] = None,
|
|
395
|
+
order_no: Optional[str] = None,
|
|
396
|
+
) -> Dict[str, Any]:
|
|
397
|
+
"""POST /merchant/issue-ticket/query — 查询工单。ticket_no 与 order_no 至少填一个。"""
|
|
398
|
+
return self._call_pay(
|
|
399
|
+
"/merchant/issue-ticket/query",
|
|
400
|
+
{"ticket_no": ticket_no, "order_no": order_no},
|
|
401
|
+
)
|
|
402
|
+
|
|
403
|
+
# =====================================================================
|
|
404
|
+
# 回调验签(不发请求)
|
|
405
|
+
# =====================================================================
|
|
406
|
+
|
|
407
|
+
def verify_pay_callback(self, payload: Mapping[str, Any]) -> bool:
|
|
408
|
+
"""代收/退款回调验签(api_secret_pay,时序安全比较)。"""
|
|
409
|
+
return signer.verify_callback(payload, self._config.require_secret_pay())
|
|
410
|
+
|
|
411
|
+
def verify_payout_callback(self, payload: Mapping[str, Any]) -> bool:
|
|
412
|
+
"""代付回调验签(api_secret_payout,时序安全比较)。"""
|
|
413
|
+
return signer.verify_callback(payload, self._config.require_secret_payout())
|
|
414
|
+
|
|
415
|
+
def verify_issue_ticket_callback(self, payload: Mapping[str, Any]) -> bool:
|
|
416
|
+
"""工单回复回调验签(api_secret_pay,时序安全比较)。"""
|
|
417
|
+
return signer.verify_callback(payload, self._config.require_secret_pay())
|
|
418
|
+
|
|
347
419
|
# =====================================================================
|
|
348
420
|
# 内部:请求构建 / 发送 / 解析
|
|
349
421
|
# =====================================================================
|
|
@@ -370,11 +442,19 @@ class Client:
|
|
|
370
442
|
def _call(self, path: str, body: Mapping[str, Any], secret: str) -> Dict[str, Any]:
|
|
371
443
|
envelope, request_sign = self._request(path, body, secret)
|
|
372
444
|
code = envelope.get("code")
|
|
445
|
+
status_code = getattr(envelope, "status_code", 200)
|
|
446
|
+
if not _is_int_code(code):
|
|
447
|
+
raise TransportError(
|
|
448
|
+
f"响应信封 code 非整数: {path}",
|
|
449
|
+
status_code=status_code,
|
|
450
|
+
request_sign=request_sign,
|
|
451
|
+
)
|
|
373
452
|
if code != 0:
|
|
374
453
|
raise ApiError(
|
|
375
|
-
code=code
|
|
454
|
+
code=code,
|
|
376
455
|
message=str(envelope.get("message", "")),
|
|
377
456
|
data=envelope.get("data"),
|
|
457
|
+
status_code=status_code,
|
|
378
458
|
)
|
|
379
459
|
data = envelope.get("data")
|
|
380
460
|
payload = data if isinstance(data, dict) else {}
|
|
@@ -417,25 +497,43 @@ class Client:
|
|
|
417
497
|
)
|
|
418
498
|
|
|
419
499
|
try:
|
|
420
|
-
with
|
|
500
|
+
with self._opener.open(request, timeout=self._config.timeout) as resp:
|
|
421
501
|
status = resp.getcode()
|
|
422
502
|
raw = resp.read().decode("utf-8")
|
|
423
503
|
except urllib.error.HTTPError as exc: # 非 2xx
|
|
424
504
|
raw_body = None
|
|
425
505
|
with suppress(Exception):
|
|
426
506
|
raw_body = exc.read().decode("utf-8")
|
|
507
|
+
# 非 2xx 若携带合法且 code != 0 的业务信封(如 HTTP 503 + 300304、HTTP 500 + 300302),
|
|
508
|
+
# 返回信封交由 _call 抛 ApiError(或 call_raw 原样返回);code == 0 或非信封仍抛 TransportError。
|
|
509
|
+
if raw_body is not None:
|
|
510
|
+
with suppress(json.JSONDecodeError):
|
|
511
|
+
err_env = json.loads(raw_body)
|
|
512
|
+
if (
|
|
513
|
+
isinstance(err_env, dict)
|
|
514
|
+
and _is_int_code(err_env.get("code"))
|
|
515
|
+
and err_env["code"] != 0
|
|
516
|
+
):
|
|
517
|
+
return _Envelope(err_env, exc.code), request_sign
|
|
427
518
|
raise TransportError(
|
|
428
519
|
f"HTTP {exc.code} 请求失败: {url}",
|
|
429
520
|
status_code=exc.code,
|
|
430
521
|
body=raw_body,
|
|
431
522
|
cause=exc,
|
|
523
|
+
request_sign=request_sign,
|
|
432
524
|
) from exc
|
|
433
525
|
except urllib.error.URLError as exc: # DNS/连接/超时
|
|
434
526
|
raise TransportError(
|
|
435
|
-
f"网络请求失败: {url} ({exc.reason})",
|
|
527
|
+
f"网络请求失败: {url} ({exc.reason})",
|
|
528
|
+
cause=exc,
|
|
529
|
+
request_sign=request_sign,
|
|
436
530
|
) from exc
|
|
437
531
|
except Exception as exc: # noqa: BLE001 - 其余 IO/超时
|
|
438
|
-
raise TransportError(
|
|
532
|
+
raise TransportError(
|
|
533
|
+
f"请求异常: {url} ({exc})",
|
|
534
|
+
cause=exc,
|
|
535
|
+
request_sign=request_sign,
|
|
536
|
+
) from exc
|
|
439
537
|
|
|
440
538
|
try:
|
|
441
539
|
envelope = json.loads(raw)
|
|
@@ -445,12 +543,14 @@ class Client:
|
|
|
445
543
|
status_code=status,
|
|
446
544
|
body=raw,
|
|
447
545
|
cause=exc,
|
|
546
|
+
request_sign=request_sign,
|
|
448
547
|
) from exc
|
|
449
548
|
|
|
450
|
-
if not isinstance(envelope, dict) or "code"
|
|
549
|
+
if not isinstance(envelope, dict) or not _is_int_code(envelope.get("code")):
|
|
451
550
|
raise TransportError(
|
|
452
|
-
f"
|
|
551
|
+
f"响应缺少合法整数信封字段(code): {url}",
|
|
453
552
|
status_code=status,
|
|
454
553
|
body=raw,
|
|
554
|
+
request_sign=request_sign,
|
|
455
555
|
)
|
|
456
|
-
return envelope, request_sign
|
|
556
|
+
return _Envelope(envelope, status), request_sign
|
{bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/openapi_sdk/exceptions.py
RENAMED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
|
|
1
3
|
"""SDK 异常类型。
|
|
2
4
|
|
|
3
5
|
- ``ApiError``:业务失败(统一信封 ``code != 0``),携带 code/message/data。
|
|
@@ -20,18 +22,25 @@ class OpenApiError(Exception):
|
|
|
20
22
|
class ApiError(OpenApiError):
|
|
21
23
|
"""业务异常:统一响应信封中 ``code != 0``。
|
|
22
24
|
|
|
23
|
-
携带原始 ``code``/``message``/``data`` 供调用方判断,不在 SDK 内穷举写死分支。
|
|
25
|
+
携带原始 ``code``/``message``/``data``/``status_code`` 供调用方判断,不在 SDK 内穷举写死分支。
|
|
24
26
|
"""
|
|
25
27
|
|
|
26
|
-
def __init__(
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
code: int,
|
|
31
|
+
message: str,
|
|
32
|
+
data: Any = None,
|
|
33
|
+
status_code: Optional[int] = 200,
|
|
34
|
+
) -> None:
|
|
27
35
|
super().__init__(f"[{code}] {message}")
|
|
28
36
|
self.code = code
|
|
29
37
|
self.message = message
|
|
30
38
|
self.data = data
|
|
39
|
+
self.status_code = status_code
|
|
31
40
|
|
|
32
41
|
|
|
33
42
|
class TransportError(OpenApiError):
|
|
34
|
-
"""传输异常:HTTP 非 2xx
|
|
43
|
+
"""传输异常:HTTP 非 2xx(且非合法业务错误信封)、网络错误、超时、响应不可解析为 JSON 等。"""
|
|
35
44
|
|
|
36
45
|
def __init__(
|
|
37
46
|
self,
|
|
@@ -39,8 +48,10 @@ class TransportError(OpenApiError):
|
|
|
39
48
|
status_code: Optional[int] = None,
|
|
40
49
|
body: Optional[str] = None,
|
|
41
50
|
cause: Optional[BaseException] = None,
|
|
51
|
+
request_sign: Optional[str] = None,
|
|
42
52
|
) -> None:
|
|
43
53
|
super().__init__(message)
|
|
44
54
|
self.status_code = status_code
|
|
45
55
|
self.body = body
|
|
46
56
|
self.cause = cause
|
|
57
|
+
self.request_sign = request_sign
|
{bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/openapi_sdk/signer.py
RENAMED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
|
|
1
3
|
"""签名器:HMAC-SHA256 -> 十六进制小写。
|
|
2
4
|
|
|
3
5
|
与服务端签名实现逐字节一致。
|
|
@@ -16,9 +18,9 @@ from typing import Any, Mapping
|
|
|
16
18
|
|
|
17
19
|
__all__ = ["build_sign_base", "sign", "verify_callback"]
|
|
18
20
|
|
|
19
|
-
# 合法 sign
|
|
20
|
-
# 预校验拦截攻击者构造的非 hex/非 ASCII sign
|
|
21
|
-
_HEX_RE = re.compile(r"[0-9a-
|
|
21
|
+
# 合法 sign 必须是 64 位小写十六进制串(HMAC-SHA256 hex)。
|
|
22
|
+
# 预校验拦截攻击者构造的非 hex/非 ASCII/长度或大小写异常的 sign,与其余语言 SDK 口径统一。
|
|
23
|
+
_HEX_RE = re.compile(r"[0-9a-f]{64}")
|
|
22
24
|
|
|
23
25
|
|
|
24
26
|
def _secret_is_blank(secret: Any) -> bool:
|
|
@@ -26,6 +28,20 @@ def _secret_is_blank(secret: Any) -> bool:
|
|
|
26
28
|
return not isinstance(secret, str) or secret.strip() == ""
|
|
27
29
|
|
|
28
30
|
|
|
31
|
+
def _reject_nested_floats(value: Any) -> None:
|
|
32
|
+
"""递归校验嵌套容器不得含 float(防 ``1.0`` 序列化为 ``1.0`` 与服务端 JS ``1`` 分叉)。"""
|
|
33
|
+
if isinstance(value, float):
|
|
34
|
+
raise ValueError(
|
|
35
|
+
f"签名字段不接受浮点数(值={value!r}):金额等请用整数最小单位(int)"
|
|
36
|
+
)
|
|
37
|
+
if isinstance(value, Mapping):
|
|
38
|
+
for v in value.values():
|
|
39
|
+
_reject_nested_floats(v)
|
|
40
|
+
elif isinstance(value, list):
|
|
41
|
+
for item in value:
|
|
42
|
+
_reject_nested_floats(item)
|
|
43
|
+
|
|
44
|
+
|
|
29
45
|
def _stable_stringify(value: Any) -> str:
|
|
30
46
|
"""嵌套 object/array 的稳定 JSON 序列化,对齐 JS ``JSON.stringify`` + key 升序。
|
|
31
47
|
|
|
@@ -36,8 +52,10 @@ def _stable_stringify(value: Any) -> str:
|
|
|
36
52
|
Python ``json.dumps`` 不转义 ``/`` 与 ``<>&``,与 JS 默认行为一致;
|
|
37
53
|
会转义 ``"`` ``\\`` 及控制字符(``\\b\\f\\n\\r\\t`` 与其余 ``\\u00XX``),亦与 JS 一致。
|
|
38
54
|
|
|
39
|
-
``allow_nan=False
|
|
55
|
+
``allow_nan=False`` 结合递归浮点校验:任何浮点(含 ``1.0``、``1.5``、``NaN``、``Infinity``)
|
|
56
|
+
一律拒绝(抛 ``ValueError``),确保嵌套数值与顶层及跨语言 SDK 口径一致。
|
|
40
57
|
"""
|
|
58
|
+
_reject_nested_floats(value)
|
|
41
59
|
return json.dumps(
|
|
42
60
|
value,
|
|
43
61
|
ensure_ascii=False,
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "bebebus-merchant-openapi-sdk"
|
|
7
|
-
version = "2.
|
|
7
|
+
version = "2.3.0"
|
|
8
8
|
description = "商户支付 OpenAPI Python SDK(零第三方依赖)"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.8"
|
|
@@ -21,13 +21,13 @@ classifiers = [
|
|
|
21
21
|
dependencies = []
|
|
22
22
|
|
|
23
23
|
[project.urls]
|
|
24
|
-
Homepage = "https://github.com/bebebus/
|
|
25
|
-
Repository = "https://github.com/bebebus/
|
|
26
|
-
Issues = "https://github.com/bebebus/
|
|
24
|
+
Homepage = "https://github.com/bebebus/payment-openapi-sdk/tree/main/python"
|
|
25
|
+
Repository = "https://github.com/bebebus/payment-openapi-sdk"
|
|
26
|
+
Issues = "https://github.com/bebebus/payment-openapi-sdk/issues"
|
|
27
27
|
|
|
28
28
|
[project.optional-dependencies]
|
|
29
29
|
# 运行时仍为零第三方依赖;dev 额外提供静态检查工具。
|
|
30
|
-
dev = ["ruff==0.17.
|
|
30
|
+
dev = ["ruff==0.17.4"]
|
|
31
31
|
|
|
32
32
|
[tool.setuptools]
|
|
33
33
|
packages = ["openapi_sdk"]
|
{bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/tests/test_appendix.py
RENAMED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
|
|
1
3
|
"""附录配置与国家/币种数据文件。"""
|
|
2
4
|
|
|
3
5
|
from __future__ import annotations
|
|
@@ -53,8 +55,10 @@ class TestAppendix(unittest.TestCase):
|
|
|
53
55
|
self.assertIn("100001", codes)
|
|
54
56
|
self.assertIn("300404", codes)
|
|
55
57
|
self.assertEqual(next(e for e in errors if e["code"] == "100000")["retryable"], "depends")
|
|
56
|
-
#
|
|
57
|
-
known_non_200 = {"300304": 503}
|
|
58
|
+
# 约定非 200 的错误码:100108(落地页限流 429)、300302(订单数据暂不可用 500)、300304(建单暂不可用 503)。
|
|
59
|
+
known_non_200 = {"100108": 429, "300302": 500, "300304": 503}
|
|
60
|
+
self.assertIn("300308", codes)
|
|
61
|
+
self.assertIn("300309", codes)
|
|
58
62
|
for e in errors:
|
|
59
63
|
expected = known_non_200.get(e["code"], 200)
|
|
60
64
|
self.assertEqual(e["http"], expected, f"{e['code']} http={e['http']}")
|
{bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/tests/test_client.py
RENAMED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
|
|
1
3
|
"""客户端请求构建单元测试(标准库 unittest,不发真实网络请求)。
|
|
2
4
|
|
|
3
5
|
校验:通用字段注入、None 过滤、签名密钥选择(pay vs payout)、
|
|
@@ -55,6 +57,22 @@ class _Capture:
|
|
|
55
57
|
|
|
56
58
|
|
|
57
59
|
class TestEnvironmentAndConfig(unittest.TestCase):
|
|
60
|
+
def test_rejects_missing_identifiers_and_insecure_urls(self):
|
|
61
|
+
base = {"merchant_no": "M1", "api_key": "key", "base_url": "https://api.example.com"}
|
|
62
|
+
for field in ("merchant_no", "api_key"):
|
|
63
|
+
with self.subTest(field=field), self.assertRaises(ValueError):
|
|
64
|
+
Config(**{**base, field: ""})
|
|
65
|
+
for url in ("file:///etc/passwd", "http://api.example.com/v1"):
|
|
66
|
+
with self.subTest(url=url), self.assertRaises(ValueError):
|
|
67
|
+
Config(**{**base, "base_url": url})
|
|
68
|
+
|
|
69
|
+
def test_missing_business_secrets_fail_closed(self):
|
|
70
|
+
config = Config(merchant_no="M1", api_key="key", environment=Environment.SANDBOX)
|
|
71
|
+
with self.assertRaises(ValueError):
|
|
72
|
+
config.require_secret_pay()
|
|
73
|
+
with self.assertRaises(ValueError):
|
|
74
|
+
config.require_secret_payout()
|
|
75
|
+
|
|
58
76
|
def test_presets(self):
|
|
59
77
|
# PRODUCTION 无内置基址(按上级代理域名派生,需显式传 base_url)。
|
|
60
78
|
self.assertEqual(Environment.PRODUCTION.base_url, "")
|
|
@@ -232,6 +250,58 @@ class TestKeySelectionAndShaping(unittest.TestCase):
|
|
|
232
250
|
body = self.capture.calls[-1]["body"]
|
|
233
251
|
self.assertIsNone(body["inline"])
|
|
234
252
|
|
|
253
|
+
def test_issue_ticket_create_and_query_use_pay_secret(self):
|
|
254
|
+
client = _make_client()
|
|
255
|
+
client.issue_ticket_create(
|
|
256
|
+
order_no="P1",
|
|
257
|
+
content="用户已付款",
|
|
258
|
+
image_base64="AAAA",
|
|
259
|
+
image_mime="image/png",
|
|
260
|
+
notify_url="https://m.example.com/ticket-cb",
|
|
261
|
+
)
|
|
262
|
+
create_call = self.capture.calls[-1]
|
|
263
|
+
self.assertEqual(create_call["path"], "/merchant/issue-ticket/create")
|
|
264
|
+
self.assertEqual(create_call["secret"], "sk_pay_secret")
|
|
265
|
+
self.assertEqual(create_call["body"]["order_no"], "P1")
|
|
266
|
+
self.assertEqual(create_call["body"]["notify_url"], "https://m.example.com/ticket-cb")
|
|
267
|
+
|
|
268
|
+
client.issue_ticket_query(ticket_no="TK1")
|
|
269
|
+
query_call = self.capture.calls[-1]
|
|
270
|
+
self.assertEqual(query_call["path"], "/merchant/issue-ticket/query")
|
|
271
|
+
self.assertEqual(query_call["secret"], "sk_pay_secret")
|
|
272
|
+
self.assertEqual(query_call["body"]["ticket_no"], "TK1")
|
|
273
|
+
|
|
274
|
+
def test_pay_methods_query_rejects_removed_v2_kwargs(self):
|
|
275
|
+
client = _make_client()
|
|
276
|
+
with self.assertRaises(TypeError):
|
|
277
|
+
client.pay_methods_query(biz_type="pay") # type: ignore[call-arg]
|
|
278
|
+
with self.assertRaises(TypeError):
|
|
279
|
+
client.pay_methods_query(currency="PHP") # type: ignore[call-arg]
|
|
280
|
+
|
|
281
|
+
def test_client_callback_verify_methods(self):
|
|
282
|
+
client = _make_client()
|
|
283
|
+
pay_cb = {"merchant_no": "M00000001", "order_no": "P1", "status": "success"}
|
|
284
|
+
pay_cb["sign"] = signer.sign(pay_cb, "sk_pay_secret")
|
|
285
|
+
self.assertTrue(client.verify_pay_callback(pay_cb))
|
|
286
|
+
self.assertFalse(client.verify_payout_callback(pay_cb))
|
|
287
|
+
|
|
288
|
+
payout_cb = {"merchant_no": "M00000001", "payout_no": "W1", "status": "success"}
|
|
289
|
+
payout_cb["sign"] = signer.sign(payout_cb, "sk_payout_secret")
|
|
290
|
+
self.assertTrue(client.verify_payout_callback(payout_cb))
|
|
291
|
+
self.assertFalse(client.verify_pay_callback(payout_cb))
|
|
292
|
+
|
|
293
|
+
ticket_cb = {
|
|
294
|
+
"merchant_no": "M00000001",
|
|
295
|
+
"ticket_no": "TK1",
|
|
296
|
+
"order_no": "W1",
|
|
297
|
+
"order_type": "payout",
|
|
298
|
+
"status": "replied",
|
|
299
|
+
"content": "已核实",
|
|
300
|
+
}
|
|
301
|
+
ticket_cb["sign"] = signer.sign(ticket_cb, "sk_pay_secret")
|
|
302
|
+
self.assertTrue(client.verify_issue_ticket_callback(ticket_cb))
|
|
303
|
+
self.assertFalse(client.verify_issue_ticket_callback({**ticket_cb, "content": "篡改"}))
|
|
304
|
+
|
|
235
305
|
|
|
236
306
|
class TestEnvelopeHandling(unittest.TestCase):
|
|
237
307
|
def test_business_error_raises_api_error(self):
|
|
@@ -378,18 +448,25 @@ class TestAllEndpointsCallable(unittest.TestCase):
|
|
|
378
448
|
"payout_proof_query": "/merchant/payout/proof/query",
|
|
379
449
|
"payout_receipt_query": "/merchant/payout/receipt/query",
|
|
380
450
|
"payout_test_complete": "/merchant/payout/test/complete",
|
|
451
|
+
"issue_ticket_create": "/merchant/issue-ticket/create",
|
|
452
|
+
"issue_ticket_query": "/merchant/issue-ticket/query",
|
|
381
453
|
}
|
|
382
454
|
|
|
383
455
|
def test_methods_exist(self):
|
|
384
456
|
client = _make_client()
|
|
385
|
-
for name in
|
|
457
|
+
for name in (
|
|
458
|
+
*self.EXPECTED,
|
|
459
|
+
"verify_pay_callback",
|
|
460
|
+
"verify_payout_callback",
|
|
461
|
+
"verify_issue_ticket_callback",
|
|
462
|
+
):
|
|
386
463
|
self.assertTrue(
|
|
387
464
|
callable(getattr(client, name, None)),
|
|
388
|
-
msg=f"
|
|
465
|
+
msg=f"缺少端点或验签方法 {name}",
|
|
389
466
|
)
|
|
390
467
|
|
|
391
468
|
def test_endpoint_count(self):
|
|
392
|
-
self.assertEqual(len(self.EXPECTED),
|
|
469
|
+
self.assertEqual(len(self.EXPECTED), 15)
|
|
393
470
|
|
|
394
471
|
|
|
395
472
|
if __name__ == "__main__":
|
{bebebus_merchant_openapi_sdk-2.2.0 → bebebus_merchant_openapi_sdk-2.3.0}/tests/test_signer.py
RENAMED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
|
|
1
3
|
"""签名器单元测试(标准库 unittest)。
|
|
2
4
|
|
|
3
5
|
(a) 读取 ../../test-vectors.json,对每个向量断言 build_sign_base == base 且 sign == sign。
|
|
@@ -72,6 +74,23 @@ class TestScalarRules(unittest.TestCase):
|
|
|
72
74
|
|
|
73
75
|
SECRET = "sk_test_0123456789abcdef0123456789abcdef"
|
|
74
76
|
|
|
77
|
+
def test_invalid_callback_and_signing_inputs_fail_closed(self):
|
|
78
|
+
with self.assertRaises(ValueError):
|
|
79
|
+
build_sign_base({"amount": 1}, " ")
|
|
80
|
+
with self.assertRaises(ValueError):
|
|
81
|
+
sign({"amount": 1.5}, self.SECRET)
|
|
82
|
+
with self.assertRaises(ValueError):
|
|
83
|
+
sign({"extra": {"v": 1.0}}, self.SECRET)
|
|
84
|
+
with self.assertRaises(ValueError):
|
|
85
|
+
sign({"extra": {"items": [1, 2.5]}}, self.SECRET)
|
|
86
|
+
self.assertFalse(verify_callback({"sign": "a" * 64}, " "))
|
|
87
|
+
self.assertFalse(verify_callback(None, self.SECRET))
|
|
88
|
+
self.assertFalse(verify_callback({"sign": "不合法"}, self.SECRET))
|
|
89
|
+
self.assertFalse(verify_callback({"sign": "A" * 64}, self.SECRET))
|
|
90
|
+
self.assertFalse(verify_callback({"sign": "aa"}, self.SECRET))
|
|
91
|
+
self.assertFalse(verify_callback({"sign": "a" * 64, "amount": 1.5}, self.SECRET))
|
|
92
|
+
self.assertFalse(verify_callback({"sign": "a" * 64, "extra": {"v": 1.0}}, self.SECRET))
|
|
93
|
+
|
|
75
94
|
def test_boolean_lowercase(self):
|
|
76
95
|
base = build_sign_base({"inline": True, "disabled": False}, self.SECRET)
|
|
77
96
|
self.assertEqual(
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
|
|
3
|
+
"""真实请求构建和传输错误分类,不连接外部服务。"""
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import threading
|
|
8
|
+
import unittest
|
|
9
|
+
import urllib.error
|
|
10
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
11
|
+
from unittest.mock import patch
|
|
12
|
+
|
|
13
|
+
from openapi_sdk import ApiError, Client, Config, Environment, TransportError, signer
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _Response:
|
|
17
|
+
def __init__(self, body, status=200):
|
|
18
|
+
self.body = body
|
|
19
|
+
self.status = status
|
|
20
|
+
|
|
21
|
+
def __enter__(self):
|
|
22
|
+
return self
|
|
23
|
+
|
|
24
|
+
def __exit__(self, *_args):
|
|
25
|
+
return False
|
|
26
|
+
|
|
27
|
+
def getcode(self):
|
|
28
|
+
return self.status
|
|
29
|
+
|
|
30
|
+
def read(self):
|
|
31
|
+
return self.body
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class TestTransport(unittest.TestCase):
|
|
35
|
+
def setUp(self):
|
|
36
|
+
self.client = Client(Config(
|
|
37
|
+
merchant_no="M1", api_key="key", api_secret_pay="pay-secret",
|
|
38
|
+
api_secret_payout="payout-secret", environment=Environment.SANDBOX,
|
|
39
|
+
timeout=7,
|
|
40
|
+
))
|
|
41
|
+
|
|
42
|
+
def test_request_is_signed_and_response_retains_original_sign(self):
|
|
43
|
+
response = _Response(b'{"code":0,"data":{"order_no":"P1"}}')
|
|
44
|
+
with patch.object(self.client._opener, "open", return_value=response) as send:
|
|
45
|
+
result = self.client.pay_query(out_order_no="merchant-order")
|
|
46
|
+
request = send.call_args.args[0]
|
|
47
|
+
payload = json.loads(request.data)
|
|
48
|
+
self.assertEqual(request.full_url, "http://127.0.0.1:3090/api/open/v1/merchant/pay/query")
|
|
49
|
+
self.assertEqual(request.get_method(), "POST")
|
|
50
|
+
self.assertEqual(send.call_args.kwargs["timeout"], 7)
|
|
51
|
+
self.assertEqual(payload["merchant_no"], "M1")
|
|
52
|
+
self.assertEqual(payload["out_order_no"], "merchant-order")
|
|
53
|
+
self.assertEqual(payload["sign"], signer.sign(payload, "pay-secret"))
|
|
54
|
+
self.assertEqual(result, {"order_no": "P1"})
|
|
55
|
+
self.assertEqual(result.sign, payload["sign"])
|
|
56
|
+
|
|
57
|
+
def test_http_error_preserves_status_and_body(self):
|
|
58
|
+
error = urllib.error.HTTPError("https://example.test", 503, "unavailable", {}, io.BytesIO(b"retry"))
|
|
59
|
+
with patch.object(self.client._opener, "open", side_effect=error), self.assertRaises(TransportError) as raised:
|
|
60
|
+
self.client.pay_query(out_order_no="x")
|
|
61
|
+
self.assertEqual(raised.exception.status_code, 503)
|
|
62
|
+
self.assertEqual(raised.exception.body, "retry")
|
|
63
|
+
self.assertIs(raised.exception.cause, error)
|
|
64
|
+
|
|
65
|
+
def test_network_error_preserves_cause(self):
|
|
66
|
+
error = urllib.error.URLError("connection refused")
|
|
67
|
+
with patch.object(self.client._opener, "open", side_effect=error), self.assertRaises(TransportError) as raised:
|
|
68
|
+
self.client.pay_query(out_order_no="x")
|
|
69
|
+
self.assertIs(raised.exception.cause, error)
|
|
70
|
+
|
|
71
|
+
def test_invalid_json_or_missing_envelope_is_transport_error(self):
|
|
72
|
+
for body in (b"not-json", b'{}', b'[]', b'{"code":false,"data":{"ok":1}}', b'{"code":null}'):
|
|
73
|
+
with self.subTest(body=body), patch.object(self.client._opener, "open", return_value=_Response(body)):
|
|
74
|
+
with self.assertRaises(TransportError) as raised:
|
|
75
|
+
self.client.pay_query(out_order_no="x")
|
|
76
|
+
self.assertEqual(raised.exception.body, body.decode())
|
|
77
|
+
self.assertEqual(raised.exception.status_code, 200)
|
|
78
|
+
self.assertTrue(raised.exception.request_sign)
|
|
79
|
+
|
|
80
|
+
def test_non_2xx_business_envelope_raises_api_error_with_status(self):
|
|
81
|
+
body = b'{"code":300304,"message":"retryable","data":null}'
|
|
82
|
+
error = urllib.error.HTTPError("https://example.test", 503, "unavailable", {}, io.BytesIO(body))
|
|
83
|
+
with patch.object(self.client._opener, "open", side_effect=error), self.assertRaises(ApiError) as raised:
|
|
84
|
+
self.client.pay_query(out_order_no="x")
|
|
85
|
+
self.assertEqual(raised.exception.code, 300304)
|
|
86
|
+
self.assertEqual(raised.exception.status_code, 503)
|
|
87
|
+
|
|
88
|
+
def test_non_2xx_zero_code_remains_transport_error_with_request_sign(self):
|
|
89
|
+
body = b'{"code":0,"message":"ok","data":{}}'
|
|
90
|
+
error = urllib.error.HTTPError("https://example.test", 500, "err", {}, io.BytesIO(body))
|
|
91
|
+
with patch.object(self.client._opener, "open", side_effect=error), self.assertRaises(TransportError) as raised:
|
|
92
|
+
self.client.pay_query(out_order_no="x")
|
|
93
|
+
self.assertEqual(raised.exception.status_code, 500)
|
|
94
|
+
self.assertEqual(len(raised.exception.request_sign or ""), 64)
|
|
95
|
+
|
|
96
|
+
def test_business_error_and_raw_envelope(self):
|
|
97
|
+
body = b'{"code":123,"message":"declined","data":{"reason":"x"}}'
|
|
98
|
+
with patch.object(self.client._opener, "open", side_effect=lambda *_args, **_kwargs: _Response(body)):
|
|
99
|
+
with self.assertRaises(ApiError) as raised:
|
|
100
|
+
self.client.pay_query(out_order_no="x")
|
|
101
|
+
raw = self.client.call_raw("/merchant/pay/query", {}, "pay-secret")
|
|
102
|
+
self.assertEqual(raised.exception.code, 123)
|
|
103
|
+
self.assertEqual(raised.exception.data, {"reason": "x"})
|
|
104
|
+
self.assertEqual(raw["code"], 123)
|
|
105
|
+
|
|
106
|
+
def test_redirects_never_reach_target(self):
|
|
107
|
+
hits = []
|
|
108
|
+
|
|
109
|
+
class Handler(BaseHTTPRequestHandler):
|
|
110
|
+
status = 302
|
|
111
|
+
|
|
112
|
+
def do_POST(self):
|
|
113
|
+
if self.path == "/target":
|
|
114
|
+
hits.append(self.path)
|
|
115
|
+
self.send_response(200)
|
|
116
|
+
self.end_headers()
|
|
117
|
+
return
|
|
118
|
+
self.send_response(self.status)
|
|
119
|
+
self.send_header("Location", f"http://127.0.0.1:{self.server.server_port}/target")
|
|
120
|
+
self.end_headers()
|
|
121
|
+
|
|
122
|
+
def do_GET(self):
|
|
123
|
+
hits.append(self.path)
|
|
124
|
+
self.send_response(200)
|
|
125
|
+
self.end_headers()
|
|
126
|
+
|
|
127
|
+
def log_message(self, *_args):
|
|
128
|
+
pass
|
|
129
|
+
|
|
130
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
131
|
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
132
|
+
thread.start()
|
|
133
|
+
self.addCleanup(thread.join, 2)
|
|
134
|
+
self.addCleanup(server.server_close)
|
|
135
|
+
self.addCleanup(server.shutdown)
|
|
136
|
+
self.client = Client(Config(
|
|
137
|
+
merchant_no="M1", api_key="key", api_secret_pay="secret",
|
|
138
|
+
base_url=f"http://127.0.0.1:{server.server_port}", timeout=2,
|
|
139
|
+
))
|
|
140
|
+
for status in (301, 302, 303, 307, 308):
|
|
141
|
+
Handler.status = status
|
|
142
|
+
with self.subTest(status=status), self.assertRaises(TransportError) as raised:
|
|
143
|
+
self.client.pay_query(out_order_no="x")
|
|
144
|
+
self.assertEqual(raised.exception.status_code, status)
|
|
145
|
+
self.assertEqual(hits, [])
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
if __name__ == "__main__":
|
|
149
|
+
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|