Push notification not coming if App is closed Php Android - php

I am working on a push notification in android with PHP ( using fcm), Push notification is working fine but I am not getting any push notification whenever my App is "closed" (I am getting notification only whenever my app is "open")
Here is my code, where I am wrong?
function testingPush(){
define("FCM_URL", "https://fcm.googleapis.com/fcm/send");
define( "FCM_KEY","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$devicetype1 = "ios";
$devicetype2 = "android";
$deviceType = $rows['device_type']; // coming from database
$deviceToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$titleMessage="Push Notification Testing";
$message="Lorem Ipsum";
$msgs = array();
if (strcasecmp($devicetype1, $deviceType) == 0)
{
/* sending push to IOS */
$notification = array('body'=>$message,
'sound'=>"default",
'title'=>$titleMessage,
'badge'=>1);
$data = array('notificationType'=>1,
'displayURL'=>"https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG");
$msgs = array('to'=>$deviceToken,
'content_available'=>true,
'mutable_content'=>true,
'notification'=>$notification,
'priority'=>'high',
'data'=>$data);
}
else{
/* sening push to android */
$notification = array('contentTitle'=>$titleMessage,
'message'=>$message);
$msgs = array('to'=>$deviceToken,
'priority'=>'high',
'data'=>$notification);
}
$this->sendPushNotification_With($msgs);
}
private function sendPushNotification_With($json) {
$headers = array('Authorization: key=' . FCM_KEY,'Content-Type: application/json');
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, FCM_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($json) );
$result = curl_exec($ch );
curl_close( $ch );
}

Well I think the problem is contentTitle in $notification , replace it to title and it should work and also in your ios notification you are using notification as seperate variable, I would rather suggest you to pass the notification paramter in data , as notification don't work in background.If above don't work recheck your key

Related

FCM messages is not always delivered

I push Firebase messages from PHP and they usually get the target Android app.
Nonetheless, and occasionally, a push message is not correctly delivered if the target Android mobile was inactive for some period of time. Then, if I open the app, the message is delivered immediately.
I read about the Doze status; the battery optimizations; etc. I don't want to bother the user to explicitly whitelist the app.
Thanks in advance !
PHP:
private function sendFirebaseMessage($msg, $to_uid) {
// getting firebase token ID
$user_token_id = DB::getInstance()->getUserFirebaseTokenId($to_uid);
#API access key from Google API's Console
define( 'API_ACCESS_KEY', 'A...7' );
$fields = array
(
'to' => $user_token_id,
'data' => $msg,
"priority" => "high"
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
#Send Reponse To FireBase Server
$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 );
#Echo Result Of FireBase Server
return $user_token_id . "]XXX[" . $result;
}
Android/Java:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// Check if message contains a data payload.
Map<String, String> data = remoteMessage.getData();
if (data.size() > 0) {
Log.d(TAG, "StorableMessage data payload: " + data);
if (data.containsKey("sender_id") &&
data.containsKey("sender_name") &&
data.containsKey("chat_topic")) {
if (!ChatActivity.IsVisible) {
NotifsManager.showFirebaseNotif(this,
data.get("sender_name"),
data.get("sender_id"),
data.get("chat_topic"));
}
}
}
}
If the device is sleeping the messages are not delivered immediately, FCM works in this way.
In addition, if you add the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission in the manifest, Google may block your app in the PLay Store if it does not comply with this : https://developer.android.com/training/monitoring-device-state/doze-standby.html#exemption-cases

Set FCM channel ID in PHP for notifications

