Send push notifications via AWS Pinpoint to specified User - android

I am using react-native and amplify to send push notifications to devices via AWS Pinpoint. I can get the generated token for the devices. But I just need to send push notifications using user Id. I try to update the endpoint, but it's not working. Can anyone suggest me the proper way to handle this?
PushNotification.onRegister((token) => {
console.log('in app registration', token);
Analytics.updateEndpoint({
address: token,
channelType: "GCM",
OptOut: 'NONE',
userId: "12345"
}).then(data => {
console.log(data)
}).catch(error => {
console.log(error)
});
});

It depends how you would like to send the push notification. We have created UI that allows sending a push, which triggers a lambda.
Firstly, you need the app to update the endpoint with the token / address as you have done.
Then you can send the push from the lambda, as shown in this code.
const sendPushNotification = async () => {
const params = {
ApplicationId: "PINPOINT_ANALYTICS_ID",
SendUsersMessageRequest: {
Users: {
"12345": {} // replace numbers with userid here connected with pinpoint endpoint
},
MessageConfiguration: {
APNSMessage: {
Action: 'OPEN_APP',
Title: 'Title of push notification',
SilentPush: false,
Sound: 'default',
Body: 'Message you would like to send'
},
GCMMessage: {
Action: 'OPEN_APP',
Title: 'Title of push notification',
SilentPush: false,
Sound: 'default',
Body: 'Message you would like to send'
},
},
},
};
return pinpoint.sendUsersMessages(params).promise();
};
await sendPushNotification();

I was able to do that using #aws-amplify/analytics library. Following is the method that I used.
Analytics.configure(aws_exports);
PushNotification.onRegister((token) => {
//alert(token)
console.log('in app registration', token);
Analytics.updateEndpoint({
address: token, // The unique identifier for the recipient. For example, an address could be a device token, email address, or mobile phone number.
attributes: {
// Custom attributes that your app reports to Amazon Pinpoint. You can use these attributes as selection criteria when you create a segment.
hobbies: ['piano', 'hiking'],
interests: ['basketball']
},
channelType: 'GCM', // The channel type. Valid values: APNS, GCM
userId: '221XWsdfER234',
// User attributes
optOut: 'ALL',
userAttributes: {
interests: ['football', 'basketball', 'AWS']
// ...
}
}).then((data) => {
console.log(data)
}).catch(error => {
console.log(error)
})
});

With Amazon Pinpoint, you can’t send transactional message as Push notification. Meaning, you can’t send direct Push notification to a specific recipient.
Amazon Pinpoint - Push notification supports sending notifications to a targeted audience by creating a campaign and segment.
If it’s for testing only, from Pinpoint dashboard, you can send Test message to a specific user by using User ID or by using device token.
Read more here =>
Sending Transactional Messages from Your Apps - Amazon Pinpoint

Related

Can we generate push notification using onPressed in Flutter (using Firebase)?

I know that we can use firebase cloud messaging and from the firebase console only we can generate notifications for flutter app (after we setup up everything in the app
). But is there any way by which I can generate notification on press of a button. For e.g. The admin of the app adds a new event, as soon as he/she presses [Add Event] button, a notification gets generated for each user (using firebase) that a new event has been added? How can this be achieved?
You can call your server in onPressed: (https://docs.flutter.dev/cookbook/networking/fetch-data)
Example:
onPressed: () async {
await http.get(Uri.parse("https://your-server.com/add-event"));
}
then from your server you can send a fcm notfication to the devices: (https://firebase.google.com/docs/cloud-messaging/server#implementing-the-xmpp-connection-server-protocol)
Example:
const registrationTokens = [
'YOUR_REGISTRATION_TOKENS',
];
const message = {
data: {new_event: 1},
tokens: registrationTokens,
};
getMessaging().sendMulticast(message)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});

how to push notification to all users in flutter like

hello guys i want to send notification to all users in my firebase by API like this :
`var serverToken ="" ;
sendNotify(String title , String body , String id) async{
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers:<String,String>{'Content-Type':'application/json',
'Authorization':'key=$serverToken',},
body:jsonEncode(
<String,dynamic>{
'notification':<String,dynamic>{
'body':body.toString(),
'title':title.toString()
},
'priority':'high',
'data':<String,dynamic>{
'click_action':'FLUTTER_NOTIFICATION_CLICK',
'id':id.toString()},
//'to':'all', <<<<<<< here i want to send it to all users not by token }));`
For this you should use topics ,
You need to subscribe users to the all topic and no need for tokens when sending the notification
Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.
// subscribe to topic on each app start-up
await FirebaseMessaging.instance.subscribeToTopic('all');
and your data
jsonEncode({
'topic': "all",
'data': {
'via': 'FlutterFire Cloud Messaging!!!',
'count': _messageCount.toString(),
},
'notification': {
'title': 'Hello FlutterFire!',
'body': 'This notification (#$_messageCount) was created via FCM!',
},
});

Unable to send FCM notification to device using NodeJS Admin SDK

I am following the code mentioned in the docs to send a notification through Admin SDK.
exports.sendNotification = functions.https.onRequest((req, res) => {
const message = {
data: {
type: "warning",
content: "A new weather warning has been created!",
},
topic: "weather",
};
admin
.messaging()
.send(message)
.then((response) => {
console.log("Successfully sent message:", response);
})
.catch((error) => {
console.log("Error sending message:", error);
});
res.end();
});
After running the above code using Firebase emulator, the console prints
i functions: Beginning execution of "us-central1-sendNotification"
i functions: Finished "us-central1-sendNotification" in ~1s
> Successfully sent message: projects/foo/messages/2216986345254434321
However, I don't see any notification on the device.
NOTE: If I send the notification through Firebase Notification composer or Postman to the same topic weather, the device does show a notification. I don't know what's wrong in the code above.
You're sending a data message which requires you to handle the display yourself.
Checkout Message Types for the different types of FCM messages.
In order to see your notifications, you can do either of the following:
Send a notification message instead of a data message, this means you'll use the notification key in place of the data key in your message payload object like below:
const message = {
notification: {
title: "warning",
body: "A new weather warning has been created!",
},
topic: "weather",
};
Display the data message using the flutter_local_notification plugin as outlined in firebase_messaging's documentation

cordova fcm push notifications using firebase functions issue

I am using firebase function and sending the notification like below
let pushPayload = {
notification: {
title: 'Doodles Notification',
body: "push testing",
sound: 'default',
badge: '1'
}
};
//push tokens need to be of customer as well as all the admins in the system. fetch admin push tokens
admin.messaging().sendToDevice(pushToken, pushPayload).then(
(resp) => {
console.log("push notification sent using test method")
return
}
).catch(
(err) => {
console.log("Error sending push notification:" + JSON.stringify(err))
return
}
)
The client side ionic app has method like below:
this.fcm.onNotification().subscribe(data => {
console.log("push message is:" + JSON.stringify(data))
alert(data.aps.alert.body)
});
on ios this all works great. however on android, the console.log prints
{"wasTapped":false}
I am ok with the above expected property but where is the data? The firebase documentation is confusing around it and I am sort of lost what is the correct payload I need to use that works with both ios and android.
Your pushPayload also needs to have a data array to pass data. I believe you also need speech marks around your keys:
"notification":{
"title":"Doodles Notification",
"body":"push testing",
"sound":"default",
"badge":"1"
},
"data":{
"Key1":"Test",
"Key2":"More data"
}
Documentation

Background Firebase Push Notifications in Cordova

I am using a phonegap-plugin-push for receiving notifications in Cordova Application. I am deploying on android Marsh-mellow for testing.
I want to see and store the contents of the Notifications received through Firebase Console when the app is in background.
Here is my Code -
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
var push = PushNotification.init({ "android": {"senderID": "91254247XXXX"}});
push.on('registration', function(data) {
console.log(data.registrationId);
//document.getElementById("gcm_id").innerHTML = data.registrationId;
});
push.on('notification', function(data) {
alert("On Notification function!!");
// data.message,
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData
console.log("notification event");
console.log(JSON.stringify(data));
alert(JSON.stringify(data));
//Do something
});
push.on('error', function(e) {
alert(e);
});
}
When the app is in foreground (on screen) I receive the contents (title, message, data, etc.) properly and I am able to see them in alert box directly in the app.
But when app is in background (not on screen but running in backround), I get the notification in Notification Area. When I click on the notification received, it is redirecting me to the last opened page in the app.
The function push.on('notification', function(data) {} is not called. No alert messages are shown. Can someone help me how to access the notification message and data?
I found the answer after 2 days of research. We have to set "content-available" to 1 in the data field. Else it wont call on notification block if app is in background.
And this is not possible as of now through Google Firebase Console.
We have to send our custom payload messages (data or notification or both) seperately using any one of the firebase servers.
Detailed info can be found on the plugin's GitHub Page on background notifications.
I used NodeJs firebase-admin. I followed these setup guidelines and these steps for sending messages and it worked for me.
Here is my working code (NodeJS) -
var admin = require("firebase-admin");
var serviceAccount = require("pushnotificationapp-xxxxx.json"); //this is the service account details generated from server
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://pushnotificationappxxxxx.firebaseio.com/" //your database URL here.
});
var registrationToken = "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX....."; //registration token of the device
var payload ={
"data": {
"title": 'Test Push',
"message": 'Push number 1',
"info": 'super secret info',
"content-available": '1' //FOR CALLING ON NOTIFACATION FUNCTION EVEN IF THE APP IS IN BACKGROUND
}
};
//send the notification or message
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
UPDATE :
I implemented the same using php server too.
Here is my working php code for sending notifications using HTTP POST to FCM server-
<?php
$url = 'https://fcm.googleapis.com/fcm/send';
$data =
array(
"to" => "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX.....",
"data" => array(
"title"=> 'Test Push',
"message"=> 'Push number 1',
"info"=> 'super secret info',
"content-available"=> '1')
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => array("Content-Type:application/json",
"Authorization:key=AAAA1HfFM64:APA91XXXX...."), //this is the server authorization key from project settings tab in your Firebase Project
'method' => 'POST',
'content' => json_encode($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo "Caught an error"; }
else{
echo $result;
}
?>
i was going through the same issue but i added "content-available": '1' also but my phone was not receiving any background push.
Finally i found that it was issue with my phone as mentioned here: https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#huawei-and-xiaomi-phones
Huawei and Xiaomi Phones
These phones have a particular quirk that when the app is force closed that you will no longer be able to receive notifications until the app is restarted. In order for you to receive background notifications:
On your Huawei device go to Settings > Protected apps > check "My App" where.
On your Xiaomi make sure your phone has the "Auto-start" property enabled for your app.
On your Asus make sure your phone has the "Auto-start" property enabled for your app.
Hope it will help someone.

Categories

Resources