AWS SNS sound for iOS push notification not happening - ios

I have an SNS triggered by a lambda on AWS that generates an iOS push notification, is working fine, but the problem is that the sound is not happening...
const sns = new AWS.SNS();
var payload = {
default: ' World23',
APNS: {
aps: {
alert: 'tkt',
sound: 'default',
badge: 1
}
}
};
// first have to stringify the inner APNS object...
payload.APNS = JSON.stringify(payload.APNS);
// then have to stringify the entire message payload
payload = JSON.stringify(payload);
var params = {
Message:payload,
MessageStructure: 'json',
Subject: event.body.subject,
TargetArn:TargetArn
};
sns.publish(params, function(err,data){
if(err) {
console.error('error publishing to SNS',err);
context.fail(err);
} else {
console.info('message published to SNS',data);
done(null, data);
}
});
What is wrong with my payload?, the sound and badge are not getting set.
Cheers...

The formatting for the body needed some tweaks, also the environment was the "sandbox", will have to change for prod push notifications "APNS"...
const sns = new AWS.SNS();
var payload = {
default: notifMessage,
'APNS_SANDBOX': {
'aps': {
'alert': notifMessage,
'sound': 'default',
'badge': 1
}
},
// first have to stringify the inner APNS object...
payload.APNS_SANDBOX = JSON.stringify(payload.APNS_SANDBOX);
// then have to stringify the entire message payload
payload = JSON.stringify(payload);
var params = {
// Message: event.body.message,
Message:payload,
MessageStructure: 'json',
Subject: event.body.subject,
TargetArn:TargetArn
};
console.log('params:: ', payload);
sns.publish(params, function(err,data){
if(err) {
console.error('error publishing to SNS',err);
context.fail(err);
} else {
console.info('message published to SNS',data);
done(null, data);
}
});

Related

How to create voip push notification from Node.js server

I want to send voip push to my iOS app when its not active, and I tried to use apn module from this solution but it did not work for me.
I followed official apple docs about voip push here but still have some problems to send it from the server.
I also tried to send it trough AWS sns service but got normal push for notification and etc.
What do I do wrong?
Right now my code is :
here I do format for sns item
const formatVoipPushNotificationsToSend = (type, header, launchId, sender, to = '', device_token, token) => {
const headers = {
':method': 'POST',
'apns-topic': '************.voip', //application bundle ID
':scheme': 'https',
':path': `/3/device/${device_token}`,
'authorization': `bearer ${token}`,
'apns-push-type': 'voip',
};
const aps = {
alert: {
title: header,
body: 'text' || null
},
itemId: type,
from: sender || null,
to,
launchId: launchId || null,
'content-available': 1
};
return { aps, headers };
};
and then I pass the item here and send it to the app with sns endpoint.
const pushNotifications = (item, arn, userId) => {
const payload = JSON.stringify(item);
const snsMessage = {};
snsMessage[SNS_PAYLOAD_KEY] = payload;
const params = {
Message: JSON.stringify(snsMessage),
TargetArn: arn,
MessageStructure: 'json'
};
const eventBody = item.aps.itemId ? {
[EVENT_TYPES.PUSH_SEND]: item.aps.itemId
} : {};
AmplitudeService.logEvent(EVENT_TYPES.PUSH_SEND, userId, eventBody);
return snsClient.publish(params).promise();
};
I'm using a slightly different approach:
var apn = require('apn');
const { v4: uuidv4 } = require('uuid');
const options = {
token: {
key: 'APNKey.p8',
keyId: 'S83SFJIE38',
teamId: 'JF982KSD6f'
},
production: false
};
var apnProvider = new apn.Provider(options);
// Sending the voip notification
let notification = new apn.Notification();
notification.body = "Hello there!";
notification.topic = "com.myapp.voip";
notification.payload = {
"aps": { "content-available": 1 },
"handle": "1111111",
"callerName": "Richard Feynman",
"uuid": uuidv4()
};
apnProvider.send(notification, deviceToken).then((response) => {
console.log(response);
});

How to use apns-collapse-id with FCM?

I know this question have been asked many times but none of the answers work for me. Some of the questions dont even have an answer.
I am try to bundle or group similar notifications on ios. I am using FCM Cloud Functions to trigger notifications.
Following are the methods i tried by
const payload = {
notification: {
title: "Your medical history is updated" + Math.random(),
tag: "MedicalHistory",
},
data: {
click_action: "FLUTTER_NOTIFICATION_CLICK",
sound: "default",
status: "done",
},
};
const patchedPayload = Object.assign({}, payload, {
apns: {
headers: {
"apns-collapse-id": "MedicalHistory",
},
},
});
const options = {
priority: "high",
collapseKey: "MedicalHistory",
};
await admin
.messaging()
.sendToDevice("MY_TOKEN", patchedPayload, options);
The above code does not work
const payload = {
notification: {
title: "Your medical history is updated" + Math.random(),
tag: "MedicalHistory",
},
data: {
click_action: "FLUTTER_NOTIFICATION_CLICK",
sound: "default",
status: "done",
},
apns: {
headers: {
"apns-collapse-id": "MedicalHistory",
},
},
};
const options = {
priority: "high",
collapseKey: "MedicalHistory",
};
await admin
.messaging()
.sendToDevice("MY_TOKEN", payload, options);
This does not work as well.
I dont understand where to put the apns-collapse-id. The cloud functions sample also does not show this. Neither i could find doc with code on this
I recommend using the latest send function from the firebase-admin lib, usage described here.
It seems to work fine and somewhat easier to apply.
An example of a message with android/ios specific headers:
// common data for both platforms
const notification = {
title: 'You liked!',
body: 'You really liked something...',
}
const fcmToken = '...'
// android specific headers
const android = {
collapseKey: '0'
}
// ios specific headers
const apns = {
headers: {
"apns-collapse-id": '0'
}
}
// final message
const message = {
token: fcmToken,
notification: notification,
android: android,
apns: apns,
}
// send message
admin.messaging().send(message).catch(err => console.error(err));

sending notification using firebase admin sdk not working

I am trying to send notification from Node.js server to an ios application. It seems working if I send notification from Firebase console, but isn't working if try from my node.js server using firebase-admin sdk.
I followed tutorial from https://firebase.google.com/docs/cloud-messaging/admin/send-messages.
One thing I do not understand is the response after sending notification seems working. I get below response.
{
"results": [
{
"messageId": "0:1511109840587284%a63b4c28f9fd7ecd"
}
],
"canonicalRegistrationTokenCount": 0,
"failureCount": 0,
"successCount": 1,
"multicastId": 7436388871122493000
}
Does anyone know what I am doing wrong?
-- Edit
Here is the code that sends the notification. admin is the firebase-admin instance.
router.post('/notify', (req, res) => {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "<database>.firebaseio.com"
});
var registrationTokens = [
'tokenFromIosApp'
];
var payload = {
data : {
body : 'TEST'
}
};
admin.messaging().sendToDevice(registrationTokens, payload)
.then((response) => {
console.log('Sent successfully.\n');
console.log(response);
res.status(statusCodes.Ok);
res.json(response);
})
.catch((error) => {
console.log('Sent failed.\n');
console.log(error);
res.status(statusCodes.InternalServerError);
res.json(error);
});
});
To send a notification, the payload must use the notification key:
var payload = {
notification: {
title: 'My Title',
body : 'TEST'
}
};

