# PHP 接入 Server酱：程序消息推送到微信（2026 教程）

> 在 PHP 程序中调用 Server酱 API 推送微信通知：官方SDK 与 示例代码直接可用，自动兼容 Server酱Turbo 与 Server酱³ 两种 SendKey。

- 网页版：https://sct.ftqq.com/docs/integrations/php/
- 更新日期：2026-07-17

# PHP + Server酱：任务完成/出错，微信立刻知道

> 效果：在 PHP 程序中调用 Server酱 API，任务完成、异常告警等消息实时推送到你的微信。

## 前置条件

- 一个 Server酱 SendKey（[30 秒获取教程](https://sct.ftqq.com/docs/getting-started/sendkey/)）
- 本机可运行 PHP 的环境

## 方式一：官方 SDK（推荐）

安装：

```bash
composer require easychen/serverchan-sdk
```

调用（来自官方 README）：

```php
$ret = scSend('sendkey', 'title', 'desp', ['tags'=>'服务器报警|图片']);
print_r($ret);
```

SDK 按 SendKey 前缀自动识别 Server酱Turbo（`SCT` 开头）与 Server酱³（`sctp` 开头），无需关心端点差异。

## 方式二：官方示例直调实现

以下代码来自官方示例仓库 [serverchan-demo](https://github.com/easychen/serverchan-demo)（`php/send.php`），同样自动识别两种 SendKey，可直接复制使用：

```php
<?php

$data = parse_ini_file(__DIR__ . '/../.env');
$key = $data['SENDKEY'];

$ret = sc_send('主人服务器宕机了 via PHP', "第一行\n\n第二行", $key);
echo $ret;

function sc_send($text, $desp = '', $key = '[SENDKEY]')
{
    $postdata = http_build_query(array( 'text' => $text, 'desp' => $desp ));

    // 判断 $key 是否以 'sctp' 开头，并根据匹配到的数字部分拼接相应的 URL
    if (strpos($key, 'sctp') === 0) {
        // 使用正则表达式提取 sctp 开头后面的数字
        preg_match('/^sctp(\d+)t/', $key, $matches);
        $num = $matches[1];
        $url = "https://{$num}.push.ft07.com/send/{$key}.send";
    } else {
        $url = "https://sctapi.ftqq.com/{$key}.send";
    }

    $opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata));

    $context  = stream_context_create($opts);
    return $result = file_get_contents($url, false, $context);
    ;

}
```

运行方式：

```bash
php send.php
```

> 官方示例从仓库根目录的 `.env` 文件读取 `SENDKEY`；集成到你的项目时，可改为读取环境变量 `SERVERCHAN_SENDKEY` 或你的配置系统。

## 常见问题

**免费额度够用吗？**

免费版每天 5 条。程序类通知建议在任务结束时合并推送一条摘要；量大可订阅会员目前特价最低 3 元/月，一天最多可发 1000 条（[价格详情](https://sct.ftqq.com/subscribe)）。

**消息没收到怎么办？**

先检查返回 JSON 的 `code` 是否为 `0`，再按 [常见问题与排查](https://sct.ftqq.com/docs/getting-started/faq/) 逐项检查。

**有频率限制吗？**

每分钟最多 50 条，注意不要在循环里逐条推送，先聚合再发送。

## 相关集成

- [Python 脚本推送微信通知](https://sct.ftqq.com/docs/integrations/python/)
- [Node.js 推送微信通知](https://sct.ftqq.com/docs/integrations/nodejs/)
- [Claude Code 任务完成微信通知](https://sct.ftqq.com/docs/integrations/claude-code/)


## 懒人方案：把这段话复制给你的 AI 助手

把下面这段文字原样粘贴给 Claude Code、Cursor 或任何 AI 编程助手，它就会替你完成 Server酱 的接入：

```text
请帮我把 Server酱 微信通知接入到我当前的项目/工具中：
1. API：POST https://sctapi.ftqq.com/{SendKey}.send，参数 title（必填，不能含换行）、desp（正文，支持 Markdown，可选）；成功时返回 JSON 的 code 为 0。
2. 如果我的 SendKey 以 sctp 开头，则改用 https://{uid}.push.ft07.com/send/{SendKey}.send，uid 是 SendKey 中 sctp 与 t 之间的数字。
3. SendKey 从环境变量 SERVERCHAN_SENDKEY 读取；如果没有，提醒我到 https://sct.ftqq.com 免费获取（每天 5 条额度）。
4. 安全要求：不要把 SendKey 硬编码进代码、不要打印到日志、不要提交到 git。
5. 频率约定：任务结束发 1 条结果摘要即可，批量任务合并成一条，不要每步都推。
请根据我当前的项目和场景直接写好代码/配置并验证。
```

