Firebase push notification is not working in android kotlin and PHP - php

i am trying to send push notification from my android device through my server, so i have wrote kotlin code for getting token from firebase and stored it into my server. next step i wrote php script to fetch stored tokens from my server and send message command to firebase. i have tested the same API using postman and u got the success message
{"multicast_id":7524239394194034238,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1587205979775713%03eb2b8403eb2b84"}]}[]
but the message is not received in my android application , when i directly send notification from the firebase console the notification is received in my application i think the problem is in my PHP script. i am new to this firebase configuration and PHP help me to complete this one.
below i'll add my kotlin code and PHP scripts
my kotlin file
class myfirebasemessaging: FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
super.onMessageReceived(remoteMessage)
if (remoteMessage!!.notification != null) {
val title = remoteMessage.notification!!.title
val body = remoteMessage.notification!!.body
NotificationHelper.displayNotification(applicationContext, title!!, body!!)
}
}
}
fetch token from my db
public function getAllTokens($usertype){
$stmt = $this->con->prepare("SELECT token from fcm_token WHERE user_type=?");
$stmt->bind_param("s", $usertype);
$stmt->execute();
//$stmt->bind_result($token);
$result = $stmt->get_result();
$tokens = array();
while($token = $result->fetch_assoc()){
array_push($tokens, $token['token']);
}
return $tokens;
}
Firebase send PHP
class Firebase {
public function send($registration_ids, $message) {
$fields = array(
'registration_ids' => $registration_ids,
'notification' => $message,
);
return $this->sendPushNotification($fields);
}
/*
* This function will make the actuall curl request to firebase server
* and then the message is sent
*/
private function sendPushNotification($fields) {
//importing the constant files
require_once '../Constants.php';
//firebase server url to send the curl request
$url = 'https://fcm.googleapis.com/fcm/send';
//building headers for the request
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
//Initializing curl to open a connection
$ch = curl_init();
//Setting the curl url
curl_setopt($ch, CURLOPT_URL, $url);
//setting the method as post
curl_setopt($ch, CURLOPT_POST, true);
//adding headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//disabling ssl support
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//adding the fields in json format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//finally executing the curl request
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
//Now close the connection
curl_close($ch);
//and return the result
return $result;
}
}
sett message PHP
<?php
class Push {
//notification title
private $title;
//notification message
private $message;
//notification image url
private $image;
//initializing values in this constructor
function __construct($title, $message, $image) {
$this->title = $title;
$this->message = $message;
$this->image = $image;
}
//getting the push notification
public function getPush() {
$res = array();
$res['data']['title'] = $this->title;
$res['data']['message'] = $this->message;
$res['data']['image'] = $this->image;
return $res;
}
}
*sorry for my bad english

You are receiving notification payload on your android app so change your php getPush function to use notification payload:
public function getPush() {
$res = array();
$res['title'] = $this->title;
$res['body'] = $this->message;
$res['image'] = $this->image;
return $res;
}

Related

How to Send OTP to Multiple SMS Api?

I have a php script which allows me to send OTPs to an SMS Api; but sometimes the sms gets delayed or not delivered so I was thinking of adding another Api to the code so now the OTP is sent to WhatsApp as well.
Can any one help me modify the code to add another api in the following code?
$phone = preg_replace('/[^0-9]/', '', $phone);
$curl = curl_init();
$curl = curl_init();
$params = array(
'Username' => '030XXXXXX',
'Password' => 'XXXXXX',
'From' => 'XXXXXX',
'To' => $phone,
'Message' => $message,
);
$encoded_query = http_build_query($params);
curl_setopt($curl, CURLOPT_URL, 'https://connect.jazz.com/sendsms_url.html?' . $encoded_query);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curl_error = curl_errno($curl);
curl_close($curl);
if($test_call) return $result;
if ($curl_error !== 0) {
return false;
}
if ($err) {
return false;
} else {
return true;
}
}
Thank You
Use the strategy pattern to implement your SMS providers. Then you can send your messages with jobs and when the job was failed retry that with another strategy (provider like WhatsApp).
Example job to handle the failing situation:
class SendExampleSmsJob implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
public function handle()
{
// Process sending message ...
}
/**
* Handle a job failure.
*/
public function failed(Throwable $exception)
{
// dispatch another job to send Whatsapp message or something else
}
}

Android App not vibrating outside of app

I have a little problem: If I send a notification to my android device via php from the web, a notification gets built, but isn't vibrating outside the app. It is only vibrating while I am inside the app.
Here are my codes:
PHP:
function send_notification ($token, $message, $Raum, $Notruf){
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array('to' => $token, 'notification' => array('body' => "Raum ".$Raum.", Notruf ".$Notruf), 'data' => array ('message' => $message));
$headers = array ('Authorization:key = (HERE IS MY AUTH 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_IPRESOLVE, CURL_IPRESOLVE_V4);
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;
}
$sql = 'SELECT token FROM devices as d, Sani as s WHERE d.sean = s.sean AND s.Status!=0';
$result = mysqli_query($db, $sql);
$tokens = array ();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)){
$tokens[] = $row["token"];
}
}
mysqli_close($db);
$message = array ("message" => "Raum ".$Raum.", Notruf ".$Notruf);
for ($i = 0; $i < count($tokens); ++$i) {
$message_status = send_notification ($tokens[$i], $message, $Raum, $Notruf);
echo $message_status;
}
My Android Notification Code:
public class MyNotificationManager {
private Context mCtx;
private static MyNotificationManager mInstance;
private MyNotificationManager(Context context){
mCtx=context;
}
public static synchronized MyNotificationManager getInstance(Context context){
if(mInstance== null){
mInstance = new MyNotificationManager(context);
}
return mInstance;
}
public void displayNotification(String title, String body){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx, Constants.CHANNEL_ID)
.setSmallIcon(R.drawable.sirenlight)
.setContentTitle(title)
.setVibrate(new long[] {0, 5000, 100, 5000, 100, 5000, 100, 5000, 100, 5000, 100, 5000})
.setContentText(body);
Intent intent = new Intent(mCtx, EinsatzInterface.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
if(mNotificationManager!=null){
mNotificationManager.notify(1, mBuilder.build());
}
}
}
I couldn't get any fixes online, so I am asking here.
How I said, the vibration is working, but only inside the app. If I close it, even without stopping the process, it only shows the notification and doesn't vibrate or show the correct logo.
When inside the app the notification looks like this (vibrating and icon showing):
When outside the app the notification looks like this (not vibrating and icon not showing):

How do i fix my JSON format by using php

