初始提交:卡密授权管理系统

This commit is contained in:
Fei-Qing committed 2026-06-23 11:11:54 +08:00
commit 59586775c4
202 files changed
+25427

No files matched your search

+508
View File
@@ -0,0 +1,508 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Validator;
/**
* 代理与额度管理控制器
*/
class AgentController extends Controller
{
/**
* 代理列表
*/
/**
* 代理列表
* GET /api/agents
* Query: keyword, status, sort_by, sort_order, page, page_size
*/
public function list(): void
{
$db = Database::getInstance();
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$keyword = trim($_GET['keyword'] ?? '');
$status = $_GET['status'] ?? '';
$offset = ($page - 1) * $pageSize;
$where = "WHERE u.role = 'agent' AND u.deleted_at IS NULL";
$params = [];
if ($status !== '') {
$where .= " AND u.status = ?";
$params[] = (int) $status;
}
if ($keyword) {
$where .= " AND (u.username LIKE ? OR u.nickname LIKE ?)";
$params[] = "%{$keyword}%";
$params[] = "%{$keyword}%";
}
$total = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('users')} u {$where}",
$params
);
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'username', 'total_quota', 'used_quota', 'remain_quota', 'created_at']) ? $_GET['sort_by'] : 'id';
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
$orderSql = $sortBy === 'remain_quota' ? "(COALESCE(a.total_quota, 0) - COALESCE(a.used_quota, 0) - COALESCE(a.frozen_quota, 0)) {$sortOrder}" : "u.{$sortBy} {$sortOrder}";
$agents = $db->fetchAll(
"SELECT u.id, u.username, u.nickname, u.email, u.status, u.last_login_at, u.created_at,
COALESCE(a.total_quota, 0) AS total_quota,
COALESCE(a.used_quota, 0) AS used_quota,
COALESCE(a.frozen_quota, 0) AS frozen_quota,
(COALESCE(a.total_quota, 0) - COALESCE(a.used_quota, 0) - COALESCE(a.frozen_quota, 0)) AS remain_quota
FROM {$db->table('users')} u
LEFT JOIN {$db->table('agents')} a ON u.id = a.user_id
{$where}
ORDER BY {$orderSql}
LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $agents,
'total' => (int) $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 导出代理
* GET /api/agents/export
* Query: ids, format(csv|excel)
*/
public function export(): void
{
$ids = $_GET['ids'] ?? [];
$format = strtolower($_GET['format'] ?? 'csv');
if (!in_array($format, ['csv', 'excel'])) {
$format = 'csv';
}
$db = Database::getInstance();
$where = "WHERE u.role = 'agent' AND u.deleted_at IS NULL";
$params = [];
if (!empty($ids)) {
$ids = is_array($ids) ? $ids : explode(',', $ids);
$ids = array_filter(array_map('intval', $ids));
if (!empty($ids)) {
$where .= ' AND u.id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
$params = array_merge($params, $ids);
}
}
$rows = $db->fetchAll(
"SELECT u.id, u.username, u.nickname, u.email, u.status, u.created_at,
COALESCE(a.total_quota, 0) AS total_quota,
COALESCE(a.used_quota, 0) AS used_quota,
(COALESCE(a.total_quota, 0) - COALESCE(a.used_quota, 0) - COALESCE(a.frozen_quota, 0)) AS remain_quota
FROM {$db->table('users')} u
LEFT JOIN {$db->table('agents')} a ON u.id = a.user_id
{$where}
ORDER BY u.id DESC
LIMIT 50000",
$params
);
if ($format === 'excel') {
$filename = 'agents_export_' . date('YmdHis') . '.xls';
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$html = '<table border="1"><tr><th>ID</th><th>用户名</th><th>昵称</th><th>邮箱</th><th>状态</th><th>总额度</th><th>已使用</th><th>剩余额度</th><th>创建时间</th></tr>';
foreach ($rows as $row) {
$html .= '<tr>';
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['username']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['nickname'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['email'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['status'] == 1 ? '正常' : '禁用') . '</td>';
$html .= '<td>' . htmlspecialchars($row['total_quota']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['used_quota']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['remain_quota']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
exit;
}
$filename = 'agents_export_' . date('YmdHis') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$output = fopen('php://output', 'w');
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($output, ['ID', '用户名', '昵称', '邮箱', '状态', '总额度', '已使用', '剩余额度', '创建时间']);
foreach ($rows as $row) {
fputcsv($output, [
$row['id'],
$row['username'],
$row['nickname'] ?? '',
$row['email'] ?? '',
$row['status'] == 1 ? '正常' : '禁用',
$row['total_quota'],
$row['used_quota'],
$row['remain_quota'],
$row['created_at'],
]);
}
fclose($output);
exit;
}
/**
* 给代理充值额度
*/
public function recharge(): void
{
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate([
'agent_id' => 'required|integer',
'amount' => 'required|numeric',
])) {
$this->error($validator->getFirstError());
}
$agentId = (int) $input['agent_id'];
$amount = (float) $input['amount'];
$remark = $input['remark'] ?? '';
if ($amount <= 0) {
$this->error('额度必须大于0');
}
$db = Database::getInstance();
// 验证代理存在
$agent = $db->fetch(
"SELECT u.id, a.id AS agent_record_id, COALESCE(a.total_quota, 0) AS total_quota,
COALESCE(a.used_quota, 0) AS used_quota
FROM {$db->table('users')} u
LEFT JOIN {$db->table('agents')} a ON u.id = a.user_id
WHERE u.id = ? AND u.role = 'agent' AND u.deleted_at IS NULL",
[$agentId]
);
if (!$agent) {
$this->error('代理不存在');
}
$balanceBefore = (float) ($agent['total_quota'] ?? 0) - (float) ($agent['used_quota'] ?? 0);
$db->beginTransaction();
try {
if ($agent['agent_record_id']) {
$db->execute(
"UPDATE {$db->table('agents')} SET total_quota = total_quota + ? WHERE user_id = ?",
[$amount, $agentId]
);
} else {
$db->insert(
"INSERT INTO {$db->table('agents')} (user_id, total_quota, used_quota) VALUES (?, ?, 0)",
[$agentId, $amount]
);
}
$balanceAfter = $balanceBefore + $amount;
// 记录额度变动
$db->insert(
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, remark, operator_id, created_at)
VALUES (?, 'recharge', ?, ?, ?, ?, ?, NOW())",
[$agentId, $amount, $balanceBefore, $balanceAfter, $remark, $this->getUserId()]
);
$db->commit();
} catch (\Throwable $e) {
$db->rollback();
$this->error('充值失败: ' . $e->getMessage());
}
logger('agent_recharge', 'agent', $agentId, ['amount' => $amount]);
$this->success([
'balance_before' => $balanceBefore,
'balance_after' => $balanceAfter,
], '充值成功');
}
/**
* 调整代理额度
*/
public function adjustQuota(): void
{
$input = $this->getJsonInput();
$agentId = (int) ($input['agent_id'] ?? 0);
$amount = (float) ($input['amount'] ?? 0);
$remark = $input['remark'] ?? '';
$db = Database::getInstance();
$agent = $db->fetch(
"SELECT a.* FROM {$db->table('agents')} a
JOIN {$db->table('users')} u ON a.user_id = u.id
WHERE a.user_id = ? AND u.role = 'agent'",
[$agentId]
);
if (!$agent) {
$this->error('代理不存在');
}
$balanceBefore = (float) $agent['total_quota'] - (float) $agent['used_quota'];
$balanceAfter = $balanceBefore + $amount;
if ($balanceAfter < 0) {
$this->error('调整后额度不能为负');
}
$db->beginTransaction();
try {
$db->execute(
"UPDATE {$db->table('agents')} SET total_quota = total_quota + ? WHERE user_id = ?",
[$amount, $agentId]
);
$db->insert(
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, remark, operator_id, created_at)
VALUES (?, 'adjust', ?, ?, ?, ?, ?, NOW())",
[$agentId, $amount, $balanceBefore, $balanceAfter, $remark, $this->getUserId()]
);
$db->commit();
} catch (\Throwable $e) {
$db->rollback();
$this->error('调整失败');
}
logger('agent_adjust_quota', 'agent', $agentId, ['amount' => $amount]);
$this->success([
'balance_before' => $balanceBefore,
'balance_after' => $balanceAfter,
], '调整成功');
}
/**
* 代理额度变动日志
*/
public function quotaLogs(): void
{
$db = Database::getInstance();
$page = (int) ($_GET['page'] ?? 1);
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$agentId = $_GET['agent_id'] ?? '';
$offset = ($page - 1) * $pageSize;
$where = "WHERE 1=1";
$params = [];
if ($agentId) {
$where .= " AND agent_id = ?";
$params[] = $agentId;
}
$total = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('agent_quota_logs')} {$where}",
$params
);
$logs = $db->fetchAll(
"SELECT l.*, u.username AS agent_name, op.username AS operator_name
FROM {$db->table('agent_quota_logs')} l
LEFT JOIN {$db->table('users')} u ON l.agent_id = u.id
LEFT JOIN {$db->table('users')} op ON l.operator_id = op.id
{$where}
ORDER BY l.id DESC
LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $logs,
'total' => (int) $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 获取代理可用额度 (Agent自己查看)
*/
public function myQuota(): void
{
$userId = $this->getUserId();
$db = Database::getInstance();
$agent = $db->fetch(
"SELECT total_quota, used_quota, frozen_quota FROM {$db->table('agents')} WHERE user_id = ?",
[$userId]
);
if (!$agent) {
$this->success(['total_quota' => 0, 'used_quota' => 0, 'frozen_quota' => 0, 'remain_quota' => 0]);
return;
}
$this->success([
'total_quota' => (float) $agent['total_quota'],
'used_quota' => (float) $agent['used_quota'],
'frozen_quota' => (float) $agent['frozen_quota'],
'remain_quota' => (float) $agent['total_quota'] - (float) $agent['used_quota'] - (float) $agent['frozen_quota'],
]);
}
/**
* 代理为下级用户授权(消耗额度)
*/
public function authorizeCard(): void
{
// 仅代理角色可使用此接口
if ($this->getUserRole() !== 'agent') {
$this->error('仅代理用户可执行此操作', 403);
}
$userId = $this->getUserId();
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate([
'project_id' => 'required|integer',
'card_type_id' => 'required|integer',
])) {
$this->error($validator->getFirstError());
}
$projectId = (int) $input['project_id'];
$cardTypeId = (int) $input['card_type_id'];
$bindInfo = $input['bind_info'] ?? [];
$remark = $input['remark'] ?? '';
$db = Database::getInstance();
// 验证项目
$project = $db->fetch("SELECT id FROM {$db->table('projects')} WHERE id = ? AND status = 1 AND deleted_at IS NULL", [$projectId]);
if (!$project) {
$this->error('项目不存在或已禁用');
}
// 验证卡密类型
$cardType = $db->fetch(
"SELECT * FROM {$db->table('card_types')} WHERE id = ? AND project_id = ? AND status = 1",
[$cardTypeId, $projectId]
);
if (!$cardType) {
$this->error('卡密类型不存在');
}
if ((float) $cardType['agent_cost'] <= 0) {
$this->error('该套餐未配置代理价格,无法生成');
}
// 检查额度
$agent = $db->fetch("SELECT * FROM {$db->table('agents')} WHERE user_id = ?", [$userId]);
if (!$agent) {
$this->error('代理额度账户不存在,请联系管理员充值');
}
$remainQuota = (float) ($agent['total_quota'] ?? 0) - (float) ($agent['used_quota'] ?? 0) - (float) ($agent['frozen_quota'] ?? 0);
if ($remainQuota < (float) $cardType['agent_cost']) {
$this->error('可用额度不足,请充值');
}
$snowflake = new \App\Services\SnowflakeService();
$cardKey = $snowflake->generateCardKey();
$expireTime = null;
if ($cardType['duration_days'] > 0) {
$expireTime = date('Y-m-d H:i:s', strtotime("+{$cardType['duration_days']} days"));
}
$db->beginTransaction();
try {
// 创建卡密
$cardId = $db->insert(
"INSERT INTO {$db->table('cards')} (card_key, project_id, card_type_id, type, duration_days, status, bind_info, bound_at, expire_time, use_user_id, remark)
VALUES (?, ?, ?, ?, ?, 'used', ?, NOW(), ?, ?, ?)",
[
$cardKey,
$projectId,
$cardTypeId,
$cardType['name'],
$cardType['duration_days'],
json_encode($bindInfo, JSON_UNESCAPED_UNICODE),
$expireTime,
$userId,
$remark,
]
);
// 扣减额度
$db->execute(
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
[(float) $cardType['agent_cost'], $userId]
);
$balanceBefore = $remainQuota;
$balanceAfter = $remainQuota - (float) $cardType['agent_cost'];
// 记录额度变动
$db->insert(
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
VALUES (?, 'consume', ?, ?, ?, 'card', ?, ?, ?, NOW())",
[$userId, (float) $cardType['agent_cost'], $balanceBefore, $balanceAfter, $cardId, $remark, $this->getUserId()]
);
$db->commit();
} catch (\Throwable $e) {
$db->rollback();
$this->error('授权失败: ' . $e->getMessage());
}
logger('agent_authorize', 'card', $cardId, ['project_id' => $projectId, 'card_type' => $cardType['name']]);
$this->success([
'card_id' => $cardId,
'card_key' => $cardKey,
'expire_time' => $expireTime,
], '授权成功');
}
/**
* 重置代理密码
* POST /api/agents/{id}/reset-password
*/
public function resetPassword(int $agentId): void
{
if ($this->getUserRole() !== 'admin') {
$this->error('权限不足', 403);
}
$db = Database::getInstance();
$agent = $db->fetch(
"SELECT id, username FROM {$db->table('users')} WHERE id = ? AND role = 'agent' AND deleted_at IS NULL",
[$agentId]
);
if (!$agent) {
$this->error('代理不存在');
}
$newPassword = substr(bin2hex(random_bytes(4)), 0, 8);
$db->execute(
"UPDATE {$db->table('users')} SET password = ? WHERE id = ?",
[passwordHash($newPassword), $agentId]
);
logger('reset_agent_password', 'user', $agentId, ['username' => $agent['username']]);
$this->success(['password' => $newPassword], '密码已重置');
}
}
+713
View File
@@ -0,0 +1,713 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Application;
use App\Core\Database;
use App\Core\Validator;
use App\Services\JwtService;
/**
* 认证控制器
* 处理登录、登出、Token刷新、密码修改
*/
class AuthController extends Controller
{
/**
* 管理员登录
* POST /api/auth/admin-login
*/
public function adminLogin(): void
{
$this->doLogin(['admin', 'project_admin'], 'admin');
}
/**
* 代理登录
* POST /api/auth/agent-login
*/
public function agentLogin(): void
{
$this->doLogin(['agent'], 'agent');
}
/**
* 统一登录处理
* @param array $allowedRoles 允许登录的角色
* @param string $portal 登录入口标识,用于日志
*/
private function doLogin(array $allowedRoles, string $portal): void
{
$input = $this->getJsonInput();
$account = $input['username'] ?? ($input['email'] ?? '');
$validator = new Validator($input);
if (!$validator->validate([
'password' => 'required|min:6|max:50',
])) {
$this->error($validator->getFirstError());
}
if (empty($account)) {
$this->error('请输入用户名或邮箱');
}
$db = Database::getInstance();
// 根据是否包含@选择查询方式
if (filter_var($account, FILTER_VALIDATE_EMAIL)) {
$user = $db->fetch(
"SELECT * FROM {$db->table('users')} WHERE email = ? AND deleted_at IS NULL",
[$account]
);
} else {
$user = $db->fetch(
"SELECT * FROM {$db->table('users')} WHERE username = ? AND deleted_at IS NULL",
[$account]
);
}
if (!$user || !passwordVerify($input['password'], $user['password'])) {
$this->error('用户名或密码错误');
}
if ($user['status'] != 1) {
$this->error('账号已被禁用,请联系管理员');
}
if (!in_array($user['role'], $allowedRoles, true)) {
$this->error('该账号无此入口登录权限');
}
// 更新登录信息
$db->execute(
"UPDATE {$db->table('users')} SET last_login_at = NOW(), last_login_ip = ? WHERE id = ?",
[clientIp(), $user['id']]
);
// 生成Token
$jwtService = new JwtService();
$tokens = $jwtService->generateToken($user);
logger('login', 'user', $user['id'], ['portal' => $portal, 'role' => $user['role']]);
$this->success([
'user' => [
'id' => $user['id'],
'username' => $user['username'],
'nickname' => $user['nickname'],
'role' => $user['role'],
'email' => $user['email'],
],
'token' => $tokens,
], '登录成功');
}
/**
* 代理注册
* POST /api/auth/agent-register
*/
public function agentRegister(): void
{
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate([
'username' => 'required|min:3|max:50',
'password' => 'required|min:6|max:50',
'confirm_password'=> 'required',
'email' => 'required|email|max:100',
'phone' => 'required|max:20',
])) {
$this->error($validator->getFirstError());
}
if ($input['password'] !== $input['confirm_password']) {
$this->error('两次输入的密码不一致');
}
// 手机号格式验证
if (!preg_match('/^1[3-9]\d{9}$/', $input['phone'])) {
$this->error('手机号格式不正确');
}
$db = Database::getInstance();
// 检查用户名是否已存在
$exists = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('users')} WHERE username = ? AND deleted_at IS NULL",
[$input['username']]
);
if ($exists > 0) {
$this->error('用户名已被注册');
}
// 检查邮箱是否已存在
$emailExists = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('users')} WHERE email = ? AND deleted_at IS NULL",
[$input['email']]
);
if ($emailExists > 0) {
$this->error('邮箱已被注册');
}
// 解析上级代理邀请码(用户名)
$parentId = 0;
$inviteCode = trim($input['invite_code'] ?? '');
if ($inviteCode !== '') {
$parent = $db->fetch(
"SELECT id, role FROM {$db->table('users')} WHERE username = ? AND deleted_at IS NULL AND status = 1",
[$inviteCode]
);
if (!$parent) {
$this->error('邀请码不存在或已禁用');
}
if ($parent['role'] !== 'agent') {
$this->error('邀请码无效,仅代理可邀请下级代理');
}
$parentId = (int) $parent['id'];
}
$userId = $db->insert(
"INSERT INTO {$db->table('users')} (username, password, nickname, email, phone, role, parent_id, status, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, 'agent', ?, 1, NOW(), NOW())",
[
$input['username'],
passwordHash($input['password']),
$input['username'],
$input['email'],
$input['phone'],
$parentId,
]
);
logger('agent_register', 'user', $userId, ['username' => $input['username'], 'parent_id' => $parentId]);
$this->success(['id' => $userId], '注册成功,请登录');
}
/**
* 刷新Token
*/
public function refreshToken(): void
{
$input = $this->getJsonInput();
$refreshToken = $input['refresh_token'] ?? '';
if (empty($refreshToken)) {
$this->error('缺少刷新Token');
}
$jwtService = new JwtService();
$tokens = $jwtService->refreshToken($refreshToken);
if (!$tokens) {
$this->error('刷新Token无效或已过期');
}
$this->success($tokens, 'Token刷新成功');
}
/**
* 获取当前用户信息
*/
public function me(): void
{
$userId = $this->getUserId();
if (!$userId) {
$this->error('用户不存在', 404);
}
$db = Database::getInstance();
$user = $db->fetch(
"SELECT id, username, nickname, email, phone, avatar, role, status, parent_id, last_login_at, last_login_ip, created_at
FROM {$db->table('users')}
WHERE id = ? AND deleted_at IS NULL",
[$userId]
);
if (!$user) {
$this->error('用户不存在', 404);
}
// 如果是代理,获取额度信息
if ($user['role'] === 'agent') {
$db = Database::getInstance();
$agent = $db->fetch(
"SELECT total_quota, used_quota, frozen_quota FROM {$db->table('agents')} WHERE user_id = ?",
[$user['id']]
);
$user['agent_info'] = $agent ?: ['total_quota' => 0, 'used_quota' => 0, 'frozen_quota' => 0];
}
$this->success($user);
}
/**
* 修改密码
*/
public function changePassword(): void
{
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate([
'old_password' => 'required|min:6',
'new_password' => 'required|min:6|max:50',
])) {
$this->error($validator->getFirstError());
}
$user = $this->getCurrentUser();
if (!passwordVerify($input['old_password'], $user['password'])) {
$this->error('原密码错误');
}
$db = Database::getInstance();
$db->execute(
"UPDATE {$db->table('users')} SET password = ? WHERE id = ?",
[passwordHash($input['new_password']), $user['id']]
);
logger('change_password', 'user', $user['id']);
$this->success(null, '密码修改成功');
}
/**
* 更新当前管理员个人资料
* PUT /api/auth/profile
* Body: { nickname: string, email: string, phone: string, avatar: string }
*/
public function updateProfile(): void
{
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate([
'nickname' => 'max:50',
'email' => 'email|max:100',
'phone' => 'max:20',
'avatar' => 'max:500',
])) {
$this->error($validator->getFirstError());
}
$userId = $this->getUserId();
if (!$userId) {
$this->error('用户不存在', 404);
}
$allowed = ['nickname', 'email', 'phone', 'avatar'];
$updates = [];
$params = [];
foreach ($allowed as $field) {
if (array_key_exists($field, $input)) {
$updates[] = "{$field} = ?";
$params[] = $input[$field] ?? '';
}
}
if (empty($updates)) {
$this->error('没有要更新的字段');
}
$params[] = $userId;
$db = Database::getInstance();
$db->execute(
"UPDATE {$db->table('users')} SET " . implode(', ', $updates) . " WHERE id = ?",
$params
);
logger('update_profile', 'user', $userId, ['fields' => array_keys(array_intersect_key($input, array_flip($allowed)))]);
$this->success(null, '个人资料更新成功');
}
/**
* 上传头像
* POST /api/auth/avatar
* Body: multipart/form-data, field: avatar (image file)
*/
public function uploadAvatar(): void
{
$userId = $this->getUserId();
if (!$userId) {
$this->error('用户不存在', 404);
}
if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
$this->error('请选择要上传的头像图片');
}
$file = $_FILES['avatar'];
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!in_array($file['type'], $allowedTypes)) {
$this->error('仅支持 JPG、PNG、GIF、WebP 格式的图片');
}
if ($file['size'] > 2 * 1024 * 1024) {
$this->error('图片大小不能超过 2MB');
}
// 确保上传目录存在
$uploadDir = BASE_PATH . '/public/uploads/avatars';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// 生成唯一文件名
$ext = pathinfo($file['name'], PATHINFO_EXTENSION) ?: 'jpg';
$filename = 'avatar_' . $userId . '_' . time() . '.' . $ext;
$filepath = $uploadDir . '/' . $filename;
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
$this->error('头像上传失败,请重试');
}
// 更新数据库
$avatarUrl = '/uploads/avatars/' . $filename;
$db = Database::getInstance();
$db->execute(
"UPDATE {$db->table('users')} SET avatar = ? WHERE id = ?",
[$avatarUrl, $userId]
);
// 删除旧头像文件(如果存在)
$oldUser = $db->fetch("SELECT avatar FROM {$db->table('users')} WHERE id = ?", [$userId]);
// 实际上新头像路径已更新,但旧文件还在,这里简单处理:不删除旧文件,避免并发问题
logger('upload_avatar', 'user', $userId);
$this->success(['avatar' => $avatarUrl], '头像上传成功');
}
/**
* 用户列表 (Admin专用)
* GET /api/users
* Query: role, keyword, status, start_date, end_date, sort_by, sort_order, page, page_size
*/
public function list(): void
{
$db = Database::getInstance();
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$offset = ($page - 1) * $pageSize;
$role = $_GET['role'] ?? '';
$keyword = trim($_GET['keyword'] ?? '');
$status = $_GET['status'] ?? '';
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'username', 'nickname', 'role', 'status', 'last_login_at', 'created_at']) ? $_GET['sort_by'] : 'id';
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
$where = "WHERE deleted_at IS NULL";
$params = [];
if ($role && in_array($role, ['admin', 'project_admin', 'agent'])) {
$where .= " AND role = ?";
$params[] = $role;
}
if ($status !== '') {
$where .= " AND status = ?";
$params[] = (int) $status;
}
if ($keyword) {
$where .= " AND (username LIKE ? OR nickname LIKE ? OR email LIKE ?)";
$params[] = "%{$keyword}%";
$params[] = "%{$keyword}%";
$params[] = "%{$keyword}%";
}
if ($startDate) {
$where .= " AND DATE(created_at) >= ?";
$params[] = $startDate;
}
if ($endDate) {
$where .= " AND DATE(created_at) <= ?";
$params[] = $endDate;
}
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$db->table('users')} {$where}", $params);
$users = $db->fetchAll(
"SELECT id, username, nickname, email, phone, avatar, role, project_ids, status, last_login_at, last_login_ip, created_at
FROM {$db->table('users')} {$where} ORDER BY {$sortBy} {$sortOrder} LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $users,
'total' => (int) $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 创建用户 (Admin)
*/
public function create(): void
{
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate([
'username' => 'required|min:3|max:50',
'password' => 'required|min:6|max:50',
'role' => 'required',
])) {
$this->error($validator->getFirstError());
}
if (!in_array($input['role'], ['admin', 'project_admin', 'agent'])) {
$this->error('无效的角色类型');
}
$db = Database::getInstance();
// 检查用户名唯一
$exist = $db->fetch("SELECT id FROM {$db->table('users')} WHERE username = ? AND deleted_at IS NULL", [$input['username']]);
if ($exist) {
$this->error('用户名已存在');
}
$userId = $db->insert(
"INSERT INTO {$db->table('users')} (username, password, nickname, email, role, project_ids, status) VALUES (?, ?, ?, ?, ?, ?, ?)",
[
$input['username'],
passwordHash($input['password']),
$input['nickname'] ?? '',
$input['email'] ?? '',
$input['role'],
isset($input['project_ids']) ? json_encode($input['project_ids']) : null,
$input['status'] ?? 1,
]
);
// 如果是代理,创建额度记录
if ($input['role'] === 'agent') {
$db->insert(
"INSERT INTO {$db->table('agents')} (user_id, total_quota, used_quota) VALUES (?, 0, 0)",
[$userId]
);
}
logger('create_user', 'user', $userId, ['username' => $input['username'], 'role' => $input['role']]);
$this->success(['id' => $userId], '用户创建成功');
}
/**
* 更新用户
*/
public function update(int $id): void
{
$input = $this->getJsonInput();
$db = Database::getInstance();
$user = $db->fetch("SELECT * FROM {$db->table('users')} WHERE id = ? AND deleted_at IS NULL", [$id]);
if (!$user) {
$this->error('用户不存在');
}
$updates = [];
$params = [];
if (isset($input['nickname'])) {
$updates[] = 'nickname = ?';
$params[] = $input['nickname'];
}
if (isset($input['email'])) {
$updates[] = 'email = ?';
$params[] = $input['email'];
}
if (isset($input['status'])) {
$updates[] = 'status = ?';
$params[] = $input['status'];
}
if (isset($input['password']) && !empty($input['password'])) {
$updates[] = 'password = ?';
$params[] = passwordHash($input['password']);
}
if (isset($input['project_ids']) && $user['role'] === 'project_admin') {
$updates[] = 'project_ids = ?';
$params[] = json_encode($input['project_ids']);
}
if (empty($updates)) {
$this->error('没有需要更新的字段');
}
$params[] = $id;
$db->execute("UPDATE {$db->table('users')} SET " . implode(', ', $updates) . " WHERE id = ?", $params);
logger('update_user', 'user', $id);
$this->success(null, '更新成功');
}
/**
* 删除用户
*/
public function delete(int $id): void
{
$db = Database::getInstance();
$user = $db->fetch("SELECT id, role FROM {$db->table('users')} WHERE id = ? AND deleted_at IS NULL", [$id]);
if (!$user) {
$this->error('用户不存在');
}
if ($user['role'] === 'admin') {
$this->error('不能删除超级管理员');
}
$db->execute("UPDATE {$db->table('users')} SET deleted_at = NOW() WHERE id = ?", [$id]);
logger('delete_user', 'user', $id);
$this->success(null, '删除成功');
}
/**
* 批量删除用户
* POST /api/users/batch-delete
* Body: { ids: [int] }
*/
public function batchDelete(): void
{
$input = $this->getJsonInput();
$ids = $input['ids'] ?? [];
if (!is_array($ids) || empty($ids)) {
$this->error('请选择要删除的用户');
}
$ids = array_filter(array_map('intval', $ids));
if (empty($ids)) {
$this->error('无效的用户ID');
}
$db = Database::getInstance();
$placeholders = implode(',', array_fill(0, count($ids), '?'));
// 不能删除管理员
$adminCount = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('users')} WHERE id IN ({$placeholders}) AND role = 'admin' AND deleted_at IS NULL",
$ids
);
if ($adminCount > 0) {
$this->error('选中的用户中包含管理员,不能删除');
}
$db->execute(
"UPDATE {$db->table('users')} SET deleted_at = NOW() WHERE id IN ({$placeholders})",
$ids
);
logger('batch_delete_users', 'user', 0, ['count' => count($ids)]);
$this->success(['count' => count($ids)], '批量删除成功');
}
/**
* 用户统计
* GET /api/users/stats
*/
public function stats(): void
{
$db = Database::getInstance();
$table = $db->table('users');
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$table} WHERE deleted_at IS NULL");
$admin = $db->fetchColumn("SELECT COUNT(*) FROM {$table} WHERE role = 'admin' AND deleted_at IS NULL");
$projectAdmin = $db->fetchColumn("SELECT COUNT(*) FROM {$table} WHERE role = 'project_admin' AND deleted_at IS NULL");
$agent = $db->fetchColumn("SELECT COUNT(*) FROM {$table} WHERE role = 'agent' AND deleted_at IS NULL");
$this->success([
'total' => (int) $total,
'admin' => (int) $admin,
'projectAdmin' => (int) $projectAdmin,
'agent' => (int) $agent,
]);
}
/**
* 导出用户
* GET /api/users/export
* Query: ids, format(csv|excel)
*/
public function export(): void
{
$ids = $_GET['ids'] ?? [];
$format = strtolower($_GET['format'] ?? 'csv');
if (!in_array($format, ['csv', 'excel'])) {
$format = 'csv';
}
$db = Database::getInstance();
$table = $db->table('users');
$where = 'WHERE deleted_at IS NULL';
$params = [];
if (!empty($ids)) {
$ids = is_array($ids) ? $ids : explode(',', $ids);
$ids = array_filter(array_map('intval', $ids));
if (!empty($ids)) {
$where .= ' AND id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
$params = $ids;
}
}
$rows = $db->fetchAll(
"SELECT id, username, nickname, email, role, status, last_login_at, last_login_ip, created_at
FROM {$table} {$where}
ORDER BY id DESC LIMIT 50000",
$params
);
$roleMap = ['admin' => '超级管理员', 'project_admin' => '项目管理员', 'agent' => '代理'];
if ($format === 'excel') {
$filename = 'users_export_' . date('YmdHis') . '.xls';
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$html = '<table border="1"><tr><th>ID</th><th>用户名</th><th>昵称</th><th>邮箱</th><th>角色</th><th>状态</th><th>最后登录</th><th>登录IP</th><th>创建时间</th></tr>';
foreach ($rows as $row) {
$html .= '<tr>';
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['username']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['nickname'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['email'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($roleMap[$row['role']] ?? $row['role']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['status'] == 1 ? '正常' : '禁用') . '</td>';
$html .= '<td>' . htmlspecialchars($row['last_login_at'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['last_login_ip'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
exit;
}
$filename = 'users_export_' . date('YmdHis') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$output = fopen('php://output', 'w');
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($output, ['ID', '用户名', '昵称', '邮箱', '角色', '状态', '最后登录', '登录IP', '创建时间']);
foreach ($rows as $row) {
fputcsv($output, [
$row['id'],
$row['username'],
$row['nickname'] ?? '',
$row['email'] ?? '',
$roleMap[$row['role']] ?? $row['role'],
$row['status'] == 1 ? '正常' : '禁用',
$row['last_login_at'] ?? '',
$row['last_login_ip'] ?? '',
$row['created_at'],
]);
}
fclose($output);
exit;
}
}
@@ -0,0 +1,932 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Services\PermissionService;
/**
* 卡密授权控制器
* 管理机器人QQ与联系人QQ的授权绑定关系
*/
class AuthorizationController extends Controller
{
/**
* 授权列表
* GET /api/authorizations?bot_qq=&contact_qq=&status=&project_id=&card_key=&page=&page_size=
*/
public function list(): void
{
$db = Database::getInstance();
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$offset = ($page - 1) * $pageSize;
$botQq = trim($_GET['bot_qq'] ?? '');
$contactQq = trim($_GET['contact_qq'] ?? '');
$status = $_GET['status'] ?? '';
$projectId = $_GET['project_id'] ?? '';
$cardKey = trim($_GET['card_key'] ?? '');
$isExpired = $_GET['is_expired'] ?? '';
$where = 'WHERE 1=1';
$params = [];
// 数据范围权限过滤(管理员查看全部,代理仅查看自身及下级代理的授权)
$scope = PermissionService::authorizationScope($this->getCurrentUser());
$where .= $scope['where'];
$params = array_merge($params, $scope['params']);
if ($botQq) {
$where .= ' AND a.bot_qq = ?';
$params[] = $botQq;
}
if ($contactQq) {
$where .= ' AND a.contact_qq = ?';
$params[] = $contactQq;
}
if ($status) {
$where .= ' AND a.status = ?';
$params[] = $status;
}
if ($projectId) {
$where .= ' AND a.project_id = ?';
$params[] = $projectId;
}
if ($cardKey) {
$where .= ' AND a.card_key LIKE ?';
$params[] = "%{$cardKey}%";
}
if ($isExpired === '1') {
$where .= ' AND a.status = \'active\' AND a.expire_time IS NOT NULL AND a.expire_time < NOW()';
}
if ($isExpired === '0') {
$where .= ' AND (a.expire_time IS NULL OR a.expire_time >= NOW() OR a.status != \'active\')';
}
$total = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('authorizations')} a {$where}",
$params
);
$rows = $db->fetchAll(
"SELECT a.*, p.name AS project_name, ct.name AS card_type_name
FROM {$db->table('authorizations')} a
LEFT JOIN {$db->table('projects')} p ON a.project_id = p.id
LEFT JOIN {$db->table('cards')} c ON a.card_id = c.id
LEFT JOIN {$db->table('card_types')} ct ON c.card_type_id = ct.id
{$where}
ORDER BY a.id DESC
LIMIT {$offset}, {$pageSize}",
$params
);
// 实时计算过期状态
$now = time();
foreach ($rows as &$row) {
$row['is_expired'] = $row['status'] === 'active'
&& $row['expire_time']
&& strtotime($row['expire_time']) < $now;
}
$this->success([
'list' => $rows,
'total' => (int) $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 授权详情
* GET /api/authorizations/{id}
*/
public function detail(int $id): void
{
$db = Database::getInstance();
$row = $db->fetch(
"SELECT a.*, p.name AS project_name, ct.name AS card_type_name
FROM {$db->table('authorizations')} a
LEFT JOIN {$db->table('projects')} p ON a.project_id = p.id
LEFT JOIN {$db->table('cards')} c ON a.card_id = c.id
LEFT JOIN {$db->table('card_types')} ct ON c.card_type_id = ct.id
WHERE a.id = ?",
[$id]
);
if (!$row) {
$this->error('授权记录不存在', 404);
}
$row['is_expired'] = $row['status'] === 'active'
&& $row['expire_time']
&& strtotime($row['expire_time']) < time();
$this->success($row);
}
/**
* 新增授权(绑定卡密到机器人QQ/联系人QQ)
* POST /api/authorizations
* Body: { card_key, bot_qq, contact_qq, contact_name? }
*/
public function create(): void
{
$input = $this->getJsonInput();
$projectId = (int) ($input['project_id'] ?? 0);
$cardTypeId = (int) ($input['card_type_id'] ?? 0);
$botQq = trim($input['bot_qq'] ?? '');
$contactQq = trim($input['contact_qq'] ?? '');
$contactName = trim($input['contact_name'] ?? '');
// 参数校验
if (empty($projectId)) {
$this->error('请选择项目');
}
if (empty($cardTypeId)) {
$this->error('请选择套餐');
}
if (empty($botQq)) {
$this->error('机器人QQ不能为空');
}
if (empty($contactQq)) {
$this->error('联系人QQ不能为空');
}
if (!preg_match('/^\d{5,15}$/', $botQq)) {
$this->error('机器人QQ格式不正确');
}
if (!preg_match('/^\d{5,15}$/', $contactQq)) {
$this->error('联系人QQ格式不正确');
}
$db = Database::getInstance();
$userId = $this->getUserId() ?? 0;
$currentRole = $this->getUserRole();
// 验证项目存在
$project = $db->fetch("SELECT * FROM {$db->table('projects')} WHERE id = ? AND deleted_at IS NULL", [$projectId]);
if (!$project) {
$this->error('项目不存在');
}
// 验证套餐
$cardType = $db->fetch(
"SELECT * FROM {$db->table('card_types')} WHERE id = ? AND project_id = ?",
[$cardTypeId, $projectId]
);
if (!$cardType) {
$this->error('套餐不存在或不属于该项目');
}
// 项目管理员:只能在自己负责的项目中创建授权
if ($currentRole === 'project_admin') {
$currentUser = $this->getCurrentUser();
$projectIds = $currentUser['project_ids'] ?? [];
if (!in_array($projectId, $projectIds)) {
$this->error('无权在此项目中创建授权', 403);
}
}
// 代理扣费
$needDeductQuota = false;
$deductAmount = 0;
$quotaBefore = 0;
if ($currentRole === 'agent') {
if ((float) $cardType['agent_cost'] <= 0) {
$this->error('该套餐未配置代理价格,无法创建授权');
}
$agentAccount = $db->fetch("SELECT * FROM {$db->table('agents')} WHERE user_id = ?", [$userId]);
if (!$agentAccount) {
$this->error('代理额度账户不存在,请联系管理员充值');
}
$remainQuota = (float) ($agentAccount['total_quota'] ?? 0) - (float) ($agentAccount['used_quota'] ?? 0) - (float) ($agentAccount['frozen_quota'] ?? 0);
if ($remainQuota < (float) $cardType['agent_cost']) {
$this->error('可用额度不足,需要 ¥' . $cardType['agent_cost'] . ',当前剩余 ¥' . $remainQuota);
}
$needDeductQuota = true;
$deductAmount = (float) $cardType['agent_cost'];
$quotaBefore = $remainQuota;
}
// 计算过期时间
$expireTime = null;
if ($cardType['duration_days'] > 0) {
$expireTime = date('Y-m-d H:i:s', strtotime("+{$cardType['duration_days']} days"));
}
// 确定 agent_id
$agentId = 0;
if ($currentRole === 'agent') {
$agentId = $userId;
}
// 写入授权记录
$authId = $db->insert(
"INSERT INTO {$db->table('authorizations')}
(card_id, card_key, project_id, project_name, bot_qq, contact_qq,
contact_name, duration_days, status, expire_time, operator_id, agent_id, authorized_at, created_at)
VALUES (0, '', ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, NOW(), NOW())",
[
$projectId,
$project['name'] ?? '',
$botQq,
$contactQq,
$contactName,
(int) $cardType['duration_days'],
$expireTime,
$userId,
$agentId,
]
);
// 如果需要扣减代理额度
if ($needDeductQuota) {
$db->execute(
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
[$deductAmount, $userId]
);
$quotaAfter = $quotaBefore - $deductAmount;
// 记录额度变动
$db->insert(
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
VALUES (?, 'consume', ?, ?, ?, 'authorization', ?, '授权扣费', ?, NOW())",
[$userId, $deductAmount, $quotaBefore, $quotaAfter, $authId, $this->getUserId()]
);
}
// 记录操作日志
$this->logAction('authorization_create', 'authorization', $authId, [
'project_id' => $projectId,
'card_type_id'=> $cardTypeId,
'bot_qq' => $botQq,
'contact_qq' => $contactQq,
]);
$this->success([
'id' => $authId,
'bot_qq' => $botQq,
'contact_qq' => $contactQq,
'expire_time' => $expireTime,
], '授权成功');
}
/**
* 公开在线授权(使用卡密激活机器人授权)
* POST /api/public/authorizations/activate
* Body: { card_key, bot_qq, contact_qq, contact_name? }
*/
public function publicActivate(): void
{
$input = $this->getJsonInput();
$cardKey = trim($input['card_key'] ?? '');
$botQq = trim($input['bot_qq'] ?? '');
$contactQq = trim($input['contact_qq'] ?? '');
$contactName = trim($input['contact_name'] ?? '');
if (empty($cardKey)) {
$this->error('卡密不能为空');
}
if (empty($botQq)) {
$this->error('机器人QQ不能为空');
}
if (empty($contactQq)) {
$this->error('联系人QQ不能为空');
}
if (!preg_match('/^\d{5,15}$/', $botQq)) {
$this->error('机器人QQ格式不正确');
}
if (!preg_match('/^\d{5,15}$/', $contactQq)) {
$this->error('联系人QQ格式不正确');
}
$db = Database::getInstance();
$card = $db->fetch(
"SELECT c.*, p.name AS project_name
FROM {$db->table('cards')} c
LEFT JOIN {$db->table('projects')} p ON c.project_id = p.id
WHERE c.card_key = ?",
[$cardKey]
);
if (!$card) {
$this->error('卡密不存在');
}
if ($card['status'] === 'disabled') {
$this->error('该卡密已被禁用');
}
if ($card['status'] === 'used') {
$this->error('该卡密已被使用');
}
// 卡密归属与使用权限验证 + 代理扣费
$currentUserId = $this->getUserId() ?? 0;
$currentRole = $this->getUserRole();
$cardAgentId = (int) ($card['use_user_id'] ?? 0);
$needDeductQuota = false;
if ($cardAgentId > 0) {
// 该卡密是某个代理生成的(已扣费)
// 公开接口无登录态 → 拒绝使用代理卡密
if (empty($currentUserId)) {
$this->error('该卡密需要登录后使用,请先登录');
}
// 非归属代理 → 禁止使用他人卡密
if ($cardAgentId !== $currentUserId) {
$this->error('此卡密不属于您,无法使用');
}
// 归属代理本人 → 允许(生成时已扣费)
} else {
// 该卡密非代理生成(管理员生成或其他渠道)
// 如果当前用户是代理,使用此类卡密需按代理价格扣费
if ($currentRole === 'agent' && $currentUserId > 0) {
$cardTypeForCost = $db->fetch(
"SELECT agent_cost FROM {$db->table('card_types')} WHERE id = ? AND project_id = ?",
[$card['card_type_id'], $card['project_id']]
);
if (!$cardTypeForCost || (float) $cardTypeForCost['agent_cost'] <= 0) {
$this->error('该卡密套餐未配置代理价格,无法使用');
}
$agentAccount = $db->fetch("SELECT * FROM {$db->table('agents')} WHERE user_id = ?", [$currentUserId]);
if (!$agentAccount) {
$this->error('代理额度账户不存在,请联系管理员充值');
}
$remainQuota = (float) ($agentAccount['total_quota'] ?? 0) - (float) ($agentAccount['used_quota'] ?? 0) - (float) ($agentAccount['frozen_quota'] ?? 0);
if ($remainQuota < (float) $cardTypeForCost['agent_cost']) {
$this->error('可用额度不足,需要 ¥' . $cardTypeForCost['agent_cost'] . ',当前剩余 ¥' . $remainQuota);
}
$needDeductQuota = true;
$deductAmount = (float) $cardTypeForCost['agent_cost'];
$quotaBefore = $remainQuota;
}
}
// 检查当前机器人QQ在同一项目下是否已有授权(未撤销),有则续费
$existingAuth = $db->fetch(
"SELECT * FROM {$db->table('authorizations')}
WHERE project_id = ? AND bot_qq = ? AND status != 'revoked'
ORDER BY expire_time IS NULL DESC, expire_time DESC, id DESC
LIMIT 1",
[$card['project_id'], $botQq]
);
$db->execute(
"UPDATE {$db->table('cards')} SET status = 'used', bound_at = NOW() WHERE id = ?",
[$card['id']]
);
$agentId = (int) ($card['use_user_id'] ?? 0);
if ($existingAuth) {
// 续费:在原有过期时间基础上累加
$baseTime = null;
if ($existingAuth['expire_time']) {
$baseTime = max(date('Y-m-d H:i:s'), $existingAuth['expire_time']);
}
$newExpireTime = null;
if ($card['duration_days'] > 0) {
if ($baseTime) {
$newExpireTime = date('Y-m-d H:i:s', strtotime("+{$card['duration_days']} days", strtotime($baseTime)));
} else {
// 原授权为永久,新卡密有时长:从当前时间开始加
$newExpireTime = date('Y-m-d H:i:s', strtotime("+{$card['duration_days']} days"));
}
} else {
// 新卡密为永久卡,直接变为永久
$newExpireTime = null;
}
$newDuration = (int) $existingAuth['duration_days'] + (int) $card['duration_days'];
$db->execute(
"UPDATE {$db->table('authorizations')}
SET expire_time = ?, duration_days = ?, status = 'active', contact_qq = ?, contact_name = ?, updated_at = NOW()
WHERE id = ?",
[$newExpireTime, $newDuration, $contactQq, $contactName, $existingAuth['id']]
);
// 记录使用记录(便于追踪每次续费卡密)
$renewAuthId = $db->insert(
"INSERT INTO {$db->table('authorizations')}
(card_id, card_key, project_id, project_name, bot_qq, contact_qq,
contact_name, duration_days, status, expire_time, operator_id, agent_id, authorized_at, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, NOW(), NOW())",
[
$card['id'],
$card['card_key'],
$card['project_id'],
$card['project_name'] ?? '',
$botQq,
$contactQq,
$contactName,
(int) $card['duration_days'],
$newExpireTime,
0,
$agentId,
]
);
// 如果需要扣减代理额度(续费场景)
if ($needDeductQuota) {
$db->execute(
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
[$deductAmount, $currentUserId]
);
$quotaAfter = $quotaBefore - $deductAmount;
// 记录额度变动
$db->insert(
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
VALUES (?, 'consume', ?, ?, ?, 'authorization', ?, '续费扣费', ?, NOW())",
[$currentUserId, $deductAmount, $quotaBefore, $quotaAfter, $renewAuthId, $this->getUserId()]
);
}
$this->success([
'id' => (int) $existingAuth['id'],
'card_key' => $cardKey,
'bot_qq' => $botQq,
'contact_qq' => $contactQq,
'contact_name'=> $contactName,
'project_id' => (int) $card['project_id'],
'project_name'=> $card['project_name'] ?? '',
'expire_time' => $newExpireTime,
'is_renew' => true,
], '续费成功');
return;
}
$expireTime = null;
if ($card['duration_days'] > 0) {
$expireTime = date('Y-m-d H:i:s', strtotime("+{$card['duration_days']} days"));
}
$authId = $db->insert(
"INSERT INTO {$db->table('authorizations')}
(card_id, card_key, project_id, project_name, bot_qq, contact_qq,
contact_name, duration_days, status, expire_time, operator_id, agent_id, authorized_at, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, NOW(), NOW())",
[
$card['id'],
$card['card_key'],
$card['project_id'],
$card['project_name'] ?? '',
$botQq,
$contactQq,
$contactName,
(int) $card['duration_days'],
$expireTime,
0,
$agentId,
]
);
// 如果需要扣减代理额度(新授权场景)
if ($needDeductQuota) {
$db->execute(
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
[$deductAmount, $currentUserId]
);
$quotaAfter = $quotaBefore - $deductAmount;
// 记录额度变动
$db->insert(
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
VALUES (?, 'consume', ?, ?, ?, 'authorization', ?, '授权扣费', ?, NOW())",
[$currentUserId, $deductAmount, $quotaBefore, $quotaAfter, $authId, $this->getUserId()]
);
}
$this->success([
'id' => $authId,
'card_key' => $cardKey,
'bot_qq' => $botQq,
'contact_qq' => $contactQq,
'contact_name'=> $contactName,
'project_id' => (int) $card['project_id'],
'project_name'=> $card['project_name'] ?? '',
'expire_time' => $expireTime,
'is_renew' => false,
], '授权成功');
}
/**
* 撤销授权
* PUT /api/authorizations/{id}/revoke
* Body: { reason? }
*/
public function revoke(int $id): void
{
$db = Database::getInstance();
$auth = $db->fetch("SELECT * FROM {$db->table('authorizations')} WHERE id = ?", [$id]);
if (!$auth) {
$this->error('授权记录不存在', 404);
}
if ($auth['status'] === 'revoked') {
$this->error('授权已被撤销');
}
$input = $this->getJsonInput();
$reason = $input['reason'] ?? '';
$db->execute(
"UPDATE {$db->table('authorizations')}
SET status = 'revoked', revoked_at = NOW(), revoke_reason = ?, updated_at = NOW()
WHERE id = ?",
[$reason, $id]
);
$this->logAction('authorization_revoke', 'authorization', $id, [
'card_key' => $auth['card_key'],
'bot_qq' => $auth['bot_qq'],
'contact_qq' => $auth['contact_qq'],
'reason' => $reason,
]);
$this->success(null, '授权已撤销');
}
/**
* 删除授权记录
* DELETE /api/authorizations/{id}
*/
public function delete(int $id): void
{
$db = Database::getInstance();
$auth = $db->fetch("SELECT * FROM {$db->table('authorizations')} WHERE id = ?", [$id]);
if (!$auth) {
$this->error('授权记录不存在', 404);
}
$db->execute("DELETE FROM {$db->table('authorizations')} WHERE id = ?", [$id]);
$this->logAction('authorization_delete', 'authorization', $id, [
'card_key' => $auth['card_key'],
'bot_qq' => $auth['bot_qq'],
'contact_qq' => $auth['contact_qq'],
]);
$this->success(null, '授权记录已删除');
}
/**
* 批量删除授权记录
* POST /api/authorizations/batch-delete
* Body: { ids: [int] }
*/
public function batchDelete(): void
{
$input = $this->getJsonInput();
$ids = $input['ids'] ?? [];
if (!is_array($ids) || empty($ids)) {
$this->error('请选择要删除的授权记录');
}
$ids = array_filter(array_map('intval', $ids));
if (empty($ids)) {
$this->error('无效的授权ID');
}
$db = Database::getInstance();
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$this->logAction('authorization_batch_delete', 'authorization', 0, ['count' => count($ids)]);
$db->execute(
"DELETE FROM {$db->table('authorizations')} WHERE id IN ({$placeholders})",
$ids
);
$this->success(['count' => count($ids)], '批量删除成功');
}
/**
* 导出授权记录
* GET /api/authorizations/export
* Query: ids, format(csv|excel)
*/
public function export(): void
{
$ids = $_GET['ids'] ?? [];
$format = strtolower($_GET['format'] ?? 'csv');
if (!in_array($format, ['csv', 'excel'])) {
$format = 'csv';
}
$db = Database::getInstance();
$where = 'WHERE 1=1';
$params = [];
if (!empty($ids)) {
$ids = is_array($ids) ? $ids : explode(',', $ids);
$ids = array_filter(array_map('intval', $ids));
if (!empty($ids)) {
$where .= ' AND a.id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
$params = array_merge($params, $ids);
}
}
$rows = $db->fetchAll(
"SELECT a.*, p.name AS project_name, ct.name AS card_type_name
FROM {$db->table('authorizations')} a
LEFT JOIN {$db->table('projects')} p ON a.project_id = p.id
LEFT JOIN {$db->table('cards')} c ON a.card_id = c.id
LEFT JOIN {$db->table('card_types')} ct ON c.card_type_id = ct.id
{$where}
ORDER BY a.id DESC
LIMIT 50000",
$params
);
$statusMap = ['active' => '有效', 'revoked' => '已撤销'];
if ($format === 'excel') {
$filename = 'authorizations_export_' . date('YmdHis') . '.xls';
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$html = '<table border="1"><tr><th>ID</th><th>机器人QQ</th><th>联系人QQ</th><th>项目</th><th>卡密</th><th>有效天数</th><th>状态</th><th>过期时间</th><th>授权时间</th></tr>';
foreach ($rows as $row) {
$html .= '<tr>';
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['bot_qq']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['contact_qq']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['project_name'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['card_key']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['duration_days'] == 0 ? '永久' : $row['duration_days'] . '天') . '</td>';
$html .= '<td>' . htmlspecialchars($statusMap[$row['status']] ?? $row['status']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['expire_time'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['authorized_at']) . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
exit;
}
$filename = 'authorizations_export_' . date('YmdHis') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$output = fopen('php://output', 'w');
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($output, ['ID', '机器人QQ', '联系人QQ', '项目', '卡密', '有效天数', '状态', '过期时间', '授权时间']);
foreach ($rows as $row) {
fputcsv($output, [
$row['id'],
$row['bot_qq'],
$row['contact_qq'],
$row['project_name'] ?? '',
$row['card_key'],
$row['duration_days'] == 0 ? '永久' : $row['duration_days'] . '天',
$statusMap[$row['status']] ?? $row['status'],
$row['expire_time'] ?? '',
$row['authorized_at'],
]);
}
fclose($output);
exit;
}
// ========================================
// 公开接口(无需认证)
// ========================================
/**
* 按机器人QQ查询授权状态(主要查询方式)
* GET /api/public/authorizations/query?bot_qq=
*/
public function queryByBot(): void
{
$botQq = trim($_GET['bot_qq'] ?? '');
if (empty($botQq)) {
$this->error('请输入机器人QQ号');
}
$db = Database::getInstance();
$now = date('Y-m-d H:i:s');
$rows = $db->fetchAll(
"SELECT a.id, a.card_key, a.project_name, a.bot_qq, a.contact_qq, a.contact_name,
a.duration_days, a.status, a.authorized_at, a.expire_time,
p.name AS project_name_full
FROM {$db->table('authorizations')} a
LEFT JOIN {$db->table('projects')} p ON a.project_id = p.id
WHERE a.bot_qq = ?
ORDER BY a.id DESC",
[$botQq]
);
$activeCount = 0;
$expiredCount = 0;
$revokedCount = 0;
foreach ($rows as &$row) {
$row['is_expired'] = $row['status'] === 'active'
&& $row['expire_time']
&& strtotime($row['expire_time']) < time();
if ($row['is_expired']) {
$expiredCount++;
} elseif ($row['status'] === 'active') {
$activeCount++;
} elseif ($row['status'] === 'revoked') {
$revokedCount++;
}
}
$this->success([
'bot_qq' => $botQq,
'total' => count($rows),
'active_count' => $activeCount,
'expired_count' => $expiredCount,
'revoked_count' => $revokedCount,
'has_valid_auth' => $activeCount > 0,
'list' => $rows,
]);
}
/**
* 按联系人QQ查询授权状态
* GET /api/public/authorizations/query-by-contact?contact_qq=
*/
public function queryByContact(): void
{
$contactQq = trim($_GET['contact_qq'] ?? '');
if (empty($contactQq)) {
$this->error('请输入联系人QQ号');
}
$db = Database::getInstance();
$rows = $db->fetchAll(
"SELECT a.id, a.card_key, a.project_name, a.bot_qq, a.contact_qq, a.contact_name,
a.duration_days, a.status, a.authorized_at, a.expire_time
FROM {$db->table('authorizations')} a
WHERE a.contact_qq = ?
ORDER BY a.id DESC",
[$contactQq]
);
foreach ($rows as &$row) {
$row['is_expired'] = $row['status'] === 'active'
&& $row['expire_time']
&& strtotime($row['expire_time']) < time();
}
$this->success([
'contact_qq' => $contactQq,
'total' => count($rows),
'list' => $rows,
]);
}
/**
* 验证授权有效性(客户端调用)
* POST /api/public/authorizations/verify
* Body: { bot_qq, card_key?, contact_qq? }
*/
public function verify(): void
{
$input = $this->getJsonInput();
$botQq = trim($input['bot_qq'] ?? '');
$cardKey = trim($input['card_key'] ?? '');
$contactQq = trim($input['contact_qq'] ?? '');
if (empty($botQq)) {
$this->error('机器人QQ不能为空');
}
$db = Database::getInstance();
$now = date('Y-m-d H:i:s');
$where = 'WHERE a.bot_qq = ?';
$params = [$botQq];
if ($cardKey) {
$where .= ' AND a.card_key = ?';
$params[] = $cardKey;
}
if ($contactQq) {
$where .= ' AND a.contact_qq = ?';
$params[] = $contactQq;
}
$where .= " AND a.status = 'active' AND (a.expire_time IS NULL OR a.expire_time >= ?)";
$params[] = $now;
$auth = $db->fetch(
"SELECT a.* FROM {$db->table('authorizations')} a {$where} ORDER BY a.id DESC LIMIT 1",
$params
);
if (!$auth) {
$this->success([
'valid' => false,
'bot_qq' => $botQq,
'message' => '未找到有效授权',
'has_valid_auth' => false,
]);
return;
}
$this->success([
'valid' => true,
'bot_qq' => $auth['bot_qq'],
'contact_qq' => $auth['contact_qq'],
'card_key' => $auth['card_key'],
'project_name' => $auth['project_name'],
'expire_time' => $auth['expire_time'],
'days_left' => $auth['expire_time']
? max(0, (int) ceil((strtotime($auth['expire_time']) - time()) / 86400))
: -1,
'has_valid_auth' => true,
'message' => '授权有效',
]);
}
/**
* 授权统计
* GET /api/authorizations/stats
*/
public function stats(): void
{
$db = Database::getInstance();
$now = date('Y-m-d H:i:s');
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$db->table('authorizations')}");
$active = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('authorizations')}
WHERE status = 'active' AND (expire_time IS NULL OR expire_time >= ?)",
[$now]
);
$expired = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('authorizations')}
WHERE status = 'active' AND expire_time IS NOT NULL AND expire_time < ?",
[$now]
);
$revoked = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('authorizations')} WHERE status = 'revoked'"
);
$todayNew = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('authorizations')} WHERE DATE(authorized_at) = CURDATE()"
);
$this->success([
'total' => (int) $total,
'active' => (int) $active,
'expired' => (int) $expired,
'revoked' => (int) $revoked,
'today_new' => (int) $todayNew,
]);
}
/**
* 记录操作日志
*/
private function logAction(string $action, string $targetType, int $targetId, array $detail = []): void
{
try {
$db = Database::getInstance();
$userId = (int) ($_SERVER['HTTP_X_USER_ID'] ?? 0);
$db->insert(
"INSERT INTO {$db->table('logs')} (user_id, action, target_type, target_id, detail, ip, created_at)
VALUES (?, ?, ?, ?, ?, ?, NOW())",
[
$userId,
$action,
$targetType,
$targetId,
json_encode($detail, JSON_UNESCAPED_UNICODE),
$_SERVER['REMOTE_ADDR'] ?? '',
]
);
} catch (\Throwable $e) {
// 日志写入失败不影响主流程
}
}
}
@@ -0,0 +1,352 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Validator;
use App\Services\BlacklistService;
/**
* 黑名单管理控制器
*/
class BlacklistController extends Controller
{
/**
* 黑名单列表
* GET /api/blacklists
*/
public function list(): void
{
$db = Database::getInstance();
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$offset = ($page - 1) * $pageSize;
$targetType = $_GET['target_type'] ?? '';
$keyword = trim($_GET['keyword'] ?? '');
$status = $_GET['status'] ?? '';
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'created_at', 'updated_at']) ? $_GET['sort_by'] : 'id';
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
$where = "WHERE 1=1";
$params = [];
if ($targetType && in_array($targetType, ['user', 'ip'])) {
$where .= " AND target_type = ?";
$params[] = $targetType;
}
if ($status !== '') {
$where .= " AND status = ?";
$params[] = (int)$status;
}
if ($keyword) {
$where .= " AND (target_value LIKE ? OR remark LIKE ?)";
$params[] = "%{$keyword}%";
$params[] = "%{$keyword}%";
}
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$db->table('blacklists')} {$where}", $params);
$rows = $db->fetchAll(
"SELECT id, target_type, target_value, status, expire_time, operator_id, operator_name, remark, created_at, updated_at
FROM {$db->table('blacklists')} {$where}
ORDER BY {$sortBy} {$sortOrder}
LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $rows,
'total' => (int)$total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 添加黑名单
* POST /api/blacklists
*/
public function create(): void
{
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate([
'target_type' => 'required|in:user,ip',
'target_value' => 'required|max:255',
])) {
$this->error($validator->getFirstError());
}
$this->insertItem($input['target_type'], $input['target_value'], $input['expire_time'] ?? null, $input['remark'] ?? '');
(new BlacklistService())->clearCache();
logger('blacklist_create', 'blacklist', 0, [
'target_type' => $input['target_type'],
'target_value' => $input['target_value'],
'role' => ($this->getCurrentUser()['role'] ?? ''),
]);
$this->success(null, '黑名单添加成功');
}
/**
* 批量添加黑名单
* POST /api/blacklists/batch
*/
public function batchCreate(): void
{
$input = $this->getJsonInput();
$items = $input['items'] ?? [];
if (!is_array($items) || empty($items)) {
$this->error('请选择要添加的黑名单对象');
}
if (count($items) > 500) {
$this->error('单次批量添加不能超过500条');
}
$success = 0;
$failed = 0;
foreach ($items as $item) {
$type = $item['target_type'] ?? '';
$value = $item['target_value'] ?? '';
if (!in_array($type, ['user', 'ip']) || empty($value)) {
$failed++;
continue;
}
try {
$this->insertItem($type, $value, $item['expire_time'] ?? null, $item['remark'] ?? '');
$success++;
} catch (\Throwable $e) {
$failed++;
}
}
(new BlacklistService())->clearCache();
logger('blacklist_batch_create', 'blacklist', 0, ['success' => $success, 'failed' => $failed, 'role' => ($this->getCurrentUser()['role'] ?? '')]);
$this->success(['success' => $success, 'failed' => $failed], "批量添加完成,成功 {$success} 条,失败 {$failed} 条");
}
/**
* 更新黑名单状态/备注/过期时间
* PUT /api/blacklists/{id}
*/
public function update(int $id): void
{
$input = $this->getJsonInput();
$db = Database::getInstance();
$updates = [];
$params = [];
if (isset($input['status']) && in_array((int)$input['status'], [0, 1], true)) {
$updates[] = 'status = ?';
$params[] = (int)$input['status'];
}
if (array_key_exists('remark', $input)) {
$updates[] = 'remark = ?';
$params[] = $input['remark'];
}
if (array_key_exists('expire_time', $input)) {
$updates[] = 'expire_time = ?';
$params[] = empty($input['expire_time']) ? null : $input['expire_time'];
}
if (empty($updates)) {
$this->error('没有要更新的字段');
}
$params[] = $id;
$db->execute(
"UPDATE {$db->table('blacklists')} SET " . implode(', ', $updates) . " WHERE id = ?",
$params
);
(new BlacklistService())->clearCache();
logger('blacklist_update', 'blacklist', $id, array_merge($input, ['role' => ($this->getCurrentUser()['role'] ?? '')]));
$this->success(null, '黑名单更新成功');
}
/**
* 删除黑名单
* DELETE /api/blacklists/{id}
*/
public function delete(int $id): void
{
$db = Database::getInstance();
$db->execute("DELETE FROM {$db->table('blacklists')} WHERE id = ?", [$id]);
(new BlacklistService())->clearCache();
logger('blacklist_delete', 'blacklist', $id, ['role' => ($this->getCurrentUser()['role'] ?? '')]);
$this->success(null, '黑名单删除成功');
}
/**
* 批量删除黑名单
* POST /api/blacklists/batch-delete
*/
public function batchDelete(): void
{
$input = $this->getJsonInput();
$ids = $input['ids'] ?? [];
if (!is_array($ids) || empty($ids)) {
$this->error('请选择要删除的黑名单');
}
$ids = array_filter(array_map('intval', $ids));
if (empty($ids)) {
$this->error('无效的黑名单ID');
}
if (count($ids) > 500) {
$this->error('单次批量删除不能超过500条');
}
$db = Database::getInstance();
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$db->execute("DELETE FROM {$db->table('blacklists')} WHERE id IN ({$placeholders})", $ids);
(new BlacklistService())->clearCache();
logger('blacklist_batch_delete', 'blacklist', 0, ['count' => count($ids), 'role' => ($this->getCurrentUser()['role'] ?? '')]);
$this->success(['count' => count($ids)], '批量删除成功');
}
/**
* 导入黑名单(CSV)
* POST /api/blacklists/import
*/
public function import(): void
{
$file = $_FILES['file'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
$this->error('请上传CSV文件');
}
$handle = fopen($file['tmp_name'], 'r');
if (!$handle) {
$this->error('无法读取文件');
}
// 跳过 BOM
$bom = fread($handle, 3);
if ($bom !== "\xEF\xBB\xBF") {
rewind($handle);
}
$header = fgetcsv($handle);
if (!$header || !in_array('target_type', $header) || !in_array('target_value', $header)) {
fclose($handle);
$this->error('CSV格式错误,必须包含 target_type 和 target_value 列');
}
$success = 0;
$failed = 0;
$rowCount = 0;
while (($row = fgetcsv($handle)) !== false) {
$rowCount++;
if ($rowCount > 1000) break;
$data = array_combine($header, $row);
$type = $data['target_type'] ?? '';
$value = $data['target_value'] ?? '';
if (!in_array($type, ['user', 'ip']) || empty($value)) {
$failed++;
continue;
}
try {
$this->insertItem($type, $value, $data['expire_time'] ?? null, $data['remark'] ?? '');
$success++;
} catch (\Throwable $e) {
$failed++;
}
}
fclose($handle);
(new BlacklistService())->clearCache();
logger('blacklist_import', 'blacklist', 0, ['success' => $success, 'failed' => $failed, 'role' => ($this->getCurrentUser()['role'] ?? '')]);
$this->success(['success' => $success, 'failed' => $failed], "导入完成,成功 {$success} 条,失败 {$failed} 条");
}
/**
* 导出黑名单
* GET /api/blacklists/export
*/
public function export(): void
{
$ids = $_GET['ids'] ?? [];
if (!empty($ids) && !is_array($ids)) {
$ids = explode(',', $ids);
}
$db = Database::getInstance();
$params = [];
$where = "WHERE 1=1";
if (!empty($ids)) {
$ids = array_filter(array_map('intval', $ids));
$where .= " AND id IN (" . implode(',', array_fill(0, count($ids), '?')) . ")";
$params = $ids;
}
$rows = $db->fetchAll(
"SELECT target_type, target_value, status, expire_time, operator_name, remark, created_at
FROM {$db->table('blacklists')} {$where} ORDER BY id DESC LIMIT 50000",
$params
);
$filename = 'blacklist_export_' . date('YmdHis') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$output = fopen('php://output', 'w');
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($output, ['target_type', 'target_value', 'status', 'expire_time', 'operator_name', 'remark', 'created_at']);
foreach ($rows as $row) {
fputcsv($output, [
$row['target_type'],
$row['target_value'],
$row['status'],
$row['expire_time'] ?? '',
$row['operator_name'],
$row['remark'],
$row['created_at'],
]);
}
fclose($output);
exit;
}
/**
* 插入单条黑名单记录
*/
private function insertItem(string $type, string $value, ?string $expireTime, string $remark): void
{
$user = $this->getCurrentUser();
$db = Database::getInstance();
$expire = empty($expireTime) ? null : $expireTime;
$db->execute(
"INSERT INTO {$db->table('blacklists')} (target_type, target_value, status, expire_time, operator_id, operator_name, remark)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE status = VALUES(status), expire_time = VALUES(expire_time), remark = VALUES(remark), updated_at = NOW()",
[
$type,
$value,
1,
$expire,
$user['id'] ?? 0,
$user['username'] ?? 'system',
$remark,
]
);
}
}
+663
View File
@@ -0,0 +1,663 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Validator;
use App\Services\PermissionService;
use App\Services\SnowflakeService;
/**
* 卡密管理控制器
*/
class CardController extends Controller
{
/**
* 卡密列表
*/
/**
* 卡密列表
* GET /api/cards
* Query: project_id, card_type_id, status, keyword, start_date, end_date, sort_by, sort_order, page, page_size
*/
public function list(): void
{
$db = Database::getInstance();
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$offset = ($page - 1) * $pageSize;
$projectId = $_GET['project_id'] ?? '';
$status = $_GET['status'] ?? '';
$cardTypeId = $_GET['card_type_id'] ?? '';
$keyword = trim($_GET['keyword'] ?? '');
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'card_key', 'project_id', 'card_type_id', 'status', 'duration_days', 'expire_time', 'bound_at', 'created_at']) ? $_GET['sort_by'] : 'id';
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
$where = "WHERE 1=1";
$params = [];
// 数据范围权限过滤(管理员查看全部,代理仅查看自身及下级代理生成的卡密)
$scope = PermissionService::cardScope($this->getCurrentUser());
$where .= $scope['where'];
$params = array_merge($params, $scope['params']);
if ($projectId) {
$where .= " AND c.project_id = ?";
$params[] = $projectId;
}
if ($status) {
$where .= " AND c.status = ?";
$params[] = $status;
}
if ($cardTypeId) {
$where .= " AND c.card_type_id = ?";
$params[] = $cardTypeId;
}
if ($keyword) {
$where .= " AND c.card_key LIKE ?";
$params[] = "%{$keyword}%";
}
if ($startDate) {
$where .= " AND DATE(c.created_at) >= ?";
$params[] = $startDate;
}
if ($endDate) {
$where .= " AND DATE(c.created_at) <= ?";
$params[] = $endDate;
}
$total = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('cards')} c {$where}",
$params
);
$cards = $db->fetchAll(
"SELECT c.*, p.name AS project_name, ct.name AS card_type_name,
a.bot_qq, a.contact_qq, a.contact_name
FROM {$db->table('cards')} c
LEFT JOIN {$db->table('projects')} p ON c.project_id = p.id
LEFT JOIN {$db->table('card_types')} ct ON c.card_type_id = ct.id
LEFT JOIN {$db->table('authorizations')} a ON c.id = a.card_id
{$where}
ORDER BY c.{$sortBy} {$sortOrder}
LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $cards,
'total' => (int) $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 批量生成卡密
*/
public function generate(): void
{
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate([
'project_id' => 'required|integer',
'card_type_id' => 'required|integer',
'count' => 'required|integer',
])) {
$this->error($validator->getFirstError());
}
$projectId = (int) $input['project_id'];
$cardTypeId = (int) $input['card_type_id'];
$count = min((int) $input['count'], 10000); // 单次最多10000张
$remark = $input['remark'] ?? '';
$db = Database::getInstance();
// 验证项目存在
$project = $db->fetch("SELECT id FROM {$db->table('projects')} WHERE id = ? AND deleted_at IS NULL", [$projectId]);
if (!$project) {
$this->error('项目不存在');
}
// 验证卡密类型
$cardType = $db->fetch(
"SELECT * FROM {$db->table('card_types')} WHERE id = ? AND project_id = ?",
[$cardTypeId, $projectId]
);
if (!$cardType) {
$this->error('卡密类型不存在');
}
$userId = $this->getUserId();
$userRole = $this->getUserRole();
// 项目管理员:只能在自己负责的项目中生成卡密
if ($userRole === 'project_admin') {
$currentUser = $this->getCurrentUser();
$projectIds = $currentUser['project_ids'] ?? [];
if (!in_array($projectId, $projectIds)) {
$this->error('无权在此项目中生成卡密', 403);
}
}
// 代理身份:验证余额并扣费
$needDeduct = false;
$deductAmount = 0;
$quotaBefore = 0;
if ($userRole === 'agent') {
if ((float) $cardType['agent_cost'] <= 0) {
$this->error('该套餐未配置代理价格,无法生成');
}
$agent = $db->fetch("SELECT * FROM {$db->table('agents')} WHERE user_id = ?", [$userId]);
if (!$agent) {
$this->error('代理额度账户不存在,请联系管理员充值');
}
$remainQuota = (float) ($agent['total_quota'] ?? 0) - (float) ($agent['used_quota'] ?? 0) - (float) ($agent['frozen_quota'] ?? 0);
$totalCost = (float) $cardType['agent_cost'] * $count;
if ($remainQuota < $totalCost) {
$this->error("可用额度不足,需要 ¥{$totalCost},当前剩余 ¥{$remainQuota}");
}
$needDeduct = true;
$deductAmount = $totalCost;
$quotaBefore = $remainQuota;
}
$snowflake = new SnowflakeService();
$cards = [];
$db->beginTransaction();
try {
for ($i = 0; $i < $count; $i++) {
$cardKey = $snowflake->generateCardKey();
$db->insert(
"INSERT INTO {$db->table('cards')} (card_key, project_id, card_type_id, type, duration_days, status, use_user_id, remark) VALUES (?, ?, ?, ?, ?, 'unused', ?, ?)",
[$cardKey, $projectId, $cardTypeId, $cardType['name'], $cardType['duration_days'], $userId, $remark]
);
$cards[] = $cardKey;
}
// 代理扣费
if ($needDeduct) {
$db->execute(
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
[$deductAmount, $userId]
);
$quotaAfter = $quotaBefore - $deductAmount;
// 记录额度变动
$db->insert(
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
VALUES (?, 'consume', ?, ?, ?, 'card_generate', ?, ?, ?, NOW())",
[$userId, $deductAmount, $quotaBefore, $quotaAfter, $count, "生成{$count}张卡密", $this->getUserId()]
);
}
$db->commit();
} catch (\Throwable $e) {
$db->rollback();
$this->error('生成卡密失败: ' . $e->getMessage());
}
logger('generate_cards', 'card', 0, [
'count' => $count,
'project_id' => $projectId,
'card_type_id' => $cardTypeId,
'role' => $this->getUserRole(),
]);
$this->success([
'count' => $count,
'cards' => $cards,
], "成功生成{$count}张卡密");
}
/**
* 导出卡密
* GET /api/cards/export
* Query: ids, format(csv|excel), project_id, status, card_type_id
*/
public function export(): void
{
$projectId = $_GET['project_id'] ?? '';
$status = $_GET['status'] ?? '';
$cardTypeId = $_GET['card_type_id'] ?? '';
$ids = $_GET['ids'] ?? [];
$format = strtolower($_GET['format'] ?? 'csv');
if (!in_array($format, ['csv', 'excel'])) {
$format = 'csv';
}
$db = Database::getInstance();
$where = "WHERE 1=1";
$params = [];
if (!empty($ids)) {
$ids = is_array($ids) ? $ids : explode(',', $ids);
$ids = array_filter(array_map('intval', $ids));
if (!empty($ids)) {
$where .= " AND c.id IN (" . implode(',', array_fill(0, count($ids), '?')) . ")";
$params = array_merge($params, $ids);
}
}
if ($projectId) {
$where .= " AND c.project_id = ?";
$params[] = $projectId;
}
if ($status) {
$where .= " AND c.status = ?";
$params[] = $status;
}
if ($cardTypeId) {
$where .= " AND c.card_type_id = ?";
$params[] = $cardTypeId;
}
$cards = $db->fetchAll(
"SELECT c.card_key, c.type, c.status, c.duration_days, c.expire_time, c.bound_at, c.created_at,
p.name AS project_name
FROM {$db->table('cards')} c
LEFT JOIN {$db->table('projects')} p ON c.project_id = p.id
{$where}
ORDER BY c.id DESC
LIMIT 50000",
$params
);
if ($format === 'excel') {
$this->exportExcel($cards);
} else {
$this->exportCsv($cards);
}
}
/**
* 导出CSV
*/
private function exportCsv(array $cards): never
{
$filename = 'cards_export_' . date('YmdHis') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$output = fopen('php://output', 'w');
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($output, ['卡密', '项目', '类型', '有效天数', '状态', '绑定时间', '过期时间', '生成时间']);
$statusMap = ['unused' => '未使用', 'used' => '已使用', 'disabled' => '已禁用'];
foreach ($cards as $card) {
fputcsv($output, [
$card['card_key'],
$card['project_name'] ?? '',
$card['type'],
$card['duration_days'] == 0 ? '永久' : $card['duration_days'] . '天',
$statusMap[$card['status']] ?? $card['status'],
$card['bound_at'] ?? '',
$card['expire_time'] ?? '',
$card['created_at'],
]);
}
fclose($output);
exit;
}
/**
* 导出Excel (HTML表格伪Excel)
*/
private function exportExcel(array $cards): never
{
$filename = 'cards_export_' . date('YmdHis') . '.xls';
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$statusMap = ['unused' => '未使用', 'used' => '已使用', 'disabled' => '已禁用'];
$html = '<table border="1"><tr><th>卡密</th><th>项目</th><th>类型</th><th>有效天数</th><th>状态</th><th>绑定时间</th><th>过期时间</th><th>生成时间</th></tr>';
foreach ($cards as $card) {
$html .= '<tr>';
$html .= '<td>' . htmlspecialchars($card['card_key']) . '</td>';
$html .= '<td>' . htmlspecialchars($card['project_name'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($card['type']) . '</td>';
$html .= '<td>' . htmlspecialchars($card['duration_days'] == 0 ? '永久' : $card['duration_days'] . '天') . '</td>';
$html .= '<td>' . htmlspecialchars($statusMap[$card['status']] ?? $card['status']) . '</td>';
$html .= '<td>' . htmlspecialchars($card['bound_at'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($card['expire_time'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($card['created_at']) . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
exit;
}
/**
* 导入卡密
* POST /api/cards/import
* Body: multipart/form-data { file, project_id }
*/
public function import(): void
{
if (!isset($_FILES['file'])) {
$this->error('请上传文件');
}
$projectId = (int) ($_POST['project_id'] ?? 0);
$cardTypeId = (int) ($_POST['card_type_id'] ?? 0);
if (!$projectId) {
$this->error('请选择项目');
}
if (!$cardTypeId) {
$this->error('请选择套餐');
}
$db = Database::getInstance();
$userId = $this->getUserId();
$userRole = $this->getUserRole();
// 项目管理员:只能在自己负责的项目中导入卡密
if ($userRole === 'project_admin') {
$currentUser = $this->getCurrentUser();
$projectIds = $currentUser['project_ids'] ?? [];
if (!in_array($projectId, $projectIds)) {
$this->error('无权在此项目中导入卡密', 403);
}
}
$project = $db->fetch("SELECT id FROM {$db->table('projects')} WHERE id = ? AND deleted_at IS NULL", [$projectId]);
if (!$project) {
$this->error('项目不存在');
}
$cardType = $db->fetch(
"SELECT * FROM {$db->table('card_types')} WHERE id = ? AND project_id = ?",
[$cardTypeId, $projectId]
);
if (!$cardType) {
$this->error('套餐不存在或不属于该项目');
}
$file = $_FILES['file'];
if ($file['error'] !== UPLOAD_ERR_OK) {
$this->error('文件上传失败');
}
if ($file['size'] > 10 * 1024 * 1024) {
$this->error('文件大小不能超过10MB');
}
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, ['csv', 'xlsx', 'xls'])) {
$this->error('仅支持 CSV、Excel 格式');
}
// 先读取所有行,统计数量
$rows = [];
if ($ext === 'csv') {
$handle = fopen($file['tmp_name'], 'r');
if (!$handle) {
$this->error('无法读取文件');
}
$bom = fread($handle, 3);
if ($bom !== "\xEF\xBB\xBF") {
rewind($handle);
}
$header = fgetcsv($handle);
while (($row = fgetcsv($handle)) !== false) {
$cardKey = trim($row[0] ?? '');
if ($cardKey) {
$rows[] = $cardKey;
}
}
fclose($handle);
} else {
$this->error('Excel 解析暂不支持,请上传 CSV 文件');
}
$count = count($rows);
if ($count === 0) {
$this->error('文件中没有有效的卡密数据');
}
// 代理身份:验证余额并扣费
$needDeduct = false;
$deductAmount = 0;
$quotaBefore = 0;
if ($userRole === 'agent') {
if ((float) $cardType['agent_cost'] <= 0) {
$this->error('该套餐未配置代理价格,无法导入');
}
$agent = $db->fetch("SELECT * FROM {$db->table('agents')} WHERE user_id = ?", [$userId]);
if (!$agent) {
$this->error('代理额度账户不存在,请联系管理员充值');
}
$remainQuota = (float) ($agent['total_quota'] ?? 0) - (float) ($agent['used_quota'] ?? 0) - (float) ($agent['frozen_quota'] ?? 0);
$totalCost = (float) $cardType['agent_cost'] * $count;
if ($remainQuota < $totalCost) {
$this->error("可用额度不足,需要 ¥{$totalCost},当前剩余 ¥{$remainQuota}");
}
$needDeduct = true;
$deductAmount = $totalCost;
$quotaBefore = $remainQuota;
}
$snowflake = new SnowflakeService();
$db->beginTransaction();
try {
foreach ($rows as $cardKey) {
$db->insert(
"INSERT INTO {$db->table('cards')} (card_key, project_id, card_type_id, type, duration_days, status, use_user_id, created_at) VALUES (?, ?, ?, ?, ?, 'unused', ?, NOW())",
[$cardKey, $projectId, $cardTypeId, $cardType['name'], $cardType['duration_days'], $userId]
);
}
// 代理扣费
if ($needDeduct) {
$db->execute(
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
[$deductAmount, $userId]
);
$quotaAfter = $quotaBefore - $deductAmount;
$db->insert(
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
VALUES (?, 'deduct', ?, ?, ?, 'card_import', 0, ?, ?, NOW())",
[$agent['id'], $deductAmount, $quotaBefore, $quotaAfter, "导入{$count}张卡密", $userId]
);
}
$db->commit();
} catch (\Throwable $e) {
$db->rollback();
$this->error('导入失败: ' . $e->getMessage());
}
logger('import_cards', 'card', $projectId, ['count' => $count]);
$this->success([
'success_count' => $count,
'error_count' => 0,
'errors' => [],
], "成功导入 {$count} 张卡密");
}
/**
* 禁用/启用卡密
*/
public function toggleStatus(int $id): void
{
$input = $this->getJsonInput();
$status = $input['status'] ?? '';
if (!in_array($status, ['unused', 'disabled'])) {
$this->error('无效的状态值');
}
$db = Database::getInstance();
$card = $db->fetch("SELECT id, status FROM {$db->table('cards')} WHERE id = ?", [$id]);
if (!$card) {
$this->error('卡密不存在');
}
if ($card['status'] === 'used') {
$this->error('已使用的卡密不能修改状态');
}
$db->execute("UPDATE {$db->table('cards')} SET status = ? WHERE id = ?", [$status, $id]);
logger('toggle_card_status', 'card', $id, ['status' => $status]);
$this->success(null, '操作成功');
}
/**
* 卡密详情
*/
public function detail(int $id): void
{
$db = Database::getInstance();
$card = $db->fetch(
"SELECT c.*, p.name AS project_name, ct.name AS card_type_name,
a.bot_qq, a.contact_qq, a.contact_name
FROM {$db->table('cards')} c
LEFT JOIN {$db->table('projects')} p ON c.project_id = p.id
LEFT JOIN {$db->table('card_types')} ct ON c.card_type_id = ct.id
LEFT JOIN {$db->table('authorizations')} a ON c.id = a.card_id
WHERE c.id = ?",
[$id]
);
if (!$card) {
$this->error('卡密不存在', 404);
}
// 数据范围权限检查
$scope = PermissionService::cardScope($this->getCurrentUser());
if ($scope['where'] && !in_array((int) $card['use_user_id'], $scope['params'], true)) {
$this->error('无权查看该卡密', 403);
}
$card['bind_info'] = json_decode($card['bind_info'] ?? '{}', true);
$this->success($card);
}
/**
* 批量更新卡密状态
* POST /api/cards/batch-status
* Body: { ids: [int], status: 'unused'|'disabled' }
*/
public function batchStatus(): void
{
$input = $this->getJsonInput();
$ids = $input['ids'] ?? [];
$status = $input['status'] ?? '';
if (!is_array($ids) || empty($ids)) {
$this->error('请选择要更新的卡密');
}
if (!in_array($status, ['unused', 'disabled'], true)) {
$this->error('无效的状态值,只能是 unused 或 disabled');
}
$ids = array_filter(array_map('intval', $ids));
if (empty($ids)) {
$this->error('无效的卡密ID');
}
$db = Database::getInstance();
$placeholders = implode(',', array_fill(0, count($ids), '?'));
// 检查是否有已使用的卡密
$usedCount = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('cards')} WHERE id IN ({$placeholders}) AND status = 'used'",
$ids
);
if ($usedCount > 0) {
$this->error('已使用的卡密不能修改状态');
}
$db->execute(
"UPDATE {$db->table('cards')} SET status = ? WHERE id IN ({$placeholders})",
array_merge([$status], $ids)
);
logger('batch_toggle_card_status', 'card', 0, ['count' => count($ids), 'status' => $status]);
$this->success(['count' => count($ids)], '批量状态更新成功');
}
/**
* 批量删除卡密
* POST /api/cards/batch-delete
* Body: { ids: [int] }
*/
public function batchDelete(): void
{
$input = $this->getJsonInput();
$ids = $input['ids'] ?? [];
if (!is_array($ids) || empty($ids)) {
$this->error('请选择要删除的卡密');
}
$ids = array_filter(array_map('intval', $ids));
if (empty($ids)) {
$this->error('无效的卡密ID');
}
$db = Database::getInstance();
$placeholders = implode(',', array_fill(0, count($ids), '?'));
// 删除前记录日志
logger('batch_delete_cards', 'card', 0, ['count' => count($ids)]);
$db->execute(
"DELETE FROM {$db->table('cards')} WHERE id IN ({$placeholders})",
$ids
);
$this->success(['count' => count($ids)], '批量删除成功');
}
/**
* 卡密统计
* GET /api/cards/stats
*/
public function stats(): void
{
$db = Database::getInstance();
$projectId = $_GET['project_id'] ?? '';
$where = '';
$params = [];
if ($projectId) {
$where = "WHERE project_id = ?";
$params[] = $projectId;
}
$stats = $db->fetchAll(
"SELECT status, COUNT(*) AS count FROM {$db->table('cards')} {$where} GROUP BY status",
$params
);
$result = ['unused' => 0, 'used' => 0, 'disabled' => 0, 'total' => 0];
foreach ($stats as $row) {
$result[$row['status']] = (int) $row['count'];
$result['total'] += (int) $row['count'];
}
$this->success($result);
}
}
@@ -0,0 +1,300 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Validator;
/**
* 优惠码管理控制器
*/
class CouponController extends Controller
{
/**
* 优惠码列表
* GET /api/coupons
* Query: keyword, status, project_id, sort_by, sort_order, page, page_size
*/
public function list(): void
{
$db = Database::getInstance();
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$offset = ($page - 1) * $pageSize;
$keyword = trim($_GET['keyword'] ?? '');
$status = $_GET['status'] ?? '';
$projectId = $_GET['project_id'] ?? '';
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'code', 'name', 'discount_percent', 'used_count', 'max_use_count', 'min_amount', 'status', 'expire_at', 'created_at']) ? $_GET['sort_by'] : 'id';
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
$where = 'WHERE 1=1';
$params = [];
if ($keyword) {
$where .= ' AND (code LIKE ? OR name LIKE ?)';
$params[] = "%{$keyword}%";
$params[] = "%{$keyword}%";
}
if ($status !== '') {
$where .= ' AND status = ?';
$params[] = (int) $status;
}
if ($projectId !== '') {
$where .= ' AND (project_ids = ? OR project_ids LIKE ? OR project_ids LIKE ? OR project_ids = "")';
$params[] = (string) $projectId;
$params[] = "{$projectId},%";
$params[] = "%,{$projectId}";
}
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$db->table('coupons')} {$where}", $params);
$rows = $db->fetchAll(
"SELECT * FROM {$db->table('coupons')} {$where} ORDER BY {$sortBy} {$sortOrder} LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $rows,
'total' => (int) $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 创建优惠码
* POST /api/coupons
*/
public function create(): void
{
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate(['code' => 'required|min:2|max:32', 'discount_percent' => 'required|numeric'])) {
$this->error($validator->getFirstError());
}
$code = strtoupper(trim($input['code']));
$discountPercent = (float) $input['discount_percent'];
if ($discountPercent <= 0 || $discountPercent > 100) {
$this->error('折扣百分比必须在1-100之间');
}
$db = Database::getInstance();
$exists = $db->fetchColumn("SELECT id FROM {$db->table('coupons')} WHERE code = ?", [$code]);
if ($exists) {
$this->error('优惠码已存在');
}
$id = $db->insert(
"INSERT INTO {$db->table('coupons')} (code, name, discount_percent, max_use_count, min_amount, project_ids, status, expire_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
[
$code,
$input['name'] ?? '',
$discountPercent,
(int) ($input['max_use_count'] ?? 0),
(float) ($input['min_amount'] ?? 0),
$input['project_ids'] ?? '',
(int) ($input['status'] ?? 1),
$input['expire_at'] ?: null,
]
);
$this->success(['id' => $id], '优惠码创建成功');
}
/**
* 更新优惠码
* PUT /api/coupons/{id}
*/
public function update(int $id): void
{
$input = $this->getJsonInput();
$db = Database::getInstance();
$coupon = $db->fetch("SELECT * FROM {$db->table('coupons')} WHERE id = ?", [$id]);
if (!$coupon) {
$this->error('优惠码不存在', 404);
}
$updates = [];
$params = [];
foreach (['name', 'discount_percent', 'max_use_count', 'min_amount', 'project_ids', 'status', 'expire_at'] as $field) {
if (array_key_exists($field, $input)) {
$updates[] = "`{$field}` = ?";
$val = $input[$field];
if ($field === 'discount_percent') {
if ((float) $val <= 0 || (float) $val > 100) {
$this->error('折扣百分比必须在1-100之间');
}
$val = (float) $val;
}
$params[] = $field === 'expire_at' ? ($val ?: null) : $val;
}
}
if (empty($updates)) {
$this->error('没有需要更新的字段');
}
$params[] = $id;
$db->execute("UPDATE {$db->table('coupons')} SET " . implode(', ', $updates) . ' WHERE id = ?', $params);
$this->success(null, '更新成功');
}
/**
* 删除优惠码
* DELETE /api/coupons/{id}
*/
public function delete(int $id): void
{
$db = Database::getInstance();
$db->execute("DELETE FROM {$db->table('coupons')} WHERE id = ?", [$id]);
$this->success(null, '删除成功');
}
/**
* 导出优惠码
* GET /api/coupons/export
* Query: ids, format(csv|excel)
*/
public function export(): void
{
$ids = $_GET['ids'] ?? [];
$format = strtolower($_GET['format'] ?? 'csv');
if (!in_array($format, ['csv', 'excel'])) {
$format = 'csv';
}
$db = Database::getInstance();
$where = 'WHERE 1=1';
$params = [];
if (!empty($ids)) {
$ids = is_array($ids) ? $ids : explode(',', $ids);
$ids = array_filter(array_map('intval', $ids));
if (!empty($ids)) {
$where .= ' AND id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
$params = array_merge($params, $ids);
}
}
$rows = $db->fetchAll(
"SELECT * FROM {$db->table('coupons')} {$where} ORDER BY id DESC LIMIT 50000",
$params
);
if ($format === 'excel') {
$filename = 'coupons_export_' . date('YmdHis') . '.xls';
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$html = '<table border="1"><tr><th>ID</th><th>优惠码</th><th>名称</th><th>折扣%</th><th>已用/上限</th><th>最低消费</th><th>状态</th><th>过期时间</th><th>创建时间</th></tr>';
foreach ($rows as $row) {
$html .= '<tr>';
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['code']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['name'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['discount_percent']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['used_count'] . ' / ' . ($row['max_use_count'] > 0 ? $row['max_use_count'] : '不限')) . '</td>';
$html .= '<td>' . htmlspecialchars($row['min_amount']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['status'] == 1 ? '启用' : '禁用') . '</td>';
$html .= '<td>' . htmlspecialchars($row['expire_at'] ?? '永久有效') . '</td>';
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
exit;
}
$filename = 'coupons_export_' . date('YmdHis') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$output = fopen('php://output', 'w');
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($output, ['ID', '优惠码', '名称', '折扣%', '已用/上限', '最低消费', '状态', '过期时间', '创建时间']);
foreach ($rows as $row) {
fputcsv($output, [
$row['id'],
$row['code'],
$row['name'] ?? '',
$row['discount_percent'],
$row['used_count'] . ' / ' . ($row['max_use_count'] > 0 ? $row['max_use_count'] : '不限'),
$row['min_amount'],
$row['status'] == 1 ? '启用' : '禁用',
$row['expire_at'] ?? '永久有效',
$row['created_at'],
]);
}
fclose($output);
exit;
}
/**
* 公开接口:验证优惠码
* POST /api/public/coupons/validate
* Body: { code, project_id, amount }
*/
public function validate(): void
{
$input = $this->getJsonInput();
$code = strtoupper(trim($input['code'] ?? ''));
$projectId = (int) ($input['project_id'] ?? 0);
$amount = (float) ($input['amount'] ?? 0);
if (empty($code)) {
$this->error('请输入优惠码');
}
$db = Database::getInstance();
$coupon = $db->fetch(
"SELECT * FROM {$db->table('coupons')} WHERE code = ? AND status = 1",
[$code]
);
if (!$coupon) {
$this->success(['valid' => false, 'message' => '优惠码不存在或已失效']);
return;
}
if ($coupon['expire_at'] && strtotime($coupon['expire_at']) < time()) {
$this->success(['valid' => false, 'message' => '优惠码已过期']);
return;
}
if ($coupon['max_use_count'] > 0 && $coupon['used_count'] >= $coupon['max_use_count']) {
$this->success(['valid' => false, 'message' => '优惠码已达使用上限']);
return;
}
if ($coupon['min_amount'] > 0 && $amount < $coupon['min_amount']) {
$this->success(['valid' => false, 'message' => "订单金额需满¥{$coupon['min_amount']}"]);
return;
}
if ($coupon['project_ids'] && $projectId) {
$allowedProjects = array_map('trim', explode(',', $coupon['project_ids']));
if (!in_array((string) $projectId, $allowedProjects)) {
$this->success(['valid' => false, 'message' => '该优惠码不适用于此项目']);
return;
}
}
$discountAmount = round($amount * ($coupon['discount_percent'] / 100), 2);
$this->success([
'valid' => true,
'message' => '优惠码有效',
'coupon_id' => $coupon['id'],
'code' => $coupon['code'],
'discount_percent' => (float) $coupon['discount_percent'],
'discount_amount' => $discountAmount,
'final_amount' => max(0, round($amount - $discountAmount, 2)),
]);
}
}
@@ -0,0 +1,244 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
/**
* Dashboard与统计控制器
*/
class DashboardController extends Controller
{
/**
* 首页Dashboard数据
*/
public function index(): void
{
$db = Database::getInstance();
$userRole = $this->getUserRole();
$userId = $this->getUserId();
$data = [];
if ($userRole === 'admin') {
// 项目总数
$data['total_projects'] = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('projects')} WHERE deleted_at IS NULL"
);
// 用户总数
$data['total_users'] = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('users')} WHERE deleted_at IS NULL"
);
// 卡密总数
$data['total_cards'] = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('cards')}"
);
// 已使用卡密
$data['used_cards'] = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('cards')} WHERE status = 'used'"
);
// 订单总数
$data['total_orders'] = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('orders')}"
);
// 已支付订单
$data['paid_orders'] = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('orders')} WHERE status = 'paid'"
);
// 总收入
$data['total_revenue'] = (float) $db->fetchColumn(
"SELECT COALESCE(SUM(amount), 0) FROM {$db->table('orders')} WHERE status = 'paid'"
);
// 今日收入
$data['today_revenue'] = (float) $db->fetchColumn(
"SELECT COALESCE(SUM(amount), 0) FROM {$db->table('orders')} WHERE status = 'paid' AND DATE(paid_at) = CURDATE()"
);
// 代理总数
$data['total_agents'] = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('users')} WHERE role = 'agent' AND deleted_at IS NULL"
);
// 近7天订单趋势
$data['order_trend'] = $db->fetchAll(
"SELECT DATE(created_at) AS date, COUNT(*) AS count, COALESCE(SUM(CASE WHEN status='paid' THEN amount ELSE 0 END), 0) AS amount
FROM {$db->table('orders')}
WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY DATE(created_at)
ORDER BY date ASC"
);
} elseif ($userRole === 'agent') {
// 代理数据
$agent = $db->fetch(
"SELECT total_quota, used_quota, frozen_quota FROM {$db->table('agents')} WHERE user_id = ?",
[$userId]
);
$data['agent_quota'] = $agent ?: ['total_quota' => 0, 'used_quota' => 0, 'frozen_quota' => 0];
$data['remain_quota'] = (float) ($data['agent_quota']['total_quota'] ?? 0) - (float) ($data['agent_quota']['used_quota'] ?? 0);
// 代理生成的卡密总数
$data['total_authorized'] = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('cards')} WHERE use_user_id = ?",
[$userId]
);
// 今日生成卡密数
$data['today_authorized'] = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('cards')} WHERE use_user_id = ? AND DATE(created_at) = CURDATE()",
[$userId]
);
}
$this->success($data);
}
/**
* 操作日志列表
* GET /api/logs
* Query: action, user_id, username, start_date, end_date, sort_by, sort_order, page, page_size
*/
public function logs(): void
{
$db = Database::getInstance();
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$offset = ($page - 1) * $pageSize;
$action = $_GET['action'] ?? '';
$userId = $_GET['user_id'] ?? '';
$username = trim($_GET['username'] ?? '');
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'user_id', 'action', 'target_type', 'target_id', 'created_at']) ? $_GET['sort_by'] : 'id';
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
$where = "WHERE 1=1";
$params = [];
if ($action) {
$where .= " AND l.action = ?";
$params[] = $action;
}
if ($userId) {
$where .= " AND l.user_id = ?";
$params[] = $userId;
}
if ($username) {
$where .= " AND (u.username LIKE ? OR u.nickname LIKE ?)";
$params[] = "%{$username}%";
$params[] = "%{$username}%";
}
if ($startDate) {
$where .= " AND DATE(l.created_at) >= ?";
$params[] = $startDate;
}
if ($endDate) {
$where .= " AND DATE(l.created_at) <= ?";
$params[] = $endDate;
}
$total = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('logs')} l LEFT JOIN {$db->table('users')} u ON l.user_id = u.id {$where}",
$params
);
$logs = $db->fetchAll(
"SELECT l.*, u.username, u.nickname
FROM {$db->table('logs')} l
LEFT JOIN {$db->table('users')} u ON l.user_id = u.id
{$where}
ORDER BY l.{$sortBy} {$sortOrder}
LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $logs,
'total' => (int) $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 导出日志
* GET /api/logs/export
* Query: ids, format(csv|excel)
*/
public function exportLogs(): void
{
$ids = $_GET['ids'] ?? [];
$format = strtolower($_GET['format'] ?? 'csv');
if (!in_array($format, ['csv', 'excel'])) {
$format = 'csv';
}
$db = Database::getInstance();
$where = 'WHERE 1=1';
$params = [];
if (!empty($ids)) {
$ids = is_array($ids) ? $ids : explode(',', $ids);
$ids = array_filter(array_map('intval', $ids));
if (!empty($ids)) {
$where .= ' AND l.id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
$params = array_merge($params, $ids);
}
}
$rows = $db->fetchAll(
"SELECT l.*, u.username, u.nickname
FROM {$db->table('logs')} l
LEFT JOIN {$db->table('users')} u ON l.user_id = u.id
{$where}
ORDER BY l.id DESC
LIMIT 50000",
$params
);
if ($format === 'excel') {
$filename = 'logs_export_' . date('YmdHis') . '.xls';
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$html = '<table border="1"><tr><th>ID</th><th>用户</th><th>昵称</th><th>操作类型</th><th>目标类型</th><th>目标ID</th><th>详情</th><th>IP</th><th>时间</th></tr>';
foreach ($rows as $row) {
$html .= '<tr>';
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['username'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['nickname'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['action']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['target_type']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['target_id']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['detail'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['ip'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
exit;
}
$filename = 'logs_export_' . date('YmdHis') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$output = fopen('php://output', 'w');
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($output, ['ID', '用户', '昵称', '操作类型', '目标类型', '目标ID', '详情', 'IP', '时间']);
foreach ($rows as $row) {
fputcsv($output, [
$row['id'],
$row['username'] ?? '',
$row['nickname'] ?? '',
$row['action'],
$row['target_type'],
$row['target_id'],
$row['detail'] ?? '',
$row['ip'] ?? '',
$row['created_at'],
]);
}
fclose($output);
exit;
}
}
+278
View File
@@ -0,0 +1,278 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Validator;
/**
* 订单管理控制器
*/
class OrderController extends Controller
{
/**
* 订单列表
*/
/**
* 订单列表
* GET /api/orders
* Query: status, pay_type, project_id, keyword, start_date, end_date, sort_by, sort_order, page, page_size
*/
public function list(): void
{
$db = Database::getInstance();
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$offset = ($page - 1) * $pageSize;
$status = $_GET['status'] ?? '';
$payType = $_GET['pay_type'] ?? '';
$projectId = $_GET['project_id'] ?? '';
$keyword = trim($_GET['keyword'] ?? '');
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'amount', 'status', 'pay_type', 'paid_at', 'created_at']) ? $_GET['sort_by'] : 'id';
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
$where = "WHERE 1=1";
$params = [];
if ($status) {
$where .= " AND o.status = ?";
$params[] = $status;
}
if ($payType) {
$where .= " AND o.pay_type = ?";
$params[] = $payType;
}
if ($projectId) {
$where .= " AND o.project_id = ?";
$params[] = $projectId;
}
if ($keyword) {
$where .= " AND (o.order_no LIKE ? OR o.trade_no LIKE ? OR c.card_key LIKE ?)";
$params[] = "%{$keyword}%";
$params[] = "%{$keyword}%";
$params[] = "%{$keyword}%";
}
if ($startDate) {
$where .= " AND DATE(o.created_at) >= ?";
$params[] = $startDate;
}
if ($endDate) {
$where .= " AND DATE(o.created_at) <= ?";
$params[] = $endDate;
}
$total = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('orders')} o {$where}",
$params
);
$orders = $db->fetchAll(
"SELECT o.*, p.name AS project_name, ct.name AS card_type_name
FROM {$db->table('orders')} o
LEFT JOIN {$db->table('projects')} p ON o.project_id = p.id
LEFT JOIN {$db->table('card_types')} ct ON o.card_type_id = ct.id
{$where}
ORDER BY o.{$sortBy} {$sortOrder}
LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $orders,
'total' => (int) $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 订单详情
*/
public function detail(int $id): void
{
$db = Database::getInstance();
$order = $db->fetch(
"SELECT o.*, p.name AS project_name, ct.name AS card_type_name, c.card_key
FROM {$db->table('orders')} o
LEFT JOIN {$db->table('projects')} p ON o.project_id = p.id
LEFT JOIN {$db->table('card_types')} ct ON o.card_type_id = ct.id
LEFT JOIN {$db->table('cards')} c ON o.card_id = c.id
WHERE o.id = ?",
[$id]
);
if (!$order) {
$this->error('订单不存在', 404);
}
$this->success($order);
}
/**
* 手动补单 (Admin操作)
*/
public function manualComplete(int $id): void
{
if ($this->getUserRole() !== 'admin') {
$this->error('仅管理员可执行此操作', 403);
}
$db = Database::getInstance();
$order = $db->fetch("SELECT * FROM {$db->table('orders')} WHERE id = ?", [$id]);
if (!$order) {
$this->error('订单不存在');
}
if ($order['status'] !== 'pending') {
$this->error('订单状态不允许补单');
}
$this->processOrderPaid($order['id']);
logger('manual_complete_order', 'order', $id);
$this->success(null, '补单成功');
}
/**
* 导出订单
* GET /api/orders/export
* Query: ids, format(csv|excel)
*/
public function export(): void
{
$ids = $_GET['ids'] ?? [];
$format = strtolower($_GET['format'] ?? 'csv');
if (!in_array($format, ['csv', 'excel'])) {
$format = 'csv';
}
$db = Database::getInstance();
$where = 'WHERE 1=1';
$params = [];
if (!empty($ids)) {
$ids = is_array($ids) ? $ids : explode(',', $ids);
$ids = array_filter(array_map('intval', $ids));
if (!empty($ids)) {
$where .= ' AND o.id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
$params = array_merge($params, $ids);
}
}
$rows = $db->fetchAll(
"SELECT o.*, p.name AS project_name, ct.name AS card_type_name, c.card_key
FROM {$db->table('orders')} o
LEFT JOIN {$db->table('projects')} p ON o.project_id = p.id
LEFT JOIN {$db->table('card_types')} ct ON o.card_type_id = ct.id
LEFT JOIN {$db->table('cards')} c ON o.card_id = c.id
{$where}
ORDER BY o.id DESC
LIMIT 50000",
$params
);
$payTypeMap = ['alipay' => '支付宝', 'wxpay' => '微信', 'qqpay' => 'QQ钱包'];
$statusMap = ['pending' => '待支付', 'paid' => '已支付', 'expired' => '已过期', 'refunded' => '已退款'];
if ($format === 'excel') {
$filename = 'orders_export_' . date('YmdHis') . '.xls';
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$html = '<table border="1"><tr><th>订单号</th><th>项目</th><th>套餐</th><th>金额</th><th>支付方式</th><th>状态</th><th>卡密</th><th>支付时间</th><th>创建时间</th></tr>';
foreach ($rows as $row) {
$html .= '<tr>';
$html .= '<td>' . htmlspecialchars($row['order_no']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['project_name'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['card_type_name'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['amount']) . '</td>';
$html .= '<td>' . htmlspecialchars($payTypeMap[$row['pay_type']] ?? ($row['pay_type'] ?: '-')) . '</td>';
$html .= '<td>' . htmlspecialchars($statusMap[$row['status']] ?? $row['status']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['card_key'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['paid_at'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
exit;
}
$filename = 'orders_export_' . date('YmdHis') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$output = fopen('php://output', 'w');
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($output, ['订单号', '项目', '套餐', '金额', '支付方式', '状态', '卡密', '支付时间', '创建时间']);
foreach ($rows as $row) {
fputcsv($output, [
$row['order_no'],
$row['project_name'] ?? '',
$row['card_type_name'] ?? '',
$row['amount'],
$payTypeMap[$row['pay_type']] ?? ($row['pay_type'] ?: '-'),
$statusMap[$row['status']] ?? $row['status'],
$row['card_key'] ?? '',
$row['paid_at'] ?? '',
$row['created_at'],
]);
}
fclose($output);
exit;
}
/**
* 处理支付成功
*/
public function processOrderPaid(int $orderId): void
{
$db = Database::getInstance();
$order = $db->fetch("SELECT * FROM {$db->table('orders')} WHERE id = ?", [$orderId]);
if (!$order || $order['status'] !== 'pending') return;
$snowflake = new \App\Services\SnowflakeService();
$cardKey = $snowflake->generateCardKey();
$cardType = $db->fetch(
"SELECT * FROM {$db->table('card_types')} WHERE id = ?",
[$order['card_type_id']]
);
$expireTime = null;
$durationDays = $cardType['duration_days'] ?? 0;
if ($durationDays > 0) {
$expireTime = date('Y-m-d H:i:s', strtotime("+{$durationDays} days"));
}
$db->beginTransaction();
try {
// 创建卡密
$cardId = $db->insert(
"INSERT INTO {$db->table('cards')} (card_key, project_id, card_type_id, type, duration_days, status, expire_time, order_id, remark)
VALUES (?, ?, ?, ?, ?, 'unused', ?, ?, '在线购买')",
[
$cardKey,
$order['project_id'],
$order['card_type_id'],
$cardType['name'] ?? '',
$durationDays,
$expireTime,
$orderId,
]
);
// 更新订单
$db->execute(
"UPDATE {$db->table('orders')} SET status = 'paid', card_id = ?, paid_at = NOW() WHERE id = ?",
[$cardId, $orderId]
);
$db->commit();
} catch (\Throwable $e) {
$db->rollback();
throw $e;
}
}
}
@@ -0,0 +1,485 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Validator;
/**
* 项目管理控制器
*/
class ProjectController extends Controller
{
/**
* 项目列表
*/
public function list(): void
{
$db = Database::getInstance();
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$keyword = trim($_GET['keyword'] ?? '');
$offset = ($page - 1) * $pageSize;
$userRole = $this->getUserRole();
$userId = $this->getUserId();
$where = "WHERE deleted_at IS NULL";
$params = [];
// 项目管理员只能看到自己的项目
if ($userRole === 'project_admin') {
$user = $this->getCurrentUser();
$projectIds = json_decode($user['project_ids'] ?? '[]', true) ?: [];
if (empty($projectIds)) {
$this->success(['list' => [], 'total' => 0, 'page' => $page, 'page_size' => $pageSize]);
return;
}
$placeholders = implode(',', array_fill(0, count($projectIds), '?'));
$where .= " AND id IN ({$placeholders})";
$params = $projectIds;
}
if ($keyword) {
$where .= " AND name LIKE ?";
$params[] = "%{$keyword}%";
}
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$db->table('projects')} {$where}", $params);
$projects = $db->fetchAll(
"SELECT * FROM {$db->table('projects')} {$where} ORDER BY id DESC LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $projects,
'total' => (int) $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 项目详情
*/
public function detail(int $id): void
{
$db = Database::getInstance();
$project = $db->fetch("SELECT * FROM {$db->table('projects')} WHERE id = ? AND deleted_at IS NULL", [$id]);
if (!$project) {
$this->error('项目不存在', 404);
}
// 获取卡密类型
$types = $db->fetchAll(
"SELECT * FROM {$db->table('card_types')} WHERE project_id = ? AND status = 1 ORDER BY sort ASC",
[$id]
);
$project['card_types'] = $types;
$this->success($project);
}
/**
* 创建项目
*/
public function create(): void
{
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate(['name' => 'required|min:1|max:100'])) {
$this->error($validator->getFirstError());
}
$db = Database::getInstance();
$apiKey = 'ak_' . bin2hex(random_bytes(16));
$id = $db->insert(
"INSERT INTO {$db->table('projects')} (name, description, api_key, status) VALUES (?, ?, ?, ?)",
[$input['name'], $input['description'] ?? '', $apiKey, $input['status'] ?? 1]
);
logger('create_project', 'project', $id, ['name' => $input['name']]);
$this->success(['id' => $id, 'api_key' => $apiKey], '项目创建成功');
}
/**
* 更新项目
*/
public function update(int $id): void
{
$input = $this->getJsonInput();
$db = Database::getInstance();
$project = $db->fetch("SELECT id FROM {$db->table('projects')} WHERE id = ? AND deleted_at IS NULL", [$id]);
if (!$project) {
$this->error('项目不存在');
}
$updates = [];
$params = [];
foreach (['name', 'description', 'status'] as $field) {
if (isset($input[$field])) {
$updates[] = "{$field} = ?";
$params[] = $input[$field];
}
}
if (empty($updates)) {
$this->error('没有需要更新的字段');
}
$params[] = $id;
$db->execute("UPDATE {$db->table('projects')} SET " . implode(', ', $updates) . " WHERE id = ?", $params);
logger('update_project', 'project', $id);
$this->success(null, '更新成功');
}
/**
* 删除项目
*/
public function delete(int $id): void
{
$db = Database::getInstance();
$db->execute("UPDATE {$db->table('projects')} SET deleted_at = NOW() WHERE id = ?", [$id]);
logger('delete_project', 'project', $id);
$this->success(null, '删除成功');
}
/**
* 重新生成API Key
*/
public function regenerateApiKey(int $id): void
{
$db = Database::getInstance();
$apiKey = 'ak_' . bin2hex(random_bytes(16));
$db->execute("UPDATE {$db->table('projects')} SET api_key = ? WHERE id = ?", [$apiKey, $id]);
logger('regenerate_api_key', 'project', $id);
$this->success(['api_key' => $apiKey], 'API Key已重新生成');
}
/**
* 获取项目的卡密类型列表
*/
public function cardTypes(int $projectId): void
{
$db = Database::getInstance();
$types = $db->fetchAll(
"SELECT * FROM {$db->table('card_types')} WHERE project_id = ? ORDER BY sort ASC",
[$projectId]
);
$this->success($types);
}
/**
* 创建卡密类型
*/
public function createCardType(int $projectId): void
{
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate([
'name' => 'required|min:1|max:50',
'duration_days' => 'required|integer',
'price' => 'required|numeric',
'agent_cost' => 'required|numeric',
])) {
$this->error($validator->getFirstError());
}
$db = Database::getInstance();
$id = $db->insert(
"INSERT INTO {$db->table('card_types')} (project_id, name, description, duration_days, price, original_price, agent_cost, sort, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
[
$projectId,
$input['name'],
$input['description'] ?? '',
(int) $input['duration_days'],
(float) $input['price'],
(float) ($input['original_price'] ?? 0),
(float) $input['agent_cost'],
$input['sort'] ?? 0,
$input['status'] ?? 1,
]
);
logger('create_card_type', 'card_type', $id, ['project_id' => $projectId, 'name' => $input['name']]);
$this->success(['id' => $id], '卡密类型创建成功');
}
/**
* 更新卡密类型
*/
public function updateCardType(int $projectId, int $typeId): void
{
$input = $this->getJsonInput();
$db = Database::getInstance();
$updates = [];
$params = [];
foreach (['name', 'description', 'duration_days', 'price', 'original_price', 'agent_cost', 'sort', 'status'] as $field) {
if (isset($input[$field])) {
$updates[] = "{$field} = ?";
$params[] = $input[$field];
}
}
if (empty($updates)) {
$this->error('没有需要更新的字段');
}
$params[] = $typeId;
$params[] = $projectId;
$db->execute(
"UPDATE {$db->table('card_types')} SET " . implode(', ', $updates) . " WHERE id = ? AND project_id = ?",
$params
);
$this->success(null, '更新成功');
}
/**
* 删除卡密类型
*/
public function deleteCardType(int $projectId, int $typeId): void
{
$db = Database::getInstance();
$db->execute("DELETE FROM {$db->table('card_types')} WHERE id = ? AND project_id = ?", [$typeId, $projectId]);
$this->success(null, '删除成功');
}
/**
* 所有项目简单列表 (下拉选项用)
*/
public function allProjects(): void
{
$db = Database::getInstance();
$projects = $db->fetchAll(
"SELECT id, name FROM {$db->table('projects')} WHERE status = 1 AND deleted_at IS NULL ORDER BY id DESC"
);
$this->success($projects);
}
/**
* 获取所有项目的商品列表 (全量,用于商品管理页面)
*/
public function allProducts(): void
{
$db = Database::getInstance();
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$offset = ($page - 1) * $pageSize;
$projectId = $_GET['project_id'] ?? '';
$keyword = trim($_GET['keyword'] ?? '');
$status = $_GET['status'] ?? '';
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'name', 'price', 'agent_cost', 'sort', 'status', 'created_at']) ? $_GET['sort_by'] : 'id';
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
$where = 'WHERE 1=1';
$params = [];
if ($projectId) {
$where .= ' AND ct.project_id = ?';
$params[] = $projectId;
}
if ($status !== '') {
$where .= ' AND ct.status = ?';
$params[] = (int) $status;
}
if ($keyword) {
$where .= ' AND ct.name LIKE ?';
$params[] = "%{$keyword}%";
}
$total = $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('card_types')} ct {$where}",
$params
);
$products = $db->fetchAll(
"SELECT ct.*, p.name AS project_name
FROM {$db->table('card_types')} ct
LEFT JOIN {$db->table('projects')} p ON ct.project_id = p.id
{$where}
ORDER BY ct.{$sortBy} {$sortOrder}
LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $products,
'total' => (int) $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 导出商品
* GET /api/products/export
* Query: ids, format(csv|excel)
*/
public function productsExport(): void
{
$ids = $_GET['ids'] ?? [];
$format = strtolower($_GET['format'] ?? 'csv');
if (!in_array($format, ['csv', 'excel'])) {
$format = 'csv';
}
$db = Database::getInstance();
$where = 'WHERE 1=1';
$params = [];
if (!empty($ids)) {
$ids = is_array($ids) ? $ids : explode(',', $ids);
$ids = array_filter(array_map('intval', $ids));
if (!empty($ids)) {
$where .= ' AND ct.id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
$params = array_merge($params, $ids);
}
}
$rows = $db->fetchAll(
"SELECT ct.*, p.name AS project_name
FROM {$db->table('card_types')} ct
LEFT JOIN {$db->table('projects')} p ON ct.project_id = p.id
{$where}
ORDER BY ct.id DESC LIMIT 50000",
$params
);
if ($format === 'excel') {
$filename = 'products_export_' . date('YmdHis') . '.xls';
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$html = '<table border="1"><tr><th>ID</th><th>所属项目</th><th>商品名称</th><th>有效天数</th><th>售价</th><th>原价</th><th>代理价格</th><th>排序</th><th>状态</th><th>创建时间</th></tr>';
foreach ($rows as $row) {
$html .= '<tr>';
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['project_name'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['name']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['duration_days'] == 0 ? '永久' : $row['duration_days'] . '天') . '</td>';
$html .= '<td>' . htmlspecialchars($row['price']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['original_price'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['agent_cost']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['sort']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['status'] == 1 ? '启用' : '禁用') . '</td>';
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
exit;
}
$filename = 'products_export_' . date('YmdHis') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$output = fopen('php://output', 'w');
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($output, ['ID', '所属项目', '商品名称', '有效天数', '售价', '原价', '代理价格', '排序', '状态', '创建时间']);
foreach ($rows as $row) {
fputcsv($output, [
$row['id'],
$row['project_name'] ?? '',
$row['name'],
$row['duration_days'] == 0 ? '永久' : $row['duration_days'] . '天',
$row['price'],
$row['original_price'] ?? '',
$row['agent_cost'],
$row['sort'],
$row['status'] == 1 ? '启用' : '禁用',
$row['created_at'],
]);
}
fclose($output);
exit;
}
/**
* 导出项目
* GET /api/projects/export
* Query: ids, format(csv|excel)
*/
public function export(): void
{
$ids = $_GET['ids'] ?? [];
$format = strtolower($_GET['format'] ?? 'csv');
if (!in_array($format, ['csv', 'excel'])) {
$format = 'csv';
}
$db = Database::getInstance();
$where = 'WHERE deleted_at IS NULL';
$params = [];
if (!empty($ids)) {
$ids = is_array($ids) ? $ids : explode(',', $ids);
$ids = array_filter(array_map('intval', $ids));
if (!empty($ids)) {
$where .= ' AND id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
$params = array_merge($params, $ids);
}
}
$rows = $db->fetchAll(
"SELECT id, name, description, api_key, status, created_at FROM {$db->table('projects')} {$where} ORDER BY id DESC LIMIT 50000",
$params
);
if ($format === 'excel') {
$filename = 'projects_export_' . date('YmdHis') . '.xls';
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$html = '<table border="1"><tr><th>ID</th><th>项目名称</th><th>描述</th><th>API Key</th><th>状态</th><th>创建时间</th></tr>';
foreach ($rows as $row) {
$html .= '<tr>';
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['name']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['description'] ?? '') . '</td>';
$html .= '<td>' . htmlspecialchars($row['api_key']) . '</td>';
$html .= '<td>' . htmlspecialchars($row['status'] == 1 ? '启用' : '禁用') . '</td>';
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
exit;
}
$filename = 'projects_export_' . date('YmdHis') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache');
$output = fopen('php://output', 'w');
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($output, ['ID', '项目名称', '描述', 'API Key', '状态', '创建时间']);
foreach ($rows as $row) {
fputcsv($output, [
$row['id'],
$row['name'],
$row['description'] ?? '',
$row['api_key'],
$row['status'] == 1 ? '启用' : '禁用',
$row['created_at'],
]);
}
fclose($output);
exit;
}
}
@@ -0,0 +1,461 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Validator;
/**
* 公开接口控制器
* 包含:购买页、查询页、授权验证、支付回调
*/
class PublicController extends Controller
{
/**
* 获取可购买的项目列表
*/
public function projects(): void
{
$db = Database::getInstance();
$projects = $db->fetchAll(
"SELECT id, name, description FROM {$db->table('projects')} WHERE status = 1 AND deleted_at IS NULL ORDER BY id DESC"
);
$this->success($projects);
}
/**
* 获取项目的卡密类型(套餐)列表
*/
public function cardTypes(int $projectId): void
{
$db = Database::getInstance();
$types = $db->fetchAll(
"SELECT id, name, description, duration_days, price, original_price FROM {$db->table('card_types')}
WHERE project_id = ? AND status = 1 ORDER BY sort ASC",
[$projectId]
);
$this->success($types);
}
/**
* 创建订单并发起支付
*/
public function createOrder(): void
{
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate([
'project_id' => 'required|integer',
'card_type_id' => 'required|integer',
'pay_type' => 'required',
])) {
$this->error($validator->getFirstError());
}
$projectId = (int) $input['project_id'];
$cardTypeId = (int) $input['card_type_id'];
$payType = $input['pay_type'];
$contactInfo = $input['contact_info'] ?? '';
$couponCode = strtoupper(trim($input['coupon_code'] ?? ''));
$botQq = trim($input['bot_qq'] ?? '');
$contactQq = trim($input['contact_qq'] ?? '');
if (!in_array($payType, ['alipay', 'wxpay', 'qqpay'])) {
$this->error('不支持的支付方式');
}
$db = Database::getInstance();
// 验证项目
$project = $db->fetch(
"SELECT id, name FROM {$db->table('projects')} WHERE id = ? AND status = 1 AND deleted_at IS NULL",
[$projectId]
);
if (!$project) {
$this->error('项目不存在或已下架');
}
// 验证卡密类型
$cardType = $db->fetch(
"SELECT * FROM {$db->table('card_types')} WHERE id = ? AND project_id = ? AND status = 1",
[$cardTypeId, $projectId]
);
if (!$cardType) {
$this->error('套餐不存在或已下架');
}
if ((float) $cardType['price'] <= 0) {
$this->error('套餐价格配置错误');
}
$originalAmount = (float) $cardType['price'];
$finalAmount = $originalAmount;
$validCoupon = null;
// 验证优惠码
if ($couponCode) {
$validCoupon = $db->fetch(
"SELECT * FROM {$db->table('coupons')} WHERE code = ? AND status = 1",
[$couponCode]
);
if (!$validCoupon) {
$this->error('优惠码不存在或已失效');
}
if ($validCoupon['expire_at'] && strtotime($validCoupon['expire_at']) < time()) {
$this->error('优惠码已过期');
}
if ($validCoupon['max_use_count'] > 0 && $validCoupon['used_count'] >= $validCoupon['max_use_count']) {
$this->error('优惠码已达使用上限');
}
if ($validCoupon['min_amount'] > 0 && $originalAmount < $validCoupon['min_amount']) {
$this->error("订单金额需满¥{$validCoupon['min_amount']}");
}
if ($validCoupon['project_ids']) {
$allowedProjects = array_map('trim', explode(',', $validCoupon['project_ids']));
if (!in_array((string) $projectId, $allowedProjects)) {
$this->error('该优惠码不适用于此项目');
}
}
$discountAmount = round($originalAmount * ($validCoupon['discount_percent'] / 100), 2);
$finalAmount = max(0.01, round($originalAmount - $discountAmount, 2));
}
// 生成订单号
$orderNo = date('YmdHis') . rand(10000, 99999);
$expireMinutes = 15;
$expiredAt = date('Y-m-d H:i:s', strtotime("+{$expireMinutes} minutes"));
$orderId = $db->insert(
"INSERT INTO {$db->table('orders')} (order_no, project_id, card_type_id, amount, pay_amount, pay_type, status, contact_info, coupon_code, expired_at, created_at)
VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, NOW())",
[
$orderNo,
$projectId,
$cardTypeId,
$originalAmount,
$finalAmount,
$payType,
$contactInfo,
$couponCode,
$expiredAt,
]
);
// 优惠码使用计数+1
if ($validCoupon) {
$db->execute(
"UPDATE {$db->table('coupons')} SET used_count = used_count + 1 WHERE id = ?",
[$validCoupon['id']]
);
}
// 构建支付参数
$payUrl = $this->buildPayUrl($orderNo, $finalAmount, $payType, $project['name'] . ' - ' . $cardType['name']);
$this->success([
'order_id' => $orderId,
'order_no' => $orderNo,
'amount' => $originalAmount,
'pay_amount' => $finalAmount,
'coupon_code' => $couponCode,
'pay_url' => $payUrl,
'expired_at' => $expiredAt,
], '订单创建成功');
}
/**
* 构建支付链接
*/
private function buildPayUrl(string $orderNo, float $amount, string $payType, string $subject): string
{
// 优先从数据库读取支付配置,回退到文件配置
$apiUrl = $this->getPaymentConfig('payment_api_url', config('app.payment.api_url', ''));
$appId = $this->getPaymentConfig('payment_app_id', config('app.payment.app_id', ''));
$appKey = $this->getPaymentConfig('payment_app_key', config('app.payment.app_key', ''));
$notifyUrl = config('app.payment.notify_url', '');
$returnUrl = config('app.payment.return_url', '');
$typeMap = ['alipay' => 'alipay', 'wxpay' => 'wxpay', 'qqpay' => 'qqpay'];
$params = [
'pid' => $appId,
'type' => $typeMap[$payType] ?? $payType,
'out_trade_no' => $orderNo,
'notify_url' => $notifyUrl,
'return_url' => $returnUrl,
'name' => $subject,
'money' => $amount,
];
// 签名
ksort($params);
$signStr = '';
foreach ($params as $k => $v) {
$signStr .= $k . '=' . $v . '&';
}
$signStr = rtrim($signStr, '&');
$params['sign'] = md5($signStr . $appKey);
$params['sign_type'] = 'MD5';
return $apiUrl . '/submit.php?' . http_build_query($params);
}
/**
* 从数据库获取支付配置
*/
private function getPaymentConfig(string $key, string $default = ''): string
{
try {
$db = Database::getInstance();
$value = $db->fetchColumn(
"SELECT `value` FROM {$db->table('configs')} WHERE `key` = ?",
[$key]
);
return $value !== false ? $value : $default;
} catch (\Throwable $e) {
return $default;
}
}
/**
* 支付异步回调
*/
public function paymentNotify(): void
{
$tradeNo = $_GET['trade_no'] ?? $_POST['trade_no'] ?? '';
$outTradeNo = $_GET['out_trade_no'] ?? $_POST['out_trade_no'] ?? '';
$tradeStatus = $_GET['trade_status'] ?? $_POST['trade_status'] ?? '';
$sign = $_GET['sign'] ?? $_POST['sign'] ?? '';
// 验证签名
$appKey = $this->getPaymentConfig('payment_app_key', config('app.payment.app_key', ''));
$params = $_GET + $_POST;
unset($params['sign'], $params['sign_type']);
ksort($params);
$signStr = '';
foreach ($params as $k => $v) {
$signStr .= $k . '=' . $v . '&';
}
$signStr = rtrim($signStr, '&');
$calcSign = md5($signStr . $appKey);
if ($calcSign !== $sign) {
echo 'sign error';
exit;
}
if ($tradeStatus !== 'TRADE_SUCCESS') {
echo 'fail';
exit;
}
$db = Database::getInstance();
$order = $db->fetch(
"SELECT * FROM {$db->table('orders')} WHERE order_no = ? AND status = 'pending'",
[$outTradeNo]
);
if (!$order) {
echo 'order not found';
exit;
}
// 更新订单
$db->beginTransaction();
try {
$db->execute(
"UPDATE {$db->table('orders')} SET trade_no = ?, status = 'paid', paid_at = NOW() WHERE id = ?",
[$tradeNo, $order['id']]
);
// 生成卡密发货
$orderController = new OrderController();
$orderController->processOrderPaid($order['id']);
$db->commit();
} catch (\Throwable $e) {
$db->rollback();
error_log('Payment notify error: ' . $e->getMessage());
echo 'error';
exit;
}
echo 'success';
exit;
}
/**
* 查询卡密状态
*/
public function queryCard(): void
{
$cardKey = $this->getInput('card_key', '');
if (empty($cardKey)) {
$this->error('请输入卡密');
}
$db = Database::getInstance();
$card = $db->fetch(
"SELECT c.card_key, c.type, c.status, c.duration_days, c.bind_info, c.bound_at, c.expire_time, c.created_at,
p.name AS project_name
FROM {$db->table('cards')} c
LEFT JOIN {$db->table('projects')} p ON c.project_id = p.id
WHERE c.card_key = ?",
[$cardKey]
);
if (!$card) {
$this->error('卡密不存在');
}
$card['bind_info'] = json_decode($card['bind_info'] ?? '{}', true);
$statusText = match ($card['status']) {
'unused' => '未使用',
'used' => '已使用',
'disabled' => '已禁用',
default => '未知',
};
$card['status_text'] = $statusText;
$card['is_expired'] = $card['expire_time'] && strtotime($card['expire_time']) < time();
$this->success($card);
}
/**
* 授权验证接口 (客户端调用)
* Header: X-Api-Key: {project_api_key}
* POST: {card_key, machine_id, ip, device_info}
*/
public function verify(): void
{
$projectId = $_SERVER['HTTP_X_PROJECT_ID'] ?? 0;
$input = $this->getJsonInput();
$cardKey = $input['card_key'] ?? '';
$machineId = $input['machine_id'] ?? '';
$deviceIp = $input['ip'] ?? clientIp();
$deviceInfo = $input['device_info'] ?? '';
if (empty($cardKey) || empty($machineId)) {
$this->error('参数不完整', 400);
}
$db = Database::getInstance();
$card = $db->fetch(
"SELECT * FROM {$db->table('cards')} WHERE card_key = ? AND project_id = ?",
[$cardKey, $projectId]
);
if (!$card) {
// 尝试查找跨项目卡密(兼容)
$card = $db->fetch(
"SELECT * FROM {$db->table('cards')} WHERE card_key = ?",
[$cardKey]
);
if (!$card) {
$this->success(['valid' => false, 'message' => '卡密不存在'], 'ok');
return;
}
}
if ($card['status'] === 'disabled') {
$this->success(['valid' => false, 'message' => '卡密已被禁用'], 'ok');
return;
}
if ($card['status'] === 'unused') {
// 首次激活:绑定机器指纹
$bindInfo = [
'machine_id' => $machineId,
'ip' => $deviceIp,
'device_info' => $deviceInfo,
'first_bind_at' => date('Y-m-d H:i:s'),
];
$expireTime = null;
if ($card['duration_days'] > 0) {
$expireTime = date('Y-m-d H:i:s', strtotime("+{$card['duration_days']} days"));
}
$db->execute(
"UPDATE {$db->table('cards')} SET status = 'used', bind_info = ?, bound_at = NOW(), expire_time = ? WHERE id = ?",
[json_encode($bindInfo, JSON_UNESCAPED_UNICODE), $expireTime, $card['id']]
);
$this->success([
'valid' => true,
'message' => '激活成功',
'type' => $card['type'],
'duration_days' => $card['duration_days'],
'expire_time' => $expireTime,
'is_permanent' => $card['duration_days'] == 0,
], 'ok');
return;
}
if ($card['status'] === 'used') {
// 验证绑定
$bindInfo = json_decode($card['bind_info'] ?? '{}', true);
if (($bindInfo['machine_id'] ?? '') !== $machineId) {
$this->success(['valid' => false, 'message' => '设备不匹配,请使用绑定的设备'], 'ok');
return;
}
// 检查是否过期
if ($card['expire_time'] && strtotime($card['expire_time']) < time()) {
$this->success(['valid' => false, 'message' => '授权已过期'], 'ok');
return;
}
$this->success([
'valid' => true,
'message' => '授权有效',
'type' => $card['type'],
'duration_days' => $card['duration_days'],
'expire_time' => $card['expire_time'],
'bound_at' => $card['bound_at'],
'is_permanent' => $card['duration_days'] == 0,
'remaining_days' => $card['expire_time'] ? max(0, ceil((strtotime($card['expire_time']) - time()) / 86400)) : null,
], 'ok');
return;
}
}
/**
* 查询订单状态
*/
public function queryOrder(): void
{
$orderNo = $this->getInput('order_no', '');
if (empty($orderNo)) {
$this->error('缺少订单号');
}
$db = Database::getInstance();
$order = $db->fetch(
"SELECT o.id, o.order_no, o.amount, o.status, o.paid_at, o.created_at,
c.card_key,
p.name AS project_name,
ct.name AS card_type_name
FROM {$db->table('orders')} o
LEFT JOIN {$db->table('cards')} c ON o.card_id = c.id
LEFT JOIN {$db->table('projects')} p ON o.project_id = p.id
LEFT JOIN {$db->table('card_types')} ct ON o.card_type_id = ct.id
WHERE o.order_no = ?",
[$orderNo]
);
if (!$order) {
$this->error('订单不存在');
}
$this->success($order);
}
}
@@ -0,0 +1,147 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Validator;
/**
* 系统配置控制器
*/
class SystemController extends Controller
{
/**
* 获取系统配置 (支持批量获取)
* GET /api/system/configs?keys=key1,key2,key3
*/
public function getConfigs(): void
{
$keysStr = $_GET['keys'] ?? '';
$db = Database::getInstance();
if ($keysStr) {
$keys = explode(',', $keysStr);
$placeholders = implode(',', array_fill(0, count($keys), '?'));
$rows = $db->fetchAll(
"SELECT `key`, `value` FROM {$db->table('configs')} WHERE `key` IN ({$placeholders})",
$keys
);
} else {
$rows = $db->fetchAll(
"SELECT `key`, `value`, `description` FROM {$db->table('configs')} ORDER BY id ASC"
);
}
$result = [];
foreach ($rows as $row) {
$result[$row['key']] = $row['value'];
}
$this->success($result);
}
/**
* 保存系统配置 (批量)
* POST /api/system/configs
* Body: { "configs": { "key1": "value1", "key2": "value2" } }
*/
public function saveConfigs(): void
{
$input = $this->getJsonInput();
$configs = $input['configs'] ?? [];
if (empty($configs) || !is_array($configs)) {
$this->error('参数错误');
}
$db = Database::getInstance();
$db->beginTransaction();
try {
foreach ($configs as $key => $value) {
// 使用 INSERT ... ON DUPLICATE KEY UPDATE
$db->execute(
"INSERT INTO {$db->table('configs')} (`key`, `value`) VALUES (?, ?)
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`)",
[$key, $value]
);
}
$db->commit();
} catch (\Throwable $e) {
$db->rollback();
$this->error('保存失败: ' . $e->getMessage());
return;
}
logger('update_system_config', 'config', 0, $configs);
$this->success(null, '配置保存成功');
}
/**
* 测试支付网关连接
* POST /api/system/test-payment
*/
public function testPayment(): void
{
$input = $this->getJsonInput();
$apiUrl = $input['api_url'] ?? '';
$appId = $input['app_id'] ?? '';
$appKey = $input['app_key'] ?? '';
if (empty($apiUrl) || empty($appId) || empty($appKey)) {
$this->error('参数不完整');
}
// 构建测试请求参数
$params = [
'pid' => $appId,
'type' => 'alipay',
'out_trade_no' => 'TEST_' . date('YmdHis'),
'notify_url' => '',
'return_url' => '',
'name' => 'test',
'money' => '0.01',
];
ksort($params);
$signStr = '';
foreach ($params as $k => $v) {
$signStr .= $k . '=' . $v . '&';
}
$signStr = rtrim($signStr, '&');
$params['sign'] = md5($signStr . $appKey);
$params['sign_type'] = 'MD5';
// 测试连接 (尝试请求网关)
$testUrl = rtrim($apiUrl, '/submit.php') . '/api.php?act=query&pid=' . $appId . '&key=' . $appKey;
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $testUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_USERAGENT => 'CardAuth/1.0',
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
$this->error('连接失败: ' . $error);
return;
}
if ($httpCode >= 200 && $httpCode < 300) {
$this->success([
'http_code' => $httpCode,
'response' => $response,
], '连接测试成功,网关可达');
} else {
$this->error("连接失败,HTTP状态码: {$httpCode}");
}
}
}