Laravel Web Push notification using edujugon push-notification - android

I have a problem in my project. I am using edujugon push-notification for push notification of my app, I created push notification to android, ios devices successfully with title, body. But when I integrate the notification in my web devices it does not show the title and body rather it shows the site is upgrated in backend. Also I want to set an url in my web notification. But dont know how.
Here is my code
public static function sendPushNotification($devices, $pushData, $partner = false) {
$android = $devices->where('type', 2)->pluck('token')->all();
if (!empty($android)) {
$push = new PushNotification('fcm');
$push->setMessage(
[
'data' => $pushData,
]
)
->setDevicesToken($android)
->send();
}
$ios = $devices->where('type', 1)->pluck('token')->all();
if (!empty($ios)) {
$push = new PushNotification('apn');
$feedback = $push->setMessage(
[
'aps' => [
'alert' => [
'title' => $pushData['title'],
'body' => $pushData['body'],
],
'sound' => 'default',
'badge' => 1
],
'data' => $pushData
]
)->setDevicesToken($ios)->send()->getFeedback();
}
$web = $devices->where('type', 3)->pluck('token')->all();
if (!empty($web)) {
$push = new PushNotification('fcm');
$push->setMessage($pushData)->setDevicesToken($web)->send();
}
}
and my push data is
$pushData = [
'title' => 'Test',
'body' => 'Test',
];
Please help me solving this

You should write this
if (!empty($web)) {
$push = new PushNotification('fcm');
$push->setMessage(
[
'notification' => $pushData,
]
)->setDevicesToken($web)->send();
}
Hopefully this will solve your problem.

Related

How to add click action when sending FCM notification from Node.js admin SDK to Flutter app?

I have a cloud function which executes this code to send the notification to the user, I am getting notification correctly but I want to navigate to a particular screen for that I have to add click action something like this.
clickAction: FLUTTER_NOTIFICATION_CLICK
I have tried to put this property in different lines of code but nothing seem to work, can someone please tell where should I put it exactly?
This is my index.js file!
const message = {
token: data['guestFcmToken'],
notification: {
title: `New message from ${data['hostName']}.`,
body: data['type'] === 'image' ? 'Photo' : data['lastMessage'],
},
data: {
showForegroundNotification: 'false',
screen: 'chat'
},
}
console.log('Sending message');
const response = await admin.messaging().send(message);
console.log(response);
You can add clickAction: 'FLUTTER_NOTIFICATION_CLICK' in the following way
message = {
token: data['guestFcmToken'],
notification: {
title: `New message from ${data['hostName']}.`,
body: data['type'] === 'image' ? 'Photo' : data['lastMessage'],
},
data: {
showForegroundNotification: 'false',
screen: 'chat'
},
android: {
notification: {
clickAction: 'FLUTTER_NOTIFICATION_CLICK',
},
}
};

How to add settings for Android in the message

I have a code that prepares and sends a notification to a mobile application
// Create the notification
const payload = {
notification: {
title: "Title",
body: "Body",
},
};
// Options
const options = {
contentAvailable: true,
priority: 'high'
};
admin
.messaging()
.sendToDevice(tokenSnapshot, payload, options)
.then(response => {
console.warn(">> Notification sent successfully: ", response);
return response;
})
.catch(error => {
console.warn(">> Notification sent failed: ", error);
});
I would like to add here information such as:
priority: 'max'
visibility: 'public'
These are features supported in Android
It is mentioned in the documentation that it exists.
But there is nothing mentioned how to use it
Can anyone give advice?
The purpose of this is to display Notifications on your phone when it is in the background

Sending Images from android device to api

