AWS Pinpoint Service GCM(FCM) channel pinpoint.sendMessage sending duplicate push notifications - amazon-web-services

Getting duplicate push notifications while sending one push notification through AWS Pinpoint Service using FCM channel pinpoint.sendMessage method.
pushing notification on an FCM token but getting two different request IDs.
Push Notification callback Reponse
Why does this happen?
How can stop to send duplicate notification from node server?. and I am using "aws-sdk": "^2.1266.0". Any help would be appreciated.
code sample to send push notification :
export const sendPushNotification = async (userId: number, payload: RealTimeNotificationPayload) => {
const deviceTokens = await getAllDeviceTokensForUser(userId);
logInfo('deviceTokens==', deviceTokens)
const tokensTobeRemoved = [];
const pushNotificationPromises = deviceTokens.map(async (deviceToken) => {
const pinpoint = new AWS.Pinpoint();
const params = {
ApplicationId: commonConfig.aws.pinPointApplicationId,
MessageRequest: {
Addresses: {
[deviceToken]: {
ChannelType: PushNotifications.ChannelType.GCM
}
},
MessageConfiguration: {
GCMMessage: {
RawContent: JSON.stringify({
notification: {
title: "Title",
body: "Test body"
}
}),
Priority: 'medium',
SilentPush: false,
TimeToLive: 30,
} as AWS.Pinpoint.GCMMessage
}
}
} as AWS.Pinpoint.Types.SendMessagesRequest;
logInfo('params.MessageRequest==', params.MessageRequest.MessageConfiguration)
await pinpoint.sendMessages(params, async function (err, data) {
if (err) {
logError(err, `Error while sending push notification device token ${deviceToken}`);
}
else {
if (checkIfTokenInvalid(deviceToken, data)) {
tokensTobeRemoved.push(deviceToken);
}
console.log("Response data==> ", JSON.stringify(data, null, 4));
logInfo('data==', deviceToken, data.MessageResponse.Result[deviceToken].DeliveryStatus)
}
}).promise();
})
await Promise.all(pushNotificationPromises);
logInfo('tokensTobeRemoved==', tokensTobeRemoved)
if (tokensTobeRemoved.length) {
await deleteInvalidDeviceTokens(tokensTobeRemoved);
}
}

Related

How To Set Up Lambda To Work With Pinpoint's APNS Sandbox?

