摘要

之前写过Gotify:https://segmentfault.com/a/1190000047531644

现在又了解到一个无需部署服务的消息推送 - ntfy

相关链接:
https://f-droid.org/zh_Hans/packages/io.heckel.ntfy/
https://ntfy.sh/

下载客户端

https://github.com/binwiederhier/ntfy-android/releases

image.png

安装后,打开app创建一个订阅主题,自己命名,建议复杂一些,以免和别人一样。

服务端

只需要替换下方客户端的主题名称就行。

<?php

// 获取参数
$topic    = $_GET['topic']    ?? '客户端的主题名称';
$title    = $_GET['title']    ?? '';
$message  = $_GET['message']  ?? '';

// 过滤空值
$data = array_filter([
    "topic"    => $topic,
    "title"    => $title,
    "message"  => $message
], fn($v) => $v !== '' && $v !== null);

// 必填校验
if (empty($data['title']) || empty($data['message'])) {
    exit(json_encode(["ok"=>false,"error"=>"title/message 必填"], JSON_UNESCAPED_UNICODE));
}

// 默认 priority
$data['priority'] = $data['priority'] ?? 5;

// 👉 关键:确保 JSON 编码成功
$json = json_encode($data, JSON_UNESCAPED_UNICODE);

if ($json === false) {
    exit(json_encode([
        "ok" => false,
        "error" => "JSON编码失败: " . json_last_error_msg()
    ], JSON_UNESCAPED_UNICODE));
}

// 👉 用字符串长度避免某些服务器问题
$headers = [
    "Content-Type: application/json",
    "Content-Length: " . strlen($json)
];

// 发送
$ch = curl_init("https://ntfy.sh");

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $json,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10
]);

$response = curl_exec($ch);

// 错误处理
if (curl_errno($ch)) {
    $result = ["ok"=>false,"error"=>curl_error($ch)];
} else {
    $result = ["ok"=>true,"res"=>json_decode($response)];
}

curl_close($ch);

header('Content-Type: application/json');
echo json_encode($result, JSON_UNESCAPED_UNICODE);

然后执行代码:

https:/xxx.com/ntfy/index.php?title=111&message=222

就可以PUSH消息给你手机了。

当然,记得将ntfy设置电池优化无限制,自启动,后台锁定。

本文作者

TANKING

标签: none

添加新评论