I try to send json format to my android app , but i find that my json format is uncorrect.
{data={"image":"http:\/\/www.androidhive.info\/wp-content\/uploads\/2016\/01\/Air-1.png","message":{"chat_room_id":"","created_at":"2017-03-22 3:34:30","message_id":"","message":"77"},"user":{"user_id":null,"gcm_registration_id":null,"name":null,"created_at":null,"email":null}}, flag=0, title=Google Cloud Messaging, is_background=false}
I set the data like this:
$app->post('/users/send_to_all',
function() use ($app) {
$response = array();
verifyRequiredParams(array('user_id', 'message'));
require_once __DIR__ . '/../libs/gcm/gcm.php';
require_once __DIR__ . '/../libs/gcm/push.php';
$db = new DbHandler();
$user_id = $app->request->post('user_id');
$message = $app->request->post('message');
require_once __DIR__ . '/../libs/gcm/gcm.php';
require_once __DIR__ . '/../libs/gcm/push.php';
$gcm = new GCM();
$push = new Push();
//get the user using userid
$user = $db->getUser($user_id);
//creating tmp message , skipping database insertion
$msg = array();
$msg['message'] = $message;
$msg['message_id'] = '';
$msg['chat_room_id'] = '';
$msg['created_at'] = date('Y-m-d G:i:s');
$data = array();
$data['user'] = $user;
$data['message'] = $msg;
$data['image'] = 'http://www.androidhive.info/wp-content/uploads/2016/01/Air-1.png';
$push->setTitle("Google Cloud Messaging");
$push->setIsBackground(FALSE);
$push->setFlag(PUSH_FLAG_USER);
$push->setData($data);
//sending message to topic `global`
//on the device every user should subscribe to `global` topic
$gcm->sendToTopic('global', $push->getPush());
$response['user'] = $user;
$response['error'] = false;
echoRespnse(200, $response);
});
Here is my Push.php about getPush():
public function getPush() {
$res = array();
$res['title'] = $this->title;
$res['is_background'] = $this->is_background;
$res['flag'] = $this->flag;
$res['data'] = $this->data;
return $res;
}
Here is my Gcm.php about sendToTopic:
//sending message to a topic by topic id
public function sendToTopic($to, $message) {
$fields = array(
'to' => '/topics/' . $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
I'm really not familiar with php , how do i fix the JSON format ?
Any help would be appreciated , thanks in advance !
I update my question , i find json_encode in my Gcm.php:
It's on curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
class GCM {
//constructor
function __construct() {
}
//sending push message to single user by gcm registration id (array 最後面有, 待看)
public function send($to, $message) {
$fields = array(
'to' => $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//sending message to a topic by topic id
public function sendToTopic($to, $message) {
$fields = array(
'to' => '/topics/' . $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//sending push message to multiple users by gcm registration ids
public function sendMultiple($registration_ids, $message) {
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//function makes curl request to gcm servers (__DIR__ 待看)
private function sendPushNotification($fields) {
//include config
include_once __DIR__ . '/../../include/config.php';
//Set POST variable
//$url = 'https://gcm-http.googleapis.com/gcm/send';
$url='https://fcm.googleapis.com/fcm/send';
$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);
return $result;
}
}
?>
It's still let my json format incorrect , how do i fix ?
PHP has some built-in json functions, you need json_encode() and json_decode().
For example this code:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Will print:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Here's the link to documentation for json_encode() and for the entire json in php documentation.
Hope this helps.
Your JSON is invalid. try:
{"data":{"image":"http:\/\/www.androidhive.info\/wp-content\/uploads\/2016\/01\/Air-1.png","message":{"chat_room_id":"","created_at":"2017-03-22 3:34:30","message_id":"","message":"77"},"user":{"user_id":null,"gcm_registration_id":null,"name":null,"created_at":null,"email":null}}, "flag":0, "title":"Google Cloud Messaging", "is_background":false}
Notice ive replaced usage of = with : and wrapped keys and strings in quotes (")
To get it into a nice json string with php you need to build your array correctly first. Possible way is to setup a response array and then you can json_encode() it.
$response =[
'data' => $data,
'flag' => 0,
'title' => 'Google Cloud Messaging',
'is_background' => false.
];
now you can
json_encode($response);

How to POST via Reddit API (addcomment)

I've been able to successfully log a user in and return their details. The next step is to get them to post a comment via my app.
I tried modifying code from the reddit-php-sdk -- https://github.com/jcleblanc/reddit-php-sdk/blob/master/reddit.php -- but I can't get it to work.
My code is as follows:
function addComment($name, $text, $token){
$response = null;
if ($name && $text){
$urlComment = "https://ssl.reddit.com/api/comment";
$postData = sprintf("thing_id=%s&text=%s",
$name,
$text);
$response = runCurl($urlComment, $token, $postData);
}
return $response;
}
function runCurl($url, $token, $postVals = null, $headers = null, $auth = false){
$ch = curl_init($url);
$auth_mode = 'oauth';
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10
);
$headers = array("Authorization: Bearer {$token}");
$options[CURLOPT_HEADER] = false;
$options[CURLINFO_HEADER_OUT] = false;
$options[CURLOPT_HTTPHEADER] = $headers;
if (!empty($_SERVER['HTTP_USER_AGENT'])){
$options[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
}
if ($postVals != null){
$options[CURLOPT_POSTFIELDS] = $postVals;
$options[CURLOPT_CUSTOMREQUEST] = "POST";
}
curl_setopt_array($ch, $options);
$apiResponse = curl_exec($ch);
$response = json_decode($apiResponse);
//check if non-valid JSON is returned
if ($error = json_last_error()){
$response = $apiResponse;
}
curl_close($ch);
return $response;
}
$thing_id = 't2_'; // Not the actual thing id
$perma_id = '2daoej'; // Not the actual perma id
$name = $thing_id . $perma_id;
$text = "test text";
$reddit_access_token = $_SESSION['reddit_access_token'] // This is set after login
addComment($name, $text, $reddit_access_token);
The addComment function puts the comment together according to their API -- http://www.reddit.com/dev/api
addComment then calls runCurl to make the request. My guess is that the curl request is messed up because I'm not receiving any response whatsoever. I'm not getting any errors so I'm not sure what's going wrong. Any help would really be appreciated. Thanks!
If you are using your own oAuth solution, I would suggest using the SDK as I said in my comment, but extend it to overwrite the construct method.
class MyReddit extends reddit {
public function __construct()
{
//set API endpoint
$this->apiHost = ENDPOINT_OAUTH;
}
public function setAuthVars($accessToken, $tokenType)
{
$this->access_token = $accessToken;
$this->token_type = $tokenType;
//set auth mode for requests
$this->auth_mode = 'oauth';
}
}
You just need to make sure that you call setAuthVars before running any api calls.

Google cloud messaging unreliable between devices? Switch to other protocol or other service?

I am working for a few days on an app which is based on real time communication between devices. In the past I was using GCM for notifications via POST methods using the OkHttp library. So far, so good.
But when it comes to real time communication I face a lot of issues around connection timeouts or even mesages which are never delivered.
My implementation is simple. First the user from his phone sends a request via POST and my online server to another phone (driver) which than confirms the request and replies back to the sender via another POST method and via the online server.
But only about 80% of the replies get back to the user, or they arrive after several minutes.
Can the problem be in my implementation?? Or should I switch to GCM Cloud Connection Server (XMPP)??
I am in serious need of some suggestions, please light me up.
Regards.
Php implementation:
<?php
include_once '../includes/db_connect.php';
// Query database for driver's regId
if(!empty($_POST["str"])) {
$sql = "SELECT * FROM DRIVERS WHERE NAME = '$_POST[driver]' " ;
$result = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_assoc($result);
$gcmRegID = $row["REGID"];
$clientId = $_POST["clientId"];
$street = $_POST["str"];
$number = $_POST["nr"];
$bloc = $_POST["bl"];
$scara = $_POST["sc"];
if (isset($gcmRegID)) {
$gcmRegIds = array($gcmRegID);
$message = array("jstr" => $street, "jnr" => $number, "jbl" => $bloc, "jsc" => $scara, "jId" => $clientId);
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
}
}
// Reply to the client if available or not
if(!empty($_POST["response"])) {
$gcmRegID = $_POST["clientId"];
$response = $_POST["response"];
$gcmRegIds = array($gcmRegID);
$message = array("jresp" => $response);
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
}
//generic php function to send GCM push notification
function sendPushNotificationToGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message
);
// Google Cloud Messaging GCM API Key
define("GOOGLE_API_KEY", "**************");
$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);
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;
}
?>
Order Activity - for sending request to the driver
public void callDriver (View view){
MySendTask send = new MySendTask();
send.execute();
Toast.makeText(getApplicationContext(), "Button Pressed :)",
Toast.LENGTH_SHORT).show();
}
private class MySendTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
progressb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String str = streetName.getText().toString();
String nr = streetNr.getText().toString();
String bl = bloc.getText().toString();
String sc = scara.getText().toString();
SharedPreferences prefs = getSharedPreferences("Notification", MODE_PRIVATE);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
try {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(10000, TimeUnit.MILLISECONDS);
RequestBody formBody = new FormEncodingBuilder()
.add("clientId", registrationId)
.add("driver", "Peter Bleul")
.add("str", str)
.add("nr", nr)
.add("bl", bl)
.add("sc", sc)
.build();
Request request = new Request.Builder()
.url("http://edmon.net/andr/index.php")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), "Order successfully sent!",
Toast.LENGTH_SHORT).show();
progressb.setVisibility(View.INVISIBLE);
}
}
}
GCM does not guarantee message delivery. GCM also throttles message delivery which can often result in significant delays. For more details on this topic see: http://developer.android.com/google/gcm/adv.html (goto the "Lifetime of a Message" section").
I have experienced issues similar to yours in the app I work on.
Thus it does not seem that GCM is a good candidate for real-time communication.
I have found an excellent example, with great sample applications explaining the process wonderfully, thanks to: Antoine Cambell
I reccomend it for everyone seaking answers for a simmilar application.

Categories