I'm trying to send FCM notification to Android device using PHP. My code is working for devices before Android O.
In Android O, we need to set channel ID in request as well to receive notifications, which I cannot figure out how to do.
I have done the necessary setup in the app and using Firebase Console I can receive a notification, but it fails when I try sending it through the PHP script.
I also looked into the link below but it doesn't work for me.
Android FCM define channel ID and send notification to this channel through PHP
My PHP code:
$notification = new Notification();
$notification->setTitle("startSession");
$notification->setBody($_POST['child_id']);
$notification->setNotificationChannel('my_channel_id');
$requestData = $notification->getNotification();
$firebase_token = $_POST['token'];
$firebase_api = 'my_value';
$fields = array(
'to' => $firebase_token,
'data' => $requestData,
);
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . $firebase_api,
'Content-Type: application/json'
);
$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);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if($result === FALSE){
die('Curl failed: ' . curl_error($ch));
$return_obj = array('responseCode'=>'0' , 'responseMsg'=> 'Error inserting, please try
again.', 'errorCode'=>'1');
}else{
$return_obj = array('responseCode'=>'1' , 'responseMsg'=> 'Successfully inserted.',
'errorCode'=>'0');
}
// Close connection
echo json_encode($return_obj);
curl_close($ch);
My notification class code is:
<?php
class Notification{
private $title;
private $body;
private $answer_value;
private $android_channel_id;
function __construct(){
}
public function setTitle($title){
$this->title = $title;
}
public function setBody($body){
$this->body = $body;
}
public function setAnswer($answer){
$this->answer_value = $answer;
}
public function setNotificationChannel($channel){
$this->android_channel_id = $channel;
}
public function getNotificatin(){
$notification = array();
$notification['title'] = $this->title;
$notification['body'] = $this->body;
$notification['answer'] = $this->answer_value;
$notification['android_channel_id'] = $this->android_channel_id;
return $notification;
}
}
?>
I'm sure the syntax is correct as the notification still works on devices with Android < 26.
Any help will be really appreciated. Thanks!
You can set your channel Id in server side PHP
PHP server side
<?php
function Notify($title,$body,$target,$chid)
{
define( 'API_ACCESS_KEY', 'enter here your API Key' );
$fcmMsg = array(
'title' => $title,
'body' => $body,
'channelId' => $chid,
);
$fcmFields = array(
'to' => $target, //tokens sending for notification
'notification' => $fcmMsg,
);
$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, true );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fcmFields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result . "\n\n";
}
?>
I define function Notify with 4 parameters title,body,target,chid to use it just call the function and define its parameters,
You must add your channelId in your client side (Android part), with
out channelId you can't get notifications in Android 8.0 and later

GCM Register Broken

I created some PHP code that gets a GCM register from the database and sends a push to an Android device. This code works ok, but when the user deletes the app on Android for example the GCM register in the database gets invalid.
How do I know when the GCM register is invalid in order to delete it from the database using PHP?
This is the code that sends push:
//Getting api key
$api_key = "....";
//Getting registration token we have to make it as array
$reg_token = array($token);
//Getting the message
$message = $versiculo;
//Creating a message array
$msg = array
(
'message' => $message,
'title' => $capitulo,
'id_versiculo' => $id,
);
//Creating a new array fileds and adding the msg array and registration token array here
$fields = array
(
'registration_ids' => $reg_token,
'data' => $msg
);
//Adding the api key in one more array header
$headers = array
(
'Authorization: key=' . $api_key,
'Content-Type: application/json'
);
//Using curl to perform http request
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/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 ) );
//Getting the result
$result = curl_exec($ch );
curl_close( $ch );
When the client app is uninstalled, the corresponding token will be invalidated, where if you send a message to that specific token, it would return a NotRegistered error, in which case you can delete (or archive) that token.
As mentioned in the comments, please proceed to migrate your app to FCM, as Google already provided a notice of deprecation (see my answer here).
For FCM, the behavior is actually the same. See this similar/possibly duplicate post.

How to execute Curl to send notification to users in Firefox

