Files
jinghui 721a2be32b
release / release (release) Canceled after 0s
feat(payment): integrate epay (易支付) gateway for CNY recharges
- new EpayClient: V1 md5 signing, submit.php page pay, api.php order query
- create/verify epay payment links with CNY exchange-rate conversion
- signed async notify handler (/admin/payment/callback_epay) with amount
  check plus idempotent crediting, and a gateway query fallback
- epay channel config form, channel row and payment_method enum extended
- RechargeModal: send payment_method (was payment_channel, so every recharge
  fell through to Stripe and 500'd) and re-enable the channel picker
- payment config encryption key moved to a local .env, never committed
2026-11-13 15:17:05 +08:00

136 lines
4.7 KiB
Python

"""
Epay (易支付) V1 protocol client.
Protocol reference: https://pay.88531.cn gateway (classic epay / V1):
* Submit page : GET {gateway}/submit.php (browser side, no IP whitelist)
* API order : POST {gateway}/mapi.php (server side, IP whitelist)
* Query order : GET {gateway}/api.php?act=order (uses plaintext `key`, no sign)
* Async notify: GET {notify_url} -> reply exactly `success`
Signature (MD5):
1. drop `sign`, `sign_type` and params whose value is empty
2. sort params by ASCII ascending
3. join as `k1=v1&k2=v2` -- values are NOT url-encoded
4. append the merchant key directly (no separator), md5 -> 32 char LOWERCASE hex
"""
import hashlib
import json
import logging
import urllib.error
import urllib.request
from typing import Optional
from urllib.parse import quote, urlencode
logger = logging.getLogger(__name__)
SIGN_TYPE = "MD5"
def build_sign(params: dict, key: str) -> str:
"""Build the epay V1 MD5 signature for `params`."""
parts = []
for field in sorted(params.keys()):
if field in ("sign", "sign_type"):
continue
value = params[field]
if value is None or value == "":
continue
if isinstance(value, (list, dict, tuple, set)):
continue
parts.append(f"{field}={value}")
raw = "&".join(parts) + str(key)
return hashlib.md5(raw.encode("utf-8")).hexdigest().lower()
def verify_sign(params: dict, key: str) -> bool:
"""Verify an inbound epay notify. Comparison is case insensitive."""
given = str(params.get("sign", "") or "").strip()
if not given:
return False
return build_sign(params, key).lower() == given.lower()
class EpayClient:
"""Builds epay payment requests."""
def __init__(self, gateway: str, pid: str, key: str):
self.gateway = (gateway or "").rstrip("/")
self.pid = str(pid or "")
self.key = str(key or "")
@property
def configured(self) -> bool:
return bool(self.gateway and self.pid and self.key)
def build_submit_url(
self,
out_trade_no: str,
name: str,
money: float,
notify_url: str,
return_url: str = "",
pay_type: str = "",
param: str = "",
) -> Optional[str]:
"""Build the browser payment URL ({gateway}/submit.php).
Returns None when the client is not configured or the URL cannot be built.
"""
if not self.configured:
logger.error("Epay client is not configured (gateway/pid/key missing)")
return None
if not out_trade_no or not notify_url:
logger.error("Epay payment requires out_trade_no and notify_url")
return None
params = {
"pid": self.pid,
"out_trade_no": out_trade_no,
"notify_url": notify_url,
"name": str(name or "Deposit")[:64],
"money": f"{float(money):.2f}",
"sign_type": SIGN_TYPE,
}
if return_url:
params["return_url"] = return_url
if pay_type:
params["type"] = str(pay_type)
if param:
params["param"] = str(param)
params["sign"] = build_sign(params, self.key)
# urlencode for the actual HTTP request only -- the signature above was
# computed on the raw (decoded) values, exactly as the gateway expects.
query = urlencode(list(params.items()), quote_via=quote, safe="")
return f"{self.gateway}/submit.php?{query}"
def query_order(self, out_trade_no: str, timeout: float = 8.0) -> Optional[dict]:
"""Query one order through {gateway}/api.php?act=order.
Returns the parsed JSON body, or None when the gateway is unreachable
or rejects the call (e.g. our IP is not whitelisted).
"""
if not self.configured or not out_trade_no:
return None
params = {
"act": "order",
"pid": self.pid,
"key": self.key,
"out_trade_no": out_trade_no,
}
url = f"{self.gateway}/api.php?{urlencode(list(params.items()), quote_via=quote, safe='')}"
try:
with urllib.request.urlopen(url, timeout=timeout) as resp:
payload = resp.read().decode("utf-8", "replace")
except (urllib.error.URLError, OSError, ValueError) as exc:
logger.error(f"Epay order query failed for {out_trade_no}: {exc}")
return None
try:
data = json.loads(payload)
except json.JSONDecodeError:
logger.error(f"Epay order query returned non-JSON for {out_trade_no}: {payload[:200]}")
return None
if not isinstance(data, dict):
return None
return data