How to execute Curl to send notification to users in Firefox - php

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.

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

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.

Android Push notifications and SSL

Im desperate and would realy appreciate your help. I had a php script which sends FCM-Push notifications to my android application but unfortunately since i added a self signed SSl certificate to my server, my application always crash when i submit the request from my application. This is the method of how i submit push notifications:
Php:
$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://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 );
If i outcomment the above code - everything works just fine but of course the application don't receive any push notfications anymore. Please help!
My LogCat in the applications says:
10-03 20:08:02.582 8870-8870/de.xxxxxx.xxxxxxx E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.xxxxxx.xxxxxxx, PID: 8870
java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v7.widget.RecyclerView$Adapter android.support.v7.widget.RecyclerView.getAdapter()' on a null object reference

Google Cloud Messaging Push Notifications only work once (PHP, Android)

I am having trouble getting Google Cloud Messaging for Android working.
I have had it working before but it decides to stop working after the first couple of times.
In order to get it working again I have to delete my API key and recreate it.
I am using PHP with a SERVER API key with a IP whitelist of ::/0 (All IPv6 apparently)
Note: My android app requests a device message key each time the app is opened (Usually returns the same message key)
The Error I get is: Unauthorized Error 401
When I got to the following url to check my app message id i get 'invalid token'.
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14
The PHP code I am using is:
$data = array( 'message' => 'Hello World!222!' );
$ids = array('APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14');
$apiKey = 'AIzaSyATkp_UTZh....'; //obviously the complete key is used...
$url = 'https://android.googleapis.com/gcm/send';
$post = array('registration_ids' => $ids, 'data' => $data);
$headers = array( 'Authorization: key=' . $apiKey, '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, json_encode( $post ) );
$result = curl_exec( $ch );
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;
Thanks for any help given.
EDIT: It seems to work since I unregistered my device and reregistered it with GCM. I am not sure if this is a permanent fix but it works for now.

Php schedule events

I have php script hosted in ftp server.
Its accessed from android app.
I did enabled Google Cloud Messaging in android and also php script.
So I want to send message every one hour.
So I need php schedule for trigger every one hour.
Message is constant.
My php code is:
<?php
define( "API_ACCESS_KEY", "***********************");
// Message to be sent
$message = "welcome to android app";
//RegistrationIds
$registrationid = "******************";
//call to gcm notification
send_push_notification($registrationid,$message);
//gcm push notification function
function send_push_notification($registrationids,$messages){
//GCM Implementation Code
// Set POST variables
$url = "https://android.googleapis.com/gcm/send";
$fields = array(
'registration_ids' => array($registrationids),
'data' => array( "message" => $messages ),
);
$headers = array(
'Authorization: key=' . API_ACCESS_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 );
cur_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 ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
}
?>
I want to call send push notification method every one hour.
You can use cron job for this. You dont have to add anything to the PHP script. Just running it every hour will solve the issue. Below is how you can add a cronjob. I believe you are on a Linux server.
0 * * * * /usr/bin/php /path/to/your/php/script.php
See this link to see how you can add/edit/delete cron tab - http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/

Categories