firebase - php - send notification to everyone - java

I want to send a background notification from fcm to all my users. This is my code, the only problem I've faced is that I have to put a token id. I need to send notification to all of my users without defining the token values
This is my code :
<?php
define('API_ACCESS_KEY','Api');
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$token='token';
$notification = [
'title' =>'title',
'body' => 'body of message.',
'icon' =>'myIcon',
'sound' => 'mySound'
];
$extraNotificationData = ["message" => $notification,"moredata" =>'dd'];
$fcmNotification = [
//'registration_ids' => $tokenList, //multple token array
'to' => $token, //single token
'notification' => $notification,
'data' => $extraNotificationData
];
$headers = [
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
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($fcmNotification));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
It works fine and send notifications successfully, but how can I send notification to everyone?

It looks like there is no such feature to send notifications to all devices.
However, there is a workaround for your problem using topics. For this you will need to subscribe all users to a specific topic during the app startup.
FirebaseMessaging.getInstance().subscribeToTopic("your_topic");
Then you can send the notification to that topic so that the notification will be sent to all users.
'to' => '/topics/your_topic', // using topic instead of token

If i get your question.
You need to subscribe a Topic and then you just need to use that Topic.
The users who subscribed to it, will get the notification.
Docs:-
Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.
https://firebase.google.com/docs/cloud-messaging/android/topic-messaging

There are two ways to send notification to multiple users.
Create a topic with all the users in it and send the push to that topic.
Example: https://firebase.google.com/docs/cloud-messaging/android/send-multiple
Send notification to application the package id. But this will send notification even to the non authenticated user.

Related

how to get registration id from firebase to send notification

There is a php code to prepare a bundle for sending notification to firebae :
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
(
'body' => $_GET['body'],
'title' => $_GET['title'],
'vibrate' => 1,
'sound' => 1,
);
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
I want same in java, i did all well and getting response 200 from firebase.
but i dont know how to get registration-id . As done in php like :
$registrationIds = array( $_GET['id'] );
Please help me to find out the registration-id.
To get the registrationId of a device(iOS or Android) the device needs to send/store it in a DB some where. I recommend using the realtime database provided by firebase.
First to get registrationId from the iOS App. Use let token = FIRInstanceID.instanceID().token(). This Token is known as the registrationId
Take this token and store it in your DB.
Server side you need to get that token out of your DB and place it as the value for the registration_ids or as the value for the "to" key. That should be it.
What about the "to"
So it's well laid out on how to use "to" in this StackoverflowPost
You don't get the "to" parameter from the client.

How to send android push notification from website chat

I have completed programming a website chat like whatsapp design and I have created application in android. The app browser this website chat (only show website like chrome browser).
I need help to understand how can I get notification on my application when user get message The android notification should show "you have new message".
My question is how I can send data from website to android using push notification
The website chat
Your android application should be GCM registered and then you can send a GCM from your website which will then be pushed to your application.
For more details see : https://developer.android.com/google/gcm/client.html
For detailed tutorial see : http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
public function notificationToAndroidAction($pushId){
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => array($pushId),
'data' => array("message" => 'hello!'),
);
$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_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarily
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 'sent';
}

PHP post data not being set calling Java Rest Web Service

I know there are a lot of questions related to this issue, but I'm facing an specific requirement for this purpose of posting data from PHP to a Rest Web Service. The details are explained above, but in summary, when I post data to a url (REST WS) and set the CURLOPT_POSTFIELDS the data is not being added to the request.
The scenario: I have a lot of Java Web Services (REST) running as modules, for example, I have a fileUploadModule which is a REST, I have a databaseModule which is another rest and finally a SearchModule, which is another REST.
I can invoke them directly my rest modules using a link like:
http://[MY IP]:8020/system.file.ws.module.ModuleFile/getResults/jsonp?fileName=fileName
http://[MY IP]:8021/system.search.ws.module.ModuleSearch/getResults/jsonp?xmlQuery=myXml
For the case of files and database, the programmer that was managing the code before me used gwt that connected to the module through a proxy; for instance:
http://[MY_PROXY_IP]:8013/system.file.ws.module.ModuleFile/getResults/jsonp?fileName=fileName
and in my proxy I can print the value of the request received, in this case I use a GET and I can print the request as:
GET /system.file.ws.module.ModuleFile/getResults/jsonp?fileName=idc1&folderType=campaign&callback=__gwt_jsonp__.P0.onSuccess&failureCallback=__gwt_jsonp__.P0.onFailure HTTP/1.1
. Now I am responsible for search that should run through PHP. I tested the url directly to the module and it works, but if I try to it by a proxy it does not seems to be working, it reach my proxy but when I print the request it is incomplete:
POST /system.search.ws.module.ModuleSearch/getResults HTTP/1.1
and I am supposed to receive something like the module file, I share my php code, all seems to be ok, but I don't know what can I be doing wrong... when I set the parameters in CURLOPT_POSTFIELDS the string is not being set
$url = "http://192.168.3.41:8013/system.search.ws.module.ModuleSearch/getResults";
try {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, 1);
$rawXml = $_POST['rawXml'];
$rawXml = str_replace("%", "%25", $rawXml);
$rawXml = str_replace("&", "%26", $rawXml);
$rawXml = str_replace("=", "%3D", $rawXml);
echo $rawXml;
curl_setopt ($ch, CURLOPT_POSTFIELDS,'xmlQuery='.$rawXml);
$info = curl_exec ($ch);
curl_close ($ch);
echo $info;
} catch (Exception $e){
echo $e->getMessage();
}
please I would really appreciate your help or observations. Than you very much in advance.
After long time, I saw this without an answer. I discovered the fail of this some time ago. This issue occurred because, when reaching server side, for some reason a batch file I did not noiced was adding an additional line to my content, and whenever I read the request content with my proxies, I used a "\n" delimiter, I mean, I have been reading my data using as the EOF indicator a line jump, that's why the content was never shown. I had to modify the code inside my proxy to allow reading the request until the end, not when finding a "\n" character. I mean, the content of the post was set in every case, but a batch process was corrupting that data. So thata was the issue, I just solved it by making sure that my reader always read my entire file considering even line jumps and white lines.
Regards.

How do I emulate a PHP cURL request in Java?

$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $urls[$vidCount]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);
curl_close($ch);
So I have a cURL request that takes a URL and produces a file in the filesystem.
How do I emulate the above PHP cURL request in Java?
I have tried HttpURLConnection, but I am getting 403 Forbidden. The same call in cURL works properly. Is there some architecture difference between the two that I need to reconcile?
I believe it could be something in the headers that cURL might be setting automatically where Java is not. I'm not really sure but I would appreciate any advice I can get.
Thanks.
I am not sure why you trying to emulate PHP behavior in Java. If the end result is really what you need to reach, than use the Java HttpURLConnection or even URLConnection.

POST data from PHP and GET data in java servlet

is there any method that I can retrieve data (eg, username and password) from PHP to a Java servlet? Thanks
Create a POST request in PHP:
Use cURL:
$ch = curl_init('http://www.example.com:8080/my-servlet/');
$data = '...' # the data you want to send
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
A better, more concise approach, using pecl_http:
$response = http_post_data('http://www.example.com:8080/my-servlet/', $data);
POST and GET pretty much do not depend on the language being used, so if I understand your question correctly, you can use either $_POST['var'] in PHP or request.getParameter("var") in Java on the page that receives the POST data.

Categories

Resources