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
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 implemented FCM for my app. I'm using php to send the notification for the registered ids in my DB . I want to send a specific message for each user. Now when I push the notification, I'm getting the same message for all the users.
Example:
I have two registered users in the DB:
1- User called John and his custom message is "Welcome"
2- User called Marco and his custom message is "Happy birth day"
Now when I push the notification all the two users are getting the same message "Welcome".
This is my code:
<?php
function send_notification ($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message,
'priority' => "high",
);
$headers = array(
'Authorization:key = FCM Server 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_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
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($ch));
}
curl_close($ch);
return $result;
}
include("conn.php");
mysql_select_db($db, $conn);
$query_users = sprintf("Select token, message From users");
$users = mysql_query($query_users, $conn) or die(mysql_error());
$row_users = mysql_fetch_assoc($users);
$totalRows_users = mysql_num_rows($users);
if($totalRows_users > 0 ) {
do {
$tokens[] = $row_users["token"];
$message = $row_users["message"];
} while ($row_users = mysql_fetch_assoc($users));
}
$message_status = send_notification($tokens, $message);
echo $message_status;
?>
you can send fcm with multiple token at once (1000 token limit if i'm not mistake), but, you cannot send with multiple messages
the message that you send is the message from your last record in your queries
$message = $row_users["message"];
if you want to send with different message, then you need to call
send_notification($tokens, $message);
multiple times.
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
I need to create a Listener for new events on server in android.
I was using a request to the server cyclically for new events before.
But this is not a suitable way because of performances and internet traffic.
Another way could be using a listener, but I don't know HOW TO ?
Please guide me!
Polling the server may drain the battery
You can take advantage of Google Cloud Messaging for Android
Google Cloud Messaging (GCM) for Android is a service that allows you
to send data from your server to your users' Android-powered device,
and also to receive messages from devices on the same connection. The
GCM service handles all aspects of queueing of messages and delivery
to the target Android application running on the target device, and it
is completely free.
It will work on Android >= 2.2 (on phones that have the Play Store)
Here is the link to official documentation
Here is a sample php code that sends push notification
<?php
function sendPushNotification($registration_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
define('GOOGLE_API_KEY', 'AIzaSyCjctNK2valabAWL7rWUTcoRA-UAXI_3ro');
$headers = array(
'Authorization:key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
echo json_encode($fields);
$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;
}
?>
Here is a good article on android push 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.