I am Working on Xamarin Forms Platform to Implement the Firebase Notification. I have add google-services.json and GoogleService-Info.plist in android and IOS applicaition respectively by setting appropriate property.I have generated token code natively and using dependency service I am getting the generated token for sending notification on same or different device. For sending the Notification I am using php since my application use php as mediator for communicating with database and xamarin forms.
class MyFirebaseIIDService : FirebaseInstanceIdService, IPushHelper
{
public string GetPushToken()
{
return FirebaseInstanceId.Instance.Token;
}
}
public interface IPushHelper
{
string GetPushToken();
}
This is how I am Accessing Token in Xamarin Forms
string token = DependencyService.Get<IPushHelper>().GetPushToken();
PHP Code For Sending Notification
$fields = array(
'to' => $token // Token Generated By Xamarin Forms
'data'=> array("message"=>$message) // Message For Notification
);
//Header Including API Key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$api_key
);
$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('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
Also, I have tried shell_exec() for running curl
$result =shell_exec('curl -X POST --header "Authorization: key='.$api_key.'" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"'.$token.'\",\"priority\":\"high\",\"notification\":{\"body\": \"'.stripslashes($message).'\"}}"');
Output for result:
"{"multicast_id":8563984716459935776,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1585669578263131%631c6722f9fd7ecd"}]}"
But My Application does not recieve push Notification and I could see the send notication in firebase console.
Please Help me for sending and getting Notification using Firebase
Related
I have built web version in Codeigniter and have been working in mobile version with react Native.
To make new order notification, I am going to use firebase clouding message.
how , where can I get this device token ?
public function sendFCMNotification($registration_ids, $message){
$SERVER_API_KEY ='my server api key';
// payload data, it will vary according to requirement
$data = [
"registration_ids" => $registration_ids,
"data" => $message
];
$dataString = json_encode($data);
$headers = [
'Authorization: key=' . $SERVER_API_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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
In your React-Native app, you can get the token like this:
messaging().getToken().then(token => { saveTokenToDatabase(token);});
then listen for any token change
messaging().onTokenRefresh(token => {saveTokenToDatabase(token);});
The method saveTokenToDatabase is used to save the token to your backend so that you can access it later to send messages
In android you need to use this class to get device token
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onNewToken(String token) {
super.onNewToken(token);
Log.e("newToken", token);
//Add your token in your sharefpreferences.
SharedPreferenceManager app_sp = new SharedPreferenceManager(this);
app_sp.putString(Constants.FIREBASE_TOKEN, token);
this service request which update device token on to your server
// updatetokenAPI.updateToken(token);
I'm building an PHP website. I want to push notification to client(who login to my website) so I use Firebase Cloud Messaging.
I already registered Firebase app and write a function to send message
public function sendMessage($data, $target)
{
//FCM api URL
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'MY SERVER KEY';
$fields = array();
$fields['data'] = $data;
if (is_array($target)) {
$fields['registration_ids'] = $target;
} else {
$fields['to'] = $target;
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $server_key
);
$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('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
But I don't know how to get $target to let Firebase send message to.
Now I want when user register/login on my website, I will request token from Firebase and save it to my DB.
Because when I want send message to that user, I need provide target(token) for Firebase. Anyone please help me?
At first, client should have application that uses your firebase project.
Then you can sand message to it application, and you have 2 ways to do it:
You have to acquire his registration token
His app on smartphone should be registered in some topic, ex. "general".
I am trying to get notification in my app using GCM. i am using android studio tool and i tried lots of tutorials. most of them where done using eclips tool.
finally, i tried this one,
http://rmarcejaeger.com/2015/09/18/tutorial-how-to-implement-push-notifications-using-google-cloud-messaging-for-android-part-1-client-app/#comment-576070,
https://github.com/googlesamples/google-services/tree/master/android/gcm
and i finish android client part using above tutorial. But the problem is, i need to setup app server in php which connect my application through GCM. i have no idea to make it possible. i tried the follwing link,
https://developers.google.com/cloud-messaging/server
but i couldn't get much more.So please anyone suggest me better solution.
you need to understand below steps
for more details Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL
First you need to create browser key from Console.
This is the code you need to add for Sending notification GOOGLE_API_KEY is the key you created from Console.
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// 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;
}
}
?>
Now using this method of GCM class you can send notification to the device by calling its method.
pass reg.id that is token id you got from Android device and message you want to pass.
$gcm = new GCM();
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
How can i get Response if the Message was sent or Not, using Php Script, Then i want to use the Response to Determine If the Device is Online or Not,
Here is my Php Script to Send a Message :
function send_push_notification($registration_ids, $message) {
$regId=$registration_ids;
$msg=$message;
$message = array("message" => $msg);
$regArray[]=$registration_ids;
$url = 'https://android.googleapis.com/gcm/send';
$fields = array('registration_ids' => $regArray, 'data' => $message,);
$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_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result=curl_exec($ch);
echo $result;
if($result==FALSE)
{
die('Curl Failed');
}
curl_close($ch);
}
Thanks
The response your server gets from GCM server doesn't tell you if the message was sent or not. It only tells you if the message was accepted by the GCM server or rejected. If it's accepted, GCM server will try to deliver it, but there's no guarantee it would succeed. If it's rejected, you get an error message (such as InvalidRegistration, MissingRegistration, etc...).
If you want an acknowledgment of delivery, you must have code in your Android app that upon receiving of the message makes a call to your server, to acknowledge the message was received.
You don't get response from the app; you can only get response from the GCM system itself. When the CURL call completes, $result contains a JSON-encoded object; its id property contains a message ID upon success.
I have created an Android app with Googles' OAuth 2.0 (from developer console) and has an API key for Android application (it use Google Maps, which works by the way).
However, my problem is that I'm using Push Notifications and it works on the android application though (I get the registration ID), but on the server it doesn't work at all.
I'm using PHP and the problem seems to be the API key which is the same as the one I've for the Android application.
So what key am I supposed to use? And how do I retrieve it?
Code:
<?php
function send_push_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=An_Api_Key',
'Content-Type: application/json'
);
//print_r($headers);
// 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;
}?>
Please check allowed IP addresses in your Google API. You can restrict API access to certain IP addresses and by default one IP address is set when you create new API project.
Remove that IP address so that any IP address (Including your local machine's server) can connect and access the API.
I have implemented similar kind of code and got 401 error. Above fix worked for me. Hope that helps you as well.