From 721f8b990d5e38d6ebd4924d87554640be55c0a3 Mon Sep 17 00:00:00 2001 From: stefanfeng Date: Tue, 20 Oct 2026 14:37:02 +0800 Subject: [PATCH] fix: acknowledge signed payment notice before querying provider --- digital-avatar-app/backend/main.py | 2 +- digital-avatar-app/backend/routers/tokens.py | 26 +++++++------------ .../backend/tests/test_takeover_scheduler.py | 2 +- .../tests/test_virtual_payment_flow.py | 14 ++++++---- .../docs/HUIHUI_VIRTUAL_CALLBACK.md | 2 +- 5 files changed, 21 insertions(+), 25 deletions(-) diff --git a/digital-avatar-app/backend/main.py b/digital-avatar-app/backend/main.py index ce82645..87dd5f3 100644 --- a/digital-avatar-app/backend/main.py +++ b/digital-avatar-app/backend/main.py @@ -320,7 +320,7 @@ def start_maintenance_scheduler(): ) maintenance_scheduler.add_job( reconcile_huihui_org_notices_job, - trigger=IntervalTrigger(seconds=30), + trigger=IntervalTrigger(seconds=10), id="reconcile_huihui_org_notices", max_instances=1, coalesce=True, diff --git a/digital-avatar-app/backend/routers/tokens.py b/digital-avatar-app/backend/routers/tokens.py index c672bfc..a4bc8aa 100644 --- a/digital-avatar-app/backend/routers/tokens.py +++ b/digital-avatar-app/backend/routers/tokens.py @@ -896,19 +896,10 @@ def _process_huihui_org_notice(payload: dict, db: Session): raise HTTPException(status_code=409, detail="payment number conflicts with prior notice") if not order.provider_order_no: raise HTTPException(status_code=422, detail="provider order number missing") - if not user.huihui_token or not user.huihui_user_id: - _save_huihui_org_notice(db, order, payment_no, amount_cents, expected_product_id, "unavailable") - return ok({"received": True, "paid": False, "awaitingProvider": True}) - try: - provider_status = _huihui_org_provider_status(order, user, expected_product_id, payment_no) - except HuihuiPaymentError: - _save_huihui_org_notice(db, order, payment_no, amount_cents, expected_product_id, "unavailable") - return ok({"received": True, "paid": False, "awaitingProvider": True}) - if provider_status not in {2, 3, 4}: - _save_huihui_org_notice(db, order, payment_no, amount_cents, expected_product_id, str(provider_status)) - return ok({"received": True, "paid": False, "awaitingProvider": True}) - _settle_verified_huihui_org_order(db, order, payment_no, notice) - return ok({"received": True, "paid": True}) + # The provider may not mark its order paid until it receives our HTTP 200. + # Never synchronously query the provider before acknowledging a signed notice. + _save_huihui_org_notice(db, order, payment_no, amount_cents, expected_product_id) + return ok({"received": True, "paid": False, "awaitingProvider": True}) def _huihui_org_provider_status(order: TokenPaymentOrder, user: User, product_id: str, payment_no: str) -> int: @@ -936,7 +927,7 @@ def _huihui_org_provider_status(order: TokenPaymentOrder, user: User, product_id def _save_huihui_org_notice( db: Session, order: TokenPaymentOrder, payment_no: str, amount_cents: int, - product_id: str, provider_status: str, + product_id: str, ) -> None: notice = db.get(HuihuiOrgPaymentNotice, order.order_no) if notice and ( @@ -952,10 +943,11 @@ def _save_huihui_org_notice( ) db.add(notice) notice.status = "awaiting_provider" - notice.last_provider_status = provider_status + notice.last_provider_status = "not_checked" notice.last_error = "" - notice.attempts = int(notice.attempts or 0) + 1 - notice.next_check_at = datetime.utcnow() + timedelta(seconds=_huihui_notice_retry_seconds(notice.attempts)) + first_check = datetime.utcnow() + timedelta(seconds=5) + if notice.next_check_at is None or notice.next_check_at > first_check: + notice.next_check_at = first_check try: db.commit() except IntegrityError: diff --git a/digital-avatar-app/backend/tests/test_takeover_scheduler.py b/digital-avatar-app/backend/tests/test_takeover_scheduler.py index 2d62bb5..fb71615 100644 --- a/digital-avatar-app/backend/tests/test_takeover_scheduler.py +++ b/digital-avatar-app/backend/tests/test_takeover_scheduler.py @@ -61,7 +61,7 @@ def test_scheduler_uses_boxim_and_restart_safe_service( assert close_orders_call.kwargs["trigger"].interval.total_seconds() == 60 assert reconcile_call.args[0] is main.reconcile_huihui_org_notices_job assert reconcile_call.kwargs["id"] == "reconcile_huihui_org_notices" - assert reconcile_call.kwargs["trigger"].interval.total_seconds() == 30 + assert reconcile_call.kwargs["trigger"].interval.total_seconds() == 10 maintenance_scheduler.start.assert_called_once_with() assert scheduler.add_job.call_count == 2 diff --git a/digital-avatar-app/backend/tests/test_virtual_payment_flow.py b/digital-avatar-app/backend/tests/test_virtual_payment_flow.py index e5d0f68..3bb7540 100644 --- a/digital-avatar-app/backend/tests/test_virtual_payment_flow.py +++ b/digital-avatar-app/backend/tests/test_virtual_payment_flow.py @@ -133,26 +133,30 @@ def test_huihui_org_callback_verifies_provider_before_granting_points(authorizat pending = send(payload, callback_path=legacy_path) assert pending.status_code == 200 assert pending.json()["data"] == {"received": True, "paid": False, "awaitingProvider": True} + provider.get_order.assert_not_called() db = SessionLocal() try: assert db.get(HuihuiOrgPaymentNotice, order_no).status == "awaiting_provider" assert db.query(TokenPaymentOrder).filter(TokenPaymentOrder.order_no == order_no).one().status == "pending" finally: db.close() - provider.get_order.return_value = {**provider_data, "payStatus": 2} assert send({**payload, "paymentNo": "wrong"}).status_code == 409 - provider.get_order.return_value = {**provider_data, "payStatus": 2, "chargeAmount": 2} - assert send(payload).status_code == 422 - provider.get_order.return_value = {**provider_data, "payStatus": 2} db = SessionLocal() try: notice = db.get(HuihuiOrgPaymentNotice, order_no) notice.next_check_at = datetime.utcnow() - timedelta(seconds=1) db.commit() from routers.tokens import reconcile_huihui_org_notices + provider.get_order.return_value = {**provider_data, "payStatus": 2, "chargeAmount": 2} + assert reconcile_huihui_org_notices(db) == 0 + assert db.get(HuihuiOrgPaymentNotice, order_no).status == "rejected" + assert db.query(TokenPaymentOrder).filter(TokenPaymentOrder.order_no == order_no).one().status == "pending" + assert send(payload).status_code == 200 + notice.next_check_at = datetime.utcnow() - timedelta(seconds=1) + db.commit() provider.get_order.return_value = provider_data assert reconcile_huihui_org_notices(db) == 0 - assert db.get(HuihuiOrgPaymentNotice, order_no).attempts == 2 + assert db.get(HuihuiOrgPaymentNotice, order_no).attempts == 1 assert db.query(TokenPaymentOrder).filter(TokenPaymentOrder.order_no == order_no).one().status == "pending" notice.next_check_at = datetime.utcnow() - timedelta(seconds=1) db.commit() diff --git a/digital-avatar-app/docs/HUIHUI_VIRTUAL_CALLBACK.md b/digital-avatar-app/docs/HUIHUI_VIRTUAL_CALLBACK.md index e804f49..0dae623 100644 --- a/digital-avatar-app/docs/HUIHUI_VIRTUAL_CALLBACK.md +++ b/digital-avatar-app/docs/HUIHUI_VIRTUAL_CALLBACK.md @@ -28,6 +28,6 @@ - `X-Huihui-Timestamp`:Unix 秒级时间戳,允许与本服务时间相差不超过 300 秒。 - `X-Huihui-Signature`:小写十六进制 HMAC-SHA256,待签名数据为 `时间戳 + 换行符 + 原始请求体字节`。组织充值订单使用服务端配置的 `HUIHUI_ORG_CALLBACK_SECRET`(至少 16 字符),微信直连虚拟支付订单使用独立的 `HUIHUI_VIRTUAL_CALLBACK_SECRET`(至少 32 字符)。不要重排 JSON 后签名,也不要把密钥发给前端。 -成功接收并查单确认已支付时返回 HTTP 200,`{"code":200,"message":"success","data":{"received":true,"paid":true}}`。如果成功通知先于会会查单状态更新到达,会保存已验签通知并返回 HTTP 200、`{"received":true,"paid":false,"awaitingProvider":true}`;此时**不发放积分**,后台仅对这类通知做有上限的延迟复核,查单确认已支付后才入账。重复通知返回 `duplicate: true`,同一订单及支付流水不会重复入账。验签、字段、订单或金额不符返回 HTTP 4xx。服务端未配置密钥时返回 HTTP 503。 +成功通知经签名及本地订单信息核对后,先持久保存并立即返回 HTTP 200、`{"received":true,"paid":false,"awaitingProvider":true}`;回调入口**不等待会会查单**,也**不立即发放积分**。后台仅针对已保存的通知做有上限的延迟复核,待会会查单确认已支付、订单号与支付流水等字段一致后才入账。已入账订单的重复通知返回 `duplicate: true`,不会重复发放积分。验签、字段、订单或金额不符返回 HTTP 4xx。服务端未配置密钥时返回 HTTP 503。 上线前需由会会确认:其服务端是否能按此格式签名并发送通知、支付成功状态与支付流水号字段的正式定义、失败通知及重试/超时策略。小程序支付发起和退款仍需独立对接和验收;仅完成此回调不代表虚拟支付全流程已可用。