NativeScript Plugin Firebase token not registering to Adobe Mobile Services - firebase

I'm working on a NativeScript mobile application where I'm using nativescript-plugin-firebase to retrieve a Firebase token I then send to Adobe Mobile Services so that I can send push notifications from there to users of both platforms (Android and iOS):
FirebasePlugin.init({
onMessageReceivedCallback: () => { ... },
onPushTokenReceivedCallback: (token: string) => {
AdobeAnalytics.getInstance().optIn();
AdobeAnalytics.getInstance().setPushIdentifier(isAndroid ? token : new NSData({ base64Encoding: token }));
}
});
This works fine on Android, where I can then send notifications from AMS to individual devices using the token or to multiple ones using AMS's segments.
However, on iOS it only works using the token, as AMS thinks there are no iOS devices registered. The requests triggered by setPushIdentifier returns 200 OK and something like this on both platforms:
{
"d_blob": "...",
"d_mid": "...",
"d_ottl": 7200,
"dcs_region": 6,
"ibs": [],
"id_sync_ttl": 604800,
"subdomain": "mysandbox",
"tid": "..."
}
I use a modified version of nativescript-adobe-marketing-cloud 1.5.0 that exposes that setPushIdentifier, but the implementation doesn't change.
I have also tried replacing nativescript-plugin-firebase with push-plugin, in which case I get an APNs token when using iOS instead of a Firebase one:
PushPlugin.init({
onMessageReceivedCallback: () => { ... },
onPushTokenReceivedCallback: (token: string) => {
AdobeAnalytics.getInstance().optIn();
AdobeAnalytics.getInstance().setPushIdentifier(isAndroid ? token : new NSData({ base64Encoding: token }));
}
});
But the same thing happens.

Related

How to send SMS programmatically using Amazon Amplify SDK for my Android app users?

I want to send a welcome message (SMS) to phone number of my app's user when they will sign up using their phone number. I couldn't find official documentation for this particular task.
Amazon lets you do this. Assuming you're using Cognito for sign-up, you'll want to use the post-confirmation Cognito lambda trigger.
Set up your SNS account via the AWS Console, to send SMS messages. Send yourself a test message via the console.
Run amplify auth update
When it gets to the question Do you want to configure Lambda Triggers for Cognito?, answer Yes and choose the Post Confirmation trigger
You need to grant SNS (SMS) permissions to the lambda. Update the PostConfirmation-cloudformation-template.json file to add a new statement under Resources.lambdaexecutionpolicy.Properties.PolicyDocument.Statement:
{
"Resources": {
"lambdaexecutionpolicy": {
"Properties": {
"PolicyDocument": {
"Statement": [
{
"Effect": "Allow",
"Action": "sns:*",
"Resource": "*"
}
]
...
}
...
}
...
}
...
}
...
}
Use this code for the trigger:
var aws = require('aws-sdk');
var sms = new aws.SNS();
exports.handler = (event, context, callback) => {
console.log(event);
if (event.request.userAttributes.phone_number) {
sendSMS(event.request.userAttributes.phone_number, "Congratulations " + event.userName + ", you have been confirmed: ", function (status) {
// Return to Amazon Cognito
callback(null, event);
});
} else {
// Nothing to do, the user's phone number is unknown
callback(null, event);
}
};
function sendSMS(to, message, completedCallback) {
const params = {
Message: message, /* required */
PhoneNumber: to
};
sns.publish(params, function (err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
console.log(data);
}
completedCallback("SMS Sent");
})
};
Not sure if sending SMS is a service, Amazon Amplify provides.
But you could use a service like Twilio to send SMS (and much more) to phones.
AWS Amplify can help you setting up SMS, Email and Push notifications to your users by integrating with Amazon Pinpoint. Take a look at the documentation here: https://aws-amplify.github.io/docs/js/push-notifications.
Amazon Pinpoint allows you to create user segmentation, message templates, campaigns (with A/B testing and canary as well), Journeys (for email only so far), and so many more other things. You can integrate it and configure it using AWS Amplify, but some of those features I've mentioned are still not supported by AWS Amplify and you will have to either use the AWS Console to configure or use the AWS SDK to integrate with your app. You can leverage the AWS Amplify Auth module in order to get a valid Cognito token which will allow you to interact with Amazon Pinpoint directly.

this.fcm.onNotification().subscribe() not called on Android device

I have an Ionic 4 app which I have integrated with Firebase for authentication etc. I want to implement Firebase's cloud messaging so I can push messages to my app on both Android and iOS. I have done this pretty easily on iOS and I have sent a message via Postman which shows on my iPhone and I see the JSON of the message I have sent. When I try it on Android it doesn't work. Both devices receive the message but handle it very diferently.
I have read in a lot of places that you need to set the click_action to FCM_PLUGIN_ACTIVITY but when I do that the app doesn't even open on Android. When I take it out the app loads when you click the message but it doesn't show the body of the message like on iOS in my alert.
import { FCM } from '#ionic-native/fcm/ngx';
...
constructor(public platform: Platform, public fcm: FCM)
...
this.platform.ready().then(() => {
this.fcm.onNotification().subscribe(data => {
alert(JSON.stringify(data));
});
this.fcm.onTokenRefresh().subscribe(token => {
// Register your new token in your back-end if you want
// backend.registerToken(token);
});
}).catch((error) => {
this.showFailureMessage(error.message);
});
This is what I am posting off to... https://fcm.googleapis.com/fcm/send
{
"notification":{
"title":"My Title",
"body":"My Body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY"
"icon":"fcm_push_icon",
},
"data":{
"type":"Something",
},
"to":"/topics/all",
"priority":"high",
"restricted_package_name":""
}
Any help would be very much appreciated.
You seem to be missing the data.wasTapped part in your subscribe. Here, try this:
this.fcm.onNotification().subscribe(data => {
if (data.wasTapped) {
alert('Received in background');
alert(JSON.stringify(data));
} else {
alert('Received in foreground');
alert(JSON.stringify(data));
}
});

