CodeIgniter 中 Slack 通知需手动封装 JSON POST 请求,关键包括:设 Content-Type: application/json、用 json_encode() 构造 payload、校验 HTTP 200 响应;否则易返回 400 或静默失败。

Slack 通知在 CodeIgniter 中无法开箱即用,必须手动封装 HTTP 请求并处理 Slack Webhook 协议;直接调用 curl 或依赖第三方库都可行,但关键在于请求体格式、错误响应识别和超时控制。
Slack Webhook 的 POST 请求必须用 application/json
Slack 官方 Webhook 只接受 POST 方法且要求 Content-Type: application/json。用 CodeIgniter 原生 curl 封装时,若漏设 header 或误用 http_build_query()(它生成 application/x-www-form-urlencoded),会返回 400 Bad Request 或静默失败。
- 必须把消息体转成 JSON 字符串,不能传 PHP 数组或 URL 编码字符串
- 推荐用
json_encode(['text' => 'Hello from CI'])构造 payload - header 数组中必须显式包含
['Content-Type: application/json'] - 禁用
CURLOPT_POST+CURLOPT_POSTFIELDS组合,改用CURLOPT_CUSTOMREQUEST+CURLOPT_POSTFIELDS手动发 JSON
CodeIgniter 3 中封装 Slack 客户端的最小可行代码
在 application/libraries/Slack.php 中定义类,复用框架已加载的辅助函数和配置能力:
class Slack {
protected $ci;
protected $webhook_url;
public function __construct($config = []) {
$this->ci =& get_instance();
$this->ci->load->helper('url');
$this->webhook_url = isset($config['webhook_url'])
? $config['webhook_url']
: $this->ci->config->item('slack_webhook_url');
}
public function send($message, $channel = null) {
if (empty($this->webhook_url)) {
log_message('error', 'Slack webhook URL not configured');
return false;
}
$payload = ['text' => $message];
if ($channel) {
$payload['channel'] = $channel;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->webhook_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // Slack 建议超时 ≤ 3s,设 5s 留余量
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code !== 200) {
log_message('error', "Slack send failed: HTTP {$http_code}, response: {$response}");
return false;
}
return true;
}
}
使用前需在 application/config/config.php 添加:$config['slack_webhook_url'] = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX';
常见失败原因与调试建议
Slack 返回成功只表示“接收了请求”,不等于消息发出。真正出问题时往往没有明显报错,只能靠日志和响应体判断。
- 收到
{"ok":false,"error":"invalid_payload"}→ payload 不是合法 JSON,检查是否多嵌套了一层或用了单引号 - 收到空响应或
NULL→ cURL 被服务器禁用,确认extension=php_curl.dll已启用且未被disable_functions屏蔽 - 消息发到错误频道 →
channel字段值必须带#(如#alerts)或@username,且当前 webhook 对该频道有权限 - 中文乱码 → 确保 PHP 文件保存为 UTF-8 无 BOM,
json_encode()不加JSON_UNESCAPED_UNICODE会导致 \uXXXX 转义,Slack 可识别,但可读性差
Webhook URL 是一次性凭证,泄露即失效;不要硬编码在控制器里,务必通过配置项或环境变量注入。另外 Slack 不支持批量消息合并,每次 send() 都是一次独立 HTTP 请求,高频调用需加队列或节流。


















