初始化提交
This commit is contained in:
110
.gitignore
vendored
Normal file
110
.gitignore
vendored
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
*.so
|
||||||
|
.Python
|
||||||
|
build/
|
||||||
|
develop-eggs/
|
||||||
|
dist/
|
||||||
|
downloads/
|
||||||
|
eggs/
|
||||||
|
.eggs/
|
||||||
|
lib/
|
||||||
|
lib64/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
wheels/
|
||||||
|
pip-wheel-metadata/
|
||||||
|
share/python-wheels/
|
||||||
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
MANIFEST
|
||||||
|
|
||||||
|
# Virtual Environment
|
||||||
|
venv/
|
||||||
|
env/
|
||||||
|
ENV/
|
||||||
|
env.bak/
|
||||||
|
venv.bak/
|
||||||
|
.venv
|
||||||
|
|
||||||
|
# Flask
|
||||||
|
instance/
|
||||||
|
.webassets-cache
|
||||||
|
|
||||||
|
# SQLite
|
||||||
|
*.db
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite3
|
||||||
|
|
||||||
|
# Environment variables
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.development.local
|
||||||
|
.env.test.local
|
||||||
|
.env.production.local
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# Node.js
|
||||||
|
node_modules/
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
# Build outputs
|
||||||
|
dist/
|
||||||
|
dist-ssr/
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Vite
|
||||||
|
.vite/
|
||||||
|
vite.config.*.timestamp-*
|
||||||
|
|
||||||
|
# TypeScript
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
# Testing
|
||||||
|
coverage/
|
||||||
|
.nyc_output/
|
||||||
|
*.lcov
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# OS
|
||||||
|
Thumbs.db
|
||||||
|
.DS_Store
|
||||||
|
Desktop.ini
|
||||||
|
|
||||||
|
# Temporary files
|
||||||
|
*.tmp
|
||||||
|
*.temp
|
||||||
|
*.bak
|
||||||
|
*.cache
|
||||||
|
|
||||||
|
# Database
|
||||||
|
*.db-journal
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
|
||||||
|
# Backup files
|
||||||
|
*.backup
|
||||||
|
*.old
|
||||||
|
|
||||||
|
# Local configuration
|
||||||
|
config.local.py
|
||||||
|
settings.local.py
|
||||||
|
|
||||||
76
NBATransfer-backend/app.py
Normal file
76
NBATransfer-backend/app.py
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
from flask import Flask
|
||||||
|
from flask_cors import CORS
|
||||||
|
from config import config
|
||||||
|
from extensions import db, jwt, mail
|
||||||
|
import os
|
||||||
|
|
||||||
|
# 初始化扩展
|
||||||
|
# jwt = JWTManager() # Moved to extensions.py
|
||||||
|
# mail = Mail() # Moved to extensions.py
|
||||||
|
|
||||||
|
|
||||||
|
def create_app(config_name='default'):
|
||||||
|
"""应用工厂函数"""
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
# 加载配置
|
||||||
|
app.config.from_object(config[config_name])
|
||||||
|
|
||||||
|
# 初始化扩展
|
||||||
|
db.init_app(app)
|
||||||
|
jwt.init_app(app)
|
||||||
|
mail.init_app(app)
|
||||||
|
CORS(app, resources={
|
||||||
|
r"/api/*": {"origins": "*"},
|
||||||
|
r"/v1/*": {"origins": "*"}
|
||||||
|
})
|
||||||
|
|
||||||
|
# 注册蓝图
|
||||||
|
from routes.auth import auth_bp
|
||||||
|
from routes.user import user_bp
|
||||||
|
from routes.order import order_bp
|
||||||
|
from routes.api_service import api_bp
|
||||||
|
from routes.admin import admin_bp
|
||||||
|
from routes.apikey import apikey_bp
|
||||||
|
from routes.v1_api import v1_bp
|
||||||
|
|
||||||
|
app.register_blueprint(auth_bp, url_prefix='/api/auth')
|
||||||
|
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||||
|
app.register_blueprint(order_bp, url_prefix='/api/order')
|
||||||
|
app.register_blueprint(api_bp, url_prefix='/api/service')
|
||||||
|
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||||
|
app.register_blueprint(apikey_bp, url_prefix='/api/apikey')
|
||||||
|
app.register_blueprint(v1_bp, url_prefix='/v1')
|
||||||
|
|
||||||
|
# 创建数据库表
|
||||||
|
with app.app_context():
|
||||||
|
db.create_all()
|
||||||
|
# 创建默认管理员账户
|
||||||
|
from models import User
|
||||||
|
admin = User.query.filter_by(email='admin@nba.com').first()
|
||||||
|
if not admin:
|
||||||
|
admin = User(
|
||||||
|
email='admin@nba.com',
|
||||||
|
username='Admin',
|
||||||
|
is_admin=True,
|
||||||
|
is_active=True
|
||||||
|
)
|
||||||
|
admin.set_password('admin123')
|
||||||
|
db.session.add(admin)
|
||||||
|
db.session.commit()
|
||||||
|
print('默认管理员账户已创建: admin@nba.com / admin123')
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index():
|
||||||
|
return {'message': 'Nano Banana API Transfer Service', 'version': '1.0.0'}
|
||||||
|
|
||||||
|
@app.route('/health')
|
||||||
|
def health():
|
||||||
|
return {'status': 'healthy'}
|
||||||
|
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app = create_app(os.getenv('FLASK_ENV', 'development'))
|
||||||
|
app.run(host='0.0.0.0', port=5000, debug=True)
|
||||||
58
NBATransfer-backend/config.py
Normal file
58
NBATransfer-backend/config.py
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import os
|
||||||
|
from datetime import timedelta
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
"""基础配置"""
|
||||||
|
# Flask配置
|
||||||
|
SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key-change-in-production')
|
||||||
|
|
||||||
|
# 数据库配置
|
||||||
|
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URI', 'sqlite:///nba_transfer.db')
|
||||||
|
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||||
|
|
||||||
|
# JWT配置
|
||||||
|
JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY', 'jwt-secret-key-change-in-production')
|
||||||
|
JWT_ACCESS_TOKEN_EXPIRES = timedelta(hours=24)
|
||||||
|
JWT_REFRESH_TOKEN_EXPIRES = timedelta(days=30)
|
||||||
|
|
||||||
|
# 邮件配置
|
||||||
|
MAIL_SERVER = os.getenv('MAIL_SERVER', 'smtp.qq.com')
|
||||||
|
MAIL_PORT = int(os.getenv('MAIL_PORT', 465))
|
||||||
|
MAIL_USE_TLS = os.getenv('MAIL_USE_TLS', 'False') == 'True'
|
||||||
|
MAIL_USE_SSL = os.getenv('MAIL_USE_SSL', 'True') == 'True'
|
||||||
|
MAIL_USERNAME = os.getenv('MAIL_USERNAME')
|
||||||
|
MAIL_PASSWORD = os.getenv('MAIL_PASSWORD')
|
||||||
|
MAIL_DEFAULT_SENDER = os.getenv('MAIL_USERNAME')
|
||||||
|
|
||||||
|
# 支付配置
|
||||||
|
WECHAT_PAY_APP_ID = os.getenv('WECHAT_PAY_APP_ID')
|
||||||
|
WECHAT_PAY_MCH_ID = os.getenv('WECHAT_PAY_MCH_ID')
|
||||||
|
WECHAT_PAY_API_KEY = os.getenv('WECHAT_PAY_API_KEY')
|
||||||
|
ALIPAY_APP_ID = os.getenv('ALIPAY_APP_ID')
|
||||||
|
ALIPAY_PRIVATE_KEY = os.getenv('ALIPAY_PRIVATE_KEY')
|
||||||
|
ALIPAY_PUBLIC_KEY = os.getenv('ALIPAY_PUBLIC_KEY')
|
||||||
|
|
||||||
|
# 注意:
|
||||||
|
# 模型 API 配置 (DeepSeek, NanoBanana) 和 价格策略
|
||||||
|
# 已迁移至 modelapiservice 模块下的 config.py 中独立管理
|
||||||
|
# 此处不再保留,避免重复定义和混乱
|
||||||
|
|
||||||
|
|
||||||
|
class DevelopmentConfig(Config):
|
||||||
|
"""开发环境配置"""
|
||||||
|
DEBUG = True
|
||||||
|
|
||||||
|
|
||||||
|
class ProductionConfig(Config):
|
||||||
|
"""生产环境配置"""
|
||||||
|
DEBUG = False
|
||||||
|
|
||||||
|
|
||||||
|
config = {
|
||||||
|
'development': DevelopmentConfig,
|
||||||
|
'production': ProductionConfig,
|
||||||
|
'default': DevelopmentConfig
|
||||||
|
}
|
||||||
7
NBATransfer-backend/extensions.py
Normal file
7
NBATransfer-backend/extensions.py
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
from flask_jwt_extended import JWTManager
|
||||||
|
from flask_mail import Mail
|
||||||
|
|
||||||
|
db = SQLAlchemy()
|
||||||
|
jwt = JWTManager()
|
||||||
|
mail = Mail()
|
||||||
16
NBATransfer-backend/modelapiservice/DeepSeek/config.py
Normal file
16
NBATransfer-backend/modelapiservice/DeepSeek/config.py
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# DeepSeek 模型配置
|
||||||
|
import os
|
||||||
|
|
||||||
|
# 价格配置 (CNY per 1M tokens)
|
||||||
|
TOKEN_PRICE_INPUT = 400.0 / 1000000 # 4元 / 1M tokens
|
||||||
|
TOKEN_PRICE_OUTPUT = 1600.0 / 1000000 # 16元 / 1M tokens
|
||||||
|
|
||||||
|
# 最低余额要求
|
||||||
|
MIN_BALANCE = 0.01
|
||||||
|
|
||||||
|
# API 配置 (优先从环境变量获取)
|
||||||
|
def get_config():
|
||||||
|
return {
|
||||||
|
'api_url': os.getenv('DEEPSEEK_API_URL', 'https://api.deepseek.com'),
|
||||||
|
'api_key': os.getenv('DEEPSEEK_API_KEY')
|
||||||
|
}
|
||||||
54
NBATransfer-backend/modelapiservice/DeepSeek/service.py
Normal file
54
NBATransfer-backend/modelapiservice/DeepSeek/service.py
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
from ..base import ModelService
|
||||||
|
from .config import TOKEN_PRICE_INPUT, TOKEN_PRICE_OUTPUT, MIN_BALANCE, get_config
|
||||||
|
from typing import Dict, Any, Tuple, Generator, Union
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class DeepSeekService(ModelService):
|
||||||
|
def get_api_config(self) -> Tuple[str, str]:
|
||||||
|
config = get_config()
|
||||||
|
return config['api_url'], config['api_key']
|
||||||
|
|
||||||
|
def check_balance(self, balance: float) -> Tuple[bool, float, str]:
|
||||||
|
if balance < MIN_BALANCE:
|
||||||
|
return False, MIN_BALANCE, f'余额不足。当前余额: {balance}, 需要至少: {MIN_BALANCE}'
|
||||||
|
return True, 0.0, ""
|
||||||
|
|
||||||
|
def calculate_cost(self, usage: Dict[str, Any] = None, stream: bool = False) -> float:
|
||||||
|
if not usage:
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
prompt_tokens = usage.get('prompt_tokens', 0)
|
||||||
|
completion_tokens = usage.get('completion_tokens', 0)
|
||||||
|
|
||||||
|
cost = (prompt_tokens * TOKEN_PRICE_INPUT) + (completion_tokens * TOKEN_PRICE_OUTPUT)
|
||||||
|
return cost
|
||||||
|
|
||||||
|
def prepare_payload(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
payload = {k: v for k, v in data.items() if k not in ['user']}
|
||||||
|
# 强制 DeepSeek 返回 usage
|
||||||
|
if data.get('stream', False):
|
||||||
|
if 'stream_options' not in payload:
|
||||||
|
payload['stream_options'] = {"include_usage": True}
|
||||||
|
return payload
|
||||||
|
|
||||||
|
def handle_response(self, response, stream: bool) -> Union[Dict[str, Any], Generator]:
|
||||||
|
# Response handling is mostly done in the route handler for stream/json split
|
||||||
|
# but we can provide helper methods to parse usage
|
||||||
|
pass
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def parse_stream_usage(chunk_text: str) -> Dict[str, Any]:
|
||||||
|
"""解析流式响应中的 usage"""
|
||||||
|
try:
|
||||||
|
for line in chunk_text.split('\n'):
|
||||||
|
if line.startswith('data: ') and line != 'data: [DONE]':
|
||||||
|
json_str = line[6:]
|
||||||
|
data_obj = json.loads(json_str)
|
||||||
|
if 'usage' in data_obj and data_obj['usage']:
|
||||||
|
return data_obj['usage']
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return None
|
||||||
12
NBATransfer-backend/modelapiservice/NanoBanana/config.py
Normal file
12
NBATransfer-backend/modelapiservice/NanoBanana/config.py
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
# Nano Banana 模型配置
|
||||||
|
import os
|
||||||
|
|
||||||
|
# 价格配置 (CNY per call)
|
||||||
|
IMAGE_GENERATION_PRICE = float(os.getenv('IMAGE_GENERATION_PRICE', 0.15))
|
||||||
|
|
||||||
|
# API 配置 (优先从环境变量获取)
|
||||||
|
def get_config():
|
||||||
|
return {
|
||||||
|
'api_url': os.getenv('NANO_BANANA_API_URL', 'https://api.nanobanana.com/v1'),
|
||||||
|
'api_key': os.getenv('NANO_BANANA_API_KEY')
|
||||||
|
}
|
||||||
26
NBATransfer-backend/modelapiservice/NanoBanana/service.py
Normal file
26
NBATransfer-backend/modelapiservice/NanoBanana/service.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
from ..base import ModelService
|
||||||
|
from .config import IMAGE_GENERATION_PRICE, get_config
|
||||||
|
from typing import Dict, Any, Tuple, Generator, Union
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class NanoBananaService(ModelService):
|
||||||
|
def get_api_config(self) -> Tuple[str, str]:
|
||||||
|
config = get_config()
|
||||||
|
return config['api_url'], config['api_key']
|
||||||
|
|
||||||
|
def check_balance(self, balance: float) -> Tuple[bool, float, str]:
|
||||||
|
if balance < IMAGE_GENERATION_PRICE:
|
||||||
|
return False, IMAGE_GENERATION_PRICE, f'余额不足。当前余额: {balance}, 需要: {IMAGE_GENERATION_PRICE}'
|
||||||
|
return True, IMAGE_GENERATION_PRICE, ""
|
||||||
|
|
||||||
|
def calculate_cost(self, usage: Dict[str, Any] = None, stream: bool = False) -> float:
|
||||||
|
# 固定按次计费
|
||||||
|
return IMAGE_GENERATION_PRICE
|
||||||
|
|
||||||
|
def prepare_payload(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
return {k: v for k, v in data.items() if k not in ['user']}
|
||||||
|
|
||||||
|
def handle_response(self, response, stream: bool) -> Union[Dict[str, Any], Generator]:
|
||||||
|
pass
|
||||||
10
NBATransfer-backend/modelapiservice/__init__.py
Normal file
10
NBATransfer-backend/modelapiservice/__init__.py
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
from .DeepSeek.service import DeepSeekService
|
||||||
|
from .NanoBanana.service import NanoBananaService
|
||||||
|
|
||||||
|
def get_model_service(model_name: str):
|
||||||
|
"""根据模型名称获取对应的服务实例"""
|
||||||
|
if model_name.startswith('deepseek-'):
|
||||||
|
return DeepSeekService()
|
||||||
|
else:
|
||||||
|
# 默认使用 Nano Banana 服务 (包括文生图等)
|
||||||
|
return NanoBananaService()
|
||||||
33
NBATransfer-backend/modelapiservice/base.py
Normal file
33
NBATransfer-backend/modelapiservice/base.py
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import Dict, Any, Generator, Union, Tuple
|
||||||
|
import requests
|
||||||
|
|
||||||
|
class ModelService(ABC):
|
||||||
|
"""大模型服务基类"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get_api_config(self) -> Tuple[str, str]:
|
||||||
|
"""获取 API URL 和 Key"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def calculate_cost(self, usage: Dict[str, Any] = None, stream: bool = False) -> float:
|
||||||
|
"""计算费用"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def check_balance(self, balance: float) -> Tuple[bool, float, str]:
|
||||||
|
"""检查余额是否充足
|
||||||
|
Returns: (is_sufficient, estimated_cost, error_message)
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def prepare_payload(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
"""准备请求载荷"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def handle_response(self, response: requests.Response, stream: bool) -> Union[Dict[str, Any], Generator]:
|
||||||
|
"""处理响应"""
|
||||||
|
pass
|
||||||
233
NBATransfer-backend/models.py
Normal file
233
NBATransfer-backend/models.py
Normal file
@@ -0,0 +1,233 @@
|
|||||||
|
from datetime import datetime, timedelta
|
||||||
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
|
import secrets
|
||||||
|
import string
|
||||||
|
from extensions import db
|
||||||
|
|
||||||
|
# db = SQLAlchemy() # Moved to extensions.py
|
||||||
|
|
||||||
|
|
||||||
|
class User(db.Model):
|
||||||
|
"""用户模型"""
|
||||||
|
__tablename__ = 'users'
|
||||||
|
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
email = db.Column(db.String(120), unique=True, nullable=False, index=True)
|
||||||
|
password_hash = db.Column(db.String(255), nullable=False)
|
||||||
|
username = db.Column(db.String(80))
|
||||||
|
balance = db.Column(db.Float, default=0.0) # 账户余额
|
||||||
|
is_active = db.Column(db.Boolean, default=True)
|
||||||
|
is_admin = db.Column(db.Boolean, default=False)
|
||||||
|
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||||
|
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
# 关系
|
||||||
|
orders = db.relationship('Order', backref='user', lazy='dynamic', cascade='all, delete-orphan')
|
||||||
|
api_calls = db.relationship('ApiCall', backref='user', lazy='dynamic', cascade='all, delete-orphan')
|
||||||
|
transactions = db.relationship('Transaction', backref='user', lazy='dynamic', cascade='all, delete-orphan')
|
||||||
|
api_keys = db.relationship('APIKey', backref='user', lazy='dynamic', cascade='all, delete-orphan')
|
||||||
|
verification_codes = db.relationship('VerificationCode', backref='user', lazy='dynamic', cascade='all, delete-orphan')
|
||||||
|
|
||||||
|
# 验证状态
|
||||||
|
email_verified = db.Column(db.Boolean, default=False)
|
||||||
|
email_verified_at = db.Column(db.DateTime)
|
||||||
|
|
||||||
|
def set_password(self, password):
|
||||||
|
"""设置密码"""
|
||||||
|
self.password_hash = generate_password_hash(password)
|
||||||
|
|
||||||
|
def check_password(self, password):
|
||||||
|
"""验证密码"""
|
||||||
|
return check_password_hash(self.password_hash, password)
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
"""转换为字典"""
|
||||||
|
return {
|
||||||
|
'id': self.id,
|
||||||
|
'email': self.email,
|
||||||
|
'username': self.username,
|
||||||
|
'balance': self.balance,
|
||||||
|
'is_active': self.is_active,
|
||||||
|
'is_admin': self.is_admin,
|
||||||
|
'created_at': self.created_at.isoformat(),
|
||||||
|
'updated_at': self.updated_at.isoformat()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Order(db.Model):
|
||||||
|
"""订单模型"""
|
||||||
|
__tablename__ = 'orders'
|
||||||
|
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
order_no = db.Column(db.String(50), unique=True, nullable=False, index=True)
|
||||||
|
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
|
||||||
|
amount = db.Column(db.Float, nullable=False) # 充值金额
|
||||||
|
payment_method = db.Column(db.String(20)) # wechat, alipay
|
||||||
|
status = db.Column(db.String(20), default='pending') # pending, paid, cancelled, failed
|
||||||
|
transaction_id = db.Column(db.String(100)) # 第三方交易ID
|
||||||
|
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||||
|
paid_at = db.Column(db.DateTime)
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
"""转换为字典"""
|
||||||
|
return {
|
||||||
|
'id': self.id,
|
||||||
|
'order_no': self.order_no,
|
||||||
|
'user_id': self.user_id,
|
||||||
|
'amount': self.amount,
|
||||||
|
'payment_method': self.payment_method,
|
||||||
|
'status': self.status,
|
||||||
|
'transaction_id': self.transaction_id,
|
||||||
|
'created_at': self.created_at.isoformat(),
|
||||||
|
'paid_at': self.paid_at.isoformat() if self.paid_at else None
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Transaction(db.Model):
|
||||||
|
"""交易记录模型"""
|
||||||
|
__tablename__ = 'transactions'
|
||||||
|
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
|
||||||
|
type = db.Column(db.String(20), nullable=False) # recharge, consume, refund
|
||||||
|
amount = db.Column(db.Float, nullable=False)
|
||||||
|
balance_before = db.Column(db.Float, nullable=False)
|
||||||
|
balance_after = db.Column(db.Float, nullable=False)
|
||||||
|
description = db.Column(db.String(255))
|
||||||
|
order_id = db.Column(db.Integer, db.ForeignKey('orders.id'))
|
||||||
|
api_call_id = db.Column(db.Integer, db.ForeignKey('api_calls.id'))
|
||||||
|
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
"""转换为字典"""
|
||||||
|
return {
|
||||||
|
'id': self.id,
|
||||||
|
'user_id': self.user_id,
|
||||||
|
'type': self.type,
|
||||||
|
'amount': self.amount,
|
||||||
|
'balance_before': self.balance_before,
|
||||||
|
'balance_after': self.balance_after,
|
||||||
|
'description': self.description,
|
||||||
|
'order_id': self.order_id,
|
||||||
|
'api_call_id': self.api_call_id,
|
||||||
|
'created_at': self.created_at.isoformat()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ApiCall(db.Model):
|
||||||
|
"""API调用记录模型"""
|
||||||
|
__tablename__ = 'api_calls'
|
||||||
|
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
|
||||||
|
api_type = db.Column(db.String(50), default='text_to_image') # text_to_image
|
||||||
|
prompt = db.Column(db.Text)
|
||||||
|
parameters = db.Column(db.Text) # JSON格式的参数
|
||||||
|
status = db.Column(db.String(20), default='pending') # pending, processing, success, failed
|
||||||
|
result_url = db.Column(db.String(500)) # 生成结果的URL
|
||||||
|
cost = db.Column(db.Float, default=0.0) # 本次调用费用
|
||||||
|
error_message = db.Column(db.Text)
|
||||||
|
request_time = db.Column(db.DateTime, default=datetime.utcnow)
|
||||||
|
response_time = db.Column(db.DateTime)
|
||||||
|
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
"""转换为字典"""
|
||||||
|
return {
|
||||||
|
'id': self.id,
|
||||||
|
'user_id': self.user_id,
|
||||||
|
'api_type': self.api_type,
|
||||||
|
'prompt': self.prompt,
|
||||||
|
'status': self.status,
|
||||||
|
'result_url': self.result_url,
|
||||||
|
'cost': self.cost,
|
||||||
|
'error_message': self.error_message,
|
||||||
|
'request_time': self.request_time.isoformat(),
|
||||||
|
'response_time': self.response_time.isoformat() if self.response_time else None,
|
||||||
|
'created_at': self.created_at.isoformat()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class SystemConfig(db.Model):
|
||||||
|
"""系统配置模型"""
|
||||||
|
__tablename__ = 'system_configs'
|
||||||
|
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
key = db.Column(db.String(50), unique=True, nullable=False)
|
||||||
|
value = db.Column(db.Text)
|
||||||
|
description = db.Column(db.String(255))
|
||||||
|
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
"""转换为字典"""
|
||||||
|
return {
|
||||||
|
'id': self.id,
|
||||||
|
'key': self.key,
|
||||||
|
'value': self.value,
|
||||||
|
'description': self.description,
|
||||||
|
'updated_at': self.updated_at.isoformat()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class VerificationCode(db.Model):
|
||||||
|
"""邮箱验证码模型"""
|
||||||
|
__tablename__ = 'verification_codes'
|
||||||
|
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
|
||||||
|
email = db.Column(db.String(120), nullable=False)
|
||||||
|
code = db.Column(db.String(6), nullable=False) # 6位验证码
|
||||||
|
purpose = db.Column(db.String(20), default='register') # register, password_reset
|
||||||
|
used = db.Column(db.Boolean, default=False)
|
||||||
|
expired_at = db.Column(db.DateTime, nullable=False) # 过期时间
|
||||||
|
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
|
def is_valid(self):
|
||||||
|
"""检查验证码是否有效"""
|
||||||
|
return not self.used and datetime.utcnow() < self.expired_at
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def generate_code():
|
||||||
|
"""生成6位验证码"""
|
||||||
|
return ''.join(secrets.choice(string.digits) for _ in range(6))
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
return {
|
||||||
|
'id': self.id,
|
||||||
|
'email': self.email,
|
||||||
|
'purpose': self.purpose,
|
||||||
|
'expired_at': self.expired_at.isoformat()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class APIKey(db.Model):
|
||||||
|
"""API密钥模型 - 用户可自己生成"""
|
||||||
|
__tablename__ = 'api_keys'
|
||||||
|
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
|
||||||
|
name = db.Column(db.String(100), nullable=False) # API密钥名称
|
||||||
|
api_key = db.Column(db.String(100), unique=True, nullable=False, index=True) # 实际密钥
|
||||||
|
# secret_key 字段已移除
|
||||||
|
is_active = db.Column(db.Boolean, default=True)
|
||||||
|
last_used_at = db.Column(db.DateTime) # 最后使用时间
|
||||||
|
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def generate_key():
|
||||||
|
"""生成 API Key"""
|
||||||
|
api_key = 'sk_' + ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(32))
|
||||||
|
return api_key
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
"""转换为字典"""
|
||||||
|
data = {
|
||||||
|
'id': self.id,
|
||||||
|
'name': self.name,
|
||||||
|
'api_key': self.api_key,
|
||||||
|
'is_active': self.is_active,
|
||||||
|
'last_used_at': self.last_used_at.isoformat() if self.last_used_at else None,
|
||||||
|
'created_at': self.created_at.isoformat()
|
||||||
|
}
|
||||||
|
return data
|
||||||
9
NBATransfer-backend/requirements.txt
Normal file
9
NBATransfer-backend/requirements.txt
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
Flask==3.0.0
|
||||||
|
Flask-SQLAlchemy==3.1.1
|
||||||
|
Flask-CORS==4.0.0
|
||||||
|
Flask-JWT-Extended==4.6.0
|
||||||
|
Flask-Mail==0.9.1
|
||||||
|
python-dotenv==1.0.0
|
||||||
|
requests==2.31.0
|
||||||
|
Werkzeug==3.0.1
|
||||||
|
email-validator==2.1.0
|
||||||
113
NBATransfer-backend/routes/admin.py
Normal file
113
NBATransfer-backend/routes/admin.py
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
"""管理员相关路由"""
|
||||||
|
from flask import Blueprint, request, jsonify
|
||||||
|
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||||
|
from models import User
|
||||||
|
from services.admin_service import AdminService
|
||||||
|
|
||||||
|
admin_bp = Blueprint('admin', __name__)
|
||||||
|
|
||||||
|
def admin_required():
|
||||||
|
"""管理员权限验证装饰器"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
user = User.query.get(current_user_id)
|
||||||
|
|
||||||
|
if not user or not user.is_admin:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return user
|
||||||
|
|
||||||
|
@admin_bp.route('/users', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_users():
|
||||||
|
"""获取用户列表"""
|
||||||
|
if not admin_required():
|
||||||
|
return jsonify({'error': '需要管理员权限'}), 403
|
||||||
|
|
||||||
|
# 分页参数
|
||||||
|
page = request.args.get('page', 1, type=int)
|
||||||
|
per_page = request.args.get('per_page', 20, type=int)
|
||||||
|
search = request.args.get('search', '')
|
||||||
|
|
||||||
|
result, status_code = AdminService.get_users(page, per_page, search)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@admin_bp.route('/users/<int:user_id>', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_user_detail(user_id):
|
||||||
|
"""获取用户详情"""
|
||||||
|
if not admin_required():
|
||||||
|
return jsonify({'error': '需要管理员权限'}), 403
|
||||||
|
|
||||||
|
result, status_code = AdminService.get_user_detail(user_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@admin_bp.route('/users/<int:user_id>/toggle-status', methods=['POST'])
|
||||||
|
@jwt_required()
|
||||||
|
def toggle_user_status(user_id):
|
||||||
|
"""启用/禁用用户"""
|
||||||
|
admin = admin_required()
|
||||||
|
if not admin:
|
||||||
|
return jsonify({'error': '需要管理员权限'}), 403
|
||||||
|
|
||||||
|
result, status_code = AdminService.toggle_user_status(admin.id, user_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@admin_bp.route('/users/<int:user_id>/adjust-balance', methods=['POST'])
|
||||||
|
@jwt_required()
|
||||||
|
def adjust_balance(user_id):
|
||||||
|
"""调整用户余额"""
|
||||||
|
if not admin_required():
|
||||||
|
return jsonify({'error': '需要管理员权限'}), 403
|
||||||
|
|
||||||
|
data = request.get_json()
|
||||||
|
result, status_code = AdminService.adjust_balance(user_id, data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@admin_bp.route('/orders', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_all_orders():
|
||||||
|
"""获取所有订单"""
|
||||||
|
if not admin_required():
|
||||||
|
return jsonify({'error': '需要管理员权限'}), 403
|
||||||
|
|
||||||
|
page = request.args.get('page', 1, type=int)
|
||||||
|
per_page = request.args.get('per_page', 20, type=int)
|
||||||
|
status = request.args.get('status')
|
||||||
|
|
||||||
|
result, status_code = AdminService.get_all_orders(page, per_page, status)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@admin_bp.route('/api-calls', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_all_api_calls():
|
||||||
|
"""获取所有API调用记录"""
|
||||||
|
if not admin_required():
|
||||||
|
return jsonify({'error': '需要管理员权限'}), 403
|
||||||
|
|
||||||
|
page = request.args.get('page', 1, type=int)
|
||||||
|
per_page = request.args.get('per_page', 20, type=int)
|
||||||
|
status = request.args.get('status')
|
||||||
|
|
||||||
|
result, status_code = AdminService.get_all_api_calls(page, per_page, status)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@admin_bp.route('/stats/overview', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_overview_stats():
|
||||||
|
"""获取总览统计"""
|
||||||
|
if not admin_required():
|
||||||
|
return jsonify({'error': '需要管理员权限'}), 403
|
||||||
|
|
||||||
|
result, status_code = AdminService.get_overview_stats()
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@admin_bp.route('/stats/chart', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_chart_data():
|
||||||
|
"""获取图表数据(最近7天)"""
|
||||||
|
if not admin_required():
|
||||||
|
return jsonify({'error': '需要管理员权限'}), 403
|
||||||
|
|
||||||
|
days = request.args.get('days', 7, type=int)
|
||||||
|
result, status_code = AdminService.get_chart_data(days)
|
||||||
|
return jsonify(result), status_code
|
||||||
45
NBATransfer-backend/routes/api_service.py
Normal file
45
NBATransfer-backend/routes/api_service.py
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
"""API服务相关路由 - 支持 Nano Banana API 代理"""
|
||||||
|
from flask import Blueprint, request, jsonify, current_app
|
||||||
|
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||||
|
from services.api_proxy_service import ApiProxyService
|
||||||
|
|
||||||
|
api_bp = Blueprint('api_service', __name__)
|
||||||
|
|
||||||
|
@api_bp.route('/text-to-image', methods=['POST'])
|
||||||
|
@jwt_required()
|
||||||
|
def text_to_image():
|
||||||
|
"""
|
||||||
|
通用 API 代理 (支持文生图和对话)
|
||||||
|
"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
data = request.get_json()
|
||||||
|
|
||||||
|
result, status_code = ApiProxyService.handle_api_request(current_user_id, data)
|
||||||
|
|
||||||
|
if status_code == 200 and data.get('stream', False):
|
||||||
|
return current_app.response_class(result, mimetype='text/event-stream')
|
||||||
|
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@api_bp.route('/models', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_models():
|
||||||
|
"""
|
||||||
|
获取可用的模型列表
|
||||||
|
"""
|
||||||
|
result, status_code = ApiProxyService.get_models()
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@api_bp.route('/pricing', methods=['GET'])
|
||||||
|
def get_pricing():
|
||||||
|
"""获取价格信息(公开接口)"""
|
||||||
|
result, status_code = ApiProxyService.get_pricing()
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@api_bp.route('/call/<int:call_id>', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_api_call(call_id):
|
||||||
|
"""获取API调用详情"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
result, status_code = ApiProxyService.get_api_call(current_user_id, call_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
56
NBATransfer-backend/routes/apikey.py
Normal file
56
NBATransfer-backend/routes/apikey.py
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
"""用户 API Key 管理相关路由"""
|
||||||
|
from flask import Blueprint, request, jsonify
|
||||||
|
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||||
|
from services.apikey_service import APIKeyService
|
||||||
|
|
||||||
|
apikey_bp = Blueprint('apikey', __name__)
|
||||||
|
|
||||||
|
@apikey_bp.route('/keys', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def list_api_keys():
|
||||||
|
"""获取用户的所有 API Key"""
|
||||||
|
user_id = get_jwt_identity()
|
||||||
|
result, status_code = APIKeyService.list_api_keys(user_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@apikey_bp.route('/keys', methods=['POST'])
|
||||||
|
@jwt_required()
|
||||||
|
def create_api_key():
|
||||||
|
"""创建新的 API Key"""
|
||||||
|
user_id = get_jwt_identity()
|
||||||
|
data = request.get_json()
|
||||||
|
result, status_code = APIKeyService.create_api_key(user_id, data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@apikey_bp.route('/keys/<int:key_id>', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_api_key(key_id):
|
||||||
|
"""获取单个 API Key 详情"""
|
||||||
|
user_id = get_jwt_identity()
|
||||||
|
result, status_code = APIKeyService.get_api_key(user_id, key_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@apikey_bp.route('/keys/<int:key_id>', methods=['PUT'])
|
||||||
|
@jwt_required()
|
||||||
|
def update_api_key(key_id):
|
||||||
|
"""更新 API Key 名称或状态"""
|
||||||
|
user_id = get_jwt_identity()
|
||||||
|
data = request.get_json()
|
||||||
|
result, status_code = APIKeyService.update_api_key(user_id, key_id, data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@apikey_bp.route('/keys/<int:key_id>', methods=['DELETE'])
|
||||||
|
@jwt_required()
|
||||||
|
def delete_api_key(key_id):
|
||||||
|
"""删除 API Key"""
|
||||||
|
user_id = get_jwt_identity()
|
||||||
|
result, status_code = APIKeyService.delete_api_key(user_id, key_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@apikey_bp.route('/keys/<int:key_id>/regenerate', methods=['POST'])
|
||||||
|
@jwt_required()
|
||||||
|
def regenerate_api_key(key_id):
|
||||||
|
"""重置/轮换 API Key"""
|
||||||
|
user_id = get_jwt_identity()
|
||||||
|
result, status_code = APIKeyService.regenerate_api_key(user_id, key_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
70
NBATransfer-backend/routes/auth.py
Normal file
70
NBATransfer-backend/routes/auth.py
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
"""认证相关路由"""
|
||||||
|
from flask import Blueprint, request, jsonify
|
||||||
|
from flask_jwt_extended import jwt_required, get_jwt_identity, create_access_token
|
||||||
|
from services.auth_service import AuthService
|
||||||
|
from services.user_service import UserService
|
||||||
|
|
||||||
|
auth_bp = Blueprint('auth', __name__)
|
||||||
|
|
||||||
|
@auth_bp.route('/send-verification-code', methods=['POST'])
|
||||||
|
def send_verification_code():
|
||||||
|
"""发送验证码"""
|
||||||
|
data = request.get_json()
|
||||||
|
result, status_code = AuthService.send_verification_code(data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@auth_bp.route('/register', methods=['POST'])
|
||||||
|
def register():
|
||||||
|
"""用户注册 - 需要验证码"""
|
||||||
|
data = request.get_json()
|
||||||
|
result, status_code = AuthService.register(data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@auth_bp.route('/login', methods=['POST'])
|
||||||
|
def login():
|
||||||
|
"""用户登录"""
|
||||||
|
data = request.get_json()
|
||||||
|
result, status_code = AuthService.login(data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@auth_bp.route('/me', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_current_user():
|
||||||
|
"""获取当前用户信息"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
result, status_code = UserService.get_profile(current_user_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@auth_bp.route('/change-password', methods=['POST'])
|
||||||
|
@jwt_required()
|
||||||
|
def change_password():
|
||||||
|
"""修改密码"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
data = request.get_json()
|
||||||
|
result, status_code = AuthService.change_password(current_user_id, data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@auth_bp.route('/reset-password', methods=['POST'])
|
||||||
|
def reset_password():
|
||||||
|
"""重置密码 - 需要验证码"""
|
||||||
|
data = request.get_json()
|
||||||
|
result, status_code = AuthService.reset_password(data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@auth_bp.route('/verify-code', methods=['POST'])
|
||||||
|
def verify_code():
|
||||||
|
"""验证验证码是否有效(不标记为已使用)"""
|
||||||
|
data = request.get_json()
|
||||||
|
result, status_code = AuthService.verify_code(data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@auth_bp.route('/refresh', methods=['POST'])
|
||||||
|
@jwt_required(refresh=True)
|
||||||
|
def refresh():
|
||||||
|
"""刷新访问令牌"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
access_token = create_access_token(identity=current_user_id)
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
'access_token': access_token
|
||||||
|
}), 200
|
||||||
57
NBATransfer-backend/routes/order.py
Normal file
57
NBATransfer-backend/routes/order.py
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
"""订单相关路由"""
|
||||||
|
from flask import Blueprint, request, jsonify
|
||||||
|
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||||
|
from services.order_service import OrderService
|
||||||
|
|
||||||
|
order_bp = Blueprint('order', __name__)
|
||||||
|
|
||||||
|
@order_bp.route('/create', methods=['POST'])
|
||||||
|
@jwt_required()
|
||||||
|
def create_order():
|
||||||
|
"""创建充值订单"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
data = request.get_json()
|
||||||
|
result, status_code = OrderService.create_order(current_user_id, data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@order_bp.route('/list', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_orders():
|
||||||
|
"""获取订单列表"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
|
||||||
|
# 分页参数
|
||||||
|
page = request.args.get('page', 1, type=int)
|
||||||
|
per_page = request.args.get('per_page', 20, type=int)
|
||||||
|
status = request.args.get('status')
|
||||||
|
|
||||||
|
result, status_code = OrderService.get_orders(current_user_id, page, per_page, status)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@order_bp.route('/<int:order_id>', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_order(order_id):
|
||||||
|
"""获取订单详情"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
result, status_code = OrderService.get_order(current_user_id, order_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@order_bp.route('/callback/alipay', methods=['POST'])
|
||||||
|
def alipay_callback():
|
||||||
|
"""支付宝支付回调(预留接口)"""
|
||||||
|
data = request.get_json() or request.form.to_dict()
|
||||||
|
result, status_code = OrderService.alipay_callback(data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@order_bp.route('/callback/wechat', methods=['POST'])
|
||||||
|
def wechat_callback():
|
||||||
|
"""微信支付回调(预留接口)"""
|
||||||
|
data = request.get_json() or request.form.to_dict()
|
||||||
|
result, status_code = OrderService.wechat_callback(data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@order_bp.route('/notify/<order_no>', methods=['POST'])
|
||||||
|
def payment_notify(order_no):
|
||||||
|
"""模拟支付通知(仅用于测试)"""
|
||||||
|
result, status_code = OrderService.payment_notify(order_no)
|
||||||
|
return jsonify(result), status_code
|
||||||
65
NBATransfer-backend/routes/user.py
Normal file
65
NBATransfer-backend/routes/user.py
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
"""用户相关路由"""
|
||||||
|
from flask import Blueprint, request, jsonify
|
||||||
|
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||||
|
from services.user_service import UserService
|
||||||
|
|
||||||
|
user_bp = Blueprint('user', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
@user_bp.route('/profile', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_profile():
|
||||||
|
"""获取用户资料"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
result, status_code = UserService.get_profile(current_user_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
|
||||||
|
@user_bp.route('/profile', methods=['PUT'])
|
||||||
|
@jwt_required()
|
||||||
|
def update_profile():
|
||||||
|
"""更新用户资料"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
data = request.get_json()
|
||||||
|
result, status_code = UserService.update_profile(current_user_id, data)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
|
||||||
|
@user_bp.route('/balance', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_balance():
|
||||||
|
"""获取账户余额"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
result, status_code = UserService.get_balance(current_user_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
|
||||||
|
@user_bp.route('/transactions', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_transactions():
|
||||||
|
"""获取交易记录"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
page = request.args.get('page', 1, type=int)
|
||||||
|
per_page = request.args.get('per_page', 20, type=int)
|
||||||
|
result, status_code = UserService.get_transactions(current_user_id, page, per_page)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
|
||||||
|
@user_bp.route('/api-calls', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_api_calls():
|
||||||
|
"""获取API调用记录"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
page = request.args.get('page', 1, type=int)
|
||||||
|
per_page = request.args.get('per_page', 20, type=int)
|
||||||
|
result, status_code = UserService.get_api_calls(current_user_id, page, per_page)
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
|
||||||
|
@user_bp.route('/stats', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_stats():
|
||||||
|
"""获取用户统计信息"""
|
||||||
|
current_user_id = get_jwt_identity()
|
||||||
|
result, status_code = UserService.get_stats(current_user_id)
|
||||||
|
return jsonify(result), status_code
|
||||||
36
NBATransfer-backend/routes/v1_api.py
Normal file
36
NBATransfer-backend/routes/v1_api.py
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
"""对外公开的 API 路由 (v1) - 支持 API Key 认证"""
|
||||||
|
from flask import Blueprint, request, jsonify, current_app
|
||||||
|
from services.apikey_service import APIKeyService
|
||||||
|
from services.v1_service import V1Service
|
||||||
|
|
||||||
|
v1_bp = Blueprint('v1_api', __name__)
|
||||||
|
|
||||||
|
@v1_bp.route('/chat/completions', methods=['POST'])
|
||||||
|
def chat_completions():
|
||||||
|
"""
|
||||||
|
OpenAI 兼容的 Chat Completions 接口
|
||||||
|
支持多模型,通过 modelapiservice 分发
|
||||||
|
"""
|
||||||
|
# 1. 认证
|
||||||
|
auth_header = request.headers.get('Authorization')
|
||||||
|
user, error = APIKeyService.authenticate_api_key(auth_header)
|
||||||
|
|
||||||
|
if error:
|
||||||
|
return jsonify({'error': {'message': error, 'type': 'auth_error', 'code': 401}}), 401
|
||||||
|
|
||||||
|
# 2. 获取请求数据
|
||||||
|
data = request.get_json()
|
||||||
|
if not data:
|
||||||
|
return jsonify({'error': {'message': '无效的 JSON 请求体', 'type': 'invalid_request_error', 'code': 400}}), 400
|
||||||
|
|
||||||
|
result, status_code = V1Service.chat_completions(user, data)
|
||||||
|
|
||||||
|
if status_code == 200 and data.get('stream', False):
|
||||||
|
return current_app.response_class(result, mimetype='text/event-stream')
|
||||||
|
|
||||||
|
return jsonify(result), status_code
|
||||||
|
|
||||||
|
@v1_bp.route('/text-to-image', methods=['POST'])
|
||||||
|
def text_to_image_alias():
|
||||||
|
"""兼容旧接口路径"""
|
||||||
|
return chat_completions()
|
||||||
244
NBATransfer-backend/services/admin_service.py
Normal file
244
NBATransfer-backend/services/admin_service.py
Normal file
@@ -0,0 +1,244 @@
|
|||||||
|
from models import db, User, Order, ApiCall, Transaction
|
||||||
|
from sqlalchemy import desc, func
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
class AdminService:
|
||||||
|
@staticmethod
|
||||||
|
def get_users(page=1, per_page=20, search=''):
|
||||||
|
"""获取用户列表"""
|
||||||
|
query = User.query
|
||||||
|
|
||||||
|
if search:
|
||||||
|
query = query.filter(
|
||||||
|
(User.email.contains(search)) | (User.username.contains(search))
|
||||||
|
)
|
||||||
|
|
||||||
|
# 分页查询
|
||||||
|
pagination = query.order_by(desc(User.created_at))\
|
||||||
|
.paginate(page=page, per_page=per_page, error_out=False)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'users': [user.to_dict() for user in pagination.items],
|
||||||
|
'total': pagination.total,
|
||||||
|
'page': page,
|
||||||
|
'per_page': per_page,
|
||||||
|
'pages': pagination.pages
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_user_detail(user_id):
|
||||||
|
"""获取用户详情"""
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
# 统计信息
|
||||||
|
total_recharge = db.session.query(func.sum(Transaction.amount))\
|
||||||
|
.filter_by(user_id=user_id, type='recharge').scalar() or 0
|
||||||
|
|
||||||
|
total_consume = db.session.query(func.sum(Transaction.amount))\
|
||||||
|
.filter_by(user_id=user_id, type='consume').scalar() or 0
|
||||||
|
|
||||||
|
total_api_calls = ApiCall.query.filter_by(user_id=user_id).count()
|
||||||
|
|
||||||
|
return {
|
||||||
|
'user': user.to_dict(),
|
||||||
|
'stats': {
|
||||||
|
'total_recharge': total_recharge,
|
||||||
|
'total_consume': abs(total_consume),
|
||||||
|
'total_api_calls': total_api_calls
|
||||||
|
}
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def toggle_user_status(admin_user_id, user_id):
|
||||||
|
"""启用/禁用用户"""
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
# 检查是否尝试禁用其他管理员 (需要传入当前管理员ID)
|
||||||
|
if user.is_admin and user.id != admin_user_id:
|
||||||
|
return {'error': '不能禁用其他管理员'}, 403
|
||||||
|
|
||||||
|
user.is_active = not user.is_active
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.session.commit()
|
||||||
|
return {
|
||||||
|
'message': f'用户已{"启用" if user.is_active else "禁用"}',
|
||||||
|
'user': user.to_dict()
|
||||||
|
}, 200
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return {'error': '操作失败'}, 500
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def adjust_balance(user_id, data):
|
||||||
|
"""调整用户余额"""
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
amount = data.get('amount')
|
||||||
|
description = data.get('description', '管理员调整余额')
|
||||||
|
|
||||||
|
if amount is None or amount == 0:
|
||||||
|
return {'error': '金额不能为0'}, 400
|
||||||
|
|
||||||
|
try:
|
||||||
|
balance_before = user.balance
|
||||||
|
user.balance += amount
|
||||||
|
balance_after = user.balance
|
||||||
|
|
||||||
|
# 创建交易记录
|
||||||
|
transaction = Transaction(
|
||||||
|
user_id=user_id,
|
||||||
|
type='recharge' if amount > 0 else 'consume',
|
||||||
|
amount=amount,
|
||||||
|
balance_before=balance_before,
|
||||||
|
balance_after=balance_after,
|
||||||
|
description=description
|
||||||
|
)
|
||||||
|
|
||||||
|
db.session.add(transaction)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
return {
|
||||||
|
'message': '余额调整成功',
|
||||||
|
'user': user.to_dict(),
|
||||||
|
'transaction': transaction.to_dict()
|
||||||
|
}, 200
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return {'error': '余额调整失败'}, 500
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_all_orders(page=1, per_page=20, status=None):
|
||||||
|
"""获取所有订单"""
|
||||||
|
query = Order.query
|
||||||
|
|
||||||
|
if status:
|
||||||
|
query = query.filter_by(status=status)
|
||||||
|
|
||||||
|
# 分页查询
|
||||||
|
pagination = query.order_by(desc(Order.created_at))\
|
||||||
|
.paginate(page=page, per_page=per_page, error_out=False)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'orders': [order.to_dict() for order in pagination.items],
|
||||||
|
'total': pagination.total,
|
||||||
|
'page': page,
|
||||||
|
'per_page': per_page,
|
||||||
|
'pages': pagination.pages
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_all_api_calls(page=1, per_page=20, status=None):
|
||||||
|
"""获取所有API调用记录"""
|
||||||
|
query = ApiCall.query
|
||||||
|
|
||||||
|
if status:
|
||||||
|
query = query.filter_by(status=status)
|
||||||
|
|
||||||
|
# 分页查询
|
||||||
|
pagination = query.order_by(desc(ApiCall.created_at))\
|
||||||
|
.paginate(page=page, per_page=per_page, error_out=False)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'api_calls': [call.to_dict() for call in pagination.items],
|
||||||
|
'total': pagination.total,
|
||||||
|
'page': page,
|
||||||
|
'per_page': per_page,
|
||||||
|
'pages': pagination.pages
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_overview_stats():
|
||||||
|
"""获取总览统计"""
|
||||||
|
# 用户统计
|
||||||
|
total_users = User.query.count()
|
||||||
|
active_users = User.query.filter_by(is_active=True).count()
|
||||||
|
|
||||||
|
# 订单统计
|
||||||
|
total_orders = Order.query.count()
|
||||||
|
paid_orders = Order.query.filter_by(status='paid').count()
|
||||||
|
total_revenue = db.session.query(func.sum(Order.amount))\
|
||||||
|
.filter_by(status='paid').scalar() or 0
|
||||||
|
|
||||||
|
# API调用统计
|
||||||
|
total_api_calls = ApiCall.query.count()
|
||||||
|
success_calls = ApiCall.query.filter_by(status='success').count()
|
||||||
|
failed_calls = ApiCall.query.filter_by(status='failed').count()
|
||||||
|
|
||||||
|
# 今日统计
|
||||||
|
today = datetime.utcnow().date()
|
||||||
|
today_start = datetime.combine(today, datetime.min.time())
|
||||||
|
|
||||||
|
today_users = User.query.filter(User.created_at >= today_start).count()
|
||||||
|
today_orders = Order.query.filter(Order.created_at >= today_start).count()
|
||||||
|
today_revenue = db.session.query(func.sum(Order.amount))\
|
||||||
|
.filter(Order.created_at >= today_start, Order.status == 'paid').scalar() or 0
|
||||||
|
today_api_calls = ApiCall.query.filter(ApiCall.created_at >= today_start).count()
|
||||||
|
|
||||||
|
return {
|
||||||
|
'total': {
|
||||||
|
'users': total_users,
|
||||||
|
'active_users': active_users,
|
||||||
|
'orders': total_orders,
|
||||||
|
'paid_orders': paid_orders,
|
||||||
|
'revenue': total_revenue,
|
||||||
|
'api_calls': total_api_calls,
|
||||||
|
'success_calls': success_calls,
|
||||||
|
'failed_calls': failed_calls
|
||||||
|
},
|
||||||
|
'today': {
|
||||||
|
'users': today_users,
|
||||||
|
'orders': today_orders,
|
||||||
|
'revenue': today_revenue,
|
||||||
|
'api_calls': today_api_calls
|
||||||
|
}
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_chart_data(days=7):
|
||||||
|
"""获取图表数据"""
|
||||||
|
# 计算日期范围
|
||||||
|
end_date = datetime.utcnow().date()
|
||||||
|
start_date = end_date - timedelta(days=days-1)
|
||||||
|
|
||||||
|
chart_data = []
|
||||||
|
|
||||||
|
for i in range(days):
|
||||||
|
date = start_date + timedelta(days=i)
|
||||||
|
date_start = datetime.combine(date, datetime.min.time())
|
||||||
|
date_end = datetime.combine(date, datetime.max.time())
|
||||||
|
|
||||||
|
# 统计当天数据
|
||||||
|
users = User.query.filter(
|
||||||
|
User.created_at >= date_start,
|
||||||
|
User.created_at <= date_end
|
||||||
|
).count()
|
||||||
|
|
||||||
|
revenue = db.session.query(func.sum(Order.amount))\
|
||||||
|
.filter(
|
||||||
|
Order.created_at >= date_start,
|
||||||
|
Order.created_at <= date_end,
|
||||||
|
Order.status == 'paid'
|
||||||
|
).scalar() or 0
|
||||||
|
|
||||||
|
api_calls = ApiCall.query.filter(
|
||||||
|
ApiCall.created_at >= date_start,
|
||||||
|
ApiCall.created_at <= date_end
|
||||||
|
).count()
|
||||||
|
|
||||||
|
chart_data.append({
|
||||||
|
'date': date.isoformat(),
|
||||||
|
'users': users,
|
||||||
|
'revenue': float(revenue),
|
||||||
|
'api_calls': api_calls
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
'chart_data': chart_data
|
||||||
|
}, 200
|
||||||
258
NBATransfer-backend/services/api_proxy_service.py
Normal file
258
NBATransfer-backend/services/api_proxy_service.py
Normal file
@@ -0,0 +1,258 @@
|
|||||||
|
from flask import current_app
|
||||||
|
from models import db, User, ApiCall, Transaction
|
||||||
|
from datetime import datetime
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from modelapiservice import get_model_service
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class ApiProxyService:
|
||||||
|
@staticmethod
|
||||||
|
def deduct_balance(user_id, api_call_id, cost, model):
|
||||||
|
"""统一扣费逻辑"""
|
||||||
|
try:
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
api_call = ApiCall.query.get(api_call_id)
|
||||||
|
if not user or not api_call:
|
||||||
|
return
|
||||||
|
|
||||||
|
# 刷新用户数据
|
||||||
|
db.session.refresh(user)
|
||||||
|
|
||||||
|
balance_before = user.balance
|
||||||
|
user.balance -= cost
|
||||||
|
balance_after = user.balance
|
||||||
|
|
||||||
|
api_call.status = 'success'
|
||||||
|
api_call.cost = cost
|
||||||
|
db.session.add(api_call)
|
||||||
|
|
||||||
|
transaction = Transaction(
|
||||||
|
user_id=user.id,
|
||||||
|
type='consume',
|
||||||
|
amount=-cost,
|
||||||
|
balance_before=balance_before,
|
||||||
|
balance_after=balance_after,
|
||||||
|
description=f'API调用 - {model}',
|
||||||
|
api_call_id=api_call.id
|
||||||
|
)
|
||||||
|
db.session.add(transaction)
|
||||||
|
db.session.commit()
|
||||||
|
logger.info(f"扣费成功: 用户 {user.id}, 消费 {cost}, 余额 {balance_before} -> {balance_after}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f'扣费失败: {e}')
|
||||||
|
db.session.rollback()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def handle_api_request(user_id, data):
|
||||||
|
"""
|
||||||
|
通用 API 代理 (支持文生图和对话)
|
||||||
|
"""
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
if not user.is_active:
|
||||||
|
return {'error': '账户已被禁用'}, 403
|
||||||
|
|
||||||
|
model = data.get('model')
|
||||||
|
messages = data.get('messages', [])
|
||||||
|
stream = data.get('stream', False)
|
||||||
|
|
||||||
|
# 验证必要字段
|
||||||
|
if not model:
|
||||||
|
return {'error': 'model字段不能为空'}, 400
|
||||||
|
|
||||||
|
if not messages or len(messages) == 0:
|
||||||
|
return {'error': 'messages不能为空'}, 400
|
||||||
|
|
||||||
|
# 获取模型服务并检查余额
|
||||||
|
try:
|
||||||
|
service = get_model_service(model)
|
||||||
|
except Exception as e:
|
||||||
|
return {'error': f'不支持的模型: {model}'}, 400
|
||||||
|
|
||||||
|
is_sufficient, estimated_cost, error_msg = service.check_balance(user.balance)
|
||||||
|
if not is_sufficient:
|
||||||
|
return {
|
||||||
|
'error': '余额不足',
|
||||||
|
'message': error_msg,
|
||||||
|
'required': estimated_cost,
|
||||||
|
'balance': user.balance
|
||||||
|
}, 402
|
||||||
|
|
||||||
|
prompt = messages[0].get('content', '') if messages else ''
|
||||||
|
if not prompt:
|
||||||
|
prompt = "Empty prompt"
|
||||||
|
|
||||||
|
# 创建API调用记录
|
||||||
|
api_call = ApiCall(
|
||||||
|
user_id=user_id,
|
||||||
|
api_type='chat_completion',
|
||||||
|
prompt=prompt[:500], # 截断
|
||||||
|
parameters=json.dumps({
|
||||||
|
'model': model,
|
||||||
|
'stream': stream
|
||||||
|
}),
|
||||||
|
status='processing',
|
||||||
|
cost=estimated_cost,
|
||||||
|
request_time=datetime.utcnow()
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.session.add(api_call)
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
# 准备请求
|
||||||
|
api_url, api_key = service.get_api_config()
|
||||||
|
if not api_url or not api_key:
|
||||||
|
raise ValueError(f'模型 {model} API 配置未完成')
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
'Authorization': f'Bearer {api_key}',
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
}
|
||||||
|
|
||||||
|
payload = service.prepare_payload(data)
|
||||||
|
target_url = f'{api_url}/chat/completions'
|
||||||
|
|
||||||
|
logger.info(f'API 转发: {target_url}, User: {user.id}, Model: {model}')
|
||||||
|
|
||||||
|
response = requests.post(
|
||||||
|
target_url,
|
||||||
|
headers=headers,
|
||||||
|
json=payload,
|
||||||
|
stream=stream,
|
||||||
|
timeout=300
|
||||||
|
)
|
||||||
|
|
||||||
|
if response.status_code != 200:
|
||||||
|
error_msg = f'第三方 API 返回错误: {response.status_code}'
|
||||||
|
try:
|
||||||
|
error_detail = response.json()
|
||||||
|
error_msg += f' - {error_detail}'
|
||||||
|
except:
|
||||||
|
error_msg += f' - {response.text[:200]}'
|
||||||
|
|
||||||
|
api_call.status = 'failed'
|
||||||
|
api_call.error_message = error_msg
|
||||||
|
db.session.commit()
|
||||||
|
return {'error': 'API 调用失败', 'details': error_msg}, 502
|
||||||
|
|
||||||
|
# 处理响应
|
||||||
|
if stream:
|
||||||
|
# 流式响应处理
|
||||||
|
def generate():
|
||||||
|
final_usage = None
|
||||||
|
try:
|
||||||
|
for chunk in response.iter_content(chunk_size=1024):
|
||||||
|
if chunk:
|
||||||
|
if hasattr(service, 'parse_stream_usage'):
|
||||||
|
try:
|
||||||
|
text_chunk = chunk.decode('utf-8', errors='ignore')
|
||||||
|
usage = service.parse_stream_usage(text_chunk)
|
||||||
|
if usage:
|
||||||
|
final_usage = usage
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
yield chunk
|
||||||
|
|
||||||
|
# 计算最终费用
|
||||||
|
actual_cost = service.calculate_cost(final_usage, stream=True)
|
||||||
|
if actual_cost == 0 and estimated_cost > 0:
|
||||||
|
actual_cost = estimated_cost
|
||||||
|
|
||||||
|
with current_app.app_context():
|
||||||
|
ApiProxyService.deduct_balance(user.id, api_call.id, actual_cost, model)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f'Stream error: {e}')
|
||||||
|
|
||||||
|
return generate(), 200 # Special return for stream
|
||||||
|
else:
|
||||||
|
result = response.json()
|
||||||
|
api_call.status = 'success'
|
||||||
|
api_call.response_time = datetime.utcnow()
|
||||||
|
|
||||||
|
# 计算费用
|
||||||
|
usage = result.get('usage')
|
||||||
|
final_cost = service.calculate_cost(usage, stream=False)
|
||||||
|
if final_cost == 0 and estimated_cost > 0:
|
||||||
|
final_cost = estimated_cost
|
||||||
|
|
||||||
|
# 简化响应格式
|
||||||
|
simplified_result = {
|
||||||
|
'success': True,
|
||||||
|
'api_call_id': api_call.id,
|
||||||
|
'cost': final_cost,
|
||||||
|
'model': model,
|
||||||
|
'content': ''
|
||||||
|
}
|
||||||
|
|
||||||
|
if 'choices' in result and len(result['choices']) > 0:
|
||||||
|
content = result['choices'][0].get('message', {}).get('content', '')
|
||||||
|
simplified_result['content'] = content
|
||||||
|
api_call.result_url = content[:500]
|
||||||
|
|
||||||
|
ApiProxyService.deduct_balance(user.id, api_call.id, final_cost, model)
|
||||||
|
|
||||||
|
return simplified_result, 200
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f'API 调用异常: {str(e)}', exc_info=True)
|
||||||
|
if api_call.id:
|
||||||
|
api_call.status = 'failed'
|
||||||
|
api_call.error_message = str(e)
|
||||||
|
db.session.commit()
|
||||||
|
return {'error': '服务异常', 'message': str(e)}, 500
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_models():
|
||||||
|
"""获取可用的模型列表"""
|
||||||
|
# 暂时返回硬编码的模型列表,后续可以从各 Service 聚合
|
||||||
|
return {
|
||||||
|
'object': 'list',
|
||||||
|
'data': [
|
||||||
|
{
|
||||||
|
'id': 'deepseek-chat',
|
||||||
|
'object': 'model',
|
||||||
|
'owned_by': 'deepseek',
|
||||||
|
'description': 'DeepSeek Chat V3'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 'deepseek-reasoner',
|
||||||
|
'object': 'model',
|
||||||
|
'owned_by': 'deepseek',
|
||||||
|
'description': 'DeepSeek Reasoner (R1)'
|
||||||
|
},
|
||||||
|
# ... 其他模型 ...
|
||||||
|
]
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_pricing():
|
||||||
|
"""获取价格信息"""
|
||||||
|
pricing = {
|
||||||
|
'text_to_image': {
|
||||||
|
'price': current_app.config.get('IMAGE_GENERATION_PRICE', 0),
|
||||||
|
'currency': 'CNY',
|
||||||
|
'unit': '每张图片'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
'pricing': pricing
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_api_call(user_id, call_id):
|
||||||
|
"""获取API调用详情"""
|
||||||
|
api_call = ApiCall.query.filter_by(id=call_id, user_id=user_id).first()
|
||||||
|
|
||||||
|
if not api_call:
|
||||||
|
return {'error': 'API调用记录不存在'}, 404
|
||||||
|
|
||||||
|
return api_call.to_dict(), 200
|
||||||
165
NBATransfer-backend/services/apikey_service.py
Normal file
165
NBATransfer-backend/services/apikey_service.py
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
from models import db, User, APIKey
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
class APIKeyService:
|
||||||
|
@staticmethod
|
||||||
|
def list_api_keys(user_id):
|
||||||
|
"""获取用户的所有 API Key"""
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
keys = APIKey.query.filter_by(user_id=user_id).all()
|
||||||
|
|
||||||
|
return {
|
||||||
|
'total': len(keys),
|
||||||
|
'keys': [key.to_dict() for key in keys]
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_api_key(user_id, data):
|
||||||
|
"""创建新的 API Key"""
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
name = data.get('name', '').strip()
|
||||||
|
|
||||||
|
if not name:
|
||||||
|
return {'error': 'API Key 名称不能为空'}, 400
|
||||||
|
|
||||||
|
if len(name) > 100:
|
||||||
|
return {'error': 'API Key 名称长度不能超过100个字符'}, 400
|
||||||
|
|
||||||
|
# 生成 API Key
|
||||||
|
api_key = APIKey.generate_key()
|
||||||
|
|
||||||
|
# 创建数据库记录
|
||||||
|
new_key = APIKey(
|
||||||
|
user_id=user_id,
|
||||||
|
name=name,
|
||||||
|
api_key=api_key
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.session.add(new_key)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
return {
|
||||||
|
'message': 'API Key 创建成功',
|
||||||
|
'key': new_key.to_dict()
|
||||||
|
}, 201
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return {'error': '创建失败,请稍后重试'}, 500
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_api_key(user_id, key_id):
|
||||||
|
"""获取单个 API Key 详情"""
|
||||||
|
key = APIKey.query.filter_by(id=key_id, user_id=user_id).first()
|
||||||
|
|
||||||
|
if not key:
|
||||||
|
return {'error': 'API Key 不存在'}, 404
|
||||||
|
|
||||||
|
return key.to_dict(), 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def update_api_key(user_id, key_id, data):
|
||||||
|
"""更新 API Key 名称或状态"""
|
||||||
|
key = APIKey.query.filter_by(id=key_id, user_id=user_id).first()
|
||||||
|
|
||||||
|
if not key:
|
||||||
|
return {'error': 'API Key 不存在'}, 404
|
||||||
|
|
||||||
|
if 'name' in data:
|
||||||
|
name = data.get('name', '').strip()
|
||||||
|
if not name or len(name) > 100:
|
||||||
|
return {'error': 'API Key 名称无效'}, 400
|
||||||
|
key.name = name
|
||||||
|
|
||||||
|
if 'is_active' in data:
|
||||||
|
key.is_active = bool(data.get('is_active'))
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.session.commit()
|
||||||
|
return {
|
||||||
|
'message': 'API Key 更新成功',
|
||||||
|
'key': key.to_dict()
|
||||||
|
}, 200
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return {'error': '更新失败,请稍后重试'}, 500
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def delete_api_key(user_id, key_id):
|
||||||
|
"""删除 API Key"""
|
||||||
|
key = APIKey.query.filter_by(id=key_id, user_id=user_id).first()
|
||||||
|
|
||||||
|
if not key:
|
||||||
|
return {'error': 'API Key 不存在'}, 404
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.session.delete(key)
|
||||||
|
db.session.commit()
|
||||||
|
return {'message': 'API Key 已删除'}, 200
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return {'error': '删除失败,请稍后重试'}, 500
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def regenerate_api_key(user_id, key_id):
|
||||||
|
"""重置/轮换 API Key"""
|
||||||
|
key = APIKey.query.filter_by(id=key_id, user_id=user_id).first()
|
||||||
|
|
||||||
|
if not key:
|
||||||
|
return {'error': 'API Key 不存在'}, 404
|
||||||
|
|
||||||
|
# 生成新的 API Key
|
||||||
|
new_api_key = APIKey.generate_key()
|
||||||
|
key.api_key = new_api_key
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.session.commit()
|
||||||
|
return {
|
||||||
|
'message': 'API Key 已重置',
|
||||||
|
'key': key.to_dict()
|
||||||
|
}, 200
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return {'error': '重置失败,请稍后重试'}, 500
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def authenticate_api_key(auth_header):
|
||||||
|
"""验证 API Key 并返回用户"""
|
||||||
|
if not auth_header:
|
||||||
|
return None, "缺少 Authorization 头"
|
||||||
|
|
||||||
|
parts = auth_header.split()
|
||||||
|
if parts[0].lower() != "bearer":
|
||||||
|
return None, "Authorization 头格式错误"
|
||||||
|
|
||||||
|
if len(parts) == 1:
|
||||||
|
return None, "无效的 Token"
|
||||||
|
|
||||||
|
api_key_str = parts[1]
|
||||||
|
|
||||||
|
# 查找 API Key
|
||||||
|
api_key = APIKey.query.filter_by(api_key=api_key_str).first()
|
||||||
|
|
||||||
|
if not api_key:
|
||||||
|
return None, "无效的 API Key"
|
||||||
|
|
||||||
|
if not api_key.is_active:
|
||||||
|
return None, "API Key 已被禁用"
|
||||||
|
|
||||||
|
# 更新最后使用时间
|
||||||
|
api_key.last_used_at = datetime.utcnow()
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
user = User.query.get(api_key.user_id)
|
||||||
|
if not user or not user.is_active:
|
||||||
|
return None, "账户不存在或已被禁用"
|
||||||
|
|
||||||
|
return user, None
|
||||||
290
NBATransfer-backend/services/auth_service.py
Normal file
290
NBATransfer-backend/services/auth_service.py
Normal file
@@ -0,0 +1,290 @@
|
|||||||
|
from flask import current_app, jsonify
|
||||||
|
from flask_mail import Message
|
||||||
|
from flask_jwt_extended import create_access_token, create_refresh_token
|
||||||
|
from models import db, User, VerificationCode
|
||||||
|
from email_validator import validate_email, EmailNotValidError
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
import re
|
||||||
|
|
||||||
|
class AuthService:
|
||||||
|
@staticmethod
|
||||||
|
def send_verification_email(email, code, purpose='register'):
|
||||||
|
"""发送验证码邮件"""
|
||||||
|
try:
|
||||||
|
subject = '验证码' if purpose == 'register' else '密码重置验证码'
|
||||||
|
body = f"""
|
||||||
|
您好!
|
||||||
|
|
||||||
|
感谢您使用 Nano Banana API 转售平台。
|
||||||
|
|
||||||
|
您的验证码是:{code}
|
||||||
|
|
||||||
|
此验证码有效期为10分钟,请勿泄露给他人。
|
||||||
|
|
||||||
|
如果不是您本人操作,请忽略此邮件。
|
||||||
|
|
||||||
|
---
|
||||||
|
Nano Banana API 平台
|
||||||
|
"""
|
||||||
|
msg = Message(
|
||||||
|
subject=f'[Nano Banana] {subject}',
|
||||||
|
recipients=[email],
|
||||||
|
body=body
|
||||||
|
)
|
||||||
|
|
||||||
|
# 这里使用 Flask-Mail 发送
|
||||||
|
from extensions import mail
|
||||||
|
mail.send(msg)
|
||||||
|
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f'发送邮件失败: {str(e)}')
|
||||||
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def send_verification_code(data):
|
||||||
|
"""发送验证码逻辑"""
|
||||||
|
email = data.get('email', '').strip().lower()
|
||||||
|
purpose = data.get('purpose', 'register')
|
||||||
|
|
||||||
|
if not email:
|
||||||
|
return {'error': '邮箱不能为空'}, 400
|
||||||
|
|
||||||
|
# 验证邮箱格式
|
||||||
|
try:
|
||||||
|
validate_email(email, check_deliverability=False)
|
||||||
|
except EmailNotValidError:
|
||||||
|
return {'error': '邮箱格式不正确'}, 400
|
||||||
|
|
||||||
|
# 如果是注册,检查邮箱是否已存在
|
||||||
|
if purpose == 'register':
|
||||||
|
user = User.query.filter_by(email=email).first()
|
||||||
|
if user:
|
||||||
|
# 如果用户已存在且已验证邮箱,则提示已注册
|
||||||
|
if user.email_verified:
|
||||||
|
return {'error': '该邮箱已被注册'}, 400
|
||||||
|
# 如果用户存在但未验证,可以继续发送验证码(重发)
|
||||||
|
else:
|
||||||
|
# 创建临时用户记录用于验证码关联
|
||||||
|
user = User(email=email, username=email.split('@')[0])
|
||||||
|
user.set_password('temp_pending_registration')
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
else:
|
||||||
|
# 密码重置:检查用户是否存在
|
||||||
|
user = User.query.filter_by(email=email).first()
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
# 生成验证码
|
||||||
|
code = VerificationCode.generate_code()
|
||||||
|
|
||||||
|
# 删除旧的未使用验证码
|
||||||
|
VerificationCode.query.filter_by(
|
||||||
|
email=email,
|
||||||
|
purpose=purpose,
|
||||||
|
used=False
|
||||||
|
).delete()
|
||||||
|
|
||||||
|
# 创建新的验证码
|
||||||
|
verification = VerificationCode(
|
||||||
|
user_id=user.id,
|
||||||
|
email=email,
|
||||||
|
code=code,
|
||||||
|
purpose=purpose,
|
||||||
|
expired_at=datetime.utcnow() + timedelta(minutes=10)
|
||||||
|
)
|
||||||
|
db.session.add(verification)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
# 发送邮件
|
||||||
|
send_success = AuthService.send_verification_email(email, code, purpose)
|
||||||
|
|
||||||
|
if send_success:
|
||||||
|
return {
|
||||||
|
'message': '验证码已发送到您的邮箱',
|
||||||
|
'email': email,
|
||||||
|
'purpose': purpose
|
||||||
|
}, 200
|
||||||
|
else:
|
||||||
|
return {'error': '邮件发送失败,请检查邮箱配置'}, 500
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def register(data):
|
||||||
|
"""用户注册逻辑"""
|
||||||
|
if not data or not data.get('email') or not data.get('password') or not data.get('code'):
|
||||||
|
return {'error': '邮箱、密码和验证码不能为空'}, 400
|
||||||
|
|
||||||
|
email = data.get('email').strip().lower()
|
||||||
|
password = data.get('password')
|
||||||
|
code = data.get('code')
|
||||||
|
username = data.get('username', '').strip()
|
||||||
|
|
||||||
|
try:
|
||||||
|
validate_email(email, check_deliverability=False)
|
||||||
|
except EmailNotValidError:
|
||||||
|
return {'error': '邮箱格式不正确'}, 400
|
||||||
|
|
||||||
|
if len(password) < 6:
|
||||||
|
return {'error': '密码长度至少为6位'}, 400
|
||||||
|
|
||||||
|
verification = VerificationCode.query.filter_by(
|
||||||
|
email=email,
|
||||||
|
code=code,
|
||||||
|
purpose='register',
|
||||||
|
used=False
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if not verification:
|
||||||
|
return {'error': '验证码不存在或已过期'}, 400
|
||||||
|
|
||||||
|
if not verification.is_valid():
|
||||||
|
return {'error': '验证码已过期'}, 400
|
||||||
|
|
||||||
|
existing_user = User.query.filter_by(email=email).filter(
|
||||||
|
User.id != verification.user_id
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if existing_user:
|
||||||
|
return {'error': '该邮箱已被注册'}, 400
|
||||||
|
|
||||||
|
user = User.query.get(verification.user_id)
|
||||||
|
user.username = username or email.split('@')[0]
|
||||||
|
user.set_password(password)
|
||||||
|
user.email_verified = True
|
||||||
|
user.email_verified_at = datetime.utcnow()
|
||||||
|
user.is_active = True
|
||||||
|
|
||||||
|
verification.used = True
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.session.commit()
|
||||||
|
access_token = create_access_token(identity=user.id)
|
||||||
|
refresh_token = create_refresh_token(identity=user.id)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'message': '注册成功',
|
||||||
|
'access_token': access_token,
|
||||||
|
'refresh_token': refresh_token,
|
||||||
|
'user': user.to_dict()
|
||||||
|
}, 201
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
print(f'注册错误: {str(e)}')
|
||||||
|
return {'error': '注册失败,请稍后重试'}, 500
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def login(data):
|
||||||
|
"""用户登录逻辑"""
|
||||||
|
if not data or not data.get('email') or not data.get('password'):
|
||||||
|
return {'error': '邮箱和密码不能为空'}, 400
|
||||||
|
|
||||||
|
email = data.get('email').strip().lower()
|
||||||
|
password = data.get('password')
|
||||||
|
|
||||||
|
user = User.query.filter_by(email=email).first()
|
||||||
|
|
||||||
|
if not user or not user.check_password(password):
|
||||||
|
return {'error': '邮箱或密码错误'}, 401
|
||||||
|
|
||||||
|
if not user.is_active:
|
||||||
|
return {'error': '账户已被禁用'}, 403
|
||||||
|
|
||||||
|
# 如果用户未验证邮箱 (理论上注册流程保证了已验证,但为了兼容旧数据)
|
||||||
|
if not user.email_verified:
|
||||||
|
return {'error': '邮箱未验证,请先完成注册验证'}, 403
|
||||||
|
|
||||||
|
access_token = create_access_token(identity=user.id)
|
||||||
|
refresh_token = create_refresh_token(identity=user.id)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'message': '登录成功',
|
||||||
|
'access_token': access_token,
|
||||||
|
'refresh_token': refresh_token,
|
||||||
|
'user': user.to_dict()
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def change_password(user_id, data):
|
||||||
|
"""修改密码"""
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
old_password = data.get('old_password')
|
||||||
|
new_password = data.get('new_password')
|
||||||
|
|
||||||
|
if not old_password or not new_password:
|
||||||
|
return {'error': '参数不能为空'}, 400
|
||||||
|
|
||||||
|
if not user.check_password(old_password):
|
||||||
|
return {'error': '原密码错误'}, 401
|
||||||
|
|
||||||
|
if len(new_password) < 6:
|
||||||
|
return {'error': '新密码长度至少为6位'}, 400
|
||||||
|
|
||||||
|
user.set_password(new_password)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
return {'message': '密码修改成功'}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def reset_password(data):
|
||||||
|
"""重置密码"""
|
||||||
|
email = data.get('email', '').strip().lower()
|
||||||
|
code = data.get('code')
|
||||||
|
new_password = data.get('new_password')
|
||||||
|
|
||||||
|
if not email or not code or not new_password:
|
||||||
|
return {'error': '参数不能为空'}, 400
|
||||||
|
|
||||||
|
# 验证验证码
|
||||||
|
verification = VerificationCode.query.filter_by(
|
||||||
|
email=email,
|
||||||
|
code=code,
|
||||||
|
purpose='password_reset',
|
||||||
|
used=False
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if not verification or not verification.is_valid():
|
||||||
|
return {'error': '验证码不存在或已过期'}, 400
|
||||||
|
|
||||||
|
user = User.query.get(verification.user_id)
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
if len(new_password) < 6:
|
||||||
|
return {'error': '密码长度至少为6位'}, 400
|
||||||
|
|
||||||
|
# 更新密码
|
||||||
|
user.set_password(new_password)
|
||||||
|
verification.used = True
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
return {'message': '密码重置成功'}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def verify_code(data):
|
||||||
|
"""验证验证码是否有效"""
|
||||||
|
email = data.get('email', '').strip().lower()
|
||||||
|
code = data.get('code')
|
||||||
|
purpose = data.get('purpose', 'register')
|
||||||
|
|
||||||
|
if not email or not code:
|
||||||
|
return {'error': '参数不能为空'}, 400
|
||||||
|
|
||||||
|
verification = VerificationCode.query.filter_by(
|
||||||
|
email=email,
|
||||||
|
code=code,
|
||||||
|
purpose=purpose,
|
||||||
|
used=False
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if not verification:
|
||||||
|
return {'error': '验证码错误'}, 400
|
||||||
|
|
||||||
|
if not verification.is_valid():
|
||||||
|
return {'error': '验证码已过期'}, 400
|
||||||
|
|
||||||
|
return {'message': '验证码有效'}, 200
|
||||||
150
NBATransfer-backend/services/order_service.py
Normal file
150
NBATransfer-backend/services/order_service.py
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
from flask import current_app
|
||||||
|
from models import db, User, Order, Transaction
|
||||||
|
from datetime import datetime
|
||||||
|
import uuid
|
||||||
|
from sqlalchemy import desc
|
||||||
|
|
||||||
|
class OrderService:
|
||||||
|
@staticmethod
|
||||||
|
def _generate_order_no():
|
||||||
|
"""生成订单号"""
|
||||||
|
return f"ORD{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:8].upper()}"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_order(user_id, data):
|
||||||
|
"""创建充值订单"""
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
amount = data.get('amount')
|
||||||
|
payment_method = data.get('payment_method', 'alipay') # alipay, wechat
|
||||||
|
|
||||||
|
# 验证金额
|
||||||
|
if not amount or amount <= 0:
|
||||||
|
return {'error': '充值金额必须大于0'}, 400
|
||||||
|
|
||||||
|
# 验证支付方式
|
||||||
|
if payment_method not in ['alipay', 'wechat']:
|
||||||
|
return {'error': '不支持的支付方式'}, 400
|
||||||
|
|
||||||
|
# 创建订单
|
||||||
|
order = Order(
|
||||||
|
order_no=OrderService._generate_order_no(),
|
||||||
|
user_id=user_id,
|
||||||
|
amount=amount,
|
||||||
|
payment_method=payment_method,
|
||||||
|
status='pending'
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.session.add(order)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
# TODO: 调用支付接口
|
||||||
|
# 这里返回支付参数,前端跳转到支付页面
|
||||||
|
payment_params = {
|
||||||
|
'order_no': order.order_no,
|
||||||
|
'amount': order.amount,
|
||||||
|
'payment_method': payment_method,
|
||||||
|
# 实际项目中应返回支付宝或微信的支付参数
|
||||||
|
'qr_code': f'https://payment.example.com/qr/{order.order_no}',
|
||||||
|
'payment_url': f'https://payment.example.com/pay/{order.order_no}'
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
'message': '订单创建成功',
|
||||||
|
'order': order.to_dict(),
|
||||||
|
'payment': payment_params
|
||||||
|
}, 201
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return {'error': '订单创建失败'}, 500
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_orders(user_id, page=1, per_page=20, status=None):
|
||||||
|
"""获取订单列表"""
|
||||||
|
query = Order.query.filter_by(user_id=user_id)
|
||||||
|
|
||||||
|
if status:
|
||||||
|
query = query.filter_by(status=status)
|
||||||
|
|
||||||
|
# 分页查询
|
||||||
|
pagination = query.order_by(desc(Order.created_at))\
|
||||||
|
.paginate(page=page, per_page=per_page, error_out=False)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'orders': [order.to_dict() for order in pagination.items],
|
||||||
|
'total': pagination.total,
|
||||||
|
'page': page,
|
||||||
|
'per_page': per_page,
|
||||||
|
'pages': pagination.pages
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_order(user_id, order_id):
|
||||||
|
"""获取订单详情"""
|
||||||
|
order = Order.query.filter_by(id=order_id, user_id=user_id).first()
|
||||||
|
|
||||||
|
if not order:
|
||||||
|
return {'error': '订单不存在'}, 404
|
||||||
|
|
||||||
|
return order.to_dict(), 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def alipay_callback(data):
|
||||||
|
"""支付宝支付回调(预留接口)"""
|
||||||
|
# TODO: 实现支付宝回调逻辑
|
||||||
|
return {'message': '处理成功'}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def wechat_callback(data):
|
||||||
|
"""微信支付回调(预留接口)"""
|
||||||
|
# TODO: 实现微信支付回调逻辑
|
||||||
|
return {'message': '处理成功'}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def payment_notify(order_no):
|
||||||
|
"""模拟支付通知(仅用于测试)"""
|
||||||
|
order = Order.query.filter_by(order_no=order_no).first()
|
||||||
|
|
||||||
|
if not order:
|
||||||
|
return {'error': '订单不存在'}, 404
|
||||||
|
|
||||||
|
if order.status != 'pending':
|
||||||
|
return {'error': '订单状态不正确'}, 400
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 更新订单状态
|
||||||
|
order.status = 'paid'
|
||||||
|
order.paid_at = datetime.utcnow()
|
||||||
|
order.transaction_id = f"TXN{uuid.uuid4().hex[:16].upper()}"
|
||||||
|
|
||||||
|
# 增加用户余额
|
||||||
|
user = User.query.get(order.user_id)
|
||||||
|
balance_before = user.balance
|
||||||
|
user.balance += order.amount
|
||||||
|
balance_after = user.balance
|
||||||
|
|
||||||
|
# 创建交易记录
|
||||||
|
transaction = Transaction(
|
||||||
|
user_id=user.id,
|
||||||
|
type='recharge',
|
||||||
|
amount=order.amount,
|
||||||
|
balance_before=balance_before,
|
||||||
|
balance_after=balance_after,
|
||||||
|
description=f'充值 - 订单号: {order.order_no}',
|
||||||
|
order_id=order.id
|
||||||
|
)
|
||||||
|
|
||||||
|
db.session.add(transaction)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
return {
|
||||||
|
'message': '支付成功',
|
||||||
|
'order': order.to_dict()
|
||||||
|
}, 200
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return {'error': '支付处理失败'}, 500
|
||||||
89
NBATransfer-backend/services/user_service.py
Normal file
89
NBATransfer-backend/services/user_service.py
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
from flask import request
|
||||||
|
from models import db, User, Transaction, ApiCall
|
||||||
|
from sqlalchemy import desc
|
||||||
|
|
||||||
|
class UserService:
|
||||||
|
@staticmethod
|
||||||
|
def get_profile(user_id):
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
return user.to_dict(), 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def update_profile(user_id, data):
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
if 'username' in data:
|
||||||
|
user.username = data['username'].strip()
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.session.commit()
|
||||||
|
return {
|
||||||
|
'message': '资料更新成功',
|
||||||
|
'user': user.to_dict()
|
||||||
|
}, 200
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return {'error': '资料更新失败'}, 500
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_balance(user_id):
|
||||||
|
user = User.query.get(user_id)
|
||||||
|
if not user:
|
||||||
|
return {'error': '用户不存在'}, 404
|
||||||
|
|
||||||
|
return {
|
||||||
|
'balance': user.balance,
|
||||||
|
'user_id': user.id
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_transactions(user_id, page, per_page):
|
||||||
|
pagination = Transaction.query.filter_by(user_id=user_id)\
|
||||||
|
.order_by(desc(Transaction.created_at))\
|
||||||
|
.paginate(page=page, per_page=per_page, error_out=False)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'transactions': [t.to_dict() for t in pagination.items],
|
||||||
|
'total': pagination.total,
|
||||||
|
'page': page,
|
||||||
|
'per_page': per_page,
|
||||||
|
'pages': pagination.pages
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_api_calls(user_id, page, per_page):
|
||||||
|
pagination = ApiCall.query.filter_by(user_id=user_id)\
|
||||||
|
.order_by(desc(ApiCall.created_at))\
|
||||||
|
.paginate(page=page, per_page=per_page, error_out=False)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'api_calls': [call.to_dict() for call in pagination.items],
|
||||||
|
'total': pagination.total,
|
||||||
|
'page': page,
|
||||||
|
'per_page': per_page,
|
||||||
|
'pages': pagination.pages
|
||||||
|
}, 200
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_stats(user_id):
|
||||||
|
total_calls = ApiCall.query.filter_by(user_id=user_id).count()
|
||||||
|
success_calls = ApiCall.query.filter_by(user_id=user_id, status='success').count()
|
||||||
|
failed_calls = ApiCall.query.filter_by(user_id=user_id, status='failed').count()
|
||||||
|
|
||||||
|
total_cost = db.session.query(db.func.sum(Transaction.amount))\
|
||||||
|
.filter_by(user_id=user_id, type='consume').scalar() or 0
|
||||||
|
|
||||||
|
total_recharge = db.session.query(db.func.sum(Transaction.amount))\
|
||||||
|
.filter_by(user_id=user_id, type='recharge').scalar() or 0
|
||||||
|
|
||||||
|
return {
|
||||||
|
'total_calls': total_calls,
|
||||||
|
'success_calls': success_calls,
|
||||||
|
'failed_calls': failed_calls,
|
||||||
|
'total_cost': abs(total_cost),
|
||||||
|
'total_recharge': total_recharge
|
||||||
|
}, 200
|
||||||
174
NBATransfer-backend/services/v1_service.py
Normal file
174
NBATransfer-backend/services/v1_service.py
Normal file
@@ -0,0 +1,174 @@
|
|||||||
|
from flask import current_app
|
||||||
|
from models import db, User, ApiCall
|
||||||
|
from datetime import datetime
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from modelapiservice import get_model_service
|
||||||
|
from services.api_proxy_service import ApiProxyService
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class V1Service:
|
||||||
|
@staticmethod
|
||||||
|
def chat_completions(user, data):
|
||||||
|
"""
|
||||||
|
OpenAI 兼容的 Chat Completions 接口逻辑
|
||||||
|
"""
|
||||||
|
model = data.get('model')
|
||||||
|
messages = data.get('messages', [])
|
||||||
|
stream = data.get('stream', False)
|
||||||
|
|
||||||
|
if not model:
|
||||||
|
return {'error': {'message': '缺少 model 参数', 'type': 'invalid_request_error', 'code': 400}}, 400
|
||||||
|
|
||||||
|
if not messages:
|
||||||
|
return {'error': {'message': '缺少 messages 参数', 'type': 'invalid_request_error', 'code': 400}}, 400
|
||||||
|
|
||||||
|
# 获取模型服务并检查余额
|
||||||
|
try:
|
||||||
|
service = get_model_service(model)
|
||||||
|
except Exception as e:
|
||||||
|
return {'error': {'message': f'不支持的模型: {model}', 'type': 'invalid_request_error', 'code': 400}}, 400
|
||||||
|
|
||||||
|
is_sufficient, estimated_cost, error_msg = service.check_balance(user.balance)
|
||||||
|
if not is_sufficient:
|
||||||
|
return {
|
||||||
|
'error': {
|
||||||
|
'message': error_msg,
|
||||||
|
'type': 'insufficient_quota',
|
||||||
|
'code': 402
|
||||||
|
}
|
||||||
|
}, 402
|
||||||
|
|
||||||
|
prompt = messages[-1].get('content', '') if messages else 'Empty prompt'
|
||||||
|
if len(prompt) > 500:
|
||||||
|
prompt = prompt[:500] + '...'
|
||||||
|
|
||||||
|
api_call = ApiCall(
|
||||||
|
user_id=user.id,
|
||||||
|
api_type='chat_completion',
|
||||||
|
prompt=prompt,
|
||||||
|
parameters=json.dumps({
|
||||||
|
'model': model,
|
||||||
|
'stream': stream
|
||||||
|
}),
|
||||||
|
status='processing',
|
||||||
|
cost=estimated_cost, # 暂时记录预估/固定费用
|
||||||
|
request_time=datetime.utcnow()
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.session.add(api_call)
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
# 准备请求
|
||||||
|
api_url, api_key = service.get_api_config()
|
||||||
|
if not api_url or not api_key:
|
||||||
|
raise ValueError(f'模型 {model} API 配置未完成')
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
'Authorization': f'Bearer {api_key}',
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
}
|
||||||
|
|
||||||
|
payload = service.prepare_payload(data)
|
||||||
|
target_url = f'{api_url}/chat/completions'
|
||||||
|
|
||||||
|
logger.info(f'API 转发: {target_url}, User: {user.id}, Model: {model}')
|
||||||
|
|
||||||
|
response = requests.post(
|
||||||
|
target_url,
|
||||||
|
headers=headers,
|
||||||
|
json=payload,
|
||||||
|
stream=stream,
|
||||||
|
timeout=300
|
||||||
|
)
|
||||||
|
|
||||||
|
if response.status_code != 200:
|
||||||
|
error_msg = f'Upstream Error: {response.status_code}'
|
||||||
|
try:
|
||||||
|
error_detail = response.json()
|
||||||
|
error_msg += f' - {error_detail}'
|
||||||
|
except:
|
||||||
|
error_msg += f' - {response.text[:200]}'
|
||||||
|
|
||||||
|
api_call.status = 'failed'
|
||||||
|
api_call.error_message = error_msg
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
return {
|
||||||
|
'error': {
|
||||||
|
'message': error_msg,
|
||||||
|
'type': 'upstream_error',
|
||||||
|
'code': 502
|
||||||
|
}
|
||||||
|
}, 502
|
||||||
|
|
||||||
|
# 处理响应
|
||||||
|
if stream:
|
||||||
|
# 流式响应处理
|
||||||
|
def generate():
|
||||||
|
final_usage = None
|
||||||
|
try:
|
||||||
|
for chunk in response.iter_content(chunk_size=1024):
|
||||||
|
if chunk:
|
||||||
|
if hasattr(service, 'parse_stream_usage'):
|
||||||
|
try:
|
||||||
|
text_chunk = chunk.decode('utf-8', errors='ignore')
|
||||||
|
usage = service.parse_stream_usage(text_chunk)
|
||||||
|
if usage:
|
||||||
|
final_usage = usage
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
yield chunk
|
||||||
|
|
||||||
|
# 计算最终费用
|
||||||
|
actual_cost = service.calculate_cost(final_usage, stream=True)
|
||||||
|
if actual_cost == 0 and estimated_cost > 0:
|
||||||
|
actual_cost = estimated_cost
|
||||||
|
|
||||||
|
# 扣费
|
||||||
|
with current_app.app_context():
|
||||||
|
ApiProxyService.deduct_balance(user.id, api_call.id, actual_cost, model)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f'Stream error: {e}')
|
||||||
|
|
||||||
|
return generate(), 200
|
||||||
|
else:
|
||||||
|
# 普通响应
|
||||||
|
result = response.json()
|
||||||
|
api_call.status = 'success'
|
||||||
|
api_call.response_time = datetime.utcnow()
|
||||||
|
|
||||||
|
# 计算费用
|
||||||
|
usage = result.get('usage')
|
||||||
|
final_cost = service.calculate_cost(usage, stream=False)
|
||||||
|
if final_cost == 0 and estimated_cost > 0:
|
||||||
|
final_cost = estimated_cost
|
||||||
|
|
||||||
|
# 简化响应格式
|
||||||
|
simplified_result = {
|
||||||
|
'model': model,
|
||||||
|
'content': '',
|
||||||
|
'cost': final_cost
|
||||||
|
}
|
||||||
|
|
||||||
|
if 'choices' in result and len(result['choices']) > 0:
|
||||||
|
content = result['choices'][0].get('message', {}).get('content', '')
|
||||||
|
simplified_result['content'] = content
|
||||||
|
# 同时更新 api_call 记录
|
||||||
|
api_call.result_url = content[:500]
|
||||||
|
|
||||||
|
ApiProxyService.deduct_balance(user.id, api_call.id, final_cost, model)
|
||||||
|
|
||||||
|
return simplified_result, 200
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f'API Error: {e}', exc_info=True)
|
||||||
|
if api_call.id:
|
||||||
|
api_call.status = 'failed'
|
||||||
|
api_call.error_message = str(e)
|
||||||
|
db.session.commit()
|
||||||
|
return {'error': {'message': 'Internal Server Error', 'type': 'server_error', 'code': 500}}, 500
|
||||||
177
NBATransfer-backend/后端文档.md
Normal file
177
NBATransfer-backend/后端文档.md
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
# Nano Banana API 中转平台 - 后端
|
||||||
|
|
||||||
|
基于 Flask 的 Nano Banana API 中转购买平台后端服务。
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
- 📧 邮箱注册登录系统
|
||||||
|
- 💰 用户余额管理
|
||||||
|
- 💳 支付接口(支付宝/微信支付)
|
||||||
|
- 🎨 Nano Banana 文生图 API 中转
|
||||||
|
- 📊 用户统计和订单管理
|
||||||
|
- 🔐 JWT 身份认证
|
||||||
|
- 👨💼 管理员后台
|
||||||
|
|
||||||
|
## 技术栈
|
||||||
|
|
||||||
|
- Flask 3.0
|
||||||
|
- SQLite 数据库
|
||||||
|
- Flask-SQLAlchemy ORM
|
||||||
|
- Flask-JWT-Extended 认证
|
||||||
|
- Flask-CORS 跨域支持
|
||||||
|
- Flask-Mail 邮件服务
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 1. 安装依赖
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 配置环境变量
|
||||||
|
|
||||||
|
复制 `.env.example` 到 `.env` 并修改配置:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
copy .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
必需配置项:
|
||||||
|
- `SECRET_KEY`: Flask 密钥
|
||||||
|
- `JWT_SECRET_KEY`: JWT 密钥
|
||||||
|
- `NANO_BANANA_API_KEY`: Nano Banana API 密钥
|
||||||
|
- `MAIL_USERNAME`: 邮箱用户名
|
||||||
|
- `MAIL_PASSWORD`: 邮箱密码
|
||||||
|
|
||||||
|
### 3. 运行应用
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python app.py
|
||||||
|
```
|
||||||
|
|
||||||
|
服务将在 http://localhost:5000 启动
|
||||||
|
|
||||||
|
### 4. 默认管理员账号
|
||||||
|
|
||||||
|
- 邮箱: admin@nba.com
|
||||||
|
- 密码: admin123
|
||||||
|
|
||||||
|
**首次登录后请立即修改密码!**
|
||||||
|
|
||||||
|
## API 文档
|
||||||
|
|
||||||
|
### 认证相关 `/api/auth`
|
||||||
|
|
||||||
|
- `POST /register` - 用户注册
|
||||||
|
- `POST /login` - 用户登录
|
||||||
|
- `POST /refresh` - 刷新令牌
|
||||||
|
- `GET /me` - 获取当前用户信息
|
||||||
|
- `POST /change-password` - 修改密码
|
||||||
|
|
||||||
|
### 用户相关 `/api/user`
|
||||||
|
|
||||||
|
- `GET /profile` - 获取用户资料
|
||||||
|
- `PUT /profile` - 更新用户资料
|
||||||
|
- `GET /balance` - 获取账户余额
|
||||||
|
- `GET /transactions` - 获取交易记录
|
||||||
|
- `GET /api-calls` - 获取API调用记录
|
||||||
|
- `GET /stats` - 获取统计信息
|
||||||
|
|
||||||
|
### 订单相关 `/api/order`
|
||||||
|
|
||||||
|
- `POST /create` - 创建充值订单
|
||||||
|
- `GET /list` - 获取订单列表
|
||||||
|
- `GET /<order_id>` - 获取订单详情
|
||||||
|
- `POST /notify/<order_no>` - 支付通知(测试用)
|
||||||
|
|
||||||
|
### API服务 `/api/service`
|
||||||
|
|
||||||
|
- `POST /text-to-image` - 文生图API
|
||||||
|
- `GET /models` - 获取可用模型
|
||||||
|
- `GET /pricing` - 获取价格信息
|
||||||
|
- `GET /call/<call_id>` - 获取API调用详情
|
||||||
|
|
||||||
|
### 管理员 `/api/admin`
|
||||||
|
|
||||||
|
- `GET /users` - 获取用户列表
|
||||||
|
- `GET /users/<user_id>` - 获取用户详情
|
||||||
|
- `POST /users/<user_id>/toggle-status` - 启用/禁用用户
|
||||||
|
- `POST /users/<user_id>/adjust-balance` - 调整用户余额
|
||||||
|
- `GET /orders` - 获取所有订单
|
||||||
|
- `GET /api-calls` - 获取所有API调用
|
||||||
|
- `GET /stats/overview` - 获取总览统计
|
||||||
|
- `GET /stats/chart` - 获取图表数据
|
||||||
|
|
||||||
|
## 数据库结构
|
||||||
|
|
||||||
|
### 用户表 (users)
|
||||||
|
- 邮箱、密码、用户名
|
||||||
|
- 余额、激活状态、管理员标识
|
||||||
|
- 创建时间、更新时间
|
||||||
|
|
||||||
|
### 订单表 (orders)
|
||||||
|
- 订单号、用户ID、金额
|
||||||
|
- 支付方式、订单状态
|
||||||
|
- 第三方交易ID、支付时间
|
||||||
|
|
||||||
|
### 交易记录表 (transactions)
|
||||||
|
- 用户ID、交易类型(充值/消费/退款)
|
||||||
|
- 金额、前后余额
|
||||||
|
- 关联订单、关联API调用
|
||||||
|
|
||||||
|
### API调用表 (api_calls)
|
||||||
|
- 用户ID、API类型
|
||||||
|
- 提示词、参数、状态
|
||||||
|
- 结果URL、费用、错误信息
|
||||||
|
|
||||||
|
## 开发说明
|
||||||
|
|
||||||
|
### 添加新的路由
|
||||||
|
|
||||||
|
1. 在 `routes/` 目录下创建新的蓝图文件
|
||||||
|
2. 在 `app.py` 中注册蓝图
|
||||||
|
|
||||||
|
### 数据库迁移
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 进入 Python shell
|
||||||
|
python
|
||||||
|
>>> from app import create_app
|
||||||
|
>>> from models import db
|
||||||
|
>>> app = create_app()
|
||||||
|
>>> with app.app_context():
|
||||||
|
... db.create_all()
|
||||||
|
```
|
||||||
|
|
||||||
|
## 部署建议
|
||||||
|
|
||||||
|
### 使用 Gunicorn (生产环境)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install gunicorn
|
||||||
|
gunicorn -w 4 -b 0.0.0.0:5000 app:app
|
||||||
|
```
|
||||||
|
|
||||||
|
### 使用 Docker
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
FROM python:3.9
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install -r requirements.txt
|
||||||
|
COPY . .
|
||||||
|
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "app:app"]
|
||||||
|
```
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. 生产环境请修改所有默认密钥
|
||||||
|
2. 配置实际的邮件服务器
|
||||||
|
3. 接入真实的支付接口
|
||||||
|
4. 配置 HTTPS
|
||||||
|
5. 定期备份数据库
|
||||||
|
|
||||||
|
## 许可证
|
||||||
|
|
||||||
|
MIT License
|
||||||
28
NBATransfer-backend/启动后端.bat
Normal file
28
NBATransfer-backend/启动后端.bat
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
@echo off
|
||||||
|
chcp 65001 >nul
|
||||||
|
title Nano Banana API - 启动后端服务
|
||||||
|
|
||||||
|
cd /d "%~dp0NBATransfer-backend"
|
||||||
|
|
||||||
|
if not exist ".env" (
|
||||||
|
echo ❌ 错误:未找到 .env 配置文件
|
||||||
|
echo 请先运行 一键安装.bat 或手动复制 .env.example 为 .env
|
||||||
|
pause
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo ============================================
|
||||||
|
echo 🍌 Nano Banana API - 后端服务
|
||||||
|
echo ============================================
|
||||||
|
echo.
|
||||||
|
echo 启动后端服务...
|
||||||
|
echo.
|
||||||
|
echo 📍 访问地址:http://localhost:5000
|
||||||
|
echo 📍 API 文档:查看 README.md
|
||||||
|
echo.
|
||||||
|
echo 按 Ctrl+C 停止服务
|
||||||
|
echo.
|
||||||
|
|
||||||
|
python app.py
|
||||||
|
pause
|
||||||
23
NBATransfer-frontend/eslint.config.js
Normal file
23
NBATransfer-frontend/eslint.config.js
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
|
import tseslint from 'typescript-eslint'
|
||||||
|
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
js.configs.recommended,
|
||||||
|
tseslint.configs.recommended,
|
||||||
|
reactHooks.configs.flat.recommended,
|
||||||
|
reactRefresh.configs.vite,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
13
NBATransfer-frontend/index.html
Normal file
13
NBATransfer-frontend/index.html
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>大语言模型API中转站</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
4992
NBATransfer-frontend/package-lock.json
generated
Normal file
4992
NBATransfer-frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
37
NBATransfer-frontend/package.json
Normal file
37
NBATransfer-frontend/package.json
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"name": "nbatransfer",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"react": "^19.2.0",
|
||||||
|
"react-dom": "^19.2.0",
|
||||||
|
"react-router-dom": "^7.1.3",
|
||||||
|
"axios": "^1.7.9",
|
||||||
|
"zustand": "^5.0.3",
|
||||||
|
"antd": "^5.23.2",
|
||||||
|
"@ant-design/icons": "^5.5.4",
|
||||||
|
"dayjs": "^1.11.13",
|
||||||
|
"recharts": "^2.15.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.39.1",
|
||||||
|
"@types/node": "^24.10.1",
|
||||||
|
"@types/react": "^19.2.5",
|
||||||
|
"@types/react-dom": "^19.2.3",
|
||||||
|
"@vitejs/plugin-react": "^5.1.1",
|
||||||
|
"eslint": "^9.39.1",
|
||||||
|
"eslint-plugin-react-hooks": "^7.0.1",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.24",
|
||||||
|
"globals": "^16.5.0",
|
||||||
|
"typescript": "~5.9.3",
|
||||||
|
"typescript-eslint": "^8.46.4",
|
||||||
|
"vite": "^7.2.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
1
NBATransfer-frontend/public/vite.svg
Normal file
1
NBATransfer-frontend/public/vite.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 1.5 KiB |
17
NBATransfer-frontend/src/App.css
Normal file
17
NBATransfer-frontend/src/App.css
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||||
|
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||||
|
sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
|
|
||||||
|
#root {
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
50
NBATransfer-frontend/src/App.tsx
Normal file
50
NBATransfer-frontend/src/App.tsx
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
||||||
|
import { ConfigProvider } from 'antd';
|
||||||
|
import zhCN from 'antd/locale/zh_CN';
|
||||||
|
import Login from './pages/Login';
|
||||||
|
import DashboardLayout from './components/DashboardLayout';
|
||||||
|
import Dashboard from './pages/Dashboard';
|
||||||
|
import Wallet from './pages/Wallet';
|
||||||
|
import ApiKeyManagement from './pages/ApiKeyManagement';
|
||||||
|
import ApiDocumentation from './pages/ApiDocumentation';
|
||||||
|
import Settings from './pages/Settings';
|
||||||
|
import { PrivateRoute } from './components/PrivateRoute';
|
||||||
|
import { useAuthStore } from './store/auth';
|
||||||
|
import './App.css';
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ConfigProvider locale={zhCN}>
|
||||||
|
<BrowserRouter>
|
||||||
|
<Routes>
|
||||||
|
<Route
|
||||||
|
path="/login"
|
||||||
|
element={isAuthenticated ? <Navigate to="/dashboard" replace /> : <Login />}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Route
|
||||||
|
path="/dashboard"
|
||||||
|
element={
|
||||||
|
<PrivateRoute>
|
||||||
|
<DashboardLayout />
|
||||||
|
</PrivateRoute>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Route index element={<Dashboard />} />
|
||||||
|
<Route path="wallet" element={<Wallet />} />
|
||||||
|
<Route path="apikeys" element={<ApiKeyManagement />} />
|
||||||
|
<Route path="docs" element={<ApiDocumentation />} />
|
||||||
|
<Route path="settings" element={<Settings />} />
|
||||||
|
</Route>
|
||||||
|
|
||||||
|
<Route path="/" element={<Navigate to="/dashboard" replace />} />
|
||||||
|
<Route path="*" element={<Navigate to="/dashboard" replace />} />
|
||||||
|
</Routes>
|
||||||
|
</BrowserRouter>
|
||||||
|
</ConfigProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export default App;
|
||||||
65
NBATransfer-frontend/src/api/client.ts
Normal file
65
NBATransfer-frontend/src/api/client.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:5000/api';
|
||||||
|
|
||||||
|
const api = axios.create({
|
||||||
|
baseURL: API_BASE_URL,
|
||||||
|
timeout: 30000,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 请求拦截器 - 添加 token
|
||||||
|
api.interceptors.request.use(
|
||||||
|
(config) => {
|
||||||
|
const token = localStorage.getItem('access_token');
|
||||||
|
if (token) {
|
||||||
|
config.headers.Authorization = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// 响应拦截器 - 处理错误
|
||||||
|
api.interceptors.response.use(
|
||||||
|
(response) => response,
|
||||||
|
async (error) => {
|
||||||
|
const originalRequest = error.config;
|
||||||
|
|
||||||
|
// 如果 token 过期,尝试刷新
|
||||||
|
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||||
|
originalRequest._retry = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const refreshToken = localStorage.getItem('refresh_token');
|
||||||
|
if (refreshToken) {
|
||||||
|
const response = await axios.post(`${API_BASE_URL}/auth/refresh`, null, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${refreshToken}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { access_token } = response.data;
|
||||||
|
localStorage.setItem('access_token', access_token);
|
||||||
|
|
||||||
|
originalRequest.headers.Authorization = `Bearer ${access_token}`;
|
||||||
|
return api(originalRequest);
|
||||||
|
}
|
||||||
|
} catch (refreshError) {
|
||||||
|
// 刷新失败,清除 token 并跳转到登录页
|
||||||
|
localStorage.removeItem('access_token');
|
||||||
|
localStorage.removeItem('refresh_token');
|
||||||
|
window.location.href = '/login';
|
||||||
|
return Promise.reject(refreshError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
export default api;
|
||||||
10
NBATransfer-frontend/src/api/index.ts
Normal file
10
NBATransfer-frontend/src/api/index.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import api from './client';
|
||||||
|
|
||||||
|
export * from './modules/auth';
|
||||||
|
export * from './modules/user';
|
||||||
|
export * from './modules/order';
|
||||||
|
export * from './modules/service';
|
||||||
|
export * from './modules/admin';
|
||||||
|
export * from './modules/apikey';
|
||||||
|
|
||||||
|
export default api;
|
||||||
16
NBATransfer-frontend/src/api/modules/admin.ts
Normal file
16
NBATransfer-frontend/src/api/modules/admin.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import api from '../client';
|
||||||
|
|
||||||
|
export const adminAPI = {
|
||||||
|
getUsers: (params: { page?: number; per_page?: number; search?: string }) =>
|
||||||
|
api.get('/admin/users', { params }),
|
||||||
|
getUserDetail: (userId: number) => api.get(`/admin/users/${userId}`),
|
||||||
|
toggleUserStatus: (userId: number) => api.post(`/admin/users/${userId}/toggle-status`),
|
||||||
|
adjustBalance: (userId: number, data: { amount: number; description: string }) =>
|
||||||
|
api.post(`/admin/users/${userId}/adjust-balance`, data),
|
||||||
|
getAllOrders: (params: { page?: number; per_page?: number; status?: string }) =>
|
||||||
|
api.get('/admin/orders', { params }),
|
||||||
|
getAllApiCalls: (params: { page?: number; per_page?: number; status?: string }) =>
|
||||||
|
api.get('/admin/api-calls', { params }),
|
||||||
|
getOverviewStats: () => api.get('/admin/stats/overview'),
|
||||||
|
getChartData: (params: { days?: number }) => api.get('/admin/stats/chart', { params }),
|
||||||
|
};
|
||||||
10
NBATransfer-frontend/src/api/modules/apikey.ts
Normal file
10
NBATransfer-frontend/src/api/modules/apikey.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import api from '../client';
|
||||||
|
|
||||||
|
export const apikeyAPI = {
|
||||||
|
getKeys: () => api.get('/apikey/keys'),
|
||||||
|
createKey: (data: { name: string }) => api.post('/apikey/keys', data),
|
||||||
|
deleteKey: (id: number) => api.delete(`/apikey/keys/${id}`),
|
||||||
|
updateKey: (id: number, data: { name?: string; is_active?: boolean }) =>
|
||||||
|
api.put(`/apikey/keys/${id}`, data),
|
||||||
|
regenerateKey: (id: number) => api.post(`/apikey/keys/${id}/regenerate`, {}),
|
||||||
|
};
|
||||||
17
NBATransfer-frontend/src/api/modules/auth.ts
Normal file
17
NBATransfer-frontend/src/api/modules/auth.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import api from '../client';
|
||||||
|
|
||||||
|
export const authAPI = {
|
||||||
|
sendVerificationCode: (data: { email: string }) =>
|
||||||
|
api.post('/auth/send-verification-code', data),
|
||||||
|
register: (data: { email: string; password: string; verification_code: string }) =>
|
||||||
|
api.post('/auth/register', { ...data, code: data.verification_code }),
|
||||||
|
login: (data: { email: string; password: string }) =>
|
||||||
|
api.post('/auth/login', data),
|
||||||
|
getCurrentUser: () => api.get('/auth/me'),
|
||||||
|
changePassword: (data: { old_password: string; new_password: string }) =>
|
||||||
|
api.post('/auth/change-password', data),
|
||||||
|
verifyCode: (data: { email: string; code: string }) =>
|
||||||
|
api.post('/auth/verify-code', data),
|
||||||
|
resetPassword: (data: { email: string; verification_code: string; new_password: string }) =>
|
||||||
|
api.post('/auth/reset-password', { ...data, code: data.verification_code }),
|
||||||
|
};
|
||||||
10
NBATransfer-frontend/src/api/modules/order.ts
Normal file
10
NBATransfer-frontend/src/api/modules/order.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import api from '../client';
|
||||||
|
|
||||||
|
export const orderAPI = {
|
||||||
|
createOrder: (data: { amount: number; payment_method: string }) =>
|
||||||
|
api.post('/order/create', data),
|
||||||
|
getOrders: (params: { page?: number; per_page?: number; status?: string }) =>
|
||||||
|
api.get('/order/list', { params }),
|
||||||
|
getOrder: (orderId: number) => api.get(`/order/${orderId}`),
|
||||||
|
notifyPayment: (orderNo: string) => api.post(`/order/notify/${orderNo}`),
|
||||||
|
};
|
||||||
9
NBATransfer-frontend/src/api/modules/service.ts
Normal file
9
NBATransfer-frontend/src/api/modules/service.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import api from '../client';
|
||||||
|
|
||||||
|
export const apiServiceAPI = {
|
||||||
|
textToImage: (data: { model?: string; messages?: any[]; prompt?: string; parameters?: any }) =>
|
||||||
|
api.post('/service/text-to-image', data),
|
||||||
|
getModels: () => api.get('/service/models'),
|
||||||
|
getPricing: () => api.get('/service/pricing'),
|
||||||
|
getApiCall: (callId: number) => api.get(`/service/call/${callId}`),
|
||||||
|
};
|
||||||
12
NBATransfer-frontend/src/api/modules/user.ts
Normal file
12
NBATransfer-frontend/src/api/modules/user.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import api from '../client';
|
||||||
|
|
||||||
|
export const userAPI = {
|
||||||
|
getProfile: () => api.get('/user/profile'),
|
||||||
|
updateProfile: (data: { username?: string }) => api.put('/user/profile', data),
|
||||||
|
getBalance: () => api.get('/user/balance'),
|
||||||
|
getTransactions: (params: { page?: number; per_page?: number }) =>
|
||||||
|
api.get('/user/transactions', { params }),
|
||||||
|
getApiCalls: (params: { page?: number; per_page?: number }) =>
|
||||||
|
api.get('/user/api-calls', { params }),
|
||||||
|
getStats: () => api.get('/user/stats'),
|
||||||
|
};
|
||||||
1
NBATransfer-frontend/src/assets/react.svg
Normal file
1
NBATransfer-frontend/src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 4.0 KiB |
86
NBATransfer-frontend/src/components/DashboardLayout.css
Normal file
86
NBATransfer-frontend/src/components/DashboardLayout.css
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
.dashboard-layout {
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard-sider {
|
||||||
|
box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
height: 64px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo h2 {
|
||||||
|
color: #fff;
|
||||||
|
margin: 0;
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard-header {
|
||||||
|
background: #fff;
|
||||||
|
padding: 0 24px;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-info {
|
||||||
|
font-weight: 600;
|
||||||
|
color: #1890ff;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-info {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border-radius: 4px;
|
||||||
|
transition: background 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-info:hover {
|
||||||
|
background: rgba(0, 0, 0, 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
max-width: 150px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard-content {
|
||||||
|
margin: 24px;
|
||||||
|
padding: 24px;
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 8px;
|
||||||
|
min-height: calc(100vh - 112px);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.dashboard-content {
|
||||||
|
margin: 16px;
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-info {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
}
|
||||||
143
NBATransfer-frontend/src/components/DashboardLayout.tsx
Normal file
143
NBATransfer-frontend/src/components/DashboardLayout.tsx
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { Layout, Menu, Avatar, Dropdown, message } from 'antd';
|
||||||
|
import {
|
||||||
|
DashboardOutlined,
|
||||||
|
WalletOutlined,
|
||||||
|
UserOutlined,
|
||||||
|
LogoutOutlined,
|
||||||
|
SettingOutlined,
|
||||||
|
KeyOutlined,
|
||||||
|
FileTextOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
|
||||||
|
import { useAuthStore } from '../store/auth';
|
||||||
|
import { userAPI } from '../api';
|
||||||
|
import './DashboardLayout.css';
|
||||||
|
|
||||||
|
const { Header, Sider, Content } = Layout;
|
||||||
|
|
||||||
|
const DashboardLayout: React.FC = () => {
|
||||||
|
const [collapsed, setCollapsed] = useState(false);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const location = useLocation();
|
||||||
|
const { user, logout, updateUser } = useAuthStore();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// 获取最新用户信息(包括余额)
|
||||||
|
const fetchUserProfile = async () => {
|
||||||
|
try {
|
||||||
|
const response = await userAPI.getProfile();
|
||||||
|
updateUser(response.data);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch user profile:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchUserProfile();
|
||||||
|
}, [updateUser]);
|
||||||
|
|
||||||
|
const menuItems = [
|
||||||
|
{
|
||||||
|
key: '/dashboard',
|
||||||
|
icon: <DashboardOutlined />,
|
||||||
|
label: '概览',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: '/dashboard/wallet',
|
||||||
|
icon: <WalletOutlined />,
|
||||||
|
label: '我的钱包',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: '/dashboard/apikeys',
|
||||||
|
icon: <KeyOutlined />,
|
||||||
|
label: 'API密钥',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: '/dashboard/docs',
|
||||||
|
icon: <FileTextOutlined />,
|
||||||
|
label: 'API文档',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: '/dashboard/settings',
|
||||||
|
icon: <SettingOutlined />,
|
||||||
|
label: '账户设置',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
logout();
|
||||||
|
message.success('已退出登录');
|
||||||
|
navigate('/login');
|
||||||
|
};
|
||||||
|
|
||||||
|
const userMenuItems = [
|
||||||
|
{
|
||||||
|
key: 'profile',
|
||||||
|
icon: <UserOutlined />,
|
||||||
|
label: '个人资料',
|
||||||
|
onClick: () => navigate('/dashboard/settings'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'logout',
|
||||||
|
icon: <LogoutOutlined />,
|
||||||
|
label: '退出登录',
|
||||||
|
onClick: handleLogout,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// 移动端自动收起侧边栏
|
||||||
|
const handleResize = () => {
|
||||||
|
if (window.innerWidth < 768) {
|
||||||
|
setCollapsed(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleResize();
|
||||||
|
window.addEventListener('resize', handleResize);
|
||||||
|
return () => window.removeEventListener('resize', handleResize);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Layout className="dashboard-layout">
|
||||||
|
<Sider
|
||||||
|
collapsible
|
||||||
|
collapsed={collapsed}
|
||||||
|
onCollapse={setCollapsed}
|
||||||
|
breakpoint="lg"
|
||||||
|
className="dashboard-sider"
|
||||||
|
>
|
||||||
|
<div className="logo">
|
||||||
|
<h2>{collapsed ? '🍌' : '🍌 大语言模型API'}</h2>
|
||||||
|
</div>
|
||||||
|
<Menu
|
||||||
|
theme="dark"
|
||||||
|
mode="inline"
|
||||||
|
selectedKeys={[location.pathname]}
|
||||||
|
items={menuItems}
|
||||||
|
onClick={({ key }) => navigate(key)}
|
||||||
|
/>
|
||||||
|
</Sider>
|
||||||
|
<Layout>
|
||||||
|
<Header className="dashboard-header">
|
||||||
|
<div className="header-right">
|
||||||
|
<div className="balance-info">
|
||||||
|
余额: ¥{user?.balance?.toFixed(2) || '0.00'}
|
||||||
|
</div>
|
||||||
|
<Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
|
||||||
|
<div className="user-info">
|
||||||
|
<Avatar icon={<UserOutlined />} />
|
||||||
|
<span className="username">{user?.username || user?.email}</span>
|
||||||
|
</div>
|
||||||
|
</Dropdown>
|
||||||
|
</div>
|
||||||
|
</Header>
|
||||||
|
<Content className="dashboard-content">
|
||||||
|
<Outlet />
|
||||||
|
</Content>
|
||||||
|
</Layout>
|
||||||
|
</Layout>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default DashboardLayout;
|
||||||
22
NBATransfer-frontend/src/components/PrivateRoute.tsx
Normal file
22
NBATransfer-frontend/src/components/PrivateRoute.tsx
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Navigate } from 'react-router-dom';
|
||||||
|
import { useAuthStore } from '../store/auth';
|
||||||
|
|
||||||
|
interface PrivateRouteProps {
|
||||||
|
children: React.ReactNode;
|
||||||
|
requireAdmin?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PrivateRoute: React.FC<PrivateRouteProps> = ({ children, requireAdmin = false }) => {
|
||||||
|
const { isAuthenticated, user } = useAuthStore();
|
||||||
|
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
return <Navigate to="/login" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requireAdmin && !user?.is_admin) {
|
||||||
|
return <Navigate to="/" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
};
|
||||||
14
NBATransfer-frontend/src/index.css
Normal file
14
NBATransfer-frontend/src/index.css
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||||
|
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||||
|
sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
10
NBATransfer-frontend/src/main.tsx
Normal file
10
NBATransfer-frontend/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { StrictMode } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import './index.css'
|
||||||
|
import App from './App.tsx'
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<App />
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
||||||
134
NBATransfer-frontend/src/pages/ApiDocumentation.css
Normal file
134
NBATransfer-frontend/src/pages/ApiDocumentation.css
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
.doc-section {
|
||||||
|
padding: 20px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.doc-section h2 {
|
||||||
|
margin-top: 20px;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
color: #000;
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.doc-section h3 {
|
||||||
|
margin-top: 15px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
color: #333;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.doc-section p {
|
||||||
|
margin-bottom: 12px;
|
||||||
|
line-height: 1.6;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.doc-section ul,
|
||||||
|
.doc-section ol {
|
||||||
|
margin-left: 20px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
color: #666;
|
||||||
|
line-height: 1.8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.doc-section li {
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.code-block {
|
||||||
|
background: #f5f5f5;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
overflow: hidden;
|
||||||
|
margin: 15px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.code-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 10px 15px;
|
||||||
|
background: #efefef;
|
||||||
|
border-bottom: 1px solid #ddd;
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.code-block pre {
|
||||||
|
margin: 0;
|
||||||
|
padding: 15px;
|
||||||
|
overflow-x: auto;
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.endpoint-doc {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
margin: 20px 0;
|
||||||
|
padding: 15px;
|
||||||
|
background: #f0f2f5;
|
||||||
|
border-left: 4px solid #1890ff;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.method-badge {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 5px 12px;
|
||||||
|
background: #52c41a;
|
||||||
|
color: white;
|
||||||
|
border-radius: 3px;
|
||||||
|
font-weight: bold;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.endpoint-url {
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pricing-table,
|
||||||
|
.param-table,
|
||||||
|
.error-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
margin: 15px 0;
|
||||||
|
background: white;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pricing-table th,
|
||||||
|
.param-table th,
|
||||||
|
.error-table th {
|
||||||
|
background: #fafafa;
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
font-weight: 600;
|
||||||
|
text-align: left;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pricing-table td,
|
||||||
|
.param-table td,
|
||||||
|
.error-table td {
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
font-size: 13px;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pricing-table tr:hover,
|
||||||
|
.param-table tr:hover,
|
||||||
|
.error-table tr:hover {
|
||||||
|
background: #fafafa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pricing-table td:first-child,
|
||||||
|
.param-table td:first-child,
|
||||||
|
.error-table td:first-child {
|
||||||
|
font-weight: 500;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
163
NBATransfer-frontend/src/pages/ApiDocumentation.tsx
Normal file
163
NBATransfer-frontend/src/pages/ApiDocumentation.tsx
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Card, Tabs, Alert, Button, Space, message } from 'antd';
|
||||||
|
import { CopyOutlined } from '@ant-design/icons';
|
||||||
|
import './ApiDocumentation.css';
|
||||||
|
|
||||||
|
const ApiDocumentation: React.FC = () => {
|
||||||
|
const [selectedExample, setSelectedExample] = useState('curl');
|
||||||
|
|
||||||
|
const copyToClipboard = (text: string) => {
|
||||||
|
navigator.clipboard.writeText(text);
|
||||||
|
message.success('已复制到剪贴板');
|
||||||
|
};
|
||||||
|
|
||||||
|
const API_BASE_URL = 'https://api.nanobananapi.com/v1';
|
||||||
|
|
||||||
|
// 示例代码
|
||||||
|
const examples = {
|
||||||
|
curl: `curl ${API_BASE_URL}/chat/completions \\
|
||||||
|
-H "Content-Type: application/json" \\
|
||||||
|
-H "Authorization: Bearer sk_your_api_key_here" \\
|
||||||
|
-d '{
|
||||||
|
"model": "deepseek-chat",
|
||||||
|
"messages": [
|
||||||
|
{"role": "system", "content": "You are a helpful assistant."},
|
||||||
|
{"role": "user", "content": "Hello!"}
|
||||||
|
],
|
||||||
|
"stream": false
|
||||||
|
}'`,
|
||||||
|
|
||||||
|
python: `import requests
|
||||||
|
|
||||||
|
url = "${API_BASE_URL}/chat/completions"
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Authorization": "Bearer sk_your_api_key_here"
|
||||||
|
}
|
||||||
|
|
||||||
|
data = {
|
||||||
|
"model": "deepseek-chat",
|
||||||
|
"messages": [
|
||||||
|
{"role": "system", "content": "You are a helpful assistant."},
|
||||||
|
{"role": "user", "content": "Hello!"}
|
||||||
|
],
|
||||||
|
"stream": False
|
||||||
|
}
|
||||||
|
|
||||||
|
response = requests.post(url, headers=headers, json=data)
|
||||||
|
print(response.json())`,
|
||||||
|
|
||||||
|
nodejs: `const axios = require('axios');
|
||||||
|
|
||||||
|
const url = '${API_BASE_URL}/chat/completions';
|
||||||
|
const apiKey = 'sk_your_api_key_here';
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
model: 'deepseek-chat',
|
||||||
|
messages: [
|
||||||
|
{ role: 'system', content: 'You are a helpful assistant.' },
|
||||||
|
{ role: 'user', content: 'Hello!' }
|
||||||
|
],
|
||||||
|
stream: false
|
||||||
|
};
|
||||||
|
|
||||||
|
axios.post(url, data, {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': \`Bearer \${apiKey}\`
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(response => {
|
||||||
|
console.log(response.data);
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error(error);
|
||||||
|
});`
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: '24px' }}>
|
||||||
|
<Card>
|
||||||
|
<h1>🍌 大语言模型API中转站文档</h1>
|
||||||
|
|
||||||
|
<Alert
|
||||||
|
message="API 接口地址"
|
||||||
|
description={API_BASE_URL}
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
style={{ marginBottom: '20px' }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="doc-section">
|
||||||
|
<h2>认证方式</h2>
|
||||||
|
<p>所有 API 请求都需要在 HTTP 请求头中提供 API Key:</p>
|
||||||
|
|
||||||
|
<div className="code-block">
|
||||||
|
<div className="code-header">
|
||||||
|
<span>HTTP Headers</span>
|
||||||
|
<Button
|
||||||
|
type="text"
|
||||||
|
icon={<CopyOutlined />}
|
||||||
|
onClick={() =>
|
||||||
|
copyToClipboard('Authorization: Bearer sk_your_api_key_here')
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<pre>{`Authorization: Bearer sk_your_api_key_here`}</pre>
|
||||||
|
</div>
|
||||||
|
<p style={{ marginTop: '10px', fontSize: '14px', color: '#666' }}>
|
||||||
|
* 您可以在 "API 密钥管理" 页面创建和获取您的 API Key。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="doc-section" style={{ marginTop: '30px' }}>
|
||||||
|
<h2>DeepSeek API 调用示例</h2>
|
||||||
|
<p>我们完全兼容 OpenAI 格式的接口调用,只需将 Base URL 替换为我们的接口地址,并使用我们的 API Key 即可。</p>
|
||||||
|
|
||||||
|
<div style={{ marginBottom: '20px', marginTop: '20px' }}>
|
||||||
|
<Space>
|
||||||
|
{Object.keys(examples).map((lang) => (
|
||||||
|
<Button
|
||||||
|
key={lang}
|
||||||
|
type={selectedExample === lang ? 'primary' : 'default'}
|
||||||
|
onClick={() => setSelectedExample(lang)}
|
||||||
|
>
|
||||||
|
{lang === 'curl'
|
||||||
|
? 'cURL'
|
||||||
|
: lang === 'python'
|
||||||
|
? 'Python'
|
||||||
|
: 'Node.js'}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</Space>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="code-block">
|
||||||
|
<div className="code-header">
|
||||||
|
<span>
|
||||||
|
{selectedExample === 'curl'
|
||||||
|
? 'cURL'
|
||||||
|
: selectedExample === 'python'
|
||||||
|
? 'Python'
|
||||||
|
: 'Node.js'}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
type="text"
|
||||||
|
icon={<CopyOutlined />}
|
||||||
|
onClick={() =>
|
||||||
|
copyToClipboard(
|
||||||
|
examples[selectedExample as keyof typeof examples]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<pre>{examples[selectedExample as keyof typeof examples]}</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ApiDocumentation;
|
||||||
14
NBATransfer-frontend/src/pages/ApiKeyManagement.css
Normal file
14
NBATransfer-frontend/src/pages/ApiKeyManagement.css
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
.api-key-copy {
|
||||||
|
cursor: pointer;
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
user-select: all;
|
||||||
|
background: #f5f5f5;
|
||||||
|
padding: 4px 8px;
|
||||||
|
border-radius: 4px;
|
||||||
|
border: 1px solid #d9d9d9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.api-key-copy:hover {
|
||||||
|
background: #e6e6e6;
|
||||||
|
border-color: #b3b3b3;
|
||||||
|
}
|
||||||
347
NBATransfer-frontend/src/pages/ApiKeyManagement.tsx
Normal file
347
NBATransfer-frontend/src/pages/ApiKeyManagement.tsx
Normal file
@@ -0,0 +1,347 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
Button,
|
||||||
|
Table,
|
||||||
|
Modal,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
Space,
|
||||||
|
message,
|
||||||
|
Empty,
|
||||||
|
Spin,
|
||||||
|
Tag,
|
||||||
|
Tooltip,
|
||||||
|
Popconfirm,
|
||||||
|
Alert,
|
||||||
|
} from 'antd';
|
||||||
|
import {
|
||||||
|
PlusOutlined,
|
||||||
|
DeleteOutlined,
|
||||||
|
CopyOutlined,
|
||||||
|
ReloadOutlined,
|
||||||
|
LockOutlined,
|
||||||
|
UnlockOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import { apikeyAPI } from '../api';
|
||||||
|
import type { ApiKey } from '../types';
|
||||||
|
import './ApiKeyManagement.css';
|
||||||
|
|
||||||
|
const ApiKeyManagement: React.FC = () => {
|
||||||
|
const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [createModalVisible, setCreateModalVisible] = useState(false);
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
const [newKeyData, setNewKeyData] = useState<{ api_key: string } | null>(
|
||||||
|
null
|
||||||
|
);
|
||||||
|
const [newKeyModalVisible, setNewKeyModalVisible] = useState(false);
|
||||||
|
|
||||||
|
// 获取 API 密钥列表
|
||||||
|
const fetchApiKeys = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const response = await apikeyAPI.getKeys();
|
||||||
|
setApiKeys(response.data.keys || []);
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.response?.data?.error || '获取 API 密钥列表失败');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchApiKeys();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 创建新密钥
|
||||||
|
const handleCreateKey = async (values: { name: string }) => {
|
||||||
|
try {
|
||||||
|
const response = await apikeyAPI.createKey({ name: values.name });
|
||||||
|
|
||||||
|
// 展示新生成的密钥(只会显示一次)
|
||||||
|
setNewKeyData({
|
||||||
|
api_key: response.data.key.api_key,
|
||||||
|
});
|
||||||
|
setNewKeyModalVisible(true);
|
||||||
|
setCreateModalVisible(false);
|
||||||
|
form.resetFields();
|
||||||
|
|
||||||
|
// 刷新列表
|
||||||
|
await fetchApiKeys();
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.response?.data?.error || '创建 API 密钥失败');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 删除密钥
|
||||||
|
const handleDeleteKey = async (id: number) => {
|
||||||
|
try {
|
||||||
|
await apikeyAPI.deleteKey(id);
|
||||||
|
message.success('API 密钥已删除');
|
||||||
|
await fetchApiKeys();
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.response?.data?.error || '删除 API 密钥失败');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 切换密钥激活状态
|
||||||
|
const handleToggleActive = async (id: number, currentStatus: boolean) => {
|
||||||
|
try {
|
||||||
|
await apikeyAPI.updateKey(id, { is_active: !currentStatus });
|
||||||
|
message.success(!currentStatus ? 'API 密钥已激活' : 'API 密钥已停用');
|
||||||
|
await fetchApiKeys();
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.response?.data?.error || '更新 API 密钥失败');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 轮换 API Key
|
||||||
|
const handleRegenerateKey = async (id: number) => {
|
||||||
|
try {
|
||||||
|
const response = await apikeyAPI.regenerateKey(id);
|
||||||
|
|
||||||
|
// 展示新秘钥
|
||||||
|
setNewKeyData({
|
||||||
|
api_key: response.data.key.api_key,
|
||||||
|
});
|
||||||
|
setNewKeyModalVisible(true);
|
||||||
|
|
||||||
|
// 刷新列表
|
||||||
|
await fetchApiKeys();
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.response?.data?.error || '重置 Key 失败');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 复制到剪贴板
|
||||||
|
const copyToClipboard = (text: string) => {
|
||||||
|
navigator.clipboard.writeText(text);
|
||||||
|
message.success('已复制到剪贴板');
|
||||||
|
};
|
||||||
|
|
||||||
|
const columns = [
|
||||||
|
{
|
||||||
|
title: 'API Key',
|
||||||
|
dataIndex: 'api_key',
|
||||||
|
key: 'api_key',
|
||||||
|
width: 200,
|
||||||
|
render: (text: string) => (
|
||||||
|
<Tooltip title="点击复制">
|
||||||
|
<div
|
||||||
|
onClick={() => copyToClipboard(text)}
|
||||||
|
style={{
|
||||||
|
cursor: 'pointer',
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
wordBreak: 'break-all',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{text}
|
||||||
|
<CopyOutlined style={{ marginLeft: '8px' }} />
|
||||||
|
</div>
|
||||||
|
</Tooltip>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '名称',
|
||||||
|
dataIndex: 'name',
|
||||||
|
key: 'name',
|
||||||
|
width: 150,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'is_active',
|
||||||
|
key: 'is_active',
|
||||||
|
width: 100,
|
||||||
|
render: (isActive: boolean) => (
|
||||||
|
<Tag color={isActive ? 'green' : 'red'}>{isActive ? '激活' : '已停用'}</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '创建时间',
|
||||||
|
dataIndex: 'created_at',
|
||||||
|
key: 'created_at',
|
||||||
|
width: 180,
|
||||||
|
render: (text: string) => new Date(text).toLocaleString('zh-CN'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '最后使用',
|
||||||
|
dataIndex: 'last_used_at',
|
||||||
|
key: 'last_used_at',
|
||||||
|
width: 180,
|
||||||
|
render: (text?: string) =>
|
||||||
|
text ? new Date(text).toLocaleString('zh-CN') : '从未使用过',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
key: 'action',
|
||||||
|
width: 200,
|
||||||
|
render: (_: any, record: ApiKey) => (
|
||||||
|
<Space size="small" wrap>
|
||||||
|
<Button
|
||||||
|
type="text"
|
||||||
|
size="small"
|
||||||
|
icon={record.is_active ? <LockOutlined /> : <UnlockOutlined />}
|
||||||
|
onClick={() => handleToggleActive(record.id, record.is_active)}
|
||||||
|
>
|
||||||
|
{record.is_active ? '停用' : '启用'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="text"
|
||||||
|
size="small"
|
||||||
|
icon={<ReloadOutlined />}
|
||||||
|
onClick={() => handleRegenerateKey(record.id)}
|
||||||
|
>
|
||||||
|
重置 Key
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Popconfirm
|
||||||
|
title="删除 API 密钥"
|
||||||
|
description="确定要删除该 API 密钥吗?删除后无法恢复。"
|
||||||
|
onConfirm={() => handleDeleteKey(record.id)}
|
||||||
|
okText="确定"
|
||||||
|
cancelText="取消"
|
||||||
|
>
|
||||||
|
<Button type="text" danger size="small" icon={<DeleteOutlined />}>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: '24px' }}>
|
||||||
|
<Card>
|
||||||
|
<div style={{ marginBottom: '20px', display: 'flex', justifyContent: 'space-between' }}>
|
||||||
|
<h2>API 密钥管理</h2>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
icon={<PlusOutlined />}
|
||||||
|
onClick={() => setCreateModalVisible(true)}
|
||||||
|
>
|
||||||
|
创建新密钥
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Alert
|
||||||
|
message="重要提示"
|
||||||
|
description="API Key 只在创建和重置时显示一次,请妥善保管。使用 API Key 进行 API 调用时需要进行认证。"
|
||||||
|
type="warning"
|
||||||
|
showIcon
|
||||||
|
style={{ marginBottom: '20px' }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Spin spinning={loading}>
|
||||||
|
{apiKeys.length > 0 ? (
|
||||||
|
<Table
|
||||||
|
columns={columns}
|
||||||
|
dataSource={apiKeys}
|
||||||
|
rowKey="id"
|
||||||
|
pagination={false}
|
||||||
|
scroll={{ x: 1200 }}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Empty description="没有 API 密钥,点击下方按钮创建" />
|
||||||
|
)}
|
||||||
|
</Spin>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 创建密钥对话框 */}
|
||||||
|
<Modal
|
||||||
|
title="创建新 API 密钥"
|
||||||
|
open={createModalVisible}
|
||||||
|
onCancel={() => {
|
||||||
|
setCreateModalVisible(false);
|
||||||
|
form.resetFields();
|
||||||
|
}}
|
||||||
|
footer={[
|
||||||
|
<Button key="cancel" onClick={() => setCreateModalVisible(false)}>
|
||||||
|
取消
|
||||||
|
</Button>,
|
||||||
|
<Button
|
||||||
|
key="submit"
|
||||||
|
type="primary"
|
||||||
|
onClick={() => form.submit()}
|
||||||
|
>
|
||||||
|
创建
|
||||||
|
</Button>,
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Form
|
||||||
|
form={form}
|
||||||
|
layout="vertical"
|
||||||
|
onFinish={handleCreateKey}
|
||||||
|
>
|
||||||
|
<Form.Item
|
||||||
|
name="name"
|
||||||
|
label="密钥名称"
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: '请输入密钥名称' },
|
||||||
|
{ min: 1, max: 50, message: '名称长度在 1-50 个字符之间' },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Input placeholder="例如:我的应用、测试环境等" />
|
||||||
|
</Form.Item>
|
||||||
|
<Alert
|
||||||
|
message="创建后会生成 API Key,请妥善保管"
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
/>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
{/* 显示新生成的密钥 */}
|
||||||
|
<Modal
|
||||||
|
title="✨ 新 API 密钥已生成"
|
||||||
|
open={newKeyModalVisible}
|
||||||
|
onOk={() => setNewKeyModalVisible(false)}
|
||||||
|
onCancel={() => setNewKeyModalVisible(false)}
|
||||||
|
footer={[
|
||||||
|
<Button key="close" type="primary" onClick={() => setNewKeyModalVisible(false)}>
|
||||||
|
我已保存
|
||||||
|
</Button>,
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Alert
|
||||||
|
message="⚠️ 重要:API Key 仅显示一次"
|
||||||
|
description="请立即复制并妥善保管。关闭此对话框后,API Key 将不再显示。如果丢失,需要重新生成。"
|
||||||
|
type="error"
|
||||||
|
showIcon
|
||||||
|
style={{ marginBottom: '20px' }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{newKeyData && (
|
||||||
|
<div>
|
||||||
|
<div style={{ marginBottom: '15px' }}>
|
||||||
|
<label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
|
||||||
|
API Key:
|
||||||
|
</label>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
gap: '8px',
|
||||||
|
alignItems: 'center',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
value={newKeyData.api_key}
|
||||||
|
readOnly
|
||||||
|
style={{ fontFamily: 'monospace', wordBreak: 'break-all' }}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
icon={<CopyOutlined />}
|
||||||
|
onClick={() => copyToClipboard(newKeyData.api_key)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ApiKeyManagement;
|
||||||
51
NBATransfer-frontend/src/pages/Dashboard.css
Normal file
51
NBATransfer-frontend/src/pages/Dashboard.css
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
.dashboard-home h1 {
|
||||||
|
margin-bottom: 24px;
|
||||||
|
font-size: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-container {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
min-height: 400px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quick-start {
|
||||||
|
padding: 16px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quick-start h3 {
|
||||||
|
font-size: 18px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quick-start ol {
|
||||||
|
padding-left: 24px;
|
||||||
|
line-height: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quick-start ol li {
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pricing-info {
|
||||||
|
margin-top: 24px;
|
||||||
|
padding: 16px;
|
||||||
|
background: #f5f5f5;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pricing-info p {
|
||||||
|
margin: 8px 0;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.dashboard-home h1 {
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quick-start h3 {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
}
|
||||||
111
NBATransfer-frontend/src/pages/Dashboard.tsx
Normal file
111
NBATransfer-frontend/src/pages/Dashboard.tsx
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { Row, Col, Card, Statistic, Spin } from 'antd';
|
||||||
|
import { ApiOutlined, CheckCircleOutlined, CloseCircleOutlined, WalletOutlined } from '@ant-design/icons';
|
||||||
|
import { userAPI } from '../api';
|
||||||
|
import type { Stats } from '../types';
|
||||||
|
import './Dashboard.css';
|
||||||
|
|
||||||
|
const Dashboard: React.FC = () => {
|
||||||
|
const [stats, setStats] = useState<Stats | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchStats();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const fetchStats = async () => {
|
||||||
|
try {
|
||||||
|
const response = await userAPI.getStats();
|
||||||
|
setStats(response.data);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch stats:', error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="loading-container">
|
||||||
|
<Spin size="large" tip="加载中..." />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="dashboard-home">
|
||||||
|
<h1>数据概览</h1>
|
||||||
|
<Row gutter={[16, 16]}>
|
||||||
|
<Col xs={24} sm={12} lg={6}>
|
||||||
|
<Card>
|
||||||
|
<Statistic
|
||||||
|
title="总调用次数"
|
||||||
|
value={stats?.total_calls || 0}
|
||||||
|
prefix={<ApiOutlined />}
|
||||||
|
valueStyle={{ color: '#1890ff' }}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
<Col xs={24} sm={12} lg={6}>
|
||||||
|
<Card>
|
||||||
|
<Statistic
|
||||||
|
title="成功调用"
|
||||||
|
value={stats?.success_calls || 0}
|
||||||
|
prefix={<CheckCircleOutlined />}
|
||||||
|
valueStyle={{ color: '#52c41a' }}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
<Col xs={24} sm={12} lg={6}>
|
||||||
|
<Card>
|
||||||
|
<Statistic
|
||||||
|
title="失败调用"
|
||||||
|
value={stats?.failed_calls || 0}
|
||||||
|
prefix={<CloseCircleOutlined />}
|
||||||
|
valueStyle={{ color: '#ff4d4f' }}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
<Col xs={24} sm={12} lg={6}>
|
||||||
|
<Card>
|
||||||
|
<Statistic
|
||||||
|
title="总消费"
|
||||||
|
value={stats?.total_cost || 0}
|
||||||
|
prefix={<WalletOutlined />}
|
||||||
|
precision={2}
|
||||||
|
valueStyle={{ color: '#fa8c16' }}
|
||||||
|
suffix="元"
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
</Row>
|
||||||
|
|
||||||
|
<Row gutter={[16, 16]} style={{ marginTop: '24px' }}>
|
||||||
|
<Col span={24}>
|
||||||
|
<Card title="快速开始">
|
||||||
|
<div className="quick-start">
|
||||||
|
<h3>🎨 如何使用大语言模型API中转站</h3>
|
||||||
|
<ol>
|
||||||
|
<li>
|
||||||
|
<strong>充值账户</strong>: 前往"我的钱包"充值余额
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>调用API</strong>: 进入"API调用"页面生成图片
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>查看记录</strong>: 在"历史记录"查看所有调用记录
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
<div className="pricing-info">
|
||||||
|
<p><strong>⚡ 速度</strong>: 平均生成时间 10-30 秒</p>
|
||||||
|
<p><strong>🎯 质量</strong>: 专业级AI图像生成</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
</Row>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Dashboard;
|
||||||
42
NBATransfer-frontend/src/pages/Login.css
Normal file
42
NBATransfer-frontend/src/pages/Login.css
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
.login-container {
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: #f0f2f5;
|
||||||
|
background-image: url("data:image/svg+xml,%3Csvg width='64' height='64' viewBox='0 0 64 64' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M8 16c4.418 0 8-3.582 8-8s-3.582-8-8-8-8 3.582-8 8 3.582 8 8 8zm0-2c3.314 0 6-2.686 6-6s-2.686-6-6-6-6 2.686-6 6 2.686 6 6 6zm33.414-6l5.95-5.95L45.95.636 40 6.586 34.05.636 32.636 2.05 38.586 8l-5.95 5.95 1.414 1.414L40 9.414l5.95 5.95 1.414-1.414L41.414 8zM40 48c4.418 0 8-3.582 8-8s-3.582-8-8-8-8 3.582-8 8 3.582 8 8 8zm0-2c3.314 0 6-2.686 6-6s-2.686-6-6-6-6 2.686-6 6 2.686 6 6 6zM9.414 40l5.95-5.95-1.414-1.414L8 38.586l-5.95-5.95L.636 34.05 6.586 40l-5.95 5.95 1.414 1.414L8 41.414l5.95 5.95 1.414-1.414L9.414 40z' fill='%239C92AC' fill-opacity='0.05' fill-rule='evenodd'/%3E%3C/svg%3E");
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-card {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 450px;
|
||||||
|
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
|
||||||
|
border-radius: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-header {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-header h1 {
|
||||||
|
font-size: 28px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-header p {
|
||||||
|
color: #666;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 576px) {
|
||||||
|
.login-card {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-header h1 {
|
||||||
|
font-size: 24px;
|
||||||
|
}
|
||||||
|
}
|
||||||
253
NBATransfer-frontend/src/pages/Login.tsx
Normal file
253
NBATransfer-frontend/src/pages/Login.tsx
Normal file
@@ -0,0 +1,253 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Form, Input, Button, Card, message, Tabs, Space, Alert } from 'antd';
|
||||||
|
import { LockOutlined, MailOutlined } from '@ant-design/icons';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { authAPI } from '../api';
|
||||||
|
import { useAuthStore } from '../store/auth';
|
||||||
|
import './Login.css';
|
||||||
|
|
||||||
|
const Login: React.FC = () => {
|
||||||
|
const [loginLoading, setLoginLoading] = useState(false);
|
||||||
|
const [registerLoading, setRegisterLoading] = useState(false);
|
||||||
|
const [codeSent, setCodeSent] = useState(false);
|
||||||
|
const [codeLoading, setCodeLoading] = useState(false);
|
||||||
|
const [email, setEmail] = useState('');
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const setAuth = useAuthStore((state) => state.setAuth);
|
||||||
|
|
||||||
|
const onLogin = async (values: { email: string; password: string }) => {
|
||||||
|
setLoginLoading(true);
|
||||||
|
try {
|
||||||
|
const response = await authAPI.login(values);
|
||||||
|
const data = response.data;
|
||||||
|
|
||||||
|
setAuth({
|
||||||
|
user: data.user,
|
||||||
|
access_token: data.access_token,
|
||||||
|
refresh_token: data.refresh_token,
|
||||||
|
});
|
||||||
|
|
||||||
|
message.success('登录成功!');
|
||||||
|
navigate(data.user.is_admin ? '/admin' : '/dashboard');
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.response?.data?.error || '登录失败,请检查邮箱和密码');
|
||||||
|
} finally {
|
||||||
|
setLoginLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const sendVerificationCode = async () => {
|
||||||
|
if (!email) {
|
||||||
|
message.error('请先输入邮箱地址');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 简单的邮箱验证
|
||||||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
if (!emailRegex.test(email)) {
|
||||||
|
message.error('请输入有效的邮箱地址');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setCodeLoading(true);
|
||||||
|
try {
|
||||||
|
await authAPI.sendVerificationCode({ email });
|
||||||
|
setCodeSent(true);
|
||||||
|
message.success('验证码已发送到您的邮箱,请检查收件箱(5分钟内有效)');
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.response?.data?.error || '发送验证码失败');
|
||||||
|
} finally {
|
||||||
|
setCodeLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onRegister = async (values: any) => {
|
||||||
|
setRegisterLoading(true);
|
||||||
|
try {
|
||||||
|
const response = await authAPI.register({
|
||||||
|
email: values.email,
|
||||||
|
password: values.password,
|
||||||
|
verification_code: values.code,
|
||||||
|
});
|
||||||
|
const data = response.data;
|
||||||
|
|
||||||
|
setAuth({
|
||||||
|
user: data.user,
|
||||||
|
access_token: data.access_token,
|
||||||
|
refresh_token: data.refresh_token,
|
||||||
|
});
|
||||||
|
|
||||||
|
message.success('注册成功!');
|
||||||
|
navigate('/dashboard');
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.response?.data?.error || '注册失败');
|
||||||
|
} finally {
|
||||||
|
setRegisterLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loginForm = (
|
||||||
|
<Form
|
||||||
|
name="login"
|
||||||
|
onFinish={onLogin}
|
||||||
|
autoComplete="off"
|
||||||
|
size="large"
|
||||||
|
>
|
||||||
|
<Form.Item
|
||||||
|
name="email"
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: '请输入邮箱' },
|
||||||
|
{ type: 'email', message: '请输入有效的邮箱地址' },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Input prefix={<MailOutlined />} placeholder="邮箱" />
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
name="password"
|
||||||
|
rules={[{ required: true, message: '请输入密码' }]}
|
||||||
|
>
|
||||||
|
<Input.Password prefix={<LockOutlined />} placeholder="密码" />
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item>
|
||||||
|
<Button type="primary" htmlType="submit" loading={loginLoading} block>
|
||||||
|
登录
|
||||||
|
</Button>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
);
|
||||||
|
|
||||||
|
const registerForm = (
|
||||||
|
<Form
|
||||||
|
form={form}
|
||||||
|
name="register"
|
||||||
|
onFinish={onRegister}
|
||||||
|
autoComplete="off"
|
||||||
|
size="large"
|
||||||
|
>
|
||||||
|
<Alert
|
||||||
|
message="邮箱验证注册"
|
||||||
|
description="注册需要邮箱验证,我们会发送6位验证码到您的邮箱"
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
style={{ marginBottom: '20px' }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
name="email"
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: '请输入邮箱' },
|
||||||
|
{ type: 'email', message: '请输入有效的邮箱地址' },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
prefix={<MailOutlined />}
|
||||||
|
placeholder="邮箱(QQ邮箱推荐)"
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
disabled={codeSent}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item>
|
||||||
|
<Button
|
||||||
|
type="dashed"
|
||||||
|
onClick={sendVerificationCode}
|
||||||
|
loading={codeLoading}
|
||||||
|
block
|
||||||
|
disabled={codeSent}
|
||||||
|
>
|
||||||
|
{codeSent ? '✓ 验证码已发送' : '发送验证码'}
|
||||||
|
</Button>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
{codeSent && (
|
||||||
|
<>
|
||||||
|
<Form.Item
|
||||||
|
name="code"
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: '请输入验证码' },
|
||||||
|
{ len: 6, message: '验证码为6位数字' },
|
||||||
|
{ pattern: /^\d{6}$/, message: '验证码只能是6位数字' },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Input placeholder="6位验证码" maxLength={6} />
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
name="password"
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: '请输入密码' },
|
||||||
|
{ min: 6, message: '密码至少6位' },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Input.Password prefix={<LockOutlined />} placeholder="密码(至少6位)" />
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
name="confirm"
|
||||||
|
dependencies={['password']}
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: '请确认密码' },
|
||||||
|
({ getFieldValue }) => ({
|
||||||
|
validator(_, value) {
|
||||||
|
if (!value || getFieldValue('password') === value) {
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
return Promise.reject(new Error('两次密码不一致'));
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Input.Password prefix={<LockOutlined />} placeholder="确认密码" />
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item>
|
||||||
|
<Space style={{ width: '100%' }}>
|
||||||
|
<Button type="primary" htmlType="submit" loading={registerLoading} block>
|
||||||
|
注册
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setCodeSent(false);
|
||||||
|
form.resetFields();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
重新输入邮箱
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
</Form.Item>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Form>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="login-container">
|
||||||
|
<Card className="login-card">
|
||||||
|
<div className="login-header">
|
||||||
|
<h1>🍌 大语言模型API中转站</h1>
|
||||||
|
<p>专业的AI大模型API中转服务平台</p>
|
||||||
|
</div>
|
||||||
|
<Tabs
|
||||||
|
defaultActiveKey="login"
|
||||||
|
items={[
|
||||||
|
{
|
||||||
|
key: 'login',
|
||||||
|
label: '登录',
|
||||||
|
children: loginForm,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'register',
|
||||||
|
label: '注册',
|
||||||
|
children: registerForm,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Login;
|
||||||
8
NBATransfer-frontend/src/pages/Settings.css
Normal file
8
NBATransfer-frontend/src/pages/Settings.css
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
.settings-page {
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-card {
|
||||||
|
max-width: 600px;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
86
NBATransfer-frontend/src/pages/Settings.tsx
Normal file
86
NBATransfer-frontend/src/pages/Settings.tsx
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Card, Form, Input, Button, message, Divider } from 'antd';
|
||||||
|
import { LockOutlined } from '@ant-design/icons';
|
||||||
|
import { authAPI } from '../api';
|
||||||
|
import './Settings.css';
|
||||||
|
|
||||||
|
const Settings: React.FC = () => {
|
||||||
|
const [passwordLoading, setPasswordLoading] = useState(false);
|
||||||
|
const [passwordForm] = Form.useForm();
|
||||||
|
|
||||||
|
const onChangePassword = async (values: any) => {
|
||||||
|
setPasswordLoading(true);
|
||||||
|
try {
|
||||||
|
await authAPI.changePassword({
|
||||||
|
old_password: values.old_password,
|
||||||
|
new_password: values.new_password,
|
||||||
|
});
|
||||||
|
message.success('密码修改成功');
|
||||||
|
passwordForm.resetFields();
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.response?.data?.error || '密码修改失败');
|
||||||
|
} finally {
|
||||||
|
setPasswordLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="settings-page">
|
||||||
|
<h1>账户设置</h1>
|
||||||
|
|
||||||
|
<Card title="修改密码" className="settings-card">
|
||||||
|
<Form
|
||||||
|
form={passwordForm}
|
||||||
|
layout="vertical"
|
||||||
|
onFinish={onChangePassword}
|
||||||
|
>
|
||||||
|
<Form.Item
|
||||||
|
name="old_password"
|
||||||
|
label="当前密码"
|
||||||
|
rules={[{ required: true, message: '请输入当前密码' }]}
|
||||||
|
>
|
||||||
|
<Input.Password prefix={<LockOutlined />} placeholder="当前密码" />
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
name="new_password"
|
||||||
|
label="新密码"
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: '请输入新密码' },
|
||||||
|
{ min: 6, message: '密码长度至少为6位' },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Input.Password prefix={<LockOutlined />} placeholder="新密码" />
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
name="confirm_password"
|
||||||
|
label="确认新密码"
|
||||||
|
dependencies={['new_password']}
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: '请确认新密码' },
|
||||||
|
({ getFieldValue }) => ({
|
||||||
|
validator(_, value) {
|
||||||
|
if (!value || getFieldValue('new_password') === value) {
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
return Promise.reject(new Error('两次密码不一致'));
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Input.Password prefix={<LockOutlined />} placeholder="确认新密码" />
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item>
|
||||||
|
<Button type="primary" htmlType="submit" loading={passwordLoading}>
|
||||||
|
修改密码
|
||||||
|
</Button>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Settings;
|
||||||
215
NBATransfer-frontend/src/pages/Wallet.css
Normal file
215
NBATransfer-frontend/src/pages/Wallet.css
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
.wallet-page h1 {
|
||||||
|
margin-bottom: 24px;
|
||||||
|
font-size: 28px;
|
||||||
|
color: #1890ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 余额卡片 */
|
||||||
|
.balance-card {
|
||||||
|
background: linear-gradient(135deg, #1890ff 0%, #0050b3 100%);
|
||||||
|
border: none;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-display,
|
||||||
|
.api-calls-display {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 20px;
|
||||||
|
color: white;
|
||||||
|
padding: 16px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-icon,
|
||||||
|
.calls-icon {
|
||||||
|
font-size: 48px;
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-content,
|
||||||
|
.calls-content {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-label,
|
||||||
|
.calls-label {
|
||||||
|
font-size: 14px;
|
||||||
|
opacity: 0.9;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-amount {
|
||||||
|
font-size: 40px;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.calls-count {
|
||||||
|
font-size: 32px;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 充值套餐卡片 */
|
||||||
|
.package-card {
|
||||||
|
text-align: center;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
border: 2px solid transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-card:hover {
|
||||||
|
border-color: #1890ff;
|
||||||
|
box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-content {
|
||||||
|
padding: 16px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-price {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #ff7a45;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-count {
|
||||||
|
font-size: 16px;
|
||||||
|
color: #333;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-unit {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #999;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 充值提示 */
|
||||||
|
.recharge-tips {
|
||||||
|
margin-top: 24px;
|
||||||
|
padding: 20px;
|
||||||
|
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
|
||||||
|
border-radius: 8px;
|
||||||
|
border-left: 4px solid #1890ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recharge-tips h4 {
|
||||||
|
margin-bottom: 12px;
|
||||||
|
font-size: 16px;
|
||||||
|
color: #333;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recharge-tips ul {
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 24px;
|
||||||
|
line-height: 1.8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recharge-tips li {
|
||||||
|
color: #555;
|
||||||
|
margin: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 支付模态框 */
|
||||||
|
.payment-modal {
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-info {
|
||||||
|
margin-bottom: 24px;
|
||||||
|
padding: 16px;
|
||||||
|
background: #fafafa;
|
||||||
|
border-radius: 8px;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-info p {
|
||||||
|
margin: 8px 0;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.qrcode-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
padding: 24px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.qrcode-container p {
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 响应式 */
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.wallet-page h1 {
|
||||||
|
font-size: 24px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-icon,
|
||||||
|
.calls-icon {
|
||||||
|
font-size: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-amount {
|
||||||
|
font-size: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.calls-count {
|
||||||
|
font-size: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-card {
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-price {
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-count {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recharge-tips {
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recharge-tips h4 {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recharge-tips ul {
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.wallet-page h1 {
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-display,
|
||||||
|
.api-calls-display {
|
||||||
|
gap: 12px;
|
||||||
|
padding: 12px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-icon,
|
||||||
|
.calls-icon {
|
||||||
|
font-size: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-amount {
|
||||||
|
font-size: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.calls-count {
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-label,
|
||||||
|
.calls-label {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
}
|
||||||
257
NBATransfer-frontend/src/pages/Wallet.tsx
Normal file
257
NBATransfer-frontend/src/pages/Wallet.tsx
Normal file
@@ -0,0 +1,257 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import {
|
||||||
|
Card, Button, Form, InputNumber, Radio, message, Modal, QRCode, Statistic,
|
||||||
|
Row, Col, Divider, Spin
|
||||||
|
} from 'antd';
|
||||||
|
import { WalletOutlined, AlipayOutlined, WechatOutlined } from '@ant-design/icons';
|
||||||
|
import { orderAPI, userAPI } from '../api';
|
||||||
|
import { useAuthStore } from '../store/auth';
|
||||||
|
import './Wallet.css';
|
||||||
|
|
||||||
|
const Wallet: React.FC = () => {
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [modalVisible, setModalVisible] = useState(false);
|
||||||
|
const [paymentMethod, setPaymentMethod] = useState('alipay');
|
||||||
|
const [orderInfo, setOrderInfo] = useState<any>(null);
|
||||||
|
const user = useAuthStore((state) => state.user);
|
||||||
|
const updateUser = useAuthStore((state) => state.updateUser);
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
|
||||||
|
const onRecharge = async (values: { amount: number }) => {
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const response = await orderAPI.createOrder({
|
||||||
|
amount: values.amount,
|
||||||
|
payment_method: paymentMethod,
|
||||||
|
});
|
||||||
|
|
||||||
|
setOrderInfo(response.data);
|
||||||
|
setModalVisible(true);
|
||||||
|
message.success('订单创建成功,请扫码支付');
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error.response?.data?.error || '订单创建失败');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePaymentComplete = async () => {
|
||||||
|
if (!orderInfo || !user) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 模拟支付通知(实际生产环境由支付平台回调)
|
||||||
|
await orderAPI.notifyPayment(orderInfo.order.order_no);
|
||||||
|
|
||||||
|
// 刷新用户余额
|
||||||
|
const balanceResponse = await userAPI.getBalance();
|
||||||
|
|
||||||
|
updateUser({
|
||||||
|
...user,
|
||||||
|
balance: balanceResponse.data.balance
|
||||||
|
});
|
||||||
|
|
||||||
|
message.success('充值成功!');
|
||||||
|
setModalVisible(false);
|
||||||
|
setOrderInfo(null);
|
||||||
|
form.resetFields();
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error('支付确认失败');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 充值套餐选项
|
||||||
|
const rechargePackages = [
|
||||||
|
{ amount: 10 },
|
||||||
|
{ amount: 50 },
|
||||||
|
{ amount: 100 },
|
||||||
|
{ amount: 500 },
|
||||||
|
];
|
||||||
|
|
||||||
|
const getPaymentMethodName = (method: string) => {
|
||||||
|
return method === 'alipay' ? '支付宝' : '微信支付';
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="wallet-page">
|
||||||
|
<h1>💰 我的钱包</h1>
|
||||||
|
|
||||||
|
{/* 余额显示卡片 */}
|
||||||
|
<Card className="balance-card">
|
||||||
|
<Row gutter={[24, 24]}>
|
||||||
|
<Col xs={24} sm={12}>
|
||||||
|
<div className="balance-display">
|
||||||
|
<WalletOutlined className="balance-icon" />
|
||||||
|
<div className="balance-content">
|
||||||
|
<div className="balance-label">账户余额</div>
|
||||||
|
<div className="balance-amount">¥{user?.balance?.toFixed(2) || '0.00'}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Col>
|
||||||
|
</Row>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Divider />
|
||||||
|
|
||||||
|
{/* 快速充值套餐 */}
|
||||||
|
<Card title="💡 快速充值套餐" style={{ marginBottom: 24 }}>
|
||||||
|
<Row gutter={[16, 16]}>
|
||||||
|
{rechargePackages.map((pkg) => (
|
||||||
|
<Col xs={24} sm={12} md={6} key={pkg.amount}>
|
||||||
|
<Card
|
||||||
|
hoverable
|
||||||
|
className="package-card"
|
||||||
|
onClick={() => {
|
||||||
|
form.setFieldsValue({ amount: pkg.amount });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="package-content">
|
||||||
|
<div className="package-price">¥{pkg.amount}</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
))}
|
||||||
|
</Row>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 自定义充值 */}
|
||||||
|
<Card title="自定义充值金额" style={{ marginBottom: 24 }}>
|
||||||
|
<Form
|
||||||
|
form={form}
|
||||||
|
onFinish={onRecharge}
|
||||||
|
layout="vertical"
|
||||||
|
>
|
||||||
|
<Form.Item
|
||||||
|
label="充值金额"
|
||||||
|
name="amount"
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: '请输入充值金额' },
|
||||||
|
{ type: 'number', min: 1, max: 100000, message: '充值金额需在 ¥1 - ¥100000 之间' },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<InputNumber
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
min={1}
|
||||||
|
max={100000}
|
||||||
|
precision={2}
|
||||||
|
prefix="¥"
|
||||||
|
placeholder="请输入充值金额"
|
||||||
|
size="large"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item label="支付方式">
|
||||||
|
<Radio.Group
|
||||||
|
value={paymentMethod}
|
||||||
|
onChange={(e) => setPaymentMethod(e.target.value)}
|
||||||
|
size="large"
|
||||||
|
>
|
||||||
|
<Radio.Button value="alipay">
|
||||||
|
<AlipayOutlined /> 支付宝
|
||||||
|
</Radio.Button>
|
||||||
|
<Radio.Button value="wechat">
|
||||||
|
<WechatOutlined /> 微信支付
|
||||||
|
</Radio.Button>
|
||||||
|
</Radio.Group>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
htmlType="submit"
|
||||||
|
size="large"
|
||||||
|
block
|
||||||
|
loading={loading}
|
||||||
|
disabled={!user || (user.balance >= 100000)}
|
||||||
|
>
|
||||||
|
{loading ? '创建订单中...' : '立即充值'}
|
||||||
|
</Button>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
|
||||||
|
<Divider />
|
||||||
|
|
||||||
|
<div className="recharge-tips">
|
||||||
|
<h4>充值说明</h4>
|
||||||
|
<ul>
|
||||||
|
<li>✓ 充值后立即到账,无需等待</li>
|
||||||
|
<li>✓ 余额可用于所有 API 调用</li>
|
||||||
|
<li>✓ 最低充值金额: ¥1.00</li>
|
||||||
|
<li>✓ 最高余额限制: ¥100,000</li>
|
||||||
|
<li>✓ 余额永不过期</li>
|
||||||
|
<li>✓ 如有问题请联系在线客服</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 支付模态框 */}
|
||||||
|
<Modal
|
||||||
|
title="扫码支付"
|
||||||
|
open={modalVisible}
|
||||||
|
onCancel={() => setModalVisible(false)}
|
||||||
|
width={450}
|
||||||
|
footer={[
|
||||||
|
<Button key="cancel" onClick={() => setModalVisible(false)}>
|
||||||
|
取消
|
||||||
|
</Button>,
|
||||||
|
<Button key="confirm" type="primary" onClick={handlePaymentComplete}>
|
||||||
|
我已完成支付
|
||||||
|
</Button>,
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{orderInfo ? (
|
||||||
|
<div className="payment-modal">
|
||||||
|
<div className="payment-info">
|
||||||
|
<Row gutter={16} style={{ marginBottom: 24 }}>
|
||||||
|
<Col span={24}>
|
||||||
|
<Statistic
|
||||||
|
title="订单号"
|
||||||
|
value={orderInfo.order.order_no}
|
||||||
|
valueStyle={{ fontSize: '14px', fontFamily: 'monospace' }}
|
||||||
|
/>
|
||||||
|
</Col>
|
||||||
|
</Row>
|
||||||
|
<Row gutter={16} style={{ marginBottom: 24 }}>
|
||||||
|
<Col xs={12}>
|
||||||
|
<Statistic
|
||||||
|
title="充值金额"
|
||||||
|
value={orderInfo.order.amount}
|
||||||
|
prefix="¥"
|
||||||
|
/>
|
||||||
|
</Col>
|
||||||
|
<Col xs={12}>
|
||||||
|
<Statistic
|
||||||
|
title="支付方式"
|
||||||
|
value={getPaymentMethodName(orderInfo.order.payment_method)}
|
||||||
|
/>
|
||||||
|
</Col>
|
||||||
|
</Row>
|
||||||
|
</div>
|
||||||
|
<Divider />
|
||||||
|
<div className="qrcode-container">
|
||||||
|
<p style={{ textAlign: 'center', marginBottom: 16, color: '#666' }}>
|
||||||
|
请使用 {getPaymentMethodName(orderInfo.order.payment_method)} 扫描下方二维码支付
|
||||||
|
</p>
|
||||||
|
<div style={{ textAlign: 'center' }}>
|
||||||
|
<QRCode
|
||||||
|
value={orderInfo.payment?.payment_url || `payment:${orderInfo.order.order_no}`}
|
||||||
|
size={240}
|
||||||
|
level="H"
|
||||||
|
includeMargin={true}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p style={{ marginTop: 16, textAlign: 'center', fontSize: '12px', color: '#999' }}>
|
||||||
|
支付完成后,点击"我已完成支付"按钮
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<Spin />
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Wallet;
|
||||||
60
NBATransfer-frontend/src/store/auth.ts
Normal file
60
NBATransfer-frontend/src/store/auth.ts
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import { create } from 'zustand';
|
||||||
|
import { persist } from 'zustand/middleware';
|
||||||
|
|
||||||
|
export interface User {
|
||||||
|
id: number;
|
||||||
|
email: string;
|
||||||
|
username: string;
|
||||||
|
balance: number;
|
||||||
|
is_active: boolean;
|
||||||
|
is_admin: boolean;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuthState {
|
||||||
|
user: User | null;
|
||||||
|
accessToken: string | null;
|
||||||
|
refreshToken: string | null;
|
||||||
|
isAuthenticated: boolean;
|
||||||
|
setAuth: (data: { user: User; access_token: string; refresh_token: string }) => void;
|
||||||
|
updateUser: (user: User) => void;
|
||||||
|
logout: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useAuthStore = create<AuthState>()(
|
||||||
|
persist(
|
||||||
|
(set) => ({
|
||||||
|
user: null,
|
||||||
|
accessToken: null,
|
||||||
|
refreshToken: null,
|
||||||
|
isAuthenticated: false,
|
||||||
|
setAuth: (data) => {
|
||||||
|
localStorage.setItem('access_token', data.access_token);
|
||||||
|
localStorage.setItem('refresh_token', data.refresh_token);
|
||||||
|
set({
|
||||||
|
user: data.user,
|
||||||
|
accessToken: data.access_token,
|
||||||
|
refreshToken: data.refresh_token,
|
||||||
|
isAuthenticated: true,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
updateUser: (user) => {
|
||||||
|
set({ user });
|
||||||
|
},
|
||||||
|
logout: () => {
|
||||||
|
localStorage.removeItem('access_token');
|
||||||
|
localStorage.removeItem('refresh_token');
|
||||||
|
set({
|
||||||
|
user: null,
|
||||||
|
accessToken: null,
|
||||||
|
refreshToken: null,
|
||||||
|
isAuthenticated: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
name: 'auth-storage',
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
54
NBATransfer-frontend/src/types/index.ts
Normal file
54
NBATransfer-frontend/src/types/index.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
export interface User {
|
||||||
|
id: number;
|
||||||
|
email: string;
|
||||||
|
username: string;
|
||||||
|
balance: number;
|
||||||
|
is_active: boolean;
|
||||||
|
is_admin: boolean;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiKey {
|
||||||
|
id: number;
|
||||||
|
user_id: number;
|
||||||
|
api_key: string;
|
||||||
|
name: string;
|
||||||
|
is_active: boolean;
|
||||||
|
last_used_at?: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Order {
|
||||||
|
id: number;
|
||||||
|
order_no: string;
|
||||||
|
amount: number;
|
||||||
|
status: 'pending' | 'paid' | 'cancelled';
|
||||||
|
payment_method: 'alipay' | 'wechat';
|
||||||
|
created_at: string;
|
||||||
|
paid_at?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiCall {
|
||||||
|
id: number;
|
||||||
|
user_id: number;
|
||||||
|
model: string;
|
||||||
|
cost: number;
|
||||||
|
status: 'success' | 'failed' | 'processing';
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Stats {
|
||||||
|
total_calls: number;
|
||||||
|
success_calls: number;
|
||||||
|
failed_calls: number;
|
||||||
|
total_cost: number;
|
||||||
|
total_recharge: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PaginatedResponse<T> {
|
||||||
|
data: T[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
per_page: number;
|
||||||
|
pages: number;
|
||||||
|
}
|
||||||
28
NBATransfer-frontend/tsconfig.app.json
Normal file
28
NBATransfer-frontend/tsconfig.app.json
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
|
"target": "ES2022",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"types": ["vite/client"],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
7
NBATransfer-frontend/tsconfig.json
Normal file
7
NBATransfer-frontend/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{ "path": "./tsconfig.app.json" },
|
||||||
|
{ "path": "./tsconfig.node.json" }
|
||||||
|
]
|
||||||
|
}
|
||||||
26
NBATransfer-frontend/tsconfig.node.json
Normal file
26
NBATransfer-frontend/tsconfig.node.json
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||||
|
"target": "ES2023",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"types": ["node"],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
||||||
7
NBATransfer-frontend/vite.config.ts
Normal file
7
NBATransfer-frontend/vite.config.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
// https://vite.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
})
|
||||||
17
NBATransfer-frontend/前端文档.md
Normal file
17
NBATransfer-frontend/前端文档.md
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
# Nano Banana API Frontend
|
||||||
|
|
||||||
|
## Project Setup
|
||||||
|
|
||||||
|
1. Install dependencies:
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Start development server:
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Check `.env` for API URL configuration.
|
||||||
20
NBATransfer-frontend/启动前端.bat
Normal file
20
NBATransfer-frontend/启动前端.bat
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
@echo off
|
||||||
|
chcp 65001 >nul
|
||||||
|
title Nano Banana API - 启动前端服务
|
||||||
|
|
||||||
|
cd /d "%~dp0NBATransfer-frontend"
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo ============================================
|
||||||
|
echo 🍌 Nano Banana API - 前端服务
|
||||||
|
echo ============================================
|
||||||
|
echo.
|
||||||
|
echo 启动前端开发服务器...
|
||||||
|
echo.
|
||||||
|
echo 📍 访问地址:http://localhost:5173
|
||||||
|
echo.
|
||||||
|
echo 按 Ctrl+C 停止服务
|
||||||
|
echo.
|
||||||
|
|
||||||
|
call npm run dev
|
||||||
|
pause
|
||||||
312
README.md
Normal file
312
README.md
Normal file
@@ -0,0 +1,312 @@
|
|||||||
|
# Nano Banana API 中转平台
|
||||||
|
|
||||||
|
一个完整的大模型 API 中转购买平台,支持用户注册、充值、API 调用等功能。
|
||||||
|
|
||||||
|
## 项目简介
|
||||||
|
|
||||||
|
本项目是一个前后端分离的 API 中转服务平台,用户可以通过注册账户、充值余额来使用 Nano Banana 文生图 API 服务。
|
||||||
|
|
||||||
|
### 主要功能
|
||||||
|
|
||||||
|
- 📧 邮箱注册登录系统(支持邮箱验证)
|
||||||
|
- 💰 用户余额管理和充值系统
|
||||||
|
- 💳 支付接口(支持支付宝/微信支付)
|
||||||
|
- 🎨 Nano Banana 文生图 API 中转
|
||||||
|
- 🔑 API 密钥管理
|
||||||
|
- 📊 用户统计和订单管理
|
||||||
|
- 👨💼 管理员后台
|
||||||
|
- 📱 响应式设计(支持手机端和电脑端)
|
||||||
|
|
||||||
|
## 技术栈
|
||||||
|
|
||||||
|
### 后端 (NBATransfer-backend)
|
||||||
|
- **框架**: Flask 3.0
|
||||||
|
- **数据库**: SQLite
|
||||||
|
- **ORM**: Flask-SQLAlchemy
|
||||||
|
- **认证**: Flask-JWT-Extended
|
||||||
|
- **跨域**: Flask-CORS
|
||||||
|
- **邮件**: Flask-Mail
|
||||||
|
|
||||||
|
### 前端 (NBATransfer-frontend)
|
||||||
|
- **框架**: React 19 + TypeScript
|
||||||
|
- **构建工具**: Vite
|
||||||
|
- **UI 组件库**: Ant Design
|
||||||
|
- **状态管理**: Zustand
|
||||||
|
- **路由**: React Router
|
||||||
|
- **HTTP 客户端**: Axios
|
||||||
|
- **图表**: Recharts
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
.
|
||||||
|
├── NBATransfer-backend/ # 后端项目
|
||||||
|
│ ├── app.py # Flask 应用入口
|
||||||
|
│ ├── config.py # 配置文件
|
||||||
|
│ ├── models.py # 数据库模型
|
||||||
|
│ ├── routes/ # 路由模块
|
||||||
|
│ │ ├── auth.py # 认证相关
|
||||||
|
│ │ ├── user.py # 用户相关
|
||||||
|
│ │ ├── order.py # 订单相关
|
||||||
|
│ │ ├── api_service.py # API 服务
|
||||||
|
│ │ ├── admin.py # 管理员
|
||||||
|
│ │ ├── apikey.py # API 密钥
|
||||||
|
│ │ └── v1_api.py # V1 API 接口
|
||||||
|
│ ├── services/ # 业务逻辑层
|
||||||
|
│ ├── modelapiservice/ # 模型 API 服务
|
||||||
|
│ │ ├── DeepSeek/ # DeepSeek 服务
|
||||||
|
│ │ └── NanoBanana/ # NanoBanana 服务
|
||||||
|
│ └── requirements.txt # Python 依赖
|
||||||
|
│
|
||||||
|
├── NBATransfer-frontend/ # 前端项目
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── api/ # API 接口定义
|
||||||
|
│ │ ├── components/ # 公共组件
|
||||||
|
│ │ ├── pages/ # 页面组件
|
||||||
|
│ │ ├── store/ # 状态管理
|
||||||
|
│ │ ├── types/ # TypeScript 类型
|
||||||
|
│ │ └── utils/ # 工具函数
|
||||||
|
│ └── package.json # Node.js 依赖
|
||||||
|
│
|
||||||
|
└── README.md # 项目说明文档
|
||||||
|
```
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 环境要求
|
||||||
|
|
||||||
|
- Python 3.9+
|
||||||
|
- Node.js 18+
|
||||||
|
- npm 或 yarn
|
||||||
|
|
||||||
|
### 后端启动
|
||||||
|
|
||||||
|
1. 进入后端目录:
|
||||||
|
```bash
|
||||||
|
cd NBATransfer-backend
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 安装依赖:
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
3. 配置环境变量(可选):
|
||||||
|
创建 `.env` 文件并配置以下变量:
|
||||||
|
```env
|
||||||
|
SECRET_KEY=your-secret-key
|
||||||
|
JWT_SECRET_KEY=your-jwt-secret-key
|
||||||
|
DATABASE_URI=sqlite:///nba_transfer.db
|
||||||
|
MAIL_SERVER=smtp.qq.com
|
||||||
|
MAIL_PORT=465
|
||||||
|
MAIL_USE_SSL=True
|
||||||
|
MAIL_USERNAME=your-email@qq.com
|
||||||
|
MAIL_PASSWORD=your-email-password
|
||||||
|
```
|
||||||
|
|
||||||
|
4. 运行后端:
|
||||||
|
```bash
|
||||||
|
python app.py
|
||||||
|
```
|
||||||
|
|
||||||
|
或者使用批处理文件(Windows):
|
||||||
|
```bash
|
||||||
|
启动后端.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
后端服务将在 `http://localhost:5000` 启动
|
||||||
|
|
||||||
|
### 前端启动
|
||||||
|
|
||||||
|
1. 进入前端目录:
|
||||||
|
```bash
|
||||||
|
cd NBATransfer-frontend
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 安装依赖:
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
3. 配置环境变量(可选):
|
||||||
|
创建 `.env` 文件:
|
||||||
|
```env
|
||||||
|
VITE_API_URL=http://localhost:5000/api
|
||||||
|
```
|
||||||
|
|
||||||
|
4. 运行前端:
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
或者使用批处理文件(Windows):
|
||||||
|
```bash
|
||||||
|
启动前端.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
前端服务将在 `http://localhost:5173` 启动(Vite 默认端口)
|
||||||
|
|
||||||
|
## 默认账户
|
||||||
|
|
||||||
|
### 管理员账户
|
||||||
|
- **邮箱**: admin@nba.com
|
||||||
|
- **密码**: admin123
|
||||||
|
|
||||||
|
⚠️ **首次登录后请立即修改密码!**
|
||||||
|
|
||||||
|
## API 文档
|
||||||
|
|
||||||
|
### 认证相关 `/api/auth`
|
||||||
|
- `POST /register` - 用户注册
|
||||||
|
- `POST /login` - 用户登录
|
||||||
|
- `POST /refresh` - 刷新令牌
|
||||||
|
- `GET /me` - 获取当前用户信息
|
||||||
|
- `POST /change-password` - 修改密码
|
||||||
|
|
||||||
|
### 用户相关 `/api/user`
|
||||||
|
- `GET /profile` - 获取用户资料
|
||||||
|
- `PUT /profile` - 更新用户资料
|
||||||
|
- `GET /balance` - 获取账户余额
|
||||||
|
- `GET /transactions` - 获取交易记录
|
||||||
|
- `GET /api-calls` - 获取 API 调用记录
|
||||||
|
- `GET /stats` - 获取统计信息
|
||||||
|
|
||||||
|
### 订单相关 `/api/order`
|
||||||
|
- `POST /create` - 创建充值订单
|
||||||
|
- `GET /list` - 获取订单列表
|
||||||
|
- `GET /<order_id>` - 获取订单详情
|
||||||
|
- `POST /notify/<order_no>` - 支付通知(测试用)
|
||||||
|
|
||||||
|
### API 服务 `/api/service`
|
||||||
|
- `POST /text-to-image` - 文生图 API
|
||||||
|
- `GET /models` - 获取可用模型
|
||||||
|
- `GET /pricing` - 获取价格信息
|
||||||
|
- `GET /call/<call_id>` - 获取 API 调用详情
|
||||||
|
|
||||||
|
### API 密钥 `/api/apikey`
|
||||||
|
- `GET /list` - 获取 API 密钥列表
|
||||||
|
- `POST /create` - 创建 API 密钥
|
||||||
|
- `PUT /<key_id>/toggle` - 启用/禁用密钥
|
||||||
|
- `DELETE /<key_id>` - 删除密钥
|
||||||
|
|
||||||
|
### V1 API `/v1`
|
||||||
|
- `POST /chat/completions` - 聊天完成接口
|
||||||
|
- `POST /images/generations` - 图片生成接口
|
||||||
|
|
||||||
|
### 管理员 `/api/admin`
|
||||||
|
- `GET /users` - 获取用户列表
|
||||||
|
- `GET /users/<user_id>` - 获取用户详情
|
||||||
|
- `POST /users/<user_id>/toggle-status` - 启用/禁用用户
|
||||||
|
- `POST /users/<user_id>/adjust-balance` - 调整用户余额
|
||||||
|
- `GET /orders` - 获取所有订单
|
||||||
|
- `GET /api-calls` - 获取所有 API 调用
|
||||||
|
- `GET /stats/overview` - 获取总览统计
|
||||||
|
- `GET /stats/chart` - 获取图表数据
|
||||||
|
|
||||||
|
## 数据库结构
|
||||||
|
|
||||||
|
### 用户表 (users)
|
||||||
|
- 邮箱、密码、用户名
|
||||||
|
- 余额、激活状态、管理员标识
|
||||||
|
- 邮箱验证状态
|
||||||
|
- 创建时间、更新时间
|
||||||
|
|
||||||
|
### 订单表 (orders)
|
||||||
|
- 订单号、用户ID、金额
|
||||||
|
- 支付方式、订单状态
|
||||||
|
- 第三方交易ID、支付时间
|
||||||
|
|
||||||
|
### 交易记录表 (transactions)
|
||||||
|
- 用户ID、交易类型(充值/消费/退款)
|
||||||
|
- 金额、前后余额
|
||||||
|
- 关联订单、关联API调用
|
||||||
|
|
||||||
|
### API调用表 (api_calls)
|
||||||
|
- 用户ID、API类型
|
||||||
|
- 提示词、参数、状态
|
||||||
|
- 结果URL、费用、错误信息
|
||||||
|
|
||||||
|
### API密钥表 (api_keys)
|
||||||
|
- 用户ID、密钥名称
|
||||||
|
- API密钥、激活状态
|
||||||
|
- 最后使用时间
|
||||||
|
|
||||||
|
### 验证码表 (verification_codes)
|
||||||
|
- 用户ID、邮箱
|
||||||
|
- 验证码、用途、使用状态
|
||||||
|
- 过期时间
|
||||||
|
|
||||||
|
## 价格策略
|
||||||
|
|
||||||
|
- **文生图 API**: 0.15 元/张
|
||||||
|
|
||||||
|
## 开发说明
|
||||||
|
|
||||||
|
### 添加新的路由
|
||||||
|
|
||||||
|
**后端**:
|
||||||
|
1. 在 `routes/` 目录下创建新的蓝图文件
|
||||||
|
2. 在 `app.py` 中注册蓝图
|
||||||
|
|
||||||
|
**前端**:
|
||||||
|
1. 在 `src/api/modules/` 下创建 API 模块
|
||||||
|
2. 在 `src/pages/` 下创建页面组件
|
||||||
|
3. 在 `src/router/` 中配置路由
|
||||||
|
|
||||||
|
### 数据库迁移
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 进入 Python shell
|
||||||
|
python
|
||||||
|
>>> from app import create_app
|
||||||
|
>>> from models import db
|
||||||
|
>>> app = create_app()
|
||||||
|
>>> with app.app_context():
|
||||||
|
... db.create_all()
|
||||||
|
```
|
||||||
|
|
||||||
|
## 部署建议
|
||||||
|
|
||||||
|
### 后端部署
|
||||||
|
|
||||||
|
#### 使用 Gunicorn (生产环境)
|
||||||
|
```bash
|
||||||
|
pip install gunicorn
|
||||||
|
gunicorn -w 4 -b 0.0.0.0:5000 app:app
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 使用 Docker
|
||||||
|
```dockerfile
|
||||||
|
FROM python:3.9
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install -r requirements.txt
|
||||||
|
COPY . .
|
||||||
|
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "app:app"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 前端部署
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
构建产物在 `dist/` 目录,可以部署到 Nginx、Vercel、Netlify 等平台。
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. ⚠️ 生产环境请修改所有默认密钥
|
||||||
|
2. ⚠️ 配置实际的邮件服务器
|
||||||
|
3. ⚠️ 接入真实的支付接口
|
||||||
|
4. ⚠️ 配置 HTTPS
|
||||||
|
5. ⚠️ 定期备份数据库
|
||||||
|
6. ⚠️ 设置合适的 CORS 策略
|
||||||
|
|
||||||
|
## 许可证
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
## 贡献
|
||||||
|
|
||||||
|
欢迎提交 Issue 和 Pull Request!
|
||||||
|
|
||||||
17
tests/test1.py
Normal file
17
tests/test1.py
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import requests
|
||||||
|
|
||||||
|
url = "http://localhost:5000/v1/chat/completions"
|
||||||
|
headers = {
|
||||||
|
"Authorization": "Bearer sk_ie2F3ZF2ZOt8dxwKCQglce3JTKFqYay5",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
data = {
|
||||||
|
"model": "deepseek-chat",
|
||||||
|
"messages": [
|
||||||
|
{"role": "user", "content": "给我完整的输出滕王阁序"}
|
||||||
|
],
|
||||||
|
"stream": False
|
||||||
|
}
|
||||||
|
|
||||||
|
response = requests.post(url, headers=headers, json=data)
|
||||||
|
print(response.json())
|
||||||
12
要求.txt
Normal file
12
要求.txt
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
做一个nano bannano api 中转购买网站
|
||||||
|
前端使用React,后端使用python的flask
|
||||||
|
网站需要基本的邮箱注册登录机制来验证用户身份
|
||||||
|
用户登录后可以通过购买额度来获取使用API资格
|
||||||
|
API中转详细情况看“API中转文档”
|
||||||
|
网站需要适配手机端和电脑端
|
||||||
|
以完整的售卖网站为模板
|
||||||
|
数据库使用sqlite储存
|
||||||
|
支持微信支持和支付宝支持,支付接口以后会给出
|
||||||
|
api调用是0.15元一张图片生成
|
||||||
|
目前商品就只有nano bannan 文生图API
|
||||||
|
其他我没有列举完的要求你按照市面上企业级api售卖网站模板来搭建
|
||||||
Reference in New Issue
Block a user