Cloud Function for Firebase sendToDevice not showing as notification on ios

Upon sending a successful notification via Cloud Functions for Firebase, the notification is not shown as a push notification on ios device. I have found a couple of similar issues, but none present a clear solution.
cloud function:
exports.sendInitialNotification = functions.database.ref('branches/{branchId}/notifications/{notifId}').onWrite(event => {
const data = event.data.val()
if (data.finished) return
const tokens = []
const notifId = event.params.notifId
const getPayload = admin.database().ref(`notifications/${notifId}`).once('value').then(snapshot => {
const notif = snapshot.val()
const payload = {
notification: {
title: notif.title,
body: notif.message,
},
data: {
'title': notif.title,
'message': notif.message,
'id': String(notif.id),
}
}
if (notif.actions) {
payload.data['actions'] = JSON.stringify(notif.actions)
}
console.log('payload:', payload)
return payload
}, (error) => {
console.log('error at sendInitialNotification getPayload():', error)
})
const getTokens = admin.database().ref(`notifications/${notifId}/users`).once('value').then(snapshot => {
const users = snapshot.forEach((data) => {
let promise = admin.database().ref(`users/${data.key}/profile/deviceToken`).once('value').then(snap => {
if (tokens.indexOf(snap.val()) !== -1 || !snap.val()) return
return snap.val()
}, (error) => {
console.log('error retrieving tokens:', error)
})
tokens.push(promise)
})
return Promise.all(tokens)
}, (error) => {
console.log('error at sendInitialNotification getTokens()', error)
}).then((values) => {
console.log('tokens:', values)
return values
})
return Promise.all([getTokens, getPayload]).then(results => {
const tokens = results[0]
const payload = results[1]
if (payload.actions) {
payload.actions = JSON.stringify(payload.actions)
}
const options = {
priority: "high",
}
admin.messaging().sendToDevice(tokens, payload, options)
.then(response => {
data.finished = true
admin.database().ref(`notifications/${notifId}`).update({success: true, successCount: response.successCount})
console.log('successfully sent message', response)
}).catch(error => {
data.finished = true
admin.database().ref(`notifications/${notifId}`).update({success: false, error: error})
console.log('error sending message:', error)
})
})
})
...and the logs in firebase console:
successfully sent message { results: [ { error: [Object] } ],
canonicalRegistrationTokenCount: 0, failureCount: 1, successCount:
0, multicastId: 7961281827678412000 }
tokens: [
'eS_Gv0FrMC4:APA91bEBk7P1lz...' ]
payload: { notification: { title: 'test07', body: 'test07' }, data:
{ title: 'test07', message: 'test07', id: '1502383526361' } }
...but alas no notification shown on iphone. Im sure I am missing something along the OOO (order of operations) here, but not sure where the snag is. If anyone can point out my flaw please feel free to publicly chastise.
As always thank you in advance and any and all direction is appreciated!
The issue I was seeing was due to the reverse domain id in xcode not matching what was in firebase.
Typo

