简体   繁体   中英

Send Firebase notification with file PHP

My file is the following:

<?php

ignore_user_abort();
ob_start();

 $url = 'https://fcm.googleapis.com/fcm/send';

$Token = 'c128i0tYn..BA';

$fields = array('to' => $Token ,
'notification' => array('body' => 'HI', 'title' => ':)'));


define('GOOGLE_API_KEY', 'AIzaSyA9..4xU');

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

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());
curl_close($ch);
return $result;
?>

It work, perfectly but only for send notifications to a specific device(by the variable $Token).

Now I want to send notifications to all devices that have installed my app, What should I do? . Thanks!!

Change:

'to' => $Token , 

For:

'registration_ids' => $ArrayOfTokens ,

reference https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream

You can always send notification to a topic just make you notification format like:

{
   "to":"/topic/whatever-topic-you-want",
   "notification": {
                  "body":"I am the body",
                  "title":"I am title"
                   },
   "priority":"high"
}

and at the client side, if it's android device then just subscribe to the topic 'whatever-topic-you-want' using:

FirebaseMessaging.getInstance().subscribeToTopic("whatever-topic-you-want");

and all of your device subscribed to that topic will receive the notification

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM