v1.1.0: 新增安装统计与版本推送

功能说明:
- 安装统计: 每次安装独立计数(含已删除), 存活/已删除, 最后上线时间
- 版本推送: 上传安装包并推送客户端下载, 支持强制更新提示(不阻断授权)
- 客户端接口: check-update / heartbeat, verify 成功附带更新字段
- 管理端: 安装统计页 + 版本推送页; agent 不可发布版本(仅只读)
- 文档: README API 说明 + /docs 功能介绍与使用方法 + CHANGELOG

数据库:
- 新表 ca_installations / ca_project_versions
- 增量升级: backend/database/migrations/20261008_add_installations_and_versions.sql
This commit is contained in:
root committed 2026-10-08 18:19:36 +08:00
1 parent af98618810
commit e809b7a903
22 files changed
+3153 -32

No files matched your search

@@ -0,0 +1,310 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Services\InstallationService;
use App\Services\PermissionService;
/**
* 安装记录管理控制器
*/
class InstallationController extends Controller
{
/**
* 安装列表
* GET /api/installations
*/
public function list(): void
{
$db = Database::getInstance();
$user = $this->getCurrentUser() ?: [];
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$offset = ($page - 1) * $pageSize;
$filters = [
'project_id' => $_GET['project_id'] ?? '',
'status' => $_GET['status'] ?? '',
'keyword' => trim($_GET['keyword'] ?? ''),
'date_from' => $_GET['date_from'] ?? '',
'date_to' => $_GET['date_to'] ?? '',
];
$built = InstallationService::buildListWhere($user, $filters);
$where = $built['where'];
$params = $built['params'];
$total = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('installations')} i WHERE 1=1 {$where}",
$params
);
$list = $db->fetchAll(
"SELECT i.*, p.name AS project_name
FROM {$db->table('installations')} i
LEFT JOIN {$db->table('projects')} p ON p.id = i.project_id
WHERE 1=1 {$where}
ORDER BY i.id DESC
LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $list,
'total' => $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 安装统计(含已删除)
* GET /api/installations/stats
*/
public function stats(): void
{
$user = $this->getCurrentUser() ?: [];
$projectId = !empty($_GET['project_id']) ? (int) $_GET['project_id'] : null;
$this->success(InstallationService::stats($user, $projectId));
}
/**
* 安装详情
* GET /api/installations/{id}
*/
public function detail(int $id): void
{
$db = Database::getInstance();
$user = $this->getCurrentUser() ?: [];
$row = $db->fetch(
"SELECT i.*, p.name AS project_name
FROM {$db->table('installations')} i
LEFT JOIN {$db->table('projects')} p ON p.id = i.project_id
WHERE i.id = ?",
[$id]
);
if (!$row) {
$this->error('安装记录不存在', 404);
}
if (!$this->canAccess((int) $row['project_id'], $user)) {
$this->error('无权访问该安装记录', 403);
}
$this->success($row);
}
/**
* 删除安装(软删除)
* DELETE /api/installations/{id}
*/
public function delete(int $id): void
{
$db = Database::getInstance();
$user = $this->getCurrentUser() ?: [];
$role = $user['role'] ?? '';
if (!in_array($role, ['admin', 'project_admin'], true)) {
$this->error('无权删除安装记录', 403);
}
$row = $db->fetch(
"SELECT id, project_id, machine_id FROM {$db->table('installations')} WHERE id = ?",
[$id]
);
if (!$row) {
$this->error('安装记录不存在', 404);
}
if (!$this->canAccess((int) $row['project_id'], $user)) {
$this->error('无权操作该项目的安装记录', 403);
}
$db->execute(
"UPDATE {$db->table('installations')}
SET status = 'deleted', deleted_at = NOW()
WHERE id = ?",
[$id]
);
logger('installation_delete', 'installation', $id, [
'project_id' => (int) $row['project_id'],
'machine_id' => $row['machine_id'],
]);
$this->success(null, '已标记为已删除');
}
/**
* 恢复安装
* POST /api/installations/{id}/restore
*/
public function restore(int $id): void
{
$db = Database::getInstance();
$user = $this->getCurrentUser() ?: [];
$role = $user['role'] ?? '';
if (!in_array($role, ['admin', 'project_admin'], true)) {
$this->error('无权恢复安装记录', 403);
}
$row = $db->fetch(
"SELECT id, project_id, machine_id FROM {$db->table('installations')} WHERE id = ?",
[$id]
);
if (!$row) {
$this->error('安装记录不存在', 404);
}
if (!$this->canAccess((int) $row['project_id'], $user)) {
$this->error('无权操作该项目的安装记录', 403);
}
$db->execute(
"UPDATE {$db->table('installations')}
SET status = 'active', deleted_at = NULL
WHERE id = ?",
[$id]
);
logger('installation_restore', 'installation', $id, [
'project_id' => (int) $row['project_id'],
'machine_id' => $row['machine_id'],
]);
$this->success(null, '已恢复为存活');
}
/**
* 批量删除
* POST /api/installations/batch-delete
*/
public function batchDelete(): void
{
$db = Database::getInstance();
$user = $this->getCurrentUser() ?: [];
$role = $user['role'] ?? '';
if (!in_array($role, ['admin', 'project_admin'], true)) {
$this->error('无权删除安装记录', 403);
}
$input = $this->getJsonInput();
$ids = $input['ids'] ?? [];
if (empty($ids) || !is_array($ids)) {
$this->error('请选择要删除的安装记录');
}
$ids = array_map('intval', $ids);
$deleted = 0;
foreach ($ids as $id) {
$row = $db->fetch(
"SELECT id, project_id FROM {$db->table('installations')} WHERE id = ?",
[$id]
);
if (!$row || !$this->canAccess((int) $row['project_id'], $user)) {
continue;
}
$db->execute(
"UPDATE {$db->table('installations')} SET status = 'deleted', deleted_at = NOW() WHERE id = ?",
[$id]
);
$deleted++;
}
logger('installation_batch_delete', 'installation', 0, ['count' => $deleted]);
$this->success(['deleted' => $deleted], "已删除 {$deleted} 条");
}
/**
* 导出安装记录
* GET /api/installations/export
*/
public function export(): void
{
$db = Database::getInstance();
$user = $this->getCurrentUser() ?: [];
$filters = [
'project_id' => $_GET['project_id'] ?? '',
'status' => $_GET['status'] ?? '',
'keyword' => trim($_GET['keyword'] ?? ''),
'date_from' => $_GET['date_from'] ?? '',
'date_to' => $_GET['date_to'] ?? '',
];
$built = InstallationService::buildListWhere($user, $filters);
$list = $db->fetchAll(
"SELECT i.id, i.project_id, p.name AS project_name, i.machine_id, i.card_key, i.ip,
i.device_info, i.client_version, i.status, i.install_count,
i.installed_at, i.last_online_at, i.deleted_at
FROM {$db->table('installations')} i
LEFT JOIN {$db->table('projects')} p ON p.id = i.project_id
WHERE 1=1 {$built['where']}
ORDER BY i.id DESC
LIMIT 5000",
$built['params']
);
$headers = [
'ID', '项目ID', '项目名称', '机器指纹', '卡密', 'IP', '设备信息',
'客户端版本', '状态', '累计激活', '安装时间', '最后上线', '删除时间',
];
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename=installations_' . date('Ymd_His') . '.csv');
echo "\xEF\xBB\xBF"; // UTF-8 BOM
$out = fopen('php://output', 'w');
fputcsv($out, $headers);
foreach ($list as $row) {
fputcsv($out, [
$row['id'],
$row['project_id'],
$row['project_name'] ?? '',
$row['machine_id'],
$row['card_key'] ?? '',
$row['ip'] ?? '',
$row['device_info'] ?? '',
$row['client_version'] ?? '',
$row['status'],
$row['install_count'],
$row['installed_at'],
$row['last_online_at'] ?? '',
$row['deleted_at'] ?? '',
]);
}
fclose($out);
exit;
}
/**
* 权限判断
*/
private function canAccess(int $projectId, array $user): bool
{
$role = $user['role'] ?? '';
if ($role === 'admin') {
return true;
}
if ($role === 'project_admin') {
$projectIds = $user['project_ids'] ?? [];
return in_array($projectId, array_map('intval', $projectIds), true);
}
if ($role === 'agent') {
$db = Database::getInstance();
$agentIds = PermissionService::getAgentIdsUnder((int) ($user['id'] ?? 0));
if (empty($agentIds)) {
return false;
}
$placeholders = implode(',', array_fill(0, count($agentIds), '?'));
$count = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('cards')} WHERE project_id = ? AND use_user_id IN ({$placeholders})",
array_merge([$projectId], $agentIds)
);
return $count > 0;
}
return false;
}
}
@@ -0,0 +1,364 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Services\VersionService;
/**
* 项目版本/安装包管理控制器
* 发布/修改仅 admin + project_admin;agent 只读
*/
class ProjectVersionController extends Controller
{
private const ALLOWED_EXT = ['zip', 'tar', 'gz', 'tgz', '7z', 'exe', 'dmg', 'apk', 'msi', 'pkg', 'rar', 'bin'];
private const MAX_SIZE = 200 * 1024 * 1024; // 200MB
/**
* 版本列表
* GET /api/projects/{projectId}/versions
*/
public function list(int $projectId): void
{
$user = $this->getCurrentUser() ?: [];
if (!VersionService::assertProjectAccess($projectId, $user)) {
$this->error('无权访问该项目', 403);
}
$db = Database::getInstance();
$list = $db->fetchAll(
"SELECT v.*, p.name AS project_name
FROM {$db->table('project_versions')} v
LEFT JOIN {$db->table('projects')} p ON p.id = v.project_id
WHERE v.project_id = ?
ORDER BY v.id DESC",
[$projectId]
);
$this->success($list);
}
/**
* 版本详情
* GET /api/projects/{projectId}/versions/{id}
*/
public function detail(int $projectId, int $id): void
{
$user = $this->getCurrentUser() ?: [];
if (!VersionService::assertProjectAccess($projectId, $user)) {
$this->error('无权访问该项目', 403);
}
$db = Database::getInstance();
$row = $db->fetch(
"SELECT v.*, p.name AS project_name
FROM {$db->table('project_versions')} v
LEFT JOIN {$db->table('projects')} p ON p.id = v.project_id
WHERE v.id = ? AND v.project_id = ?",
[$id, $projectId]
);
if (!$row) {
$this->error('版本不存在', 404);
}
$this->success($row);
}
/**
* 上传发布版本
* POST /api/projects/{projectId}/versions (multipart)
*/
public function create(int $projectId): void
{
$user = $this->getCurrentUser() ?: [];
$role = $user['role'] ?? '';
if (!VersionService::canPublish($role)) {
$this->error('代理账号不可发布版本', 403);
}
if (!VersionService::assertProjectAccess($projectId, $user)) {
$this->error('无权操作该项目', 403);
}
$version = trim($_POST['version'] ?? '');
if ($version === '') {
$this->error('版本号不能为空');
}
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
$this->error('请上传安装包文件');
}
$file = $_FILES['file'];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, self::ALLOWED_EXT, true)) {
$this->error('仅支持 ' . implode('/', self::ALLOWED_EXT) . ' 格式的安装包');
}
if ($file['size'] > self::MAX_SIZE) {
$this->error('安装包大小不能超过 200MB');
}
$db = Database::getInstance();
$exists = $db->fetch(
"SELECT id FROM {$db->table('project_versions')} WHERE project_id = ? AND version = ?",
[$projectId, $version]
);
if ($exists) {
$this->error('该版本号已存在');
}
$uploadDir = BASE_PATH . '/public/uploads/packages/' . $projectId;
if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
$this->error('创建上传目录失败');
}
// 安全文件名:随机 + 原扩展名
$safeName = 'pkg_' . $projectId . '_' . time() . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
$filepath = $uploadDir . '/' . $safeName;
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
$this->error('安装包上传失败,请重试');
}
$checksum = '';
if (is_file($filepath)) {
$checksum = @hash_file('sha256', $filepath) ?: '';
}
$fileSize = (int) $file['size'];
$isLatest = isset($_POST['is_latest']) ? (int) $_POST['is_latest'] : 1;
$isForce = isset($_POST['is_force']) ? (int) $_POST['is_force'] : 0;
$isForce = $isForce === 1 ? 1 : 0;
$isLatest = $isLatest === 0 ? 0 : 1;
$minVersion = trim($_POST['min_client_version'] ?? '');
$changelog = $_POST['changelog'] ?? '';
$filePath = '/uploads/packages/' . $projectId . '/' . $safeName;
$db->beginTransaction();
try {
if ($isLatest) {
$db->execute(
"UPDATE {$db->table('project_versions')} SET is_latest = 0 WHERE project_id = ?",
[$projectId]
);
}
$versionId = $db->insert(
"INSERT INTO {$db->table('project_versions')}
(project_id, version, file_name, file_path, file_size, checksum, changelog,
min_client_version, is_force, is_latest, download_count, status, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 1, ?)",
[
$projectId,
$version,
$file['name'],
$filePath,
$fileSize,
$checksum,
$changelog !== '' ? $changelog : null,
$minVersion,
$isForce,
$isLatest,
(int) ($user['id'] ?? 0),
]
);
$db->commit();
} catch (\Throwable $e) {
$db->rollback();
@unlink($filepath);
$this->error('版本发布失败: ' . $e->getMessage());
}
logger('version_publish', 'project_version', $versionId, [
'project_id' => $projectId,
'version' => $version,
'is_force' => $isForce,
'is_latest' => $isLatest,
]);
$row = $db->fetch(
"SELECT * FROM {$db->table('project_versions')} WHERE id = ?",
[$versionId]
);
$this->success($row, '版本发布成功');
}
/**
* 更新版本信息(changelog / force / min_version / status)
* PUT /api/versions/{id}
*/
public function update(int $id): void
{
$user = $this->getCurrentUser() ?: [];
if (!VersionService::canPublish($user['role'] ?? '')) {
$this->error('代理账号不可修改版本', 403);
}
$db = Database::getInstance();
$row = $db->fetch(
"SELECT * FROM {$db->table('project_versions')} WHERE id = ?",
[$id]
);
if (!$row) {
$this->error('版本不存在', 404);
}
if (!VersionService::assertProjectAccess((int) $row['project_id'], $user)) {
$this->error('无权操作该项目的版本', 403);
}
$input = $this->getJsonInput();
$changelog = array_key_exists('changelog', $input) ? $input['changelog'] : $row['changelog'];
$minVersion = array_key_exists('min_client_version', $input) ? trim((string) $input['min_client_version']) : ($row['min_client_version'] ?? '');
$isForce = array_key_exists('is_force', $input) ? ((int) $input['is_force'] === 1 ? 1 : 0) : (int) $row['is_force'];
$status = array_key_exists('status', $input) ? ((int) $input['status'] === 1 ? 1 : 0) : (int) $row['status'];
$db->execute(
"UPDATE {$db->table('project_versions')}
SET changelog = ?, min_client_version = ?, is_force = ?, status = ?
WHERE id = ?",
[
$changelog !== '' ? $changelog : null,
$minVersion,
$isForce,
$status,
$id,
]
);
logger('version_update', 'project_version', $id, [
'version' => $row['version'],
'is_force' => $isForce,
]);
$this->success($db->fetch("SELECT * FROM {$db->table('project_versions')} WHERE id = ?", [$id]), '更新成功');
}
/**
* 切换强制推送
* PUT /api/versions/{id}/force
*/
public function toggleForce(int $id): void
{
$user = $this->getCurrentUser() ?: [];
if (!VersionService::canPublish($user['role'] ?? '')) {
$this->error('代理账号不可修改强制推送', 403);
}
$db = Database::getInstance();
$row = $db->fetch(
"SELECT * FROM {$db->table('project_versions')} WHERE id = ?",
[$id]
);
if (!$row) {
$this->error('版本不存在', 404);
}
if (!VersionService::assertProjectAccess((int) $row['project_id'], $user)) {
$this->error('无权操作该项目的版本', 403);
}
$input = $this->getJsonInput();
if (array_key_exists('is_force', $input)) {
$isForce = ((int) $input['is_force'] === 1) ? 1 : 0;
} else {
$isForce = ((int) $row['is_force'] === 1) ? 0 : 1;
}
$db->execute(
"UPDATE {$db->table('project_versions')} SET is_force = ? WHERE id = ?",
[$isForce, $id]
);
logger('version_force_toggle', 'project_version', $id, [
'version' => $row['version'],
'is_force' => $isForce,
]);
$this->success(
['id' => $id, 'is_force' => $isForce],
$isForce ? '已开启强制推送' : '已关闭强制推送'
);
}
/**
* 设为最新版本
* PUT /api/versions/{id}/latest
*/
public function setLatest(int $id): void
{
$user = $this->getCurrentUser() ?: [];
if (!VersionService::canPublish($user['role'] ?? '')) {
$this->error('代理账号不可设置最新版本', 403);
}
$db = Database::getInstance();
$row = $db->fetch(
"SELECT * FROM {$db->table('project_versions')} WHERE id = ?",
[$id]
);
if (!$row) {
$this->error('版本不存在', 404);
}
if (!VersionService::assertProjectAccess((int) $row['project_id'], $user)) {
$this->error('无权操作该项目的版本', 403);
}
$db->beginTransaction();
try {
$db->execute(
"UPDATE {$db->table('project_versions')} SET is_latest = 0 WHERE project_id = ?",
[(int) $row['project_id']]
);
$db->execute(
"UPDATE {$db->table('project_versions')} SET is_latest = 1, status = 1 WHERE id = ?",
[$id]
);
$db->commit();
} catch (\Throwable $e) {
$db->rollback();
$this->error('设置最新版本失败');
}
logger('version_set_latest', 'project_version', $id, ['version' => $row['version']]);
$this->success(null, '已设为最新版本');
}
/**
* 删除版本
* DELETE /api/versions/{id}
*/
public function delete(int $id): void
{
$user = $this->getCurrentUser() ?: [];
if (!VersionService::canPublish($user['role'] ?? '')) {
$this->error('代理账号不可删除版本', 403);
}
$db = Database::getInstance();
$row = $db->fetch(
"SELECT * FROM {$db->table('project_versions')} WHERE id = ?",
[$id]
);
if (!$row) {
$this->error('版本不存在', 404);
}
if (!VersionService::assertProjectAccess((int) $row['project_id'], $user)) {
$this->error('无权操作该项目的版本', 403);
}
$db->execute("DELETE FROM {$db->table('project_versions')} WHERE id = ?", [$id]);
// 删除物理文件
$abs = BASE_PATH . '/public' . $row['file_path'];
if (is_file($abs)) {
@unlink($abs);
}
logger('version_delete', 'project_version', $id, [
'project_id' => (int) $row['project_id'],
'version' => $row['version'],
]);
$this->success(null, '版本已删除');
}
}
+168 -5
View File
@@ -4,10 +4,12 @@ namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Validator;
use App\Services\InstallationService;
use App\Services\VersionService;
/**
* 公开接口控制器
* 包含:购买页、查询页、授权验证、支付回调
* 包含:购买页、查询页、授权验证、安装上报、支付回调
*/
class PublicController extends Controller
{
@@ -23,6 +25,25 @@ class PublicController extends Controller
$this->success($projects);
}
/**
* 已启用的支付方式列表(前台购买页展示用)
* GET /api/public/payment/options
*/
public function paymentOptions(): void
{
$db = Database::getInstance();
$row = $db->fetch(
"SELECT `value` FROM {$db->table('configs')} WHERE `key` = 'payment_pay_types'"
);
$types = $row ? json_decode($row['value'], true) : ['alipay', 'wxpay'];
$valid = ['alipay', 'wxpay', 'qqpay'];
$types = array_values(array_filter($types, fn($t) => in_array($t, $valid, true)));
if (empty($types)) {
$types = ['alipay', 'wxpay'];
}
$this->success(['pay_types' => $types, 'payment_enabled' => $row !== null]);
}
/**
* 获取项目的卡密类型(套餐)列表
*/
@@ -66,6 +87,17 @@ class PublicController extends Controller
$db = Database::getInstance();
// 校验支付方式是否已勾选启用
$payTypesRow = $db->fetch(
"SELECT `value` FROM {$db->table('configs')} WHERE `key` = 'payment_pay_types'"
);
if ($payTypesRow) {
$enabledPayTypes = json_decode($payTypesRow['value'], true) ?: [];
if (!in_array($payType, $enabledPayTypes, true)) {
$this->error('该支付方式未开启,请选择其他支付方式');
}
}
// 验证项目
$project = $db->fetch(
"SELECT id, name FROM {$db->table('projects')} WHERE id = ? AND status = 1 AND deleted_at IS NULL",
@@ -484,20 +516,121 @@ class PublicController extends Controller
$this->success($card);
}
/**
* 检查更新 + 上报安装/在线 (客户端调用)
* Header: X-Api-Key: {project_api_key}
* POST: {machine_id, client_version?, card_key?, device_info?}
*/
public function checkUpdate(): void
{
$projectId = (int) ($_SERVER['HTTP_X_PROJECT_ID'] ?? 0);
$input = $this->getJsonInput();
$machineId = trim((string) ($input['machine_id'] ?? ''));
$clientVersion = trim((string) ($input['client_version'] ?? ''));
$cardKey = trim((string) ($input['card_key'] ?? ''));
$deviceInfo = (string) ($input['device_info'] ?? '');
$deviceIp = (string) ($input['ip'] ?? clientIp());
if ($machineId === '') {
$this->error('缺少机器码 machine_id', 400);
}
$cardId = null;
if ($cardKey !== '') {
$db = Database::getInstance();
$card = $db->fetch(
"SELECT id FROM {$db->table('cards')} WHERE card_key = ? AND project_id = ?",
[$cardKey, $projectId]
);
if ($card) {
$cardId = (int) $card['id'];
}
}
$upsert = InstallationService::upsert(
$projectId,
$machineId,
$deviceIp,
$deviceInfo,
$clientVersion,
$cardId,
$cardKey
);
$payload = VersionService::buildUpdatePayload($projectId, $clientVersion);
$payload['install_id'] = $upsert['install_id'];
// 有更新时累计下载提示次数
if (!empty($payload['update_available']) && !empty($payload['version'])) {
$db = Database::getInstance();
$db->execute(
"UPDATE {$db->table('project_versions')} SET download_count = download_count + 1
WHERE project_id = ? AND version = ?",
[$projectId, $payload['version']]
);
}
$this->success($payload, 'ok');
}
/**
* 安装心跳 (客户端调用)
* Header: X-Api-Key: {project_api_key}
* POST: {machine_id, client_version?, card_key?, device_info?}
*/
public function heartbeat(): void
{
$projectId = (int) ($_SERVER['HTTP_X_PROJECT_ID'] ?? 0);
$input = $this->getJsonInput();
$machineId = trim((string) ($input['machine_id'] ?? ''));
if ($machineId === '') {
$this->error('缺少机器码 machine_id', 400);
}
$cardKey = trim((string) ($input['card_key'] ?? ''));
$cardId = null;
if ($cardKey !== '') {
$db = Database::getInstance();
$card = $db->fetch(
"SELECT id FROM {$db->table('cards')} WHERE card_key = ? AND project_id = ?",
[$cardKey, $projectId]
);
if ($card) {
$cardId = (int) $card['id'];
}
}
$upsert = InstallationService::heartbeat(
$projectId,
$machineId,
(string) ($input['ip'] ?? clientIp()),
(string) ($input['device_info'] ?? ''),
(string) ($input['client_version'] ?? ''),
$cardId,
$cardKey
);
$this->success(['install_id' => $upsert['install_id']], 'ok');
}
/**
* 授权验证接口 (客户端调用)
* Header: X-Api-Key: {project_api_key}
* POST: {card_key, machine_id, ip, device_info}
* POST: {card_key, machine_id, ip, device_info, client_version?}
* 成功时附带更新提示字段,并更新安装 last_online_at
*/
public function verify(): void
{
$projectId = $_SERVER['HTTP_X_PROJECT_ID'] ?? 0;
$projectId = (int) ($_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'] ?? '';
$clientVersion = (string) ($input['client_version'] ?? '');
if (empty($cardKey) || empty($machineId)) {
$this->error('参数不完整', 400);
@@ -546,6 +679,20 @@ class PublicController extends Controller
[json_encode($bindInfo, JSON_UNESCAPED_UNICODE), $expireTime, $card['id']]
);
// 登记安装记录
$upsert = InstallationService::upsert(
$projectId,
(string) $machineId,
(string) $deviceIp,
(string) $deviceInfo,
$clientVersion,
(int) $card['id'],
(string) $cardKey
);
$updatePayload = VersionService::buildUpdatePayload($projectId, $clientVersion);
$updatePayload['install_id'] = $upsert['install_id'];
$this->success([
'valid' => true,
'message' => '激活成功',
@@ -553,7 +700,7 @@ class PublicController extends Controller
'duration_days' => $card['duration_days'],
'expire_time' => $expireTime,
'is_permanent' => $card['duration_days'] == 0,
], 'ok');
] + $updatePayload, 'ok');
return;
}
@@ -572,6 +719,20 @@ class PublicController extends Controller
return;
}
// 授权有效:更新安装 last_online_at
$upsert = InstallationService::upsert(
$projectId,
(string) $machineId,
(string) $deviceIp,
(string) $deviceInfo,
$clientVersion,
(int) $card['id'],
(string) $cardKey
);
$updatePayload = VersionService::buildUpdatePayload($projectId, $clientVersion);
$updatePayload['install_id'] = $upsert['install_id'];
$this->success([
'valid' => true,
'message' => '授权有效',
@@ -581,9 +742,11 @@ class PublicController extends Controller
'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');
] + $updatePayload, 'ok');
return;
}
$this->success(['valid' => false, 'message' => '卡密状态异常'], 'ok');
}
/**