I am using php server to send FCM push notifications. I want to know how I can send push notifications to multiple topics at the same time.
Here is my code.
function sendPush($topic,$msg){
$API_ACCESS_KEY = '...';
$msg = array
(
'msg' => $msg
);
$fields = array('to' => '/topics/' . $topic, 'priority' => 'high', 'data' => $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));
$pushResult = curl_exec($ch);
curl_close($ch);
}
You use the condition key to send to multiple topics.
For example:
{
"condition": "'dogs' in topics || 'cats' in topics",
"priority" : "high",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message",
}
}
This would send the message to devices subscribed to topics "dogs" or "cats".
Relevant quote from FCM docs:
To send to combinations of multiple topics, the app server sets the condition key to a boolean condition that specifies the target topics.
Note that you are limited to 2 boolean conditions, which means you can send a single message to at most 3 topics.
Update: Now you can include 5 topics.
You can include up to five topics in your conditional expression, and
parentheses are supported. Supported operators: &&, ||, !. Note the
usage for !:
Read the documentation at:
https://firebase.google.com/docs/cloud-messaging/send-message
Related
I'm trying to send push messages from PHP but I'm getting the following error message:
{"multicast_id":4832091122368281316,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I suppose there is a mismatch with the browser ID but I don't know which one I'm supposed to use.
When I register the push notification through JS, I receive the following payload on my PHP server:
{"endpoint":"https://fcm.googleapis.com/fcm/send/XXX:YYY","expirationTime":null,"keys":{"p256dh":"ZZZ","auth":"AAA"}}
To send the message in PHP, I have used the following code (found on stackexchange):
function sendnotification($to, $title, $message, $img = "", $datapayload = "")
{
$msg = urlencode($message);
$data = array(
'title'=>$title,
'sound' => "default",
'msg'=>$msg,
'data'=>$datapayload,
'body'=>$message,
'color' => "#79bc64"
);
if($img)
{
$data["image"] = $img;
$data["style"] = "picture";
$data["picture"] = $img;
}
$fields = array(
'to'=>$to,
'notification'=>$data,
'data'=>$datapayload,
"priority" => "high",
);
$headers = array(
'Authorization: key=MYSERVERKEY',
'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 );
return $result;
I think I'm using the right server key, when I don't, I get a different error message.
For $to, I'm wondering what I should use. I thought I had to use XXX:YYY after the endpoint but it's not working (XXX is very short, YYY is very long). I have also tried ZZZ and AAA but it doesn't help either.
My questions:
What kind of ID should I be using to send the message to one specific browser ?
What should I do to send a notification to all registered browser?
Thanks!
Well you have to make sure store the token of your user browser, which you can only get when they allow on request prompt e.g.
On user Allow the request it generate the token which look like as below
This token you can use for send the message to specific browser.
So in your code where as your $to = it should be the device token.
i.e. "to": "<DEVICE_REGISTRATION_TOKEN>"
I have figured out how to send a push notification with WonderPush through two ways:
#1
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://management-api.wonderpush.com/v1/deliveries');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'accessToken' => "xxx",
'targetIds' => "123",
'campaignId' => "123abc",
'notification' => array(
'alert' => array(
'title' => "Some title",
'text' => "Some text"
)
)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
#2:
require_once('inc/WonderPush/init.php');
$wonderpush = new \WonderPush\WonderPush('xxx', 'yyy');
$response = $wonderpush->deliveries()->create(
\WonderPush\Params\DeliveriesCreateParams::_new()
->setTargetSegmentIds('#ALL')
->setTargetUserIds('123')
->setCampaignId('123abc')
->setNotification(\WonderPush\Obj\Notification::_new()
->setAlert(\WonderPush\Obj\NotificationAlert::_new()
->setTitle('Some title')
->setText('Some text')
))
);
The first method uses the pre-created "campaign" which includes a custom URL when the user clicks the notification and also buttons with possible other URLs. However, I can't change anything on-the-fly, i.e. no custom title, text or URL.
The second method is created by code and there I can have custom titles and texts, but the URL is taken from the settings in WonderPush and I can't make any buttons at all.
Can someone help me to do what I want to do with either of my examples (or a totally new way)?
There are basically two ways to do that:
You can use the notificationOverride parameter to apply a partial diff on the notification that is filled within the campaign in the dashboard.
You can use {{someParameter}} within the notification configured in the dashboard, and fill those parameters when triggering the delivery using notificationParams={"someParameter": "someValue"}.
Best,
I have a new firebase app. The purpose is to send notifications to topics from php server to iOS device.
I have successfully tested everything up to the point of sending notifications from server to specific device id.
However, topics refuse to play nice.
From the PHP side:
function call_firebase_notification ($signal){
$to = "/topics/demo";
$title = "php function test real";
$body = "php function test real body";
$payload = json_encode(array(
"to" => $to ,
"notification" => array(
"title" => $title,
"body" => $body
)
));
$headers = array(
"Authorization: key=AIzaSyBr0G...Euxr5x4_0",
"Content-Type: application/json",
"Content-Length: ". strlen($payload)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$return = curl_exec($ch);
curl_close($ch);
return $return;
}
$return = call_firebase_notification("test");
var_dump($return);
I get a most positive result: string(34) "{"message_id":9067338503195970026}"
From iOS side:
[[FIRMessaging messaging] subscribeToTopic:#"/topics/demo"];
My current partner-in-crime also says that got a positive result when subscribing.
However no notifications arrive (to note it out again: notifications successfully delivered when sending to his id) and no topics appear when trying to send notification from firebase console.
EDIT:
(note to self and to the world)
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
never use these unless absolutely necessary or bored out of your head, this was a demo snippet so i didnt really care, but generally you should update your ssl certs
Could you please try to add priority and content_available parameters on your notification payload.
{
"to": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification": {
"title": "test",
"body": "my message"
},
"priority": "high",
"content_available": true
}
I also noticed that there's a service disruption within Firebase Clould Messaging yesterday per Firebase Status Dashboard.
The answer was quite simple actually: time.
In my case it was about 2 days, but after that notifications to topics randomly worked properly.
Hi i am sending notifications to android mobile from php server. Its working fine with single notifications. But if i send 2 notifications at once. First notification is replacing by second notifications. is there any way i can see 2 notifications in queing (i.e like sms inbox message format).
Below is my php code:
<?php
define("GOOGLE_API_KEY", "API id");
define("GOOGLE_GCM_URL", "https://android.googleapis.com/gcm/send");
function send_gcm_notify($reg_id, $message) {
$fields = array(
'registration_ids' => array( $reg_id ),
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL);
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);
if ($result === FALSE) {
die('Problem occurred: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
}
$reg_id = "device id";
$msg = "Google Cloud Messaging working well";
for($i=0;$i<=3;$i++){
send_gcm_notify($reg_id, $msg);}
since you are sending data to the same notification builder.. second one is placed on top of first one. that is the default way of notification. but if you want to send multiple notifications for two tasks, you should use two notification builders and filter the received messages and call relevant notification builder. but there are limitations, so this depends on your program requirement.
if you are looking for notification as following image
StackYour notifications
I've searched a lot but couldn't find any solution for this question.
I'm using a PHP server and is trying to send PushNotifications to my Android app. But when I'm trying out my code in the browser I get this error: "Error=MissingRegistration".
Here is the code that I run:
registration_ids = array($regId);
$message = array(
'hangMessage' => $message,
'userId' => $user_id
);
$result = $gcm->send_notification($registration_ids, $message);
And this is the code that I call:
$url = "https://android.googleapis.com/gcm/send";
$fields = array(
'registration_ids' => $regisration_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type= application/json',
);
//Open connection
$ch = curl_init();
//Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//Execute psot
$result = curl_exec($ch);
if($result == false){
die('Curl failed: ' . Curl_error($ch));
}
//Close connection
curl_close($ch);
echo $result;
The Request doesn't even come all the way to the server according to the Google APIs Console Report system.
Anyone have any idea what could be wrong?
Your request should look like this :
Content-Type:application/json
Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
{
"registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."],
"data" : {
...
},
}
Therefore I believe the error might be in this line :
'Content-Type= application/json'
Try to change the = to :.
Since the content type header is invalid, the GCM server may assume a default value for the content type (which might be application/x-www-form-urlencoded;charset=UTF-8, in which case the Registration ID requires a different key, which would explain the MissingRegistration error).
BTW, the fact that you get a MissingRegistraton error means that the request does reach the GCM server. GCM requests are not logged in the Google APIs Console Report system.