public function send_fcm()
{
$project="some-project";
require_once 'vendor/autoload.php';
$client = new Google\Client();
$client->setAuthConfig('../menicon_images/some-project-firebase-adminsdk-kgpuf-afs957ea.json');
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$result = $client->fetchAccessTokenWithAssertion();
$accessToken=$result["access_token"];
$fcmUrl = 'https://fcm.googleapis.com/v1/projects/'.$project.'/messages:send';
$notification = [
'title' =>"Some title",
'body' => "SOme message",
];
$fcmNotification =[
'message' => [
'token' => "some-token-device",
'notification' => $notification,
],
];
$headers = [
'Authorization: Bearer '.$accessToken,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
$result = curl_exec($ch);
curl_close($ch);
}
我正在尝试通过 FCM 发送多个选定的设备, 以下是我的代码,目前我只能发送到一台设备。
我已经看到了能够发送到所有设备的代码,但我需要发送到特定设备而不是设备。
我正在寻找一种将令牌数组发送到 FCM 的方法
据我了解您的问题,您想向多个设备发送通知。要使用特定令牌将 FCM 消息发送到多个设备,您需要修改
$fcmNotification
数组的结构。您可以创建一组消息,每个消息都有自己的令牌,而不是使用单个 message
键和单个令牌。以下是如何修改代码的示例:
public function send_fcm()
{
$project = "some-project";
require_once 'vendor/autoload.php';
$client = new Google\Client();
$client->setAuthConfig('../menicon_images/some-project-firebase-adminsdk-kgpuf-afs957ea.json');
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$result = $client->fetchAccessTokenWithAssertion();
$accessToken = $result["access_token"];
$fcmUrl = 'https://fcm.googleapis.com/v1/projects/' . $project . '/messages:send';
$notification = [
'title' => "Some title",
'body' => "SOme message",
];
$deviceTokens = ["some-token-device1", "some-token-device2", "some-token-device3"]; // Add your device tokens to this array
$fcmNotifications = [];
foreach ($deviceTokens as $token) {
$fcmNotifications[] = [
'message' => [
'token' => $token,
'notification' => $notification,
],
];
}
$headers = [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotifications));
$result = curl_exec($ch);
curl_close($ch);
}
在此示例中,
$deviceTokens
数组包含您想要向其发送消息的设备的 FCM 令牌。然后 foreach
循环构造一个 $fcmNotifications
数组,每个数组都有自己的标记。然后使用 curl
请求将该数组发送到 FCM。
确保将
"some-token-device1"
、"some-token-device2"
等替换为您要定位的设备的实际 FCM 令牌。