showmac-pay 1.0.0__py3-none-any.whl
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.
- showmac_pay/__init__.py +40 -0
- showmac_pay/client.py +212 -0
- showmac_pay/exceptions.py +30 -0
- showmac_pay/notify.py +50 -0
- showmac_pay/sign.py +60 -0
- showmac_pay-1.0.0.dist-info/METADATA +113 -0
- showmac_pay-1.0.0.dist-info/RECORD +10 -0
- showmac_pay-1.0.0.dist-info/WHEEL +5 -0
- showmac_pay-1.0.0.dist-info/licenses/LICENSE +21 -0
- showmac_pay-1.0.0.dist-info/top_level.txt +1 -0
showmac_pay/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""ShowMac 支付网关 Python 客户端。
|
|
2
|
+
|
|
3
|
+
按网关的公开 HTTP 接口规范实现,不引入任何第三方依赖。
|
|
4
|
+
|
|
5
|
+
from showmac_pay import ShowMacPay
|
|
6
|
+
|
|
7
|
+
client = ShowMacPay(
|
|
8
|
+
mch_no="M1621873433953",
|
|
9
|
+
app_id="60cc09bce4b0f1c0b83761c9",
|
|
10
|
+
api_key=os.environ["SHOWMAC_PAY_API_KEY"],
|
|
11
|
+
api_base="https://pay.example.com",
|
|
12
|
+
)
|
|
13
|
+
order = client.unified_order(
|
|
14
|
+
mch_order_no="mho" + str(int(time.time())),
|
|
15
|
+
way_code="WX_NATIVE",
|
|
16
|
+
amount=100,
|
|
17
|
+
subject="商品标题",
|
|
18
|
+
body="商品描述",
|
|
19
|
+
notify_url="https://your-domain.com/notify/pay",
|
|
20
|
+
)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from .client import ShowMacPay
|
|
24
|
+
from .exceptions import NotifyError, PayError, SignatureError
|
|
25
|
+
from .notify import order_no_of, verify_notify
|
|
26
|
+
from .sign import sign, sign_str, verify
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"ShowMacPay",
|
|
30
|
+
"PayError",
|
|
31
|
+
"SignatureError",
|
|
32
|
+
"NotifyError",
|
|
33
|
+
"sign",
|
|
34
|
+
"sign_str",
|
|
35
|
+
"verify",
|
|
36
|
+
"verify_notify",
|
|
37
|
+
"order_no_of",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
__version__ = "1.0.0"
|
showmac_pay/client.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""HTTP 客户端。仅用标准库(urllib),不依赖 requests。
|
|
2
|
+
|
|
3
|
+
请求构造遵循网关的 HTTP 接口规范:
|
|
4
|
+
POST + ``application/json``,body 里带上 version / signType / reqTime / sign。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import time
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.request
|
|
13
|
+
from typing import Any, Dict, Mapping, Optional
|
|
14
|
+
|
|
15
|
+
from .exceptions import PayError, SignatureError
|
|
16
|
+
from .sign import sign
|
|
17
|
+
|
|
18
|
+
API_VERSION = "1.0"
|
|
19
|
+
SIGN_TYPE = "MD5"
|
|
20
|
+
|
|
21
|
+
# 与 Java SDK 的 RequestOptions 默认值保持一致
|
|
22
|
+
DEFAULT_TIMEOUT = 20.0
|
|
23
|
+
DEFAULT_HEADERS = {
|
|
24
|
+
"Content-Type": "application/json; charset=UTF-8",
|
|
25
|
+
"Accept": "application/json",
|
|
26
|
+
"Accept-Charset": "UTF-8",
|
|
27
|
+
"Accept-Language": "zh-CN",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ShowMacPay:
|
|
32
|
+
"""支付网关客户端。每个商户/应用一个实例,不要用全局可变配置。
|
|
33
|
+
|
|
34
|
+
:param mch_no: 商户号
|
|
35
|
+
:param app_id: 应用 ID
|
|
36
|
+
:param api_key: 应用密钥(网关侧叫 appSecret)
|
|
37
|
+
:param api_base: 网关地址,如 ``https://pay.example.com``
|
|
38
|
+
:param timeout: 单次请求超时(秒)
|
|
39
|
+
:param verify_response: 是否校验响应签名。**生产环境务必保持 True**,
|
|
40
|
+
关掉等于放弃防伪造能力。
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, mch_no: str, app_id: str, api_key: str, api_base: str,
|
|
44
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
45
|
+
verify_response: bool = True,
|
|
46
|
+
user_agent: str = "showmac-pay-python/1.0.0") -> None:
|
|
47
|
+
if not mch_no or not app_id or not api_key:
|
|
48
|
+
raise ValueError("mch_no / app_id / api_key 均不能为空")
|
|
49
|
+
if not api_base:
|
|
50
|
+
raise ValueError("api_base 不能为空")
|
|
51
|
+
self.mch_no = mch_no
|
|
52
|
+
self.app_id = app_id
|
|
53
|
+
self.api_key = api_key
|
|
54
|
+
self.api_base = api_base.rstrip("/")
|
|
55
|
+
self.timeout = timeout
|
|
56
|
+
self.verify_response = verify_response
|
|
57
|
+
self.user_agent = user_agent
|
|
58
|
+
|
|
59
|
+
# ------------------------------------------------------------ 底层 HTTP
|
|
60
|
+
|
|
61
|
+
def _post(self, uri: str, biz: Mapping[str, Any]) -> Dict[str, Any]:
|
|
62
|
+
"""发请求并把响应里的 ``data`` 返回;业务失败抛 :class:`PayError`。"""
|
|
63
|
+
params: Dict[str, Any] = {
|
|
64
|
+
k: v for k, v in biz.items() if v is not None and v != ""
|
|
65
|
+
}
|
|
66
|
+
params["mchNo"] = self.mch_no
|
|
67
|
+
params["appId"] = self.app_id
|
|
68
|
+
params["version"] = API_VERSION
|
|
69
|
+
params["signType"] = SIGN_TYPE
|
|
70
|
+
params["reqTime"] = str(int(time.time() * 1000))
|
|
71
|
+
params["sign"] = sign(params, self.api_key)
|
|
72
|
+
|
|
73
|
+
payload = json.dumps(params, ensure_ascii=False,
|
|
74
|
+
separators=(",", ":")).encode("utf-8")
|
|
75
|
+
headers = dict(DEFAULT_HEADERS, **{"User-Agent": self.user_agent})
|
|
76
|
+
request = urllib.request.Request(
|
|
77
|
+
f"{self.api_base}/{uri.lstrip('/')}",
|
|
78
|
+
data=payload, headers=headers, method="POST",
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
try:
|
|
82
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as resp:
|
|
83
|
+
body = resp.read().decode("utf-8")
|
|
84
|
+
status = resp.status
|
|
85
|
+
except urllib.error.HTTPError as exc:
|
|
86
|
+
detail = exc.read().decode("utf-8", "ignore")[:500]
|
|
87
|
+
raise PayError(None, f"HTTP {exc.code}: {detail}") from exc
|
|
88
|
+
except urllib.error.URLError as exc:
|
|
89
|
+
raise PayError(None, f"网络异常: {exc.reason}") from exc
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
result = json.loads(body)
|
|
93
|
+
except json.JSONDecodeError as exc:
|
|
94
|
+
raise PayError(None, f"响应不是合法 JSON (HTTP {status}): {body[:200]}") from exc
|
|
95
|
+
|
|
96
|
+
code = result.get("code")
|
|
97
|
+
if code != 0:
|
|
98
|
+
raise PayError(code if isinstance(code, int) else None,
|
|
99
|
+
result.get("msg") or "未知错误", result)
|
|
100
|
+
|
|
101
|
+
self._check_response_sign(result)
|
|
102
|
+
return result.get("data") or {}
|
|
103
|
+
|
|
104
|
+
def _check_response_sign(self, result: Mapping[str, Any]) -> None:
|
|
105
|
+
"""响应里的 sign 只覆盖 ``data``,不含 code/msg。"""
|
|
106
|
+
if not self.verify_response:
|
|
107
|
+
return
|
|
108
|
+
data = result.get("data")
|
|
109
|
+
resp_sign = result.get("sign")
|
|
110
|
+
if data is None:
|
|
111
|
+
if resp_sign:
|
|
112
|
+
raise SignatureError(0, "响应 data 为空但存在 sign,报文异常", result)
|
|
113
|
+
return
|
|
114
|
+
expected = sign(data, self.api_key) # type: ignore[arg-type]
|
|
115
|
+
if str(resp_sign or "").upper() != expected:
|
|
116
|
+
raise SignatureError(
|
|
117
|
+
0, f"响应验签失败: 收到 {resp_sign} 本地 {expected}", result)
|
|
118
|
+
|
|
119
|
+
# ------------------------------------------------------------ 业务接口
|
|
120
|
+
|
|
121
|
+
def unified_order(self, *, mch_order_no: str, way_code: str, amount: int,
|
|
122
|
+
subject: str, body: str,
|
|
123
|
+
client_ip: str = "127.0.0.1", currency: str = "CNY",
|
|
124
|
+
notify_url: Optional[str] = None,
|
|
125
|
+
return_url: Optional[str] = None,
|
|
126
|
+
expired_time: Optional[int] = None,
|
|
127
|
+
channel_extra: Optional[Mapping[str, Any]] = None,
|
|
128
|
+
ext_param: Optional[str] = None,
|
|
129
|
+
division_mode: Optional[int] = None) -> Dict[str, Any]:
|
|
130
|
+
"""统一下单。``amount`` 单位:分。
|
|
131
|
+
|
|
132
|
+
``channel_extra`` 传字典即可,内部会序列化成紧凑 JSON 字符串参与签名
|
|
133
|
+
(引号原样保留,不做 URL 编码)。
|
|
134
|
+
"""
|
|
135
|
+
biz: Dict[str, Any] = {
|
|
136
|
+
"mchOrderNo": mch_order_no,
|
|
137
|
+
"wayCode": way_code,
|
|
138
|
+
"amount": int(amount),
|
|
139
|
+
"currency": currency,
|
|
140
|
+
"clientIp": client_ip,
|
|
141
|
+
"subject": subject,
|
|
142
|
+
"body": body,
|
|
143
|
+
"notifyUrl": notify_url,
|
|
144
|
+
"returnUrl": return_url,
|
|
145
|
+
"expiredTime": expired_time,
|
|
146
|
+
"extParam": ext_param,
|
|
147
|
+
"divisionMode": division_mode,
|
|
148
|
+
}
|
|
149
|
+
if channel_extra is not None:
|
|
150
|
+
biz["channelExtra"] = json.dumps(
|
|
151
|
+
channel_extra, ensure_ascii=False, separators=(",", ":"))
|
|
152
|
+
return self._post("api/pay/unifiedOrder", biz)
|
|
153
|
+
|
|
154
|
+
def query_order(self, *, mch_order_no: Optional[str] = None,
|
|
155
|
+
pay_order_id: Optional[str] = None) -> Dict[str, Any]:
|
|
156
|
+
"""查询支付订单。两个单号至少传一个。"""
|
|
157
|
+
self._require_one(mch_order_no=mch_order_no, pay_order_id=pay_order_id)
|
|
158
|
+
return self._post("api/pay/query",
|
|
159
|
+
{"mchOrderNo": mch_order_no, "payOrderId": pay_order_id})
|
|
160
|
+
|
|
161
|
+
def close_order(self, *, mch_order_no: Optional[str] = None,
|
|
162
|
+
pay_order_id: Optional[str] = None) -> Dict[str, Any]:
|
|
163
|
+
"""关闭支付订单。"""
|
|
164
|
+
self._require_one(mch_order_no=mch_order_no, pay_order_id=pay_order_id)
|
|
165
|
+
return self._post("api/pay/close",
|
|
166
|
+
{"mchOrderNo": mch_order_no, "payOrderId": pay_order_id})
|
|
167
|
+
|
|
168
|
+
def refund(self, *, mch_refund_no: str, refund_amount: int,
|
|
169
|
+
refund_reason: str,
|
|
170
|
+
mch_order_no: Optional[str] = None,
|
|
171
|
+
pay_order_id: Optional[str] = None,
|
|
172
|
+
currency: str = "CNY", client_ip: str = "127.0.0.1",
|
|
173
|
+
notify_url: Optional[str] = None,
|
|
174
|
+
channel_extra: Optional[Mapping[str, Any]] = None,
|
|
175
|
+
ext_param: Optional[str] = None) -> Dict[str, Any]:
|
|
176
|
+
"""发起退款。``refund_amount`` 单位:分。
|
|
177
|
+
|
|
178
|
+
注意 ``currency`` 与 ``refund_reason`` 在网关侧是必填(``@NotBlank``),
|
|
179
|
+
漏传会返回「货币代码不能为空」「退款原因不能为空」,与签名无关。
|
|
180
|
+
"""
|
|
181
|
+
self._require_one(mch_order_no=mch_order_no, pay_order_id=pay_order_id)
|
|
182
|
+
biz: Dict[str, Any] = {
|
|
183
|
+
"mchRefundNo": mch_refund_no,
|
|
184
|
+
"refundAmount": int(refund_amount),
|
|
185
|
+
"currency": currency,
|
|
186
|
+
"refundReason": refund_reason,
|
|
187
|
+
"clientIp": client_ip,
|
|
188
|
+
"mchOrderNo": mch_order_no,
|
|
189
|
+
"payOrderId": pay_order_id,
|
|
190
|
+
"notifyUrl": notify_url,
|
|
191
|
+
"extParam": ext_param,
|
|
192
|
+
}
|
|
193
|
+
if channel_extra is not None:
|
|
194
|
+
biz["channelExtra"] = json.dumps(
|
|
195
|
+
channel_extra, ensure_ascii=False, separators=(",", ":"))
|
|
196
|
+
return self._post("api/refund/refundOrder", biz)
|
|
197
|
+
|
|
198
|
+
def query_refund(self, *, mch_refund_no: Optional[str] = None,
|
|
199
|
+
refund_order_id: Optional[str] = None) -> Dict[str, Any]:
|
|
200
|
+
"""查询退款订单。"""
|
|
201
|
+
self._require_one(mch_refund_no=mch_refund_no,
|
|
202
|
+
refund_order_id=refund_order_id)
|
|
203
|
+
return self._post("api/refund/query", {
|
|
204
|
+
"mchRefundNo": mch_refund_no,
|
|
205
|
+
"refundOrderId": refund_order_id,
|
|
206
|
+
})
|
|
207
|
+
|
|
208
|
+
@staticmethod
|
|
209
|
+
def _require_one(**kwargs: Any) -> None:
|
|
210
|
+
if not any(v for v in kwargs.values()):
|
|
211
|
+
names = " / ".join(kwargs)
|
|
212
|
+
raise ValueError(f"{names} 至少传一个")
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""异常定义。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PayError(Exception):
|
|
9
|
+
"""调用网关失败。
|
|
10
|
+
|
|
11
|
+
code 为网关业务码(0 表示成功,非 0 表示业务失败);网络异常、HTTP 异常时 code 为 None。
|
|
12
|
+
raw 保留网关原始响应,便于排查。
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, code: Optional[int], msg: str, raw: Any = None) -> None:
|
|
16
|
+
super().__init__(f"[{code}] {msg}")
|
|
17
|
+
self.code = code
|
|
18
|
+
self.msg = msg
|
|
19
|
+
self.raw = raw
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SignatureError(PayError):
|
|
23
|
+
"""签名相关失败:请求构造异常,或响应/通知验签不通过。"""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class NotifyError(ValueError):
|
|
27
|
+
"""异步通知不合法(缺签名、验签失败、缺必填字段)。
|
|
28
|
+
|
|
29
|
+
继承 ``ValueError``,所以 ``except ValueError`` 也能捕获,方便在框架里统一处理。
|
|
30
|
+
"""
|
showmac_pay/notify.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""异步通知处理。
|
|
2
|
+
|
|
3
|
+
网关的通知是用 **form 表单** POST 的,参数与签名算法和请求完全一致,用同一个 apiKey。
|
|
4
|
+
接收方必须做三件事:验签 -> 幂等 -> 返回 ``success``。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any, Dict, Mapping, Optional, Tuple
|
|
10
|
+
|
|
11
|
+
from .exceptions import NotifyError
|
|
12
|
+
from .sign import verify
|
|
13
|
+
|
|
14
|
+
# 订单状态:与网关 CS.PAY_ORDER_STATE 一致
|
|
15
|
+
STATE_ING = "1"
|
|
16
|
+
STATE_PAY_SUCCESS = "2"
|
|
17
|
+
STATE_FAIL = "3"
|
|
18
|
+
STATE_CANCEL = "4"
|
|
19
|
+
STATE_REFUND = "5"
|
|
20
|
+
STATE_CLOSED = "6"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def verify_notify(params: Mapping[str, Any], api_key: str,
|
|
24
|
+
required: Tuple[str, ...] = ("mchOrderNo",)) -> Dict[str, Any]:
|
|
25
|
+
"""校验通知并返回参数副本;不合法时抛 :class:`NotifyError`,调用方应返回 ``fail``。
|
|
26
|
+
|
|
27
|
+
为什么验签之后还要查 ``required``:签名算法会过滤空值,**只带 sign 的空报文**
|
|
28
|
+
也能算出合法签名(等价于对 ``key=<apiKey>`` 求 MD5)。只看签名等于放行空通知。
|
|
29
|
+
"""
|
|
30
|
+
body: Dict[str, Any] = dict(params)
|
|
31
|
+
|
|
32
|
+
if not str(body.get("sign") or "").strip():
|
|
33
|
+
raise NotifyError("通知缺少 sign")
|
|
34
|
+
if not verify(body, api_key):
|
|
35
|
+
raise NotifyError("通知验签失败")
|
|
36
|
+
for field in required:
|
|
37
|
+
if not str(body.get(field) or "").strip():
|
|
38
|
+
raise NotifyError(f"通知缺少必要字段 {field}")
|
|
39
|
+
return body
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def is_paid(params: Mapping[str, Any]) -> bool:
|
|
43
|
+
"""通知/查单结果是否表示支付成功。条码支付是同步返回,下单响应里用 orderState。"""
|
|
44
|
+
return str(params.get("state") or params.get("orderState") or "") == STATE_PAY_SUCCESS
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def order_no_of(params: Mapping[str, Any]) -> Optional[str]:
|
|
48
|
+
"""从通知里取用于幂等的单号(支付通知取 mchOrderNo,退款通知取 mchRefundNo)。"""
|
|
49
|
+
value = params.get("mchOrderNo") or params.get("mchRefundNo")
|
|
50
|
+
return None if value is None else str(value)
|
showmac_pay/sign.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""签名算法。按网关公开的接口规范实现:过滤空值 -> 排序拼接 -> MD5 大写。
|
|
2
|
+
|
|
3
|
+
这里只是按公开规范的描述(排序 + 拼接 + MD5 大写)独立实现,没有引用任何 Java 代码。
|
|
4
|
+
自测向量见 ``sdk/test-vectors/sign-vectors.json``,不依赖任何 SDK 即可复核。
|
|
5
|
+
|
|
6
|
+
注意几个容易踩的点:
|
|
7
|
+
1. 空值过滤:``None`` 与 ``""`` 不参与签名,但 ``0`` / ``False`` 要参与。
|
|
8
|
+
2. 排序:按整个 ``key=value&`` 片段做大小写不敏感比较。
|
|
9
|
+
3. 布尔值:网关端是 ``Boolean.toString()`` -> ``true``/``false``;Python 默认是
|
|
10
|
+
``True``/``False``,必须显式转换。
|
|
11
|
+
4. ``bool`` 是 ``int`` 的子类,判断顺序必须先 bool 后 int。
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
from typing import Any, Dict, Mapping, Optional
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _normalize(value: Any) -> Optional[str]:
|
|
21
|
+
"""把参数值转成参与签名的字符串;返回 None 表示该参数不参与签名。"""
|
|
22
|
+
if value is None:
|
|
23
|
+
return None
|
|
24
|
+
if isinstance(value, bool):
|
|
25
|
+
return "true" if value else "false"
|
|
26
|
+
if isinstance(value, float):
|
|
27
|
+
# Java 端金额字段是 Long,浮点传进来必然对不上;这里直接转成整数字符串
|
|
28
|
+
if value.is_integer():
|
|
29
|
+
return str(int(value))
|
|
30
|
+
return repr(value)
|
|
31
|
+
text = str(value)
|
|
32
|
+
if text == "":
|
|
33
|
+
return None
|
|
34
|
+
return text
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def sign_str(params: Mapping[str, Any], api_key: str) -> str:
|
|
38
|
+
"""拼接待签名字符串(调试与分析用)。"""
|
|
39
|
+
items = []
|
|
40
|
+
for key, value in params.items():
|
|
41
|
+
text = _normalize(value)
|
|
42
|
+
if text is None:
|
|
43
|
+
continue
|
|
44
|
+
items.append(f"{key}={text}&")
|
|
45
|
+
items.sort(key=str.upper)
|
|
46
|
+
return "".join(items) + "key=" + api_key
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def sign(params: Mapping[str, Any], api_key: str) -> str:
|
|
50
|
+
"""计算签名:MD5 后转大写。"""
|
|
51
|
+
return hashlib.md5(sign_str(params, api_key).encode("utf-8")).hexdigest().upper()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def verify(params: Mapping[str, Any], api_key: str) -> bool:
|
|
55
|
+
"""校验签名。``params`` 可以含 ``sign`` 字段,会自动剔除;比较不区分大小写。"""
|
|
56
|
+
got = str(params.get("sign") or "").strip().upper()
|
|
57
|
+
if not got:
|
|
58
|
+
return False
|
|
59
|
+
body: Dict[str, Any] = {k: v for k, v in params.items() if k != "sign"}
|
|
60
|
+
return got == sign(body, api_key)
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: showmac-pay
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: ShowMac 支付网关 Python 客户端(零第三方依赖)
|
|
5
|
+
Author: ShowMac
|
|
6
|
+
Keywords: showmac,payment,pay,sdk
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Requires-Python: >=3.8
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# showmac-pay(Python)
|
|
17
|
+
|
|
18
|
+
ShowMac 支付网关的 Python 客户端。**零第三方依赖**,只用标准库,Python 3.8+。
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install ./sdk/python # 从本仓库安装(当前尚未发布到 PyPI)
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
> 也可以只把 `sdk/python/src/showmac_pay` 整个目录拷进项目直接 import。
|
|
25
|
+
> 若日后发布到 PyPI,安装命令为 `pip install showmac-pay`。
|
|
26
|
+
|
|
27
|
+
## 快速开始
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
import os
|
|
31
|
+
import time
|
|
32
|
+
|
|
33
|
+
from showmac_pay import PayError, ShowMacPay
|
|
34
|
+
|
|
35
|
+
client = ShowMacPay(
|
|
36
|
+
mch_no="M1621873433953",
|
|
37
|
+
app_id="60cc09bce4b0f1c0b83761c9",
|
|
38
|
+
api_key=os.environ["SHOWMAC_PAY_API_KEY"], # 应用密钥,不要硬编码
|
|
39
|
+
api_base="https://<支付网关域名>",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
order = client.unified_order(
|
|
43
|
+
mch_order_no="mho" + str(int(time.time() * 1000)),
|
|
44
|
+
way_code="WX_NATIVE",
|
|
45
|
+
amount=100, # 单位:分,必须是整数
|
|
46
|
+
subject="商品标题",
|
|
47
|
+
body="商品描述",
|
|
48
|
+
notify_url="https://your-domain.com/notify/pay",
|
|
49
|
+
return_url="https://your-domain.com/pay/result",
|
|
50
|
+
channel_extra={"payDataType": "codeImgUrl"}, # 需要时传,内部会自动转 JSON
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
print(order["payOrderId"], order["payDataType"], order["payData"])
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
其余接口:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
client.query_order(mch_order_no="mho1") # 或 pay_order_id=...
|
|
60
|
+
client.close_order(pay_order_id="P...")
|
|
61
|
+
client.refund(mch_refund_no="r1", refund_amount=100,
|
|
62
|
+
refund_reason="用户取消", pay_order_id="P...") # currency 默认 CNY
|
|
63
|
+
client.query_refund(mch_refund_no="r1")
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## 异步通知
|
|
67
|
+
|
|
68
|
+
网关用 **form 表单** POST 通知,接收方要做的三件事:验签 → 幂等 → 返回 `success`。
|
|
69
|
+
|
|
70
|
+
FastAPI 示例(Flask / Django 同理,关键是取 form 参数而不是 JSON body):
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from fastapi import FastAPI, Request, Response
|
|
74
|
+
|
|
75
|
+
from showmac_pay import is_paid, order_no_of, verify_notify
|
|
76
|
+
|
|
77
|
+
app = FastAPI()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@app.post("/notify/pay")
|
|
81
|
+
async def notify(request: Request):
|
|
82
|
+
params = dict(await request.form())
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
params = verify_notify(params, API_KEY) # 验签 + 必填字段校验
|
|
86
|
+
except ValueError as exc:
|
|
87
|
+
log.warning("通知被拒: %s", exc)
|
|
88
|
+
return Response("fail", media_type="text/plain")
|
|
89
|
+
|
|
90
|
+
if is_paid(params) and not already_processed(order_no_of(params)):
|
|
91
|
+
mark_paid(params) # 用唯一索引保证幂等
|
|
92
|
+
|
|
93
|
+
return Response("success", media_type="text/plain")
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`verify_notify` 除了验签,还会检查 `mchOrderNo` 非空——因为签名算法会过滤空值,
|
|
97
|
+
**只带 `sign` 的空报文也能算出合法签名**,只看签名等于放行空通知。
|
|
98
|
+
|
|
99
|
+
## 行为说明
|
|
100
|
+
|
|
101
|
+
- 请求固定 `POST` + `application/json`,自动注入 `mchNo` / `appId` / `version` /
|
|
102
|
+
`signType` / `reqTime` / `sign`,这六个字段**不要自己再传**。
|
|
103
|
+
- 响应 `sign` 只覆盖 `data`(不含 `code`/`msg`),默认校验;关掉等于放弃防伪造。
|
|
104
|
+
- 业务失败抛 `PayError`(`.code` / `.msg` / `.raw`),响应验签失败抛 `SignatureError`。
|
|
105
|
+
- `amount` / `refund_amount` 会自动 `int()`:网关端是 `Long`,传浮点必然验签失败。
|
|
106
|
+
- 多商户:每个商户各建一个 `ShowMacPay` 实例。**不要**用全局配置(官方 Python SDK
|
|
107
|
+
就是全局的,并发下会串商户)。
|
|
108
|
+
|
|
109
|
+
## 开发
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
python -m pytest # 22 个用例,含跨语言签名向量
|
|
113
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
showmac_pay/__init__.py,sha256=qIHL2hSu8LRSy32KszowJXqok33HYzIBtJ05gER3DQU,1008
|
|
2
|
+
showmac_pay/client.py,sha256=XYcwhTJEILCX-QE0Tb3x7yNVtyn2MI3w_dYb5pR8R8Q,9014
|
|
3
|
+
showmac_pay/exceptions.py,sha256=8T3lM6gVWL0fFG8ZdzkJ6XnxkzzxULduHcLlYQStb4s,879
|
|
4
|
+
showmac_pay/notify.py,sha256=ZD-j_aKhb_OEdL83SRvdd0wBtrshSa7Tdf5a3VEYKRM,1955
|
|
5
|
+
showmac_pay/sign.py,sha256=dJMmguLsArUxx5vCrNJCrtQ3fOit3I3RQ33aq_62ANQ,2349
|
|
6
|
+
showmac_pay-1.0.0.dist-info/licenses/LICENSE,sha256=S3qW0JhNfXGGB5b5wxW3O02GwBqU03PbQ24Ie88C7OI,1064
|
|
7
|
+
showmac_pay-1.0.0.dist-info/METADATA,sha256=DVP1GUP3uZxoQPNlYOHF-sHgLv-qd-zSbQvveYeMMoE,3842
|
|
8
|
+
showmac_pay-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
showmac_pay-1.0.0.dist-info/top_level.txt,sha256=hOLzcakTZRKKODTbwol-xdxlzH_lpguGWMfKAHyoSuk,12
|
|
10
|
+
showmac_pay-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ShowMac
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
showmac_pay
|