I kinda stuck on a problem. I need to send message notification and alert notification to the device. Message notification is sent when a user send message to other and alert notification is generated to alert user from server. That mean I need multiple notification types. I am using this on my server to push notification to my device.
// This is code from the class that take user input
$notify = "This is message"
$msg = array("Message" => $notify);
$sense = $gcm->send_notification($registatoin_ids, $msg);
//This is the send notification in GCM class
public function send_notification($registatoin_ids, $message) {
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_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_POST, true);
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 post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
How can I adjust the above code to meet my requirement. I tried by sending
$fields = array(
"registration_ids" : registatoin_ids,
"data" : {
"type" : "Message",
"Message" : $message,
}
);
But I got error as
E/JSON(3444): <b>Parse error</b>: syntax error, unexpected ':', expecting ')' in <b>/home/a8709494/public_html/mobile/GCM.php</b> on line <b>25</b><br />
You need to use the => operator for this:
$fields = array(
"registration_ids" => "registatoin_ids",
"data" => array(
"type" => "Message",
"Message" => $message,
)
);
Related
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.
With the new update, FCM is now going to be used.
I tried the sample app from git and it's working all fine. I can send notifications from the console.
But I want to send the notification from the server after a certain event is triggered. I followed the same approach like in GCM but it's not working.
05-20 20:40:58.941 30132-30919/com.google.firebase.quickstart.fcm E/AndroidRuntime: FATAL EXCEPTION: pool-1-thread-1
Process: com.google.firebase.quickstart.fcm, PID: 30132
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' on a null object reference
at com.google.firebase.quickstart.fcm.MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.java:53)
at com.google.firebase.messaging.FirebaseMessagingService.zzo(Unknown Source)
at com.google.firebase.messaging.FirebaseMessagingService.zzn(Unknown Source)
at com.google.firebase.messaging.FirebaseMessagingService.zzm(Unknown Source)
at com.google.firebase.iid.zzb$2.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
05-20 20:40:59.118 30132-30279/com.google.firebase.quickstart.fcm E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb9e83390
Am following this PHP Script to send the notification.
If I try to execute the script, I get the following result.
{"multicast_id":4679427854122301046,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1463757518309261%31bd1c96f9fd7ecd"}]}
NOTE : I went through their docs and modified the code is gist to have only body and title. Even then it's not working.
You can use this complete code
<?php
function sendFCM($mess,$id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'to' => $id,
'notification' => array (
"body" => $mess,
"title" => "Title",
"icon" => "myicon"
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "AIzaSyA9vpL9OuX6moOYw-4n3YTSXpoSGQVGnyM",
'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_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
curl_close ( $ch );
}
?>
Pass message and token id as a parameter to the sendFCM($mess,$id) call.
I tried this and worked:
<?php
$ch = curl_init("https://fcm.googleapis.com/fcm/send");
$header=array('Content-Type: application/json',
"Authorization: key=GoGdfsflknEFñslknaglksjfnklj");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{ \"notification\": { \"title\": \"Test desde curl\", \"text\": \"Otra prueba\" }, \"to\" : \"SGferg-qWEFWbI:dflñkndfakllvakrgalkgjdgjslfkgjdglksdjflksjglkjlkñerhTHDFSHFZDHzdfakjsdhskjhgkjashfdasjdkf\"}");
curl_exec($ch);
curl_close($ch);
?>
This is the result:
{"multicast_id":4913280949692448120,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1473389987003950%ab9a0bb6ab9a0bb6"}]}
In order to receive the notification using remoteMessage.getNotification().getBody(), you have to use the predefined set of key option for notification.
In this case, "notification" is the key word.
The JSON response has to be formatted like this.
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
"icon" : "myicon"
}
}
You can also send notification and data payload in the same JSON response
{
"to" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
"icon" : "myicon"
},
"data" : {
"Nick" : "Mario",
"Room" : "PortugalVSDenmark"
}
}
see this: https://firebase.google.com/docs/cloud-messaging/concept-options#messages-with-both-notification-and-data-payloads
From the php gist you are sending a data only message. Your receiver is expecting a notification message so when you get the notification from the remote message it will be null, resulting in a NPE when you call getBody.
Send a notification message and it should work as expected. See notification message requirements here:
https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support
I was facing the same issue and after spending some time trying to find out the cause , my observation was --
Since the "notification" field is JSON representation of the RemoteMessage.Notification .
If you set any of the predefined fields of the Notification class in the "notification" field , on client side the JSON is successfully parsed and you have a non-null value for RemoteMessage.getNotification() on which you can call the getBody() / getTopic() / getIcon().
But if you don't set any field of the Notification class in the "notification" json field, the parsing to class fails and you will have a null value for RemoteMessage.getNotification()
So, any of the following three JSONs is a valid POST body for pushing a RemoteMessage.Notification ( in addition to the two examples shared by Andrea in earlier answer ) , i.e. these three won't cause the above NPE
{
"to" : "<<FIREBASE_INSTANCE_ID>>",
"notification" : {
"body" : "Notification Message Body"
}
}
{
"to" : "<<FIREBASE_INSTANCE_ID>>",
"notification" : {
"title" : "Notification Title"
}
}
{
"to" : "<<FIREBASE_INSTANCE_ID>>",
"notification" : {
"icon" : "Notification icon"
}
}
And none of the following three are valid for pushing a RemoteMessage.Notification -
Doesn't have the "notification" field
{
"to" : "<<FIREBASE_INSTANCE_ID>>"
}
"notification" field is an empty json
{
"to" : "<<FIREBASE_INSTANCE_ID>>",
"notification" : {
}
}
"notification" field has some key value pairs , but none of the fields defined in RemoteMessage.Notification class
{
"to" : "<<FIREBASE_INSTANCE_ID>>",
"notification" : {
"messageText" : "Notification Message Text",
"messageBody" : "Notification Message Body"
}
}
function send_fcm($tokens,$message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$priority="high";
$fields = array(
'registration_ids' =>$tokens,
'data' =>$message
);
$headers = array(
'Authorization:key=your 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));
echo json_encode($fields);
$result = curl_exec($ch);
curl_error($ch);
if ($result === FALSE)
{
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
store device ids in token variable in an array format
Try this below code this will give push notication for Android from php server side and you can get the device token from android you need pass dynamically to get push notication for more android device.
<?php
function sendmessage_android($devicetoken,$message){
$api_key = 'AIzaSyCtDch9K3ZqGF_SSLYCz4JjMS4-fkJuW';//get the api key from FCM backend
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array('registration_ids' => array($devicetoken));//get the device token from Android
$headers = array( 'Authorization: key=' . $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_RETURNTRANSFER, true );
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($fields) );
$result = curl_exec($ch);
if(curl_errno($ch)){
return 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
$cur_message=json_decode($result);
if($cur_message->success==1)
return true;
else
return false;
}
?>
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 am trying to send data to device with GCM but getting curly braces in output(as below image). I'm new to php and I wonder how to fix this issue. Here is the part of PHP server code :
public function send_notification($registatoin_ids, $message, $title) {
// include config
include_once './config.php';
$url = 'https://android.googleapis.com/gcm/send';
$data = array("title" => $title, "message" => $message);
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $data
);
$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_POST, true);
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 post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
/////////
I changed the send_message.php like this and it fixed.
if (isset($_GET["regId"]) && isset($_GET["message"]) && isset($_GET["title"])) {
$regId = $_GET["regId"];
$messagem = $_GET["message"];
$titlem = $_GET["title"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("message" => $messagem);
$title = array($titlem);
$result = $gcm->send_notification($registatoin_ids, $messagem, $titlem);
echo $result;`
}
EDIT: sorry, with JSON GCM payload data should be an assoc array. Mixed up with an older flavor of the protocol. That said, what is your intent on the Android side like?
EDIT: dump the whole extra bundle.
Bundle b = intent.getExtras();
for(String k : b.keySet())
Log.d("tag", k + "=" + b.get(k).toString());
edited:
ok, I think your problem is you're posting the value {.....} with no key. it's like saying
http://..... com?{myjson:"stuff"}
I haven't reviewed the api, but it seems it should be something like post "data=".json_encode($fields);
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.