feat(fulfillment): 增加签名 Webhook 事务 Outbox
- 新增直播履约状态事务 Outbox 与签名投递 worker - 增加 order_site 状态回传、重试和低频对账兜底 - 补充 Outbox、签名校验与集成接口测试
This commit is contained in:
@@ -2,7 +2,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
@@ -21,7 +20,6 @@ from ..services.audit_service import record_audit
|
||||
from ..services.platform_fulfillment import service
|
||||
|
||||
router = APIRouter(prefix="/api/platform-fulfillment", tags=["直播账号履约"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@router.get("/settings")
|
||||
@@ -65,10 +63,6 @@ def list_tasks(
|
||||
current: User = Depends(require_permission("platform_fulfillment:view")),
|
||||
) -> dict[str, Any]:
|
||||
del current
|
||||
try:
|
||||
service.sync_pending_tasks_if_due(db, limit=100)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("自动同步待履约订单失败,继续返回本地任务: %s", exc)
|
||||
return service.list_tasks(
|
||||
db,
|
||||
status=status,
|
||||
|
||||
@@ -2,19 +2,26 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import UTC, datetime
|
||||
from hmac import compare_digest
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..models import IntegrationInbox
|
||||
from ..schemas import (
|
||||
PlatformFulfillmentCustomerBindingAction,
|
||||
PlatformFulfillmentCustomerSessionBatchRequest,
|
||||
PlatformFulfillmentCustomerSessionRequest,
|
||||
)
|
||||
from ..services.integration.security import (
|
||||
verify_webhook_signature,
|
||||
webhook_tolerance_seconds,
|
||||
)
|
||||
from ..services.platform_fulfillment import service
|
||||
|
||||
router = APIRouter(
|
||||
@@ -33,16 +40,51 @@ def require_integration_key(
|
||||
raise HTTPException(status_code=401, detail="直播账号履约集成鉴权失败")
|
||||
|
||||
|
||||
@router.post(
|
||||
"/events/order-sync",
|
||||
dependencies=[Depends(require_integration_key)],
|
||||
)
|
||||
def sync_order_event(
|
||||
payload: dict[str, Any],
|
||||
@router.post("/events/order-sync")
|
||||
async def sync_order_event(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
x_integration_key: str = Header("", alias="X-Integration-Key"),
|
||||
x_integration_event_id: str = Header("", alias="X-Integration-Event-Id"),
|
||||
x_integration_timestamp: str = Header("", alias="X-Integration-Timestamp"),
|
||||
x_integration_signature: str = Header("", alias="X-Integration-Signature"),
|
||||
) -> dict[str, Any]:
|
||||
del payload
|
||||
return service.sync_pending_tasks(db, limit=500)
|
||||
require_integration_key(x_integration_key)
|
||||
raw_body = await request.body()
|
||||
if not verify_webhook_signature(
|
||||
secret=x_integration_key,
|
||||
timestamp=x_integration_timestamp,
|
||||
raw_body=raw_body,
|
||||
signature=x_integration_signature,
|
||||
tolerance_seconds=webhook_tolerance_seconds(),
|
||||
):
|
||||
raise HTTPException(status_code=401, detail="直播账号履约 Webhook 签名无效")
|
||||
|
||||
try:
|
||||
payload = json.loads(raw_body)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise HTTPException(status_code=400, detail="Webhook JSON 无效") from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise HTTPException(status_code=400, detail="Webhook 载荷必须是对象")
|
||||
|
||||
event_id = str(payload.get("eventId") or "").strip()
|
||||
event_type = str(payload.get("eventType") or "").strip()
|
||||
if not event_id or event_id != x_integration_event_id.strip():
|
||||
raise HTTPException(status_code=400, detail="Webhook 事件编号不一致")
|
||||
if db.get(IntegrationInbox, event_id) is not None:
|
||||
return {"fetched": 0, "created": 0, "updated": 0, "duplicate": True}
|
||||
|
||||
inbox = IntegrationInbox(
|
||||
event_id=event_id,
|
||||
source="order_site",
|
||||
event_type=event_type,
|
||||
received_at=datetime.now(UTC),
|
||||
)
|
||||
db.add(inbox)
|
||||
result = service.sync_pending_tasks(db, limit=500, commit=False)
|
||||
inbox.processed_at = datetime.now(UTC)
|
||||
db.commit()
|
||||
return {**result, "duplicate": False}
|
||||
|
||||
|
||||
@router.post(
|
||||
|
||||
Reference in New Issue
Block a user