优化斗鱼充值日志与配置

This commit is contained in:
yml2213
2026-08-14 11:27:53 +08:00
parent 0bf69c1240
commit e2a45b7893
13 changed files with 193 additions and 52 deletions
+1 -1
View File
@@ -21,7 +21,7 @@ from utils import setup_logger
@asynccontextmanager
async def lifespan(app: FastAPI):
# 初始化日志(控制台 + 按天命名文件)
_log_level = os.getenv("LOG_LEVEL", "DEBUG")
_log_level = os.getenv("LOG_LEVEL", "INFO")
_log_dir = Path(__file__).resolve().parents[2] / "logs"
setup_logger(level=_log_level, log_dir=str(_log_dir))
@@ -0,0 +1,51 @@
"""将斗鱼供应商直充默认账号模板切换为昵称。
Revision ID: 20260814_0028
Revises: 20260813_0027
Create Date: 2026-08-14
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "20260814_0028"
down_revision: Union[str, None] = "20260813_0027"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""只迁移历史默认值,保留运营人员明确配置的模板名。"""
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table("douyu_config"):
return
columns = {column["name"] for column in inspector.get_columns("douyu_config")}
if "gold_api_account_template_name" in columns:
op.execute(
sa.text(
"UPDATE douyu_config SET gold_api_account_template_name = :new "
"WHERE gold_api_account_template_name IS NULL "
"OR TRIM(gold_api_account_template_name) = '' "
"OR gold_api_account_template_name = :old"
).bindparams(new="斗鱼昵称", old="斗鱼UID")
)
def downgrade() -> None:
"""回滚时只回退本迁移设置的默认昵称。"""
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table("douyu_config"):
return
columns = {column["name"] for column in inspector.get_columns("douyu_config")}
if "gold_api_account_template_name" in columns:
op.execute(
sa.text(
"UPDATE douyu_config SET gold_api_account_template_name = :old "
"WHERE gold_api_account_template_name = :new"
).bindparams(new="斗鱼昵称", old="斗鱼UID")
)
+1 -1
View File
@@ -218,7 +218,7 @@ class DouyuConfig(Base):
gold_pay_type = Column(Integer, default=1)
gold_recharge_channel = Column(String(16), default="wechat_qr")
gold_api_product_id = Column(String(128), default="111570")
gold_api_account_template_name = Column(String(64), default="斗鱼UID")
gold_api_account_template_name = Column(String(64), default="斗鱼昵称")
gift_id = Column(String(64), default="23643")
skin_id = Column(String(64), default="2942")
updated_at = Column(DateTime, default=_utcnow, onupdate=_utcnow)
+1 -1
View File
@@ -587,7 +587,7 @@ class DouyuConfigOut(BaseModel):
gold_pay_type: int = 1
gold_recharge_channel: str = "wechat_qr"
gold_api_product_id: str = "111570"
gold_api_account_template_name: str = "斗鱼UID"
gold_api_account_template_name: str = "斗鱼昵称"
gift_id: str = "23643"
skin_id: str = "2942"
updated_at: Optional[datetime] = None
+49 -29
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
import re
import threading
import time
from decimal import Decimal
@@ -760,6 +761,15 @@ class DouyuBatchRunner:
}
return result
@staticmethod
def _supplier_out_order_id(task: DouyuTask) -> str:
"""生成可追踪的供应商外部订单号;已有订单号必须在重试时复用。"""
existing = str(task.supplier_out_order_id or "").strip()
if existing:
return existing
batch_token = re.sub(r"[^A-Za-z0-9]", "", str(task.batch_id or "")).upper()[:16] or "LOCAL"
return f"DYGF{batch_token}T{task.id}"
def _wait_supplier_gold_order(
self,
db: Session,
@@ -2456,7 +2466,7 @@ class DouyuBatchRunner:
channel = str(config.get("gold_recharge_channel") or "wechat_qr")
if channel == "supplier_api":
try:
self._execute_create_gold_supplier_order(db, task, account, config, amount)
self._execute_create_gold_supplier_order(db, task, account, cookie, config, amount)
except FishFinRechargeError as exc:
self._mark_task(db, task, "failed", str(exc), {"recharge_channel": "supplier_api"})
return
@@ -2500,24 +2510,28 @@ class DouyuBatchRunner:
db: Session,
task: DouyuTask,
account: Account,
cookie: str,
config: dict,
amount: int,
) -> None:
"""创建供应商鱼翅直充订单并轮询订单状态。"""
product_id = str(config.get("gold_api_product_id") or "").strip()
template_name = str(config.get("gold_api_account_template_name") or "斗鱼UID").strip()
template_name = str(config.get("gold_api_account_template_name") or "斗鱼昵称").strip()
if not product_id:
raise FishFinRechargeError("请先在配置中填写供应商直充商品 ID")
charge_account = str(account.uid or "").strip()
if not charge_account:
raise FishFinRechargeError("账号缺少斗鱼 UID,无法发起供应商直充")
# 充值商品按斗鱼昵称识别账号,UID 只能作为审计信息,不能作为充值值。
update_account_profile_from_cookie(account, cookie)
recharge_account = str(account.nickname or "").strip()
if not recharge_account:
raise FishFinRechargeError("账号缺少斗鱼昵称,无法发起供应商直充")
# task.id 是唯一且稳定的外部订单号来源,重试时不会创建不同的供应商订单。
order_no = f"DYGF{task.id}"
# 首次生成后持久化,网络重试或进程重启都继续查询同一笔订单。
order_no = self._supplier_out_order_id(task)
task.supplier_out_order_id = order_no
db.commit()
# pay_amount 是用户选择的充值面值;goodsFaceValue=0.993 是供货成本,不能作为支付金额。
pay_amount = Decimal(amount)
def trace(event: dict) -> None:
"""将脱敏供应商协议信息输出到任务日志,便于线上联调。"""
stage = event.get("stage")
@@ -2525,36 +2539,41 @@ class DouyuBatchRunner:
params = event.get("params") or {}
self._push_log(
"info",
"供应商直充请求 "
f"path={event.get('path')} out_order_id={params.get('out_order_id')} "
f"buy_num={params.get('buy_num')} pay_amount={params.get('pay_amount')} "
f"product_id={params.get('product_id')} types={event.get('parameter_types')} "
f"sign_digest={event.get('sign_digest')}",
"供应商直充 | 下单 "
f"| 外部单号={params.get('out_order_id') or '-'} "
f"| 数量={params.get('buy_num') or '-'} "
f"| 金额={params.get('pay_amount') or '-'} "
f"| 商品={params.get('product_id') or '-'}",
)
if event.get("json_body"):
self._push_log(
"info",
"供应商直充完整调试请求 "
f"url={event.get('url')} content_type={event.get('content_type')} "
f"body={FishFinRechargeClient._json_text(event['json_body'])} "
f"sign_params={FishFinRechargeClient._json_text(event.get('sign_params') or {})} "
f"sign_source={event.get('sign_source')}",
"debug",
"供应商协议 | 请求 "
f"| {event.get('method')} {event.get('path')} "
f"| 签名摘要={event.get('sign_digest')} "
f"| 参数={FishFinRechargeClient._json_text(event['json_body'])}",
)
elif stage == "response":
status = self._to_int(event.get("order_status"))
status_labels = {0: "待处理", 1: "处理中", 2: "成功", 3: "失败", 4: "异常"}
status_text = status_labels.get(status, "-")
reason = str(event.get("fail_reason") or event.get("message") or "-")
self._push_log(
"info",
"供应商直充响应 "
f"http={event.get('http_status')} code={event.get('code')} "
f"message={event.get('message') or '-'} keys={event.get('keys')} "
f"data_keys={event.get('data_keys')} result_keys={event.get('result_keys')}",
"供应商直充 | 响应 "
f"| HTTP={event.get('http_status') or '-'} "
f"| 业务码={event.get('code') or '-'} "
f"| 外部单号={event.get('out_order_id') or '-'} "
f"| 供应商单号={event.get('order_id') or '-'} "
f"| 状态={status_text} "
f"| 提示={reason}",
)
if event.get("response_body"):
self._push_log(
"info",
"供应商直充完整调试响应 "
f"headers={FishFinRechargeClient._json_text(event.get('response_headers') or {})} "
f"body={FishFinRechargeClient._json_text(event['response_body'])} "
f"raw={event.get('response_text')}",
"debug",
"供应商协议 | 响应 "
f"| HTTP={event.get('http_status')} "
f"| 内容={FishFinRechargeClient._json_text(event['response_body'])}",
)
client = FishFinRechargeClient(FishFinRechargeConfig.from_env(), trace=trace)
@@ -2563,7 +2582,7 @@ class DouyuBatchRunner:
pay_amount=pay_amount,
out_order_id=order_no,
product_id=product_id,
recharge_arg=[{"templateName": template_name, "templateVal": charge_account}],
recharge_arg=[{"templateName": template_name, "templateVal": recharge_account}],
order_type=0,
notify_url=client.config.notify_url,
)
@@ -2573,7 +2592,8 @@ class DouyuBatchRunner:
"recharge_channel": "supplier_api",
"out_order_id": order_no,
"order_id": self._supplier_value(order_payload, "order_id", "orderId"),
"charge_account": charge_account,
"recharge_account": recharge_account,
"douyu_uid": str(account.uid or "").strip(),
"buy_num": amount,
"product_id": product_id,
"pay_amount": format(pay_amount.normalize(), "f"),
+1 -1
View File
@@ -87,7 +87,7 @@ DOUYU_CONFIG_DEFAULTS = { "manual_id": "G4KA4Qnz4LDp7",
"gold_pay_type": 1,
"gold_recharge_channel": "wechat_qr",
"gold_api_product_id": "111570",
"gold_api_account_template_name": "斗鱼UID",
"gold_api_account_template_name": "斗鱼昵称",
"gift_id": "23643",
"skin_id": "2942",
"xpd_act_alias": "20260623KDQFH",
+1 -1
View File
@@ -2227,7 +2227,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
<>
{[
{ label: '供应商商品 ID', key: 'gold_api_product_id' },
{ label: '充值账号模板名', key: 'gold_api_account_template_name' },
{ label: '充值账号模板名(值为斗鱼昵称)', key: 'gold_api_account_template_name' },
].map(({ label, key }) => (
<Space key={key} style={{ width: '100%', justifyContent: 'space-between' }}>
<Text>{label}</Text>