"""order_site -> live-hub 的直播账号履约服务端集成接口。""" 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, 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( prefix="/api/integration/platform-fulfillment", tags=["直播账号履约集成"], ) def require_integration_key( x_integration_key: str = Header("", alias="X-Integration-Key"), ) -> None: expected = os.getenv("PLATFORM_FULFILLMENT_INTEGRATION_KEY", "").strip() if not expected: raise HTTPException(status_code=503, detail="直播账号履约集成密钥未配置") if not x_integration_key or not compare_digest(x_integration_key, expected): raise HTTPException(status_code=401, detail="直播账号履约集成鉴权失败") @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]: 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( "/customer-sessions/ensure", dependencies=[Depends(require_integration_key)] ) def ensure_customer_session( req: PlatformFulfillmentCustomerSessionRequest, db: Session = Depends(get_db), ) -> dict[str, Any]: return service.ensure_customer_session( db, source_order_item_id=req.source_order_item_id, platform_order_id=req.platform_order_id, ) @router.post( "/customer-sessions/{task_id}/binding/start", dependencies=[Depends(require_integration_key)], ) async def start_customer_binding( task_id: int, req: PlatformFulfillmentCustomerBindingAction, db: Session = Depends(get_db), ) -> dict[str, Any]: return await service.customer_start_binding( db, task_id=task_id, force_refresh=req.force_refresh, ) @router.get( "/customer-sessions/{task_id}/status", dependencies=[Depends(require_integration_key)], ) def get_customer_binding_status( task_id: int, db: Session = Depends(get_db), ) -> dict[str, Any]: return service.customer_refresh_binding(db, task_id=task_id) @router.post( "/customer-sessions/status/batch", dependencies=[Depends(require_integration_key)], ) def get_customer_binding_statuses( req: PlatformFulfillmentCustomerSessionBatchRequest, db: Session = Depends(get_db), ) -> dict[str, Any]: return service.customer_refresh_bindings(db, task_ids=req.task_ids) @router.post( "/customer-sessions/{task_id}/binding/confirm", dependencies=[Depends(require_integration_key)], ) async def confirm_customer_binding( task_id: int, db: Session = Depends(get_db), ) -> dict[str, Any]: return await service.customer_confirm_binding(db, task_id=task_id)