php 实现fcm
FCM(Firebase Cloud Messaging)在 PHP 中的实现
FCM 是 Google 提供的跨平台消息推送服务,用于向 Android、iOS 和 Web 应用发送通知。以下是在 PHP 中实现 FCM 推送的详细方法。
准备工作
确保已创建 Firebase 项目并获取服务器密钥。登录 Firebase 控制台,进入项目设置,在“云消息传递”选项卡中获取“服务器密钥”。
安装依赖
使用 Composer 安装 curl 或 guzzlehttp/guzzle 库以发送 HTTP 请求。推荐使用 Guzzle:
composer require guzzlehttp/guzzle
发送单设备通知
以下代码演示如何向单个设备发送通知:
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$serverKey = 'YOUR_FCM_SERVER_KEY';
$deviceToken = 'TARGET_DEVICE_TOKEN';
$client = new Client([
'base_uri' => 'https://fcm.googleapis.com',
'headers' => [
'Authorization' => 'key=' . $serverKey,
'Content-Type' => 'application/json',
]
]);
$response = $client->post('/fcm/send', [
'json' => [
'to' => $deviceToken,
'notification' => [
'title' => 'Notification Title',
'body' => 'Notification Body',
'sound' => 'default'
],
'data' => [
'key1' => 'value1',
'key2' => 'value2'
]
]
]);
echo $response->getBody();
?>
发送多设备通知
要向多个设备发送通知,使用 registration_ids 代替 to:
$response = $client->post('/fcm/send', [
'json' => [
'registration_ids' => ['token1', 'token2', 'token3'],
'notification' => [
'title' => 'Notification Title',
'body' => 'Notification Body'
]
]
]);
处理响应
FCM 返回的响应包含状态信息。检查 success 和 failure 字段:
$responseData = json_decode($response->getBody(), true);
if ($responseData['success'] > 0) {
echo 'Successfully sent to ' . $responseData['success'] . ' devices';
}
if ($responseData['failure'] > 0) {
echo 'Failed to send to ' . $responseData['failure'] . ' devices';
}
使用主题广播
要向订阅特定主题的设备发送通知:
$response = $client->post('/fcm/send', [
'json' => [
'to' => '/topics/your_topic_name',
'notification' => [
'title' => 'Topic Notification',
'body' => 'This is sent to all topic subscribers'
]
]
]);
自定义数据负载
除了通知,可以发送自定义数据供应用处理:
$response = $client->post('/fcm/send', [
'json' => [
'to' => $deviceToken,
'data' => [
'action' => 'open_screen',
'screen_id' => 'home'
]
]
]);
错误处理
添加异常处理以捕获网络或 API 错误:
try {
$response = $client->post('/fcm/send', [...]);
// 处理响应
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
性能优化
对于大批量发送,考虑以下优化:
- 使用 HTTP/2 连接
- 实现批处理(每次请求最多 1000 个设备)
- 使用异步请求避免阻塞
测试与调试
测试时注意:

- 验证设备令牌是否正确
- 检查 Firebase 控制台的消息统计
- 在 Android 上使用 Logcat 或在 iOS 上使用 Xcode 查看日志
通过以上方法,可以在 PHP 中高效实现 FCM 消息推送功能。根据实际需求调整通知内容和目标设备,确保正确处理响应和错误。






