Files
sbnews/server/app/api/controller/DeviceController.php
T
2026-06-11 12:15:29 +08:00

66 lines
2.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\api\controller;
use app\common\model\device\UserDevice;
use think\response\Json;
/**
* 设备信息上报
* POST /api/device/register
*/
class DeviceController extends BaseApiController
{
public array $notNeedLogin = ['register'];
/**
* 注册或更新设备信息
* 请求字段:device_id(必填)、platform、system、model、brand、app_version、
* app_version_code、screen_width、screen_height、network_type、
* language、timezone、push_cid、extrajson string
*/
public function register(): Json
{
$params = $this->request->post();
$deviceId = trim((string)($params['device_id'] ?? ''));
if (!$deviceId) {
return $this->fail('device_id 必填');
}
$now = time();
$ip = $this->request->ip() ?: '';
$ua = $this->request->header('user-agent', '');
if (mb_strlen($ua) > 500) $ua = mb_substr($ua, 0, 500);
$fields = [
'platform', 'system', 'model', 'brand', 'app_version',
'app_version_code', 'screen_width', 'screen_height',
'network_type', 'language', 'timezone', 'push_cid'
];
$data = [];
foreach ($fields as $f) {
if (isset($params[$f])) $data[$f] = $params[$f];
}
$data['ip'] = $ip;
$data['ua'] = $ua;
if (isset($params['extra'])) {
$data['extra'] = is_array($params['extra']) ? json_encode($params['extra'], JSON_UNESCAPED_UNICODE) : (string)$params['extra'];
}
$data['user_id'] = $this->userId ?: 0;
$data['last_at'] = $now;
$exist = UserDevice::where('device_id', $deviceId)->find();
if ($exist) {
$data['active_count'] = ($exist['active_count'] ?? 0) + 1;
UserDevice::where('id', $exist['id'])->update($data);
return $this->data(['id' => $exist['id'], 'is_new' => false]);
}
$data['device_id'] = $deviceId;
$data['first_at'] = $now;
$data['active_count'] = 1;
$id = UserDevice::insertGetId($data);
return $this->data(['id' => $id, 'is_new' => true]);
}
}