feat(fulfillment): 增加签名 Webhook 事务 Outbox

- 新增直播履约状态事务 Outbox 与签名投递 worker
- 增加 order_site 状态回传、重试和低频对账兜底
- 补充 Outbox、签名校验与集成接口测试
This commit is contained in:
yml
2026-11-18 10:59:20 +08:00
parent 00c4a268c2
commit bba3d9dac9
17 changed files with 967 additions and 114 deletions
@@ -0,0 +1,72 @@
"""签名 Webhook 的 HMAC 与时间窗校验。"""
from __future__ import annotations
import hashlib
import hmac
import time
DEFAULT_TOLERANCE_SECONDS = 300
def build_webhook_signature(secret: str, timestamp: str, raw_body: bytes) -> str:
content = timestamp.encode("utf-8") + b"." + raw_body
digest = hmac.new(secret.encode("utf-8"), content, hashlib.sha256).hexdigest()
return f"sha256={digest}"
def verify_webhook_signature(
*,
secret: str,
timestamp: str,
raw_body: bytes,
signature: str,
tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
now_seconds: int | None = None,
) -> bool:
return verify_webhook_signature_at(
secret=secret,
timestamp=timestamp,
raw_body=raw_body,
signature=signature,
tolerance_seconds=tolerance_seconds,
now_seconds=now_seconds,
)
def verify_webhook_signature_at(
*,
secret: str,
timestamp: str,
raw_body: bytes,
signature: str,
tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
now_seconds: int | None = None,
) -> bool:
secret = secret.strip()
timestamp = timestamp.strip()
signature = signature.strip()
if not secret or not timestamp or not signature:
return False
try:
timestamp_seconds = int(timestamp)
except ValueError:
return False
if timestamp_seconds <= 0:
return False
tolerance = max(1, int(tolerance_seconds))
current = int(now_seconds if now_seconds is not None else time.time())
if abs(current - timestamp_seconds) > tolerance:
return False
expected = build_webhook_signature(secret, timestamp, raw_body)
return hmac.compare_digest(expected, signature)
def webhook_tolerance_seconds() -> int:
import os
try:
value = int(os.getenv("PLATFORM_FULFILLMENT_WEBHOOK_TOLERANCE_SECONDS", "300"))
except ValueError:
return DEFAULT_TOLERANCE_SECONDS
return value if value > 0 else DEFAULT_TOLERANCE_SECONDS