Firebase 如何发送主题通知

我正在使用以下脚本向特定用户发送通知:

<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'My_API_KEY' );
$registrationIds = array( TOKENS );
// prep the bundle
$msg = array
(
    'body'  => "abc",
    'title'     => "Hello from Api",
    'vibrate'   => 1,
    'sound'     => 1,
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'notification'          => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
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( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
?>

脚本工作正常,但我如何向安装我的应用程序的所有用户发送通知。我在应用中创建了一个主题(提醒),可以通过 firebase 控制台向所有用户发送通知。任何人都可以指导我更新上面的脚本主题。


答案 1

我通过替换修复

$fields = array
(
    'registration_ids'  => $registrationIds,
    'notification'          => $msg
);

$fields = array
(
    'to'  => '/topics/alerts',
    'notification'          => $msg
);

答案 2

您可以在没有 curl 的情况下发送通知(这在我的服务器上不可用)。我准备了一个函数,可以向指定主题发送通知:

sendNotification("New post!", "How to send a simple FCM notification in php", ["new_post_id" => "605"], "new_post", "YOUR_SERVER_KEY");

function sendNotification($title = "", $body = "", $customData = [], $topic = "", $serverKey = ""){
    if($serverKey != ""){
        ini_set("allow_url_fopen", "On");
        $data = 
        [
            "to" => '/topics/'.$topic,
            "notification" => [
                "body" => $body,
                "title" => $title,
            ],
            "data" => $customData
        ];

        $options = array(
            'http' => array(
                'method'  => 'POST',
                'content' => json_encode( $data ),
                'header'=>  "Content-Type: application/json\r\n" .
                            "Accept: application/json\r\n" . 
                            "Authorization:key=".$serverKey
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( "https://fcm.googleapis.com/fcm/send", false, $context );
        return json_decode( $result );
    }
    return false;
}

推荐