An error occurred when trying to authenticate to the FCM servers

An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions. See https://firebase.google.com/docs/admin/setup for setup instructions
enter image description here
For solving this problem I took the following steps:
open Google Cloud Platform Dashboard
Go to API and Services
Enable API and Services
Search for Cloud Messaging
Turn on the cloud messaging and Firebase cloud messaging API.
I just came across this issue and, for me, it was because I was using a simulator.
The FCM token generated by the simulator isn't valid for firebase cloud messaging and it was throwing this error.
I put my admin.messaging().sendToDevice() into a try catch and it's working fine.
I don't know if is sends the notification only to the valid tokens or if it totally ignores all of them though
Download a new private key and delete the old one!
By default Firebase uses Firebase Cloud Messaging API (V1) so you need to use this api instead of legacy one
for Firebase Cloud Messaging API (V1) :
const data = {
message: {
token: registrationToken,
notification: {
title: "Notification Title",
body: "Notification Body ",
},
data: {
Nick: "Mario",
Room: "PortugalVSDenmark",
},
},
};
admin.messaging().send(data.message);
for Cloud Messaging API (Legacy)
1.First go to Google Cloud Platform Dashboard and enable Cloud Messaging Service
2. and then you can use like this :
var payload = {
notification: {
title: "This is a Notification",
body: "This is the body of the notification message.",
},
};
var options = {
priority: "high",
};
var registrationToken ="your device token";
admin
.messaging()
.sendToDevice(registrationToken, payload, options)
.then(function (response) {
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
Firebase Cloud Messaging API (V1) is recommended than Cloud Messaging API (Legacy)
In my case, following Abhimanyu's solution to generate a new key still couldn't solve the problem.
After digging for 5 hours, I found the root cause that Google didn't activate this API for my project!!!!
It works After I activate the Cloud Messaging permission.
Just to clarify the FCM v1 usage as pointed by #Abhishek Ghimire.
Here is how to create the message:
const message = {
token: registrationToken,
notification: {
title: "Notification Title",
body: "Notification Body ",
},
};
admin.messaging().send(message);

I am unable to make a http call while running my ionic v4 app in browser

I want to run my Ionic 4 app in browser and make a http post request. The request is sent, when the app is running on a mobile device but it doesn't work in the browser.
this.http.post(
url,
{
"req": 2,
"userId": username,
"password": password,
"orgId": 1,
"device_id": "",
"device_type": "android",
"regd_id": "",
"build_type": "production"
},
{ 'Content-Type': 'application/json'}
).then(async data => {
//some logic
}).catch(error => {
//Error Handling
});
});
if you are using the plugin cordova-plugin-advanced-http
and used the code:
import { HTTP } from '#ionic-native/http/ngx';
It not posible running this on browser because is a function that use native http of device, the same browser say that on console.
If you want to use on browser need to use:
import { HttpClient } from '#angular/common/http';
If you want to run the app in parallel (mobile/browser) need to import both plugin and use the plugin Platform and use the code to use the correspondent:
this.platform.is("ios" || "android" || "desktop")
I'm not sure about the platform names that return the plugin but do test to know it.
I hope I've helped :)

push notification does not work for ios and azure with specific token

We are using Visual Studio to create an Apache Cordova app that is connected to an Azure Mobile Service . We are using the Cordova Push Plugin to receive Notifications in our app. We have created a JavaScript method in the Azure Mobile Service to send the notifications, this method is triggered by a scheduler. Please note that the intention is to send each Notification to a particular device.
The notifications work perfectly for Android devices but not for the iOS devices.
In iOS the notification is not received however the method in Azure Mobile Service always returns “Success”.
If we set the Device Token to "Null" , then it works for iOS devices (but sends to all devices not just one).
Could anyone please help us to resolve this issue?
this is Push.Send() method in Azure
push.send(result.DeviceID, payload, {
success: function(pushResponse){
//console.log("Sent push:", pushResponse);
//update notification sent time-start
var sqlUpdate = '';
mssql.query(sqlUpdate, {
success: function(results)
{
//response.json(statusCodes.OK, results);
},
error : function()
{
//response.send(statusCodes.INTERNAL_SERVER_ERROR);
}
})
//update notification sent time-end
},
error: function (pushResponse) {
//console.log("Error Sending push:", pushResponse);
}
});
and this is my App registration Method in the app
var pushNotification = window.plugins.pushNotification;
//alert("device.platform" + device.platform);
// Platform-specific registrations.
if (device.platform == 'android' || device.platform == 'Android') {
alert("device.platform : Android ");
// Register with GCM for Android apps.
pushNotification.register(
app.successHandler, app.errorHandler,
{
"senderID": GCM_SENDER_ID,
"ecb": "app.onNotificationGCM"
});
} else if (device.platform === 'iOS') {
// Register with APNS for iOS apps.
alert("device.platform : iOS ");
pushNotification.register(
app.tokenHandler,
app.errorHandler, {
"badge":"true",
"sound":"true",
"alert":"true",
"ecb": "app.onNotificationAPN"
});
}
else if(device.platform === "Win32NT"){
// Register with MPNS for WP8 apps.
alert("Device platform Windows")
pushNotification.register(
app.channelHandler,
app.errorHandler,
{
"channelName": "MyPushChannel",
"ecb": "app.onNotificationWP8",
"uccb": "app.channelHandler",
"errcb": "app.ErrorHandler"
});
}
// #endregion notifications-registration

Resources