How Do I send VoIP push notifications to an iOS device using Amazon SNS in Node JS

I am trying to send VoIP push notifications directly to an iOS device from an App server using the NodeJS package called sns-mobile and Amazon SNS API.
However, When I try to send VoIP pushes using the below code, here is the error message that I get. Could someone please suggest me where I am going wrong, I have been spending nearly half a day to resolve this.
Invalid parameter: JSON must contain an entry for 'default' or
'APNS_VOIP
var iOSApp = new SNS({
platform: SNS.SUPPORTED_PLATFORMS.IOS,
region: 'us-west-2',
apiVersion: '2010-03-31',
accessKeyId: 'XXXXXXXXXXXXX',
secretAccessKey: 'XXXXXXXXXXXXX',
platformApplicationArn: 'arn:aws:sns:us-west-2:3303035XXXXX:app/APNS_VOIP/VoIPPushesApp'
});
iOSApp.addUser('deviceID',
JSON.stringify({
"APNS_VOIP": JSON.stringify({aps:{alert:"Hello and have a good day."}})
})
, function(err, endpointArn) {
if(err) {
console.log("The Error is :****: "+JSON.stringify(err, null, 4));
throw err;
}
// Send a simple String or data to the client
iOSApp.sendMessage(endpointArn, 'Hi There!', function(err, messageId) {
//iOSApp.sendMessage(endpointArn, messageTest, function(err, messageId) {
if(err) {
console.log("The Error in end message is :****: "+JSON.stringify(err, null, 4));
throw err;
}
console.log('Message sent, ID was: ' + messageId);
});
});
Here is the code that send a VoIP notifications to the receiver device using its device VoIP token. When a VoIP notification is received, the device calls a function called, didReceiveIncomingPushWithPayload
var AWS = require('aws-sdk');
// Amazon SNS module
AWS.config.update({
accessKeyId : 'XXXXXXXXXXXXXXXX',
secretAccessKey : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
region : 'us-west-2'
});
var amazonSNS = new AWS.SNS();
// 1. Create Platform Endpoint
var createPlatformEndpoint = function(req, res, next){
var deviceVoipToken = req.deviceVoipToken; // Obtaining the device VoIP token from the request object
amazonSNS.createPlatformEndpoint({
// App in Sandboxmode (ie running on device directly from Xcode)
PlatformApplicationArn: "arn:aws:sns:us-west-2:xxxxxxxxxxxx:app/APNS_VOIP_SANDBOX/CurieVoip",
// App in Production mode (ie running on device after archiving and installed on device with a provisioning profile)
//PlatformApplicationArn: "arn:aws:sns:us-west-2:xxxxxxxxxxxx:app/APNS_VOIP/CurieVoip",
Token: deviceVoipToken
}, function(err, data) {
if (err) {
console.log(err.stack);
response.json({"status": "failure", "statusCode" : 402})
return;
}
var endpointArn = data.EndpointArn;
req.endpointArn = data.EndpointArn; // Passing the EndpointArn to the next function
next()
})
}
// 2. Publish notification
var publishVoipNotification = function(req, res, next){
var endpointArn = req.endpointArn;
var payload = {
default : 'Hello World, default payload',
APNS_VOIP : {
aps: {
alert: 'Hi there',
sound: 'default',
badge: 1
}
}
};
// first have to stringify the inner APNS object...
payload.APNS = JSON.stringify(payload.APNS);
// then have to stringify the entire message payload
payload = JSON.stringify(payload);
console.log('sending push');
amazonSNS.publish({
MessageStructure : 'json',
Message : payload,
TargetArn : endpointArn
}, function(err, data) {
if (err) {
console.log("Error stack: "+err.stack);
var message = "There has been an error in Publishing message via AmazonSNS with error: "+err.stack;
res.json({"status": "failure", "statusCode" : 402, "message" : message})
return;
}
next();
});
}
// 3. Deleting platform endpoint after sending a voipNotification; Ref: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#deleteEndpoint-property
var deleteEndpointArn = function(req, res){
var endpointArn = req.endpointArn;
var roomName = req.roomName;
var params = {
EndpointArn: endpointArn /* required */
};
amazonSNS.deleteEndpoint(params, function(err, data) {
if (err){
var message = "Unable to deleteEndpointArn, with error: "+err.stack;
res.json({"status": "failure", "statusCode" : 400, "message":message})
}
else{
var message = "Deleted endpointArn successfully";
res.json({"status": "success", "statusCode" : 200, "message":message})
}
});
}
router.post('/sendVoipNotificationToReceiver', [createPlatformEndpoint, publishVoipNotification, deleteEndpointArn]);
Go to Amazon SNS
Click on Mobile: Push notifications
Click on Create platform Application,
User Apple Credentials "Used for development in sandbox" check this checkbox if you want to test voip notification on sandbox.
Push certificate type -- Voip Push certificate
Upload Certificate .P12 files.
Save Form and copy ARN
Create Lambda function. Code example below
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'us-east-1'});
var amazonSNS = new AWS.SNS();
const isset = (s) => {
return typeof s !== typeof undefined ? true : false;
};
exports.handler = (event, context, callback) => {
let data = event['body-json'];
if (isset(data)) {
let getAction = data['action'];
let userToken = data['token'];
let webPayload = data['payload'];
if (isset(getAction) && getAction == 'APNS_VOIP') {
amazonSNS.createPlatformEndpoint({
PlatformApplicationArn: 'YOUR APPLICATION ARN',
Token: userToken
}, function (err, data1) {
if (err) {
//handle error
console.log(err)
} else {
//Publish notification
var endpointArn = data1.EndpointArn;
console.log("endpointArn",endpointArn);
var payload = {
default: 'Silent voip push notification',
APNS_VOIP: {
//aps:webPayload
"aps" : {
"alert" : {
"title" : "Call Request"
},
"data":webPayload,
"content-available":1,
"category":"GENERAL"
}
}
};
payload.APNS_VOIP = JSON.stringify(payload.APNS_VOIP);
payload = JSON.stringify(payload);
amazonSNS.publish({
MessageStructure: 'json',
Message: payload,
MessageAttributes:{
"AWS.SNS.MOBILE.APNS.PRIORITY":{"DataType":"String","StringValue":"10"},
"AWS.SNS.MOBILE.APNS.PUSH_TYPE":{"DataType":"String","StringValue":"voip"}
},
TargetArn: endpointArn
}, function (err, data2) {
if (err) {
//handle error
console.log(err)
} else {
var params = {
EndpointArn: endpointArn /* required */
};
//Deleting platform endpoint after sending a voipNotification;
amazonSNS.deleteEndpoint(params, function (err, data3) {
if (err) {
//handle error
//console.log(err);
callback(null, {
"status": "error",
"data": [],
"message": []
});
} else {
//code success
console.log("delete",data3);
callback(null, {
"status": "Success",
"data": data3,
"message":"notification sent successfully"
});
}
});
}
});
}
});
}
else if (isset(getAction) && getAction == 'APNS_VOIP_SANDBOX') {
amazonSNS.createPlatformEndpoint({
PlatformApplicationArn: 'YOUR APPLICATION ARN',
Token: userToken
}, function (err, data1) {
if (err) {
//handle error
console.log(err)
} else {
//Publish notification
var endpointArn = data1.EndpointArn;
console.log("endpointArn",endpointArn);
var payload = {
default: 'Silent voip push notification',
APNS_VOIP_SANDBOX: {
"aps" : {
"alert" : {
"title" : "Call Request"
},
"data":webPayload,
"content-available":1,
"category":"GENERAL"
}
}
};
payload.APNS_VOIP_SANDBOX = JSON.stringify(payload.APNS_VOIP_SANDBOX);
payload = JSON.stringify(payload);
amazonSNS.publish({
MessageStructure: 'json',
Message: payload,
MessageAttributes:{
"AWS.SNS.MOBILE.APNS.PRIORITY":{"DataType":"String","StringValue":"10"},
"AWS.SNS.MOBILE.APNS.PUSH_TYPE":{"DataType":"String","StringValue":"voip"}
},
TargetArn: endpointArn
}, function (err, data2) {
if (err) {
//handle error
console.log(err)
} else {
var params = {
EndpointArn: endpointArn /* required */
};
//Deleting platform endpoint after sending a voipNotification; Ref: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#deleteEndpoint-property
amazonSNS.deleteEndpoint(params, function (err, data3) {
if (err) {
//handle error
//console.log(err);
callback(null, {
"status": "error",
"data": [],
"message": []
});
} else {
//code success
console.log("delete",data3);
callback(null, {
"status": "Success",
"data": data3,
"message":"notification sent successfully"
});
}
});
}
});
}
});
}
else {
callback(null, {
"status": "error",
"data": [],
"message": "You have not posted valid data."
});
}
}
};
https://docs.aws.amazon.com/sns/latest/dg/sns-send-custom-platform-specific-payloads-mobile-devices.html
How Do I send VoIP push notifications to an iOS device using Amazon SNS in Node JS

Resources