diff --git a/services/admin_service/consumers/billing_message_consumer.py b/services/admin_service/consumers/billing_message_consumer.py index 80b1f6e..21980db 100644 --- a/services/admin_service/consumers/billing_message_consumer.py +++ b/services/admin_service/consumers/billing_message_consumer.py @@ -8,7 +8,7 @@ import threading import time import logging from typing import Callable - +import os from services.common.config import Config from services.common.database import get_db from services.admin_service.services.billing_message_handler import BillingMessageHandler @@ -20,7 +20,7 @@ class BillingMessageConsumer: """Billing message consumer""" def __init__(self): - self.queue_name = "billing.api.calls" + self.queue_name = os.getenv("BILLING_QUEUE_NAME") or "billing.api.calls" self.connection = None self.channel = None self.consuming = False diff --git a/services/admin_service/main.py b/services/admin_service/main.py index 1de540b..e19f9ff 100644 --- a/services/admin_service/main.py +++ b/services/admin_service/main.py @@ -66,7 +66,7 @@ def stop_billing_consumer(): async def lifespan(app: FastAPI): """Application lifecycle management""" global consumer_thread - start_alipay_order_monitor() + # start_alipay_order_monitor() # Startup: Start consumer in separate thread logger.info("Admin Service starting...") @@ -82,7 +82,7 @@ async def lifespan(app: FastAPI): # Shutdown: Stop consumer logger.info("Admin Service shutting down...") stop_billing_consumer() - start_alipay_order_monitor() + # start_alipay_order_monitor() app = FastAPI(title="Admin Service", openapi_url="/openapi.json", lifespan=lifespan) diff --git a/services/admin_service/services/billing_message_handler.py b/services/admin_service/services/billing_message_handler.py index 7bdbc81..5ab2743 100644 --- a/services/admin_service/services/billing_message_handler.py +++ b/services/admin_service/services/billing_message_handler.py @@ -90,11 +90,12 @@ class BillingMessageHandler: service_id=message_data["service_id"], api_id=message_data["api_id"], tool_name=message_data["tool_name"], - input_params=message_data["input_params"], + input_params=message_data["input_params"], call_success=message_data["call_success"], unit_price=Decimal(message_data["unit_price"]), input_token=Decimal(message_data["input_token"]), output_token=Decimal(message_data["output_token"]), + charge_type=message_data["charge_type"], call_start_time=call_start_time, call_end_time=call_end_time, apikey_id=message_data.get("apikey_id"), # Support older version messages that don't have this field @@ -186,7 +187,7 @@ class BillingMessageHandler: status=1, # Completed transaction_id=call_log_id, channel_user_id=None, - callback_data=json.dumps(billing_message), + callback_data=json.dumps(self._billing_message_to_dict(billing_message)), created_at=now, updated_at=now, ) @@ -229,3 +230,30 @@ class BillingMessageHandler: except Exception as e: logger.warning(f"Failed to update wallet cache - User ID: {user_id}: {str(e)}") # Cache update failure doesn't affect main flow + + def _billing_message_to_dict(self, billing_message: BillingMessage) -> dict: + """ + Convert BillingMessage to JSON serializable dictionary + + Args: + billing_message: BillingMessage object + + Returns: + dict: JSON serializable dictionary + """ + return { + "user_id": billing_message.user_id, + "service_id": billing_message.service_id, + "api_id": billing_message.api_id, + "tool_name": billing_message.tool_name, + "input_params": billing_message.input_params, + "call_success": billing_message.call_success, + "unit_price": str(billing_message.unit_price), + "input_token": str(billing_message.input_token), + "output_token": str(billing_message.output_token), + "charge_type": billing_message.charge_type, + "call_start_time": billing_message.call_start_time.isoformat(), + "call_end_time": billing_message.call_end_time.isoformat() if billing_message.call_end_time else None, + "call_log_id": billing_message.call_log_id, + "apikey_id": billing_message.apikey_id, + } diff --git a/services/api_service/services/billing_service.py b/services/api_service/services/billing_service.py index 2791d50..ec67af2 100644 --- a/services/api_service/services/billing_service.py +++ b/services/api_service/services/billing_service.py @@ -3,6 +3,7 @@ Billing service - Handle user API call billing logic """ import json +import os import uuid import asyncio from datetime import datetime, timezone @@ -30,7 +31,7 @@ class BillingService: BILLING_LOCK_TIMEOUT = 5 # Distributed lock timeout (seconds) WALLET_CACHE_EXPIRE = 300 # Wallet cache expiration time (seconds) SERVICE_CACHE_EXPIRE = 3600 # Service price cache expiration time (seconds) - BILLING_QUEUE_NAME = "billing.api.calls" + BILLING_QUEUE_NAME = os.getenv("BILLING_QUEUE_NAME") or "billing.api.calls" def __init__(self): self.redis = redis_client @@ -150,6 +151,9 @@ class BillingService: "input_params": message.input_params, "call_success": message.call_success, "unit_price": str(message.unit_price), + "input_token": str(message.input_token), + "output_token": str(message.output_token), + "charge_type": message.charge_type, "call_start_time": message.call_start_time.isoformat(), "call_end_time": message.call_end_time.isoformat() if message.call_end_time else None, "apikey_id": message.apikey_id, diff --git a/services/api_service/services/mcp_server_factory.py b/services/api_service/services/mcp_server_factory.py index f283663..4fe887c 100644 --- a/services/api_service/services/mcp_server_factory.py +++ b/services/api_service/services/mcp_server_factory.py @@ -214,9 +214,9 @@ class McpServerFactory: api_id=call_log_id, tool_name=name, input_params=json.dumps(arguments), - unit_price=input_token_amount + output_token_amount, - input_token=Decimal(str(input_token)), - output_token=Decimal(str(output_token)), + unit_price=(input_token_amount + output_token_amount).quantize(Decimal('0.000001')), + input_token=Decimal(str(input_token)).quantize(Decimal('0')), + output_token=Decimal(str(output_token)).quantize(Decimal('0')), charge_type=pre_deduct_result.charge_type, call_start_time=call_start_time, call_end_time=call_end_time, diff --git a/services/common/config/billing_config.py b/services/common/config/billing_config.py index 91576f9..3fb6370 100644 --- a/services/common/config/billing_config.py +++ b/services/common/config/billing_config.py @@ -1,11 +1,11 @@ """ """ - +import os BILLING_LOCK_TIMEOUT = 5 WALLET_CACHE_EXPIRE = 300 SERVICE_CACHE_EXPIRE = 3600 -BILLING_QUEUE_NAME = "billing.api.calls" +BILLING_QUEUE_NAME = os.getenv("BILLING_QUEUE_NAME") or "billing.api.calls" BILLING_EXCHANGE_NAME = "billing.exchange" BILLING_ROUTING_KEY = "api.call.billing" diff --git a/services/common/models/user_wallet_history.py b/services/common/models/user_wallet_history.py index c955b44..c80200b 100644 --- a/services/common/models/user_wallet_history.py +++ b/services/common/models/user_wallet_history.py @@ -38,10 +38,10 @@ class UserWalletHistory(Base): comment="Payment method: platform, stripe, alipay, wechat", ) amount: Mapped[float] = mapped_column( - Numeric(10, 2), nullable=False, comment="Transaction amount (positive for deposit, negative for consumption, 2 decimal places)" + Numeric(16, 6), nullable=False, comment="Transaction amount (positive for deposit, negative for consumption, 6 decimal places)" ) balance_after: Mapped[float] = mapped_column( - Numeric(10, 2), nullable=False, comment="Balance after transaction (2 decimal places)" + Numeric(16, 6), nullable=False, comment="Balance after transaction (6 decimal places)" ) type: Mapped[TransactionType] = mapped_column( Enum(TransactionType, values_callable=lambda obj: [e.value for e in obj]),