Files
ywsandClaude Opus 5.5 973afd7886 收款原型并进预览站:下单表单 + 收银台 / 订单页 + 收款后台(参考 Epusdt 收银台、独角数卡浏览器缓存查单)
- 预览站 order.html:模板多选、分辨率、皮肤三色灯(绿放行 / 黄勾无视风险 / 红拦住),吸底金额条;
  「我的订单」= 本机下过的单 + 订单号/取件码查单。
- 新 pay.html:用站点「票据」样式做收银台(爱发电 / 支付宝扫码、二维码 + 倒计时、自动轮询、付好了没反应),
  到账后同页变订单页;超时关闭态;取件码存根、复制订单链接。
- cms/pay.html:收款后台(待办 / 认领 / 渠道熔断 / 订单 / 支付单 / 流水)。演示控制台收进顶部预览横幅。
- 后端:订单记模板 / 分辨率 / 皮肤名,金额按模板数;取件码 10 位好抄;接口挂 /svc/,原型独立页撤掉。
- 测试 26 条;浏览器端到端 22 条(桌面 + 手机)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 06:58:21 +00:00

270 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""支付原型场景测试:临时目录起一份服务(全模拟渠道),从 HTTP 层打。
用法:python3 tests/test_proto.py
"""
import base64, json, os, re, shutil, socket, subprocess, sys, tempfile, time, urllib.parse, urllib.request
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
RESULTS = []
def check(name, ok, detail=""):
RESULTS.append((name, bool(ok)))
print(("PASS " if ok else "FAIL ") + name + ((" —— " + str(detail)[:200]) if detail != "" else ""))
def free_port():
s = socket.socket()
s.bind(("127.0.0.1", 0))
p = s.getsockname()[1]
s.close()
return p
PORT = free_port()
BASE = "http://127.0.0.1:%d" % PORT
DATA = tempfile.mkdtemp(prefix="payproto_")
env = dict(os.environ, PAY_PORT=str(PORT), PAY_DATA_DIR=DATA, PAY_BASE_URL=BASE)
srv = subprocess.Popen([sys.executable, os.path.join(HERE, "app.py")], env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
def req(method, path, obj=None, form=None, headers=None, raw=False):
data, h = None, dict(headers or {})
if obj is not None:
data = json.dumps(obj).encode()
h["Content-Type"] = "application/json"
if form is not None:
data = urllib.parse.urlencode(form).encode()
h["Content-Type"] = "application/x-www-form-urlencoded"
r = urllib.request.Request(BASE + path, data=data, method=method, headers=h)
try:
with urllib.request.urlopen(r, timeout=20) as resp:
body = resp.read().decode()
return resp.status, (body if raw else json.loads(body))
except urllib.error.HTTPError as e:
body = e.read().decode()
return e.code, (body if raw else json.loads(body or "{}"))
for _ in range(300):
try:
urllib.request.urlopen(BASE + "/", timeout=1)
break
except Exception:
time.sleep(0.2)
def new_order(n=2):
st, j = req("POST", "/api/order", {"n_img": n})
return j["order"]["oid"], j["token"], j
def view(oid, tok):
return req("GET", "/api/order?oid=%s&t=%s" % (oid, tok))[1]
def pay(oid, tok, ch):
return req("POST", "/api/pay", {"oid": oid, "t": tok, "channel": ch})[1]
def afd_pay_link(url, amount=None, drop=False):
qs = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(url).query))
form = {"custom_order_id": qs["custom_order_id"], "remark": qs["remark"],
"amount": amount if amount is not None else qs["custom_price"]}
if drop:
form["drop"] = "on"
req("POST", "/mock/afdian/order/pay", form=form, raw=True)
return qs
def ali_scan_pay(qr_url, drop=False):
path = urllib.parse.urlparse(qr_url).path
req("GET", path, raw=True) # 扫码 → WAIT_BUYER_PAY
form = {"qr": path.rsplit("/", 1)[-1]}
if drop:
form["drop"] = "on"
return req("POST", "/mock/alipay/scanpay", form=form, raw=True)[1]
def demo(**kw):
return req("POST", "/api/demo", kw)[1]
def todos():
tok = open(os.path.join(DATA, "admin_token")).read().strip()
return req("GET", "/api/admin/overview", headers={"X-Admin-Token": tok})[1]["todo"]
def admin(path, obj):
tok = open(os.path.join(DATA, "admin_token")).read().strip()
return req("POST", path, obj, headers={"X-Admin-Token": tok})[1]
try:
# 1. 爱发电正常到账(Webhook)
oid, tok, j = new_order(2)
check("下单:应付 ¥12、状态 unpaid、两个渠道可选", j["order"]["amount"] == 12 and j["order"]["state"] == "unpaid"
and [c["name"] for c in j["channels"] if c["ok"]] == ["afdian", "alipay"])
r = pay(oid, tok, "afdian")
url = r["payment"]["display"]["url"]
check("爱发电专链带 custom_order_id=支付单号、custom_price=应付", "custom_order_id=%sP1" % oid in url
and "custom_price=12" in url, url)
afd_pay_link(url)
time.sleep(3)
v = view(oid, tok)
check("爱发电付款 → Webhook 验签 + 精确反查 → 订单 waiting", v["order"]["state"] == "waiting",
[e["kind"] + ":" + e["result"] for e in v["events"][:4]])
# 1b. 按真实下单内容建单:模板 × 1 张皮肤,金额按模板数算,非法模板/分辨率被过滤
st, jt = req("POST", "/api/order", {"templates": ["stand", "sakura", "nope", "stand"], "res": 2048, "skin_name": "a.png"})
o = jt["order"]
check("下单带模板:去重、丢掉不认识的模板,2 个模板 = ¥12,分辨率 2048,皮肤名带回",
o["amount"] == 12 and [t["n"] for t in o["templates"]] == ["站立正反", "飞跃樱花林"] and o["res"] == 2048
and o["skin_name"] == "a.png" and len(jt["token"]) == 10, o)
st, jt = req("POST", "/api/order", {"templates": ["wheat"], "res": 777})
check("不支持的分辨率 → 回落 1000", jt["order"]["res"] == 1000, jt["order"]["res"])
# 2. 同一笔 Webhook 重复推送 → 幂等
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
import sqlite3
con = sqlite3.connect(os.path.join(DATA, "pay.db"))
con.row_factory = sqlite3.Row
mo = dict(con.execute("SELECT * FROM mock_afd ORDER BY create_time DESC LIMIT 1").fetchone())
pk = serialization.load_pem_private_key(open(os.path.join(DATA, "mock_keys", "afdian_platform.pem"), "rb").read(), None)
content = "%s%s%s%s" % (mo["out_trade_no"], mo["user_id"], mo["plan_id"], mo["total_amount"])
sig = base64.b64encode(pk.sign(content.encode(), padding.PKCS1v15(), hashes.SHA256())).decode()
body = {"ec": 200, "data": {"type": "order", "order": mo, "sign": sig}}
st, resp = req("POST", "/api/notify/afdian", body)
n_settle = con.execute("SELECT COUNT(*) FROM pay_events WHERE kind='settle' AND pay_id=? AND result='activated'",
(oid + "P1",)).fetchone()[0]
dup = con.execute("SELECT COUNT(*) FROM pay_events WHERE kind='settle' AND pay_id=? AND result='dup_trade'",
(oid + "P1",)).fetchone()[0]
check("同一笔 Webhook 再推一次 → 只激活一次(dup_trade),仍回 ec=200", n_settle == 1 and dup >= 1 and resp.get("ec") == 200,
(n_settle, dup, resp))
# 3. 伪造回调(签名不对)→ 丢弃
oid3, tok3, _ = new_order(1)
p3 = pay(oid3, tok3, "afdian")["payment"]["pay_id"]
demo(kind="afdian_forge", pay_id=p3)
time.sleep(0.3)
check("伪造 Webhook(签名不对)→ 不激活", view(oid3, tok3)["order"]["state"] == "unpaid")
# 4. Webhook 丢失 → 对账补上
oid4, tok4, _ = new_order(1)
afd_pay_link(pay(oid4, tok4, "afdian")["payment"]["display"]["url"], drop=True)
time.sleep(2)
before = view(oid4, tok4)["order"]["state"]
demo(kind="jobs")
check("Webhook 丢了 → 定时对账发现并激活", before == "unpaid" and view(oid4, tok4)["order"]["state"] == "waiting", before)
# 5. 买家把金额改小 → 不激活,进待办
oid5, tok5, _ = new_order(3)
afd_pay_link(pay(oid5, tok5, "afdian")["payment"]["display"]["url"], amount="0.10")
time.sleep(3)
td = [t for t in todos() if t["oid"] == oid5]
check("实付 ¥0.10 < 应付 ¥18 → 不激活,待办「金额不足」", view(oid5, tok5)["order"]["state"] == "unpaid"
and td and td[0]["kind"] == "short", td[:1])
r = admin("/api/admin/todo", {"id": td[0]["id"], "action": "confirm", "note": "买家补了差价"})
check("后台「确认补齐」→ 订单激活", r.get("ok") and view(oid5, tok5)["order"]["state"] == "waiting", r)
# 6. 当面付正常:预下单 → 扫码 → 异步通知
oid6, tok6, _ = new_order(2)
r = pay(oid6, tok6, "alipay")
qr = r["payment"]["display"]["qr"]
check("当面付预下单 → 返回二维码内容和过期时间", r["ok"] and "/mock/alipay/scan/" in qr
and r["payment"]["expire_at"] > 0, r)
ali_scan_pay(qr)
time.sleep(3)
check("当面付付款 → 异步通知验签 → 订单 waiting", view(oid6, tok6)["order"]["state"] == "waiting")
# 7. 当面付异步通知丢失 → 页面轮询查单发现
oid7, tok7, _ = new_order(1)
r = pay(oid7, tok7, "alipay")
ali_scan_pay(r["payment"]["display"]["qr"], drop=True)
time.sleep(2)
st, v = req("GET", "/api/pay?pay_id=%s&t=%s" % (r["payment"]["pay_id"], tok7))
check("当面付通知丢了 → 页面轮询 trade.query 发现到账", v["order"]["state"] == "waiting")
# 8. 二维码过期 → 关单;订单超时 → closed;宽限内迟到付款 → 恢复
oid8, tok8, _ = new_order(1)
p8 = pay(oid8, tok8, "alipay")["payment"]
a8 = pay(oid8, tok8, "afdian")["payment"]
demo(kind="clock", seconds=16 * 60)
pays = {p["pay_id"]: p["state"] for p in view(oid8, tok8)["payments"]}
check("二维码 15 分钟没付 → 支付单关闭;爱发电支付单还在", pays[p8["pay_id"]] == "closed"
and pays[a8["pay_id"]] == "created", pays)
demo(kind="clock", seconds=25 * 3600)
check("超过 24 小时没付 → 订单 closed", view(oid8, tok8)["order"]["state"] == "closed")
afd_pay_link(a8["display"]["url"])
time.sleep(3)
check("关闭后宽限期内付了爱发电 → 订单自动恢复为 waiting", view(oid8, tok8)["order"]["state"] == "waiting",
[e["kind"] + ":" + e["result"] for e in view(oid8, tok8)["events"][:3]])
# 9. 两个渠道都付了 → 只激活一次,第二笔进待办
oid9, tok9, _ = new_order(1)
a9 = pay(oid9, tok9, "afdian")["payment"]
q9 = pay(oid9, tok9, "alipay")["payment"]
ali_scan_pay(q9["display"]["qr"])
time.sleep(3)
afd_pay_link(a9["display"]["url"])
time.sleep(3)
td = [t for t in todos() if t["oid"] == oid9]
check("先付支付宝、又付爱发电 → 订单只激活一次,爱发电那笔进待办「重复付款」",
view(oid9, tok9)["order"]["state"] == "waiting" and td and td[0]["kind"] == "duplicate", td[:1])
r = admin("/api/admin/todo", {"id": td[0]["id"], "action": "refund"})
check("爱发电重复付款点退款 → 提示去爱发电后台(没有退款接口)", not r.get("ok") and "爱发电" in r.get("error", ""), r)
# 10. 风控熔断
demo(kind="alipay_risk", on=True)
oid10, tok10, _ = new_order(1)
r = pay(oid10, tok10, "alipay")
v = view(oid10, tok10)
ali = [c for c in v["channels"] if c["name"] == "alipay"][0]
check("当面付返回风控错误码 → 熔断,页面不再提供支付宝,只剩爱发电", not r["ok"] and not ali["ok"], (r, ali))
demo(kind="alipay_risk", on=False)
demo(kind="breaker_reset")
check("后台恢复熔断后 → 支付宝重新可用",
[c for c in view(oid10, tok10)["channels"] if c["name"] == "alipay"][0]["ok"])
# 11. 买家直接在爱发电店铺下单(没带订单号)→ 按买卡密处理;后台按爱发电订单号认领
r = demo(kind="afdian_direct", amount=6)
time.sleep(3)
ev = con.execute("SELECT COUNT(*) FROM pay_events WHERE kind='card_purchase'").fetchone()[0]
check("没带订单号的爱发电成交 → 走「按实付发卡密」,不去猜是哪张单", ev >= 1)
oid11, tok11, _ = new_order(1)
r2 = admin("/api/admin/claim", {"oid": oid11, "trade_no": r["trade_no"]})
check("后台按爱发电订单号认领 → 订单激活", r2.get("ok") and view(oid11, tok11)["order"]["state"] == "waiting", r2)
# 12. 「付好了没反应?」→ 立即对账
oid12, tok12, _ = new_order(1)
afd_pay_link(pay(oid12, tok12, "afdian")["payment"]["display"]["url"], drop=True)
time.sleep(1.5)
st, r = req("POST", "/api/check", {"oid": oid12, "t": tok12})
check("买家点「付好了没反应?」→ 当场查到并激活", r.get("found") and view(oid12, tok12)["order"]["state"] == "waiting", r)
# 13. 鉴权
st, _ = req("GET", "/api/admin/overview")
check("后台接口没口令 → 403", st == 403)
st, _ = req("GET", "/api/order?oid=%s&t=wrong" % oid)
check("取件码不对 → 查不到订单", st == 404)
st, r = req("POST", "/api/pay", {"oid": oid, "t": tok, "channel": "afdian"})
check("已到账的订单不能再建支付单", not r.get("ok"), r)
finally:
srv.terminate()
try:
out = srv.communicate(timeout=5)[0].decode()
except Exception:
out = ""
shutil.rmtree(DATA, ignore_errors=True)
bad = [n for n, ok in RESULTS if not ok]
print("\n%d 条,失败 %d 条" % (len(RESULTS), len(bad)))
for n in bad:
print(" ✗ " + n)
if bad and out:
print(out[-2000:])
sys.exit(1 if bad else 0)