I am having a bit of an issue getting push notifications to be sent remotely from a lambda using AWS pinpoint.
In my application I have the following code:
PushNotification.configure(awsconfig)
PushNotificationIOS.addEventListener('registrationError', console.log)
PushNotification.onRegister(async token => {
console.log('in app registration', token)
PushNotification.updateEndpoint(token)
setRegistrationToken(token)
})
PushNotification.onNotification(notification => {
console.log('in app notification', notification)
if (Platform.OS === 'ios') {
notification.finish(PushNotificationIOS.FetchResult.NoData)
}
})
PushNotification.onNotificationOpened(notification => {
console.log('the notification is opened', notification)
})
const endpointId = Analytics.getPluggable('AWSPinpoint')._config.endpointId
console.log(`endpoint ID: ${endpointId}`)
if (Platform.OS === 'ios') {
PushNotification.requestIOSPermissions()
}
That code runs perfectly and I can take the token that is logged, go to the pinpoint console, and send a "Test Notification" by choosing "Device Tokens" and "APNS Sandbox."
After that, I set up my lambda and added the following code:
const AWS = require('aws-sdk');
async function sendTestNotification() {
console.log("CALLED SEND TEST")
const title = "Test Message"
const message = "This is a message from Pinpoint dynamically delivered via code"
const applicationId = <HARD CODED APPLICATION ID FROM PINPOINT CONSOLE>
const token = <HARD CODED DEVICE TOKEN I USED IN THE TEST NOTIFICATION>
var messageRequest = {
'Addresses': {
[token]: {
'ChannelType' : 'APNS_SANDBOX'
}
},
'MessageConfiguration': {
'APNSMessage': {
'Action': 'OPEN_APP',
'Body': message,
'Priority': 'normal',
'SilentPush': false,
'Title': title,
'TimeToLive': 30
}
}
};
AWS.config.update({ region: 'us-east-1'});
var pinpoint = new AWS.Pinpoint();
var params = {
"ApplicationId": applicationId,
"MessageRequest": messageRequest
}
pinpoint.sendMessages(params, (sendMessagesErr, sendMessagesData) => console.log(sendMessagesErr, sendMessagesData))
}
exports.handler = async (event) => {
console.log('running')
await sendTestNotification();
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
When I test the function, it runs and completes normally with no errors. However, no notifications come through. Initially, I thought it may have to do with permissions, but I have given the lambda full access to Pinpoint via a custom role, and that still did not change the result.
Any help would be much appreciated, as I am not sure where to troubleshoot next.
You haven't set the token in your MessageRequest. You have [token] under addresses:. You need to put the actual APNS token here. (I've put in some random letters in numbers here for an example...
var messageRequest = {
'Addresses': {
'483hgto483gh87egf8o2phqradgq3984hgeorigheg27r': {
'ChannelType' : 'APNS_SANDBOX'
}
},
'MessageConfiguration': {
'APNSMessage': {
'Action': 'OPEN_APP',
'Body': message,
'Priority': 'normal',
'SilentPush': false,
'Title': title,
'TimeToLive': 30
}
}
};

AWS Lambda not Pulling Data from DynamoDB and returning in on AWS Lex

I am trying to pull and display data from DynamoDb by using AWS Lambda function and have it display on AWS Lex. It is returning the if portion with the word "undefined" in the place where the data should be. The information is in the DynamoDB database. I am mainly using AWS servers and building this serverless Lex bot application.
AWS code Segments
const AWS = require('aws-sdk');
const db = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
exports.handler = async (event) => {
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
function getExamSchedule(exam2, table){
return new Promise(function(resolve){
var info = 0;
var params = {
TableName: table,
FilterExpression: "#key = :data",
ExpressionAttributeNames: {
"#key": "Resource",
},
ExpressionAttributeValues:{
":data": exam2
}
};
db.scan(params, function(err, data){
if(err){
console.log("Error: " + err);
info = 0;
} else {
console.log("Success", data);
info = {"ClassID" :data.Items[0].ClassID, "ExamDate " :data.Items[0].ExamDate,
"ExamEndTime:" :data.Items[0].ExamEndTime, "ExamLocation" :data.Items[0].ExamLocation,
"ExamStartTime" :data.Items[0].ExamStartTime};
}
resolve(info);
});
});
}
This is the portion where the issue might be occurring.
exports.handler = async (event, context, callback) => {
var exam2 = event.currentIntent.slots.ClassID;
var info = await getExamSchedule(exam2, "Final_Exams");
var res;
// if (info !== 0)
if(info != null){
res =`The exam information for ${exam2} is ${info.ClassID} Date: ${info.ExamDate}
End time: ${info.ExamEndTime} Location: ${info.ExamLocation} Start time: ${info.ExamStartTime}`;
} else {
res = `The exam is not entered into our database, please look for another exam.`;
}
callback(null, {
"dialogAction": {
"type":"Close",
"fulfillmentState": "Fulfilled",
"message":{
"contentType": "PlainText",
"content": res
}
}
});
};
Could you perhaps share some of the logs and/or stack traces that you encounter when running the code?

AWS SES send email lambda not sending every time

I want to send emails using the ses from aws from lambda. The problem is that the email is only sent some times using the same code. We don't get errors.
Here's the code:
const AWS = require('aws-sdk');
var ses = new AWS.SES();
exports.handler = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
await new Promise((resolve, reject) => {
var params = {
Destination: {
ToAddresses: [myEmail]
},
Message: {
Body: {
Text: { Data: "Test"
}
},
Subject: { Data: "Test Email"
}
},
Source: "sourceMail"
};
ses.sendEmail(params, function (err, data) {
if (err) {
console.log(err);
context.fail(err);
} else {
console.log(data);
context.succeed(event);
}
callback(null, {err: err, data: data});
});
});
}
I would be careful with using callbackWaitsForEmptyEventLoop as it can lead to unexpected results (If this is false, any outstanding events continue to run during the next invocation.).
Can you try using this simplified version:
const AWS = require('aws-sdk');
var ses = new AWS.SES();
exports.handler = async (event, context, callback) => {
const params = {
Destination: {
ToAddresses: [myEmail],
},
Message: {
Body: {
Text: { Data: 'Test' },
},
Subject: { Data: 'Test Email' },
},
Source: 'sourceMail',
};
await ses.sendEmail(params).promise();
return event;
};

After pushing on lambda FCM does not work

I want to send push notifications in my lambda function. It working as expected on localhost but when I push it to lambda code does not working.
Here is my code:
const FCM = require('fcm-node');
let sendNotification = function(regToken) {
let serverKey = 'MY_SERVER_KEY';
let fcm = new FCM(serverKey);
let message = {
to: regToken,
notification: {
title: 'Title of push notification',
body: 'Body of push notification'
}
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!", err);
} else {
console.log("Successfully sent with response: ", response);
}
});
}
You need to encapsulate functions in the exports.handler

Parse Server - Missing Push Configuration?

I've been trying to get push notifications to work with my Parse application. I tried to do so my adding the below code into my Parse server.js file but my server does not start up again when this code is contained inside of the file. I have my p12 file available and linked in the code below (on my actual sever) as well so Im not sure what the issue is.
push: {
android: {
senderId: '...',
apiKey: '...'
},
ios: {
pfx: '/file/path/to/XXX.p12',
passphrase: '', // optional password to your p12/PFX
bundleId: '',
production: false
}
}
My server is running on an Amazon EC2 instance as well.
Are you using AWS SNS to use push notification? If so, you can try setting this in your server code:
function sendPhoneNotification() {
AWS = require('aws-sdk');
AWS.config.update({
accessKeyId: '***',
secretAccessKey: '***',
region: 'ap-southeast-1'
});
var sns = new AWS.SNS();
var promise = new Parse.Promise();
sns.createPlatformEndpoint({
PlatformApplicationArn: '***',
Token: "***"
}, function (err, data) {
if (err) {
console.log("Error in endpoint" + err.stack);
//res.error("error stack 1: " + err.stack);
promise.reject(err.stack);
return promise;
}
var endpointArn = data.EndpointArn;
var payload = {
GCM: {
data: {
title: "YOUR TITLE",
message: "HELLO PUSH NOTIFICATION"
}
}
/* APNS: {
aps: {
alert: 'Hello World',
sound: 'default',
badge: 1
}
}*/
};
// payload.APNS = JSON.stringify(payload.APNS);
payload.GCM = JSON.stringify(payload.GCM);
payload = JSON.stringify(payload);
var result = sns.publish({
Message: payload,
MessageStructure: 'json',
TargetArn: endpointArn
}, function (err, data) {
if (err) {
promise.reject(err.stack);
return promise;
}
res.success("push sent " + JSON.stringify(data));
});
});
return promise;
}