文件
freeshop/push_subscribe.php
2026-08-16 17:03:10 +08:00

45 行
1.6 KiB
PHP

<?php
require __DIR__ . '/includes/init.php';
requireLogin('push_subscribe.php');
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['ok' => false, 'msg' => '方法不支持']);
exit;
}
$raw = file_get_contents('php:
$data = json_decode($raw, true);
if (!is_array($data)) {
echo json_encode(['ok' => false, 'msg' => '参数错误']);
exit;
}
if (empty($data['csrf_token']) || !verifyCsrfToken($data['csrf_token'])) {
http_response_code(403);
echo json_encode(['ok' => false, 'msg' => 'CSRF 校验失败']);
exit;
}
$sub = $data['subscription'] ?? null;
if (!is_array($sub) || empty($sub['endpoint'])) {
echo json_encode(['ok' => false, 'msg' => '订阅信息缺失']);
exit;
}
$endpoint = $sub['endpoint'];
$keys = $sub['keys'] ?? [];
$auth = $keys['auth'] ?? '';
$p256 = $keys['p256dh'] ?? '';
$uid = (int) $_SESSION['user_id'];
$action = $data['action'] ?? 'subscribe';
if ($action === 'unsubscribe') {
db()->prepare('DELETE FROM ' . tn('push_subscriptions') . ' WHERE endpoint = ? OR (user_id = ? AND auth_key = ?)')
->execute([$endpoint, $uid, $auth]);
echo json_encode(['ok' => true, 'msg' => '已取消订阅']);
exit;
}
if ($auth !== '') {
db()->prepare('DELETE FROM ' . tn('push_subscriptions') . ' WHERE auth_key = ? AND user_id = ?')
->execute([$auth, $uid]);
}
db()->prepare('INSERT INTO ' . tn('push_subscriptions') . ' (user_id, endpoint, auth_key, p256dh, created_at) VALUES (?,?,?,?,NOW())')
->execute([$uid, $endpoint, $auth, $p256]);
echo json_encode(['ok' => true, 'msg' => '订阅成功']);