I'm trying to send an image from an android device to a laravel api using react native, but it doesn't read the url of the image, i.e Unable to init from given url (file:///storage/emulated/0/DCIM/Camera/IMG_20181013_133327.jpg, it always brings that error, it doesn't read the url of the image, file:///storage/emulated/0/DCIM/Camera/IMG_20181013_133327.jpg please how can I send the image to my laravel api successfully or I can I download based on the location of the image on the android device
REACT NATIVE AXIOS
//THE IMAGES ARE FIRST SELECTED AND THE IMAGES ARRAY IS SET WITH THE URI OF THE IMAGES
imageUpload(){
ImagePicker.openPicker({
multiple: true,
cropping: true,
mediaType: 'photo'
}) .then(images => {
console.log(images);
const imagesArray = [];
if(images){
images.map(i => {
imagesArray.push({uri: i.path, type: i.mime, name: i.path});
} );
}
this.setState({
images_array: imagesArray
});
console.log(imagesArray);
console.log(this.state.images_array);
}).catch(e => console.log(e));
}
//THE IMAGES ALONG WITH OTHER DETAILS ARE SENT TO THE LARAVEL API
seller(){
this.setState({loader: true});
var data = {
name: this.state.name,
// user_id: this.state.user_id,
user_id: 18,
description: this.state.description,
amount: this.state.amountT,
qty: this.state.qty,
cat_id: this.state.cat_id,
photos: this.state.images_array
};
/* var config = {
headers: {'Authorization': "Bearer " + this.state.token}
};*/
axios.post(
'http://10.0.2.2:8000/api/sell',
data,
// config
).then((response) => {
this.setState({loader: false});
console.log(response);
Alert.alert(
'Success',
'Product posted Successfully',
[
{text: 'OK', onPress: this.props.navigation.navigate('Land', {})},
], );
}).catch((error) => {
this.setState({loader: false});
Alert.alert(
'Error',
'Internal Server Error, please try again later',
[
{text: 'OK'},
], );
console.log(error);
});
};
LARAVEL BACKEND, i.e Intervention Image api is used
public function imagesUpload($goodsId, $photos){
$images = $photos;
// $count = $images->count;
foreach($images as $image){
$uri = $image['uri'];
$filename = basename($uri);
Image::make($uri)->save(public_path('img/' . $filename));
$saver = new Images;
$saver->product_id = $goodsId;
$saver->location_url = 'img/'.$filename;
$saver->save();
}
return true;
}
using double // does not work on real devices , it may work on emulator but not on real devices .
try using this
uri:'file:///storage/emulated/0/DCIM/IMG_20161201_125218.jpg'
make sure to use /// three forward slashes.

How to open specific page from notification bar using ionic 3 and Firebase Cloud Messaging?

I already follow the instruction on Ionic 3 documentation about Push notification.
When I try to send the notification and my app on background, I cannot trigger 'notification' event so I cannot go through specific page.
But when my app is on foreground, the 'notification' event triggered automatically.
I use:
Ionic 3 as the mobile framework
Firebase Cloud Messagins as the message service
Laravel with larave-fcm plugin to send message
Backend - Laravel code for push message to firebase
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20)->setContentAvailable(true);
$notificationBuilder = new PayloadNotificationBuilder('Hello');
$notificationBuilder->setBody('Hello world')->setSound('default');
$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData(['custom' => 'test']);
$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();
$token = "token";
$downstreamResponse = FCM::sendTo($token, $option, $notification, $data);
$success = $downstreamResponse->numberSuccess();
$failure = $downstreamResponse->numberFailure();
$modification = $downstreamResponse->numberModification();
echo 'Success: '.$success;
echo "<br>";
echo 'Failure: '. $failure;
echo "<br>";
echo 'Modification: '.$modification;
print_r($downstreamResponse->tokensToDelete());
echo "<br>";
print_r($downstreamResponse->tokensToModify());
echo "<br>";
print_r($downstreamResponse->tokensToRetry());
echo "<br>";
print_r($downstreamResponse->tokensWithError());
FRONTEND - My ionic apps constructor on app.component.ts
constructor(private translate: TranslateService, private platform: Platform, settings: Settings, private config: Config, private statusBar: StatusBar, private splashScreen: SplashScreen, public push: Push, public alertCtrl: AlertController, public storage: Storage, private backgroundMode: BackgroundMode) {
this.initTranslate();
this.platform.ready().then(() => {
if(!this.backgroundMode.isActive) {
this.backgroundMode.setDefaults({silent: true});
this.backgroundMode.enable();
} else {
this.backgroundMode.disable();
this.backgroundMode.setDefaults({silent: true});
this.backgroundMode.enable();
}
this.pushSetup();
this.storage.get('test').then((val) => {
if(val == 'news'){
this.nav.setRoot(TabsPage);
}
});
});
}
Function pushSetup()
pushSetup() {
const options: PushOptions = {
android: {
senderID: '10524067XXXXX'
},
ios: {
alert: 'true',
badge: true,
sound: 'false'
},
windows: {}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => {
if(notification.additionalData.foreground){
let myAlert = this.alertCtrl.create({
title: 'Push',
message: JSON.stringify(notification)
});
myAlert.present();
} else {
this.storage.set('test', 'news');
}
});
pushObject.on('registration').subscribe((registration: any) => {
console.log(registration);
});
pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
}
I found the answer from
here.
I should send to fcm with like this
{
"data" : {
"title": "Test Notification",
"body": "This offer expires at 11:30 or whatever",
"notId": 10,
"surveyID": "ewtawgreg-gragrag-rgarhthgbad"
}
}
On laravel fcm just set title, body, notId on addData function from PayloadDataBuilder.

Error in remoteMessage.getNotification().getBody()

I implemented Firebase Cloud Messaging in my application and while using the Firebase console my application in Android and iOS receives my notifications. But because I wanted to push notification daily I created a cron job to do that in my server side. I notice that every time i trigger my cron my application crashes
In my iOS client it doesn't receive any notification.
In my android client it displays an error:
java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' on a null object reference
Where it is in my FirebaseMessagingService here is my code
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
And in my server-side
function sendNotificationFCM($apiKey, $registrationIDs, $messageText,$id) {
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $apiKey
);
$message = array(
'registration_ids' => $registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($message)
));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
I'm wondering why am I having a NPE and how can I solve it?
Try to add a notification object on your $message. The body of your POST request must be something like:
{
"to" : "aUniqueKey",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark"
},
"data" : {
"Nick" : "Mario",
"Room" : "PortugalVSDenmark"
}
}
Your remoteMessage.getNotification() returnsnull because the body of your POST request doesn't contain a notification object.
Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.
Check the Documentation for Advanced Messaging Options for your reference.
if (remoteMessage.getNotification() != null) {
sendNotification(remoteMessage.getNotification().getBody());
}
function sendNotificationFCM($apiKey, $registrationIDs, $messageText,$id) {
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $apiKey
);
$message = array(
'registration_ids' => $registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
'notification' => array(
"body" => "body of notification",
"title" => "title for notification",
)
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($message)
));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
I faced the same issue and found out the solution through few experiments.
I am using Node backend where my Sample Push (Taken from Google Firebase) looks like:
const message = {
data: {score: '850', time: '2:45'},
tokens: nTokenArray
}
admin.messaging().sendMulticast(message)
.then((response) => {
if (response.failureCount > 0) {
const failedTokens = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
console.log('resperrorresperrorresperrorresperror', resp.error);
failedTokens.push(registrationTokens[idx]);
}
});
console.log('List of tokens that caused failures: ' + failedTokens);
}
})
.catch(fcmError => {
console.log({'FCM Errors': fcmError});
})
At Android Side:
Log.d(TAG, "BodyScore: " + remoteMessage.getData().get("score"));
NullPointerException is due to when you use getNotification().getBody() instead of getData().get("score") when you are using Data Payload instead of Notification Payload at server side:
const message = {
data: {score: '850', time: '2:45'},
tokens: nTokenArray
}

Categories

Resources