below is my code which i use to execute Push to Chrome Users , now I want to notification to firefox Users , and i know that it will be now targetted via url "https://updates.push.services.mozilla.com/push"
But I don't know what I have to do.
My Code working for Chrome is Provided below .
<?php
include('header.php');
define( 'API_ACCESS_KEY', '[API-KEY comes here]' );
$sql="SELECT * FROM user_data";
$result = mysqli_query($conn, $sql) or die ('Error'.mysqli_error($conn));
$registrationIds=array();
while($row=mysqli_fetch_assoc($result)){
$registrationIds[] = $row['allow'];
}
$ids=json_encode($registrationIds);
$fields = array
(
'registration_ids' => $registrationIds
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/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 );
echo $result;
?>
You should be able to POST, just like you are above, to the Firefox user's subscription endpoint. You don't need an API key. The only header you need to send is TTL: x where x is the number of seconds you'd like Mozilla to keep the message around in case we can't deliver it immediately.
Good resources for further reading:
https://serviceworke.rs/ - live examples with annotated source code
https://hacks.mozilla.org/2016/01/web-push-arrives-in-firefox-44/ - description of how the client-side bits of Push work
https://autopush.readthedocs.org/en/latest/http.html - documentation for Mozilla's Push Service's HTTP API
https://github.com/mozilla-services/autopush - source code for Mozilla's Push Service
Lastly, if you're using Firefox 47 (currently Developer Edition), we've got a whole new suite of tools for debugging Service Workers and Push that you can find at about:debugging#workers.

Android phonegap send push notification using Google Cloud Messaging using php

I have developed the android application in cordova 3.4 now I want to get the automatic notification to their mobile. For this I refer websites as below
http://devgirl.org/2013/07/17/tutorial-implement-push-notifications-in-your-phonegap-application/
http://devgirl.org/2012/10/25/tutorial-android-push-notifications-with-phonegap/
https://github.com/hollyschinsky/PushNotificationSample30/tree/master/platforms/android
I read all above links then did all stuff they told like create project on google cloud messaging , get the project id , create server key (In textbox I given my private server IP) then API Key, I also have registration id device and I wrote code in php for sending push notification to my device but it is giving me "unauthorised Error 404"
my code is as below
define( 'API_ACCESS_KEY', 'my api key' );
//$registrationIds = array( $_GET['id'] );
$registrationIds = array($id);
//var_dump($registrationIds);die;
//prep the bundle
$msg = array
(
'message' => 'New Jobs is updated',
'title' => 'get the job in cad',
'subtitle' => 'get the job in cad',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/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 );
echo $result;
I just hit url and send the registration id of device to the my php page but this page give me the error unauthorised Error 401.
Que.1. Is this possible to send the push notification from php which is hosted on private server?
Que.2 Is device registration id compulsory for sending push notification to those user they installed the apps?
Please anybody help me how to solve this above error and if anybody have another solution then tell me. I tried from yesterday but not achieve my goal so please help me.
Here is the GCM code and its working properly with my device though its in CI framework but hope you can use it. It is compulsory to add device_id for the push and also the passphrase you'll get for the site. just try it.
function sendNotification($device_id,$message) {
/*echo $device_id;
echo "<br>";
echo $message;*/
// note: you have to specify API key in config before
$this->load->library('gcm');
// simple adding message. You can also add message in the data,
// but if you specified it with setMesage() already
// then setMessage's messages will have bigger priority
$msg = $this->gcm->setMessage($message);
//var_dump($message);
// add recepient or few
$this->gcm->addRecepient($device_id);
//var_dump($device_id);
// set additional data
//$this->gcm->setData($params);
// also you can add time to live
$this->gcm->setTtl(500);
// and unset in further
//$this->gcm->setTtl(false);
// set group for messages if needed
//$this->gcm->setGroup('Test');
// or set to default
//$this->gcm->setGroup(false);
// send
return $this->gcm->send();
}
Hope it'll solve your problem.
<?php
$register_keys = array("YOUR_REGISTRY_KEYS")
$google_api_key = "YOUR_API_KEY";
$registatoin_ids = $register_keys;
$message = array("price" => $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));
}
//print_r($result);
// Close connection
curl_close($ch